mutts 1.0.12 → 1.0.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -2
- package/dist/browser.cjs +7 -3
- package/dist/browser.cjs.map +1 -1
- package/dist/browser.d.ts +1407 -2
- package/dist/browser.dev.cjs +7 -3
- package/dist/browser.dev.cjs.map +1 -1
- package/dist/browser.dev.d.ts +2 -2
- package/dist/browser.dev.esm.js +2 -2
- package/dist/browser.esm.js +3 -3
- package/dist/chunks/{index-yK0HVxHv.cjs → index-CAdnMJev.cjs} +202 -79
- package/dist/chunks/index-CAdnMJev.cjs.map +1 -0
- package/dist/chunks/{index-BUop6B2U.esm.js → index-XsYTUhHx.esm.js} +200 -77
- package/dist/chunks/index-XsYTUhHx.esm.js.map +1 -0
- package/dist/chunks/{node-Dd0esp5F.cjs → node-DrrphEPf.cjs} +2 -2
- package/dist/chunks/{node-Dd0esp5F.cjs.map → node-DrrphEPf.cjs.map} +1 -1
- package/dist/chunks/{node-Bo7WU5S2.esm.js → node-NEZvVo4M.esm.js} +2 -2
- package/dist/chunks/{node-Bo7WU5S2.esm.js.map → node-NEZvVo4M.esm.js.map} +1 -1
- package/dist/chunks/{proxy-D2C49sXH.esm.js → proxy-BtmPFjSr.esm.js} +307 -66
- package/dist/chunks/proxy-BtmPFjSr.esm.js.map +1 -0
- package/dist/chunks/{proxy-BvM4yewA.cjs → proxy-DBHj3kGK.cjs} +313 -66
- package/dist/chunks/proxy-DBHj3kGK.cjs.map +1 -0
- package/dist/debug.cjs +537 -166
- package/dist/debug.cjs.map +1 -1
- package/dist/debug.d.ts +96 -80
- package/dist/debug.esm.js +533 -166
- package/dist/debug.esm.js.map +1 -1
- package/dist/devtools/panel.js.map +1 -1
- package/dist/mutts.umd.js +508 -140
- package/dist/mutts.umd.js.map +1 -1
- package/dist/mutts.umd.min.js +1 -1
- package/dist/mutts.umd.min.js.map +1 -1
- package/dist/node.cjs +8 -4
- package/dist/node.cjs.map +1 -1
- package/dist/node.d.ts +2 -2
- package/dist/node.dev.cjs +8 -4
- package/dist/node.dev.cjs.map +1 -1
- package/dist/node.dev.d.ts +2 -2
- package/dist/node.dev.esm.js +3 -3
- package/dist/node.esm.js +3 -3
- package/dist/{types-Bx2PhORg.d.ts → types.d.ts} +12 -0
- package/docs/ai/api-reference.md +102 -12
- package/docs/ai/manual.md +60 -24
- package/docs/debug-getReason.md +161 -0
- package/docs/flavored.md +98 -1
- package/docs/reactive/advanced.md +15 -2
- package/docs/reactive/attend.md +32 -0
- package/docs/reactive/core.md +40 -6
- package/docs/reactive/debugging.md +25 -2
- package/docs/reactive.md +2 -0
- package/package.json +2 -3
- package/dist/chunks/index-BUop6B2U.esm.js.map +0 -1
- package/dist/chunks/index-yK0HVxHv.cjs.map +0 -1
- package/dist/chunks/proxy-BvM4yewA.cjs.map +0 -1
- package/dist/chunks/proxy-D2C49sXH.esm.js.map +0 -1
- package/dist/index.d.ts +0 -1322
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mutts.umd.min.js","sources":["../src/async/index.ts","../src/async/browser.ts","../src/utils.ts","../src/decorator.ts","../src/destroyable.ts","../src/diff.ts","../src/eventful.ts","../src/flavored.ts","../src/indexable.ts","../src/iterableWeak.ts","../src/mixins.ts","../src/promiseChain.ts","../src/reactive/debug-hooks.ts","../src/zone.ts","../src/reactive/registry.ts","../src/reactive/effect-context.ts","../src/reactive/types.ts","../src/reactive/tracking.ts","../src/reactive/effects.ts","../src/reactive/deep-watch-state.ts","../src/reactive/change.ts","../src/reactive/non-reactive.ts","../src/reactive/deep-touch.ts","../src/reactive/proxy.ts","../src/reactive/buffer.ts","../src/reactive/deep-watch.ts","../src/reactive/memoize.ts","../src/reactive/satellite.ts","../src/reactive/iterator-helpers.ts","../src/reactive/array.ts","../src/reactive/map.ts","../src/reactive/set.ts","../src/reactive/index.ts","../src/std-decorators.ts","../src/index.ts","../src/reactive/record.ts"],"sourcesContent":["export type Restorer = () => () => void\nexport type Hook = () => Restorer\n\n// Queue for hooks registered before the environment is ready (circular dependency fix)\nexport const hooks = new Set<Hook>()\n\nexport const asyncHooks = {\n\taddHook(hook: Hook): () => void {\n\t\thooks.add(hook)\n\t\treturn () => hooks.delete(hook)\n\t},\n\t/**\n\t * [Hack] Sanitize a promise (or value) to prevent context leaks.\n\t * Default: Identity function.\n\t * Browser: Uses Macrotask wrapping to break microtask chains.\n\t */\n\tsanitizePromise(p: any): any {\n\t\treturn p\n\t},\n}\n\n/**\n * Register a hook that will be called whenever an asynchronous operation is initiated.\n * The hook should return a restorer function which will be called just before the async callback runs.\n * That restorer should in turn return an undoer function which will be called just after the async callback finishes.\n */\nexport const asyncHook = (hook: Hook) => asyncHooks.addHook(hook)\n","import { asyncHooks, hooks, type Restorer } from '.'\n\nconst promiseContexts = new WeakMap<Promise<any>, Set<Restorer>>()\n\n// [HACK]: Sanitization\n// If a Promise is created inside the zone, it carries the \"Sticky\" zone context.\n// If returned to the outer scope, that context leaks. We wrap it in a new Promise\n// created here (in the outer scope) to break the chain and sanitize the return value.\n// See BROWSER_ASYNC_POLYFILL.md for full details.\nasyncHooks.sanitizePromise = (res: any) => {\n\tif (res && typeof (res as any).then === 'function') {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tsetTimeout(() => {\n\t\t\t\t;(res as any).then(resolve, reject)\n\t\t\t}, 0)\n\t\t})\n\t}\n\treturn res\n}\n\nfunction captureRestorers() {\n\tconst restorers = new Set<Restorer>()\n\tfor (const hook of hooks) {\n\t\tconst restorer = hook()\n\t\tif (restorer) restorers.add(restorer)\n\t}\n\treturn restorers\n}\n\nfunction wrap<Args extends any[], R>(\n\tfn: ((...args: Args) => R) | null | undefined,\n\tcapturedRestorers?: Set<Restorer>\n) {\n\tif (typeof fn !== 'function') return fn\n\tconst restorers = capturedRestorers || captureRestorers()\n\treturn function (this: any, ...args: Args) {\n\t\tconst undoers: (() => void)[] = []\n\t\tfor (const restore of restorers) undoers.push(restore())\n\t\ttry {\n\t\t\treturn fn.apply(this, args)\n\t\t} finally {\n\t\t\t/* cf BROWSER_ASYNC_POLYFILL.md\n\t\t\t// Note: my fear about this code: in between 2~3~4 microtask waits, some other microtasks might have started, stopped, ...\n\t\t\t// We might be in the middle of another promise hook trying to setup the zone\n\t\t\t// TODO We might wish to have a flag :asyncZone.acquired - like a semaphore - that we falsify here and set back when we setup the zone\n\t\t\t// - but this might perhaps be an overkill creating more problems than it solves\n\t\t\tif (originals.queueMicrotask) {\n\t\t\t\t// Double microtask ensures we run after the first await resumption microtask\n\t\t\t\toriginals.queueMicrotask.call(globalThis, () => {\n\t\t\t\t\toriginals.queueMicrotask.call(globalThis, () => {\n\t\t\t\t\t\toriginals.queueMicrotask.call(globalThis, () => {\n\t\t\t\t\t\t\tfor (let i = undoers.length - 1; i >= 0; i--) undoers[i]()\n\t\t\t\t\t\t})\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t} else {\n\t\t\t\tfor (let i = undoers.length - 1; i >= 0; i--) undoers[i]()\n\t\t\t}*/\n\t\t}\n\t}\n}\n\nconst GLOBAL_ORIGINALS = Symbol.for('mutts.originals')\nconst GLOBAL_PROMISE = Symbol.for('mutts.OriginalPromise')\n\nlet originals: any\nlet OriginalPromise: any\n\nif ((globalThis as any)[GLOBAL_ORIGINALS]) {\n\toriginals = (globalThis as any)[GLOBAL_ORIGINALS]\n\tOriginalPromise = (globalThis as any)[GLOBAL_PROMISE]\n} else {\n\tOriginalPromise = globalThis.Promise\n\toriginals = {\n\t\t// biome-ignore lint/suspicious/noThenProperty: Intentional Promise.prototype patching\n\t\tthen: OriginalPromise.prototype.then,\n\t\tcatch: OriginalPromise.prototype.catch,\n\t\tfinally: OriginalPromise.prototype.finally,\n\t\tresolve: OriginalPromise.resolve,\n\t\treject: OriginalPromise.reject,\n\t\tall: OriginalPromise.all,\n\t\tallSettled: (OriginalPromise as any).allSettled,\n\t\trace: OriginalPromise.race,\n\t\tany: (OriginalPromise as any).any,\n\t\tsetTimeout: globalThis.setTimeout,\n\t\tsetInterval: globalThis.setInterval,\n\t\tsetImmediate: (globalThis as any).setImmediate,\n\t\trequestAnimationFrame: (globalThis as any).requestAnimationFrame,\n\t\tqueueMicrotask: globalThis.queueMicrotask,\n\t}\n\t;(globalThis as any)[GLOBAL_ORIGINALS] = originals\n\t;(globalThis as any)[GLOBAL_PROMISE] = OriginalPromise\n}\n\n// Ensure modern statics are captured even if originals was cached from an older version\nif (!originals.allSettled) originals.allSettled = (OriginalPromise as any).allSettled\nif (!originals.any) originals.any = (OriginalPromise as any).any\nif (!originals.race) originals.race = OriginalPromise.race\n\nfunction patchedThen(this: any, onFulfilled: any, onRejected: any) {\n\tconst context = promiseContexts.get(this) || captureRestorers()\n\tconst nextPromise = originals.then.call(\n\t\tthis,\n\t\twrap(onFulfilled, context),\n\t\twrap(onRejected, context)\n\t)\n\tif (context.size > 0) promiseContexts.set(nextPromise, context)\n\treturn nextPromise\n}\n\nfunction patchedCatch(this: any, onRejected: any) {\n\tconst context = promiseContexts.get(this) || captureRestorers()\n\tconst nextPromise = originals.catch.call(this, wrap(onRejected, context))\n\tif (context.size > 0) promiseContexts.set(nextPromise, context)\n\treturn nextPromise\n}\n\nfunction patchedFinally(this: any, onFinally: any) {\n\tconst context = promiseContexts.get(this) || captureRestorers()\n\tconst nextPromise = originals.finally.call(this, wrap(onFinally, context))\n\tif (context.size > 0) promiseContexts.set(nextPromise, context)\n\treturn nextPromise\n}\n\nfunction PatchedPromise<T>(\n\tthis: any,\n\texecutor: (resolve: (value: T | PromiseLike<T>) => void, reject: (reason?: any) => void) => void\n) {\n\tif (typeof executor === 'function') {\n\t\tconst p = new OriginalPromise((resolve, reject) => {\n\t\t\tconst wrappedResolve = wrap(resolve)\n\t\t\tconst wrappedReject = wrap(reject)\n\t\t\texecutor(wrappedResolve, wrappedReject)\n\t\t})\n\t\tconst context = captureRestorers()\n\t\tpromiseContexts.set(p, context) // Always set, even if empty (Sticky Root)\n\t\treturn p\n\t}\n\treturn new OriginalPromise(executor)\n}\n\n// Copy statics\nObject.assign(PatchedPromise, OriginalPromise as any)\n\n// Inherit prototype for instanceof checks\nPatchedPromise.prototype = OriginalPromise.prototype\n\nPatchedPromise.resolve = (<T>(value?: T | PromiseLike<T>): Promise<T> => {\n\tconst p = originals.resolve.call(OriginalPromise, value) as Promise<T>\n\tconst context = captureRestorers()\n\t// Ensure we don't overwrite if it already has context (e.g. from constructor)\n\tif (context.size > 0 && !promiseContexts.has(p)) promiseContexts.set(p, context)\n\treturn p\n}) as any\n\nPatchedPromise.reject = (<T = never>(reason?: any): Promise<T> => {\n\tconst p = originals.reject.call(OriginalPromise, reason) as Promise<T>\n\tconst context = captureRestorers()\n\tif (context.size > 0) promiseContexts.set(p, context)\n\treturn p\n}) as any\n\nPatchedPromise.all = (<T>(values: Iterable<T | PromiseLike<T>>): Promise<Awaited<T>[]> => {\n\tconst p = originals.all.call(OriginalPromise, values) as Promise<Awaited<T>[]>\n\tconst context = captureRestorers()\n\tif (context.size > 0) promiseContexts.set(p, context)\n\treturn p\n}) as any\n\nPatchedPromise.allSettled = (<T>(\n\tvalues: Iterable<T | PromiseLike<T>>\n): Promise<PromiseSettledResult<Awaited<T>>[]> => {\n\tconst p = (originals.allSettled as any).call(OriginalPromise, values)\n\tconst context = captureRestorers()\n\tif (context.size > 0) promiseContexts.set(p, context)\n\treturn p\n}) as any\n\nPatchedPromise.race = (<T>(values: Iterable<T | PromiseLike<T>>): Promise<Awaited<T>> => {\n\tconst p = originals.race.call(OriginalPromise, values) as Promise<Awaited<T>>\n\tconst context = captureRestorers()\n\tif (context.size > 0) promiseContexts.set(p, context)\n\treturn p\n}) as any\n\nPatchedPromise.any = (<T>(values: Iterable<T | PromiseLike<T>>): Promise<Awaited<T>> => {\n\tconst p = (originals.any as any).call(OriginalPromise, values)\n\tconst context = captureRestorers()\n\tif (context.size > 0) promiseContexts.set(p, context)\n\treturn p\n}) as any\n\n// Only apply patches if not already applied (or re-apply safely)\n// Note: OriginalPromise.prototype might be shared if we used the global one.\n// We must ensure we don't patch it twice if it's the SAME object.\nif (OriginalPromise.prototype.then !== patchedThen) {\n\t// biome-ignore lint/suspicious/noThenProperty: Intentional Promise.prototype patching\n\tOriginalPromise.prototype.then = patchedThen as any\n\tOriginalPromise.prototype.catch = patchedCatch as any\n\tOriginalPromise.prototype.finally = patchedFinally as any\n}\n\ntry {\n\tObject.defineProperty(OriginalPromise, Symbol.species, {\n\t\tget: () => PatchedPromise,\n\t\tconfigurable: true,\n\t})\n} catch (_e) {}\n\n;(globalThis as any).Promise = PatchedPromise\n\nglobalThis.setTimeout = ((callback: Function, ...args: any[]) => {\n\treturn originals.setTimeout.call(globalThis, wrap(callback as any), ...args)\n}) as any\n\nglobalThis.setInterval = ((callback: Function, ...args: any[]) => {\n\treturn originals.setInterval.call(globalThis, wrap(callback as any), ...args)\n}) as any\n\nif (originals.setImmediate) {\n\t;(globalThis as any).setImmediate = ((callback: Function, ...args: any[]) => {\n\t\treturn originals.setImmediate.call(globalThis, wrap(callback as any), ...args)\n\t}) as any\n}\n\nif (originals.requestAnimationFrame) {\n\tglobalThis.requestAnimationFrame = (callback: FrameRequestCallback) => {\n\t\treturn originals.requestAnimationFrame.call(globalThis, wrap(callback))\n\t}\n}\n\nif (originals.queueMicrotask) {\n\tglobalThis.queueMicrotask = (callback: VoidFunction): void => {\n\t\toriginals.queueMicrotask.call(globalThis, wrap(callback))\n\t}\n}\n","type ElementTypes<T extends readonly unknown[]> = {\n\t[K in keyof T]: T[K] extends readonly (infer U)[] ? U : T[K]\n}\n\n/**\n * Yields tuples containing elements from each input array, stopping at the longest array length\n * @param args - Arrays to zip together\n * @returns Generator yielding tuples containing elements from each input array\n */\nexport function* zip<T extends (readonly unknown[])[]>(...args: T): Generator<ElementTypes<T>> {\n\tif (!args.length) return []\n\tconst maxLength = Math.max(...args.map((arr) => arr.length))\n\n\tfor (let i = 0; i < maxLength; i++) {\n\t\tconst tuple = args.map((arr) => arr[i]) as ElementTypes<T>\n\t\tyield tuple\n\t}\n}\n\n/**\n * Checks if two arrays are strictly equal (shallow comparison)\n * @param a - First value\n * @param b - Second value\n * @returns True if arrays are equal or values are strictly equal\n */\nexport function arrayEquals(a: any, b: any): boolean {\n\tif (!Array.isArray(a) || !Array.isArray(b)) return false\n\tif (a === b) return true\n\tif (a.length !== b.length) return false\n\tfor (let i = 0; i < a.length; i++) {\n\t\tif (a[i] !== b[i]) return false\n\t}\n\treturn true\n}\n\nconst nativeConstructors = new Set<Function>([\n\tObject,\n\tArray,\n\tDate,\n\tFunction,\n\tSet,\n\tMap,\n\tWeakMap,\n\tWeakSet,\n\tPromise,\n\tError,\n\tTypeError,\n\tReferenceError,\n\tSyntaxError,\n\tRangeError,\n\tURIError,\n\tEvalError,\n\tReflect,\n\tProxy,\n\tRegExp,\n\tString,\n\tNumber,\n\tBoolean,\n] as Function[])\n/**\n * Checks if a function is a constructor (class or constructor function)\n * @param fn - The function to check\n * @returns True if the function is a constructor\n */\nexport function isConstructor(fn: Function): boolean {\n\treturn (\n\t\tfn &&\n\t\ttypeof fn === 'function' &&\n\t\t(nativeConstructors.has(fn) || fn.toString?.().startsWith('class '))\n\t)\n}\n\n/**\n * Checks if a value is an object\n * @param value - The value to check\n * @returns True if the value is an object\n */\nexport function isObject(value: any): value is object {\n\treturn (\n\t\ttypeof value === 'object' &&\n\t\tvalue !== null &&\n\t\t!Array.isArray(value) &&\n\t\t!(\n\t\t\tvalue instanceof Date ||\n\t\t\tvalue instanceof RegExp ||\n\t\t\tvalue instanceof Error ||\n\t\t\tvalue instanceof Set ||\n\t\t\tvalue instanceof Map ||\n\t\t\tvalue instanceof WeakSet ||\n\t\t\tvalue instanceof WeakMap ||\n\t\t\tvalue instanceof Promise ||\n\t\t\tvalue instanceof Function\n\t\t)\n\t)\n}\n\nconst hasNode = typeof Node !== 'undefined'\nexport const FoolProof = {\n\tget(obj: any, prop: any, receiver: any) {\n\t\tif (hasNode && obj instanceof Node) return (obj as any)[prop]\n\t\treturn Reflect.get(obj, prop, receiver)\n\t},\n\tset(obj: any, prop: any, value: any, receiver: any) {\n\t\tif (hasNode && obj instanceof Node) {\n\t\t\t;(obj as any)[prop] = value\n\t\t\treturn true\n\t\t} /*\n\t\tif (!(obj instanceof Object) && !Object.hasOwn(obj, prop)) {\n\t\t\tObject.defineProperty(obj, prop, {\n\t\t\t\tvalue,\n\t\t\t\tconfigurable: true,\n\t\t\t\twritable: true,\n\t\t\t\tenumerable: true,\n\t\t\t})\n\t\t\treturn true\n\t\t}*/\n\t\treturn Reflect.set(obj, prop, value, receiver)\n\t},\n}\n\nexport function isOwnAccessor(obj: any, prop: any) {\n\tconst opd = Object.getOwnPropertyDescriptor(obj, prop)\n\treturn !!(opd?.get || opd?.set)\n}\n\n/**\n * Deeply compares two values.\n * For objects, compares prototypes with === and then own properties recursively.\n * Uses a cache to handle circular references.\n * @param a - First value\n * @param b - Second value\n * @param cache - Map for circular reference protection (internal use)\n * @returns True if values are deeply equal\n */\nexport function deepCompare(a: any, b: any, cache = new Map<object, Set<object>>()): boolean {\n\tif (a === b) return true\n\n\tif (typeof a !== 'object' || a === null || typeof b !== 'object' || b === null) {\n\t\treturn a === b\n\t}\n\n\t// Prototype check\n\tif (Object.getPrototypeOf(a) !== Object.getPrototypeOf(b)) return false\n\n\t// Circular reference protection\n\tlet compared = cache.get(a)\n\tif (compared?.has(b)) return true\n\tif (!compared) {\n\t\tcompared = new Set()\n\t\tcache.set(a, compared)\n\t}\n\tcompared.add(b)\n\n\t// Handle specific object types\n\tif (Array.isArray(a)) {\n\t\tif (!Array.isArray(b) || a.length !== b.length) return false\n\t\tfor (let i = 0; i < a.length; i++) {\n\t\t\tif (!deepCompare(a[i], b[i], cache)) return false\n\t\t}\n\t\treturn true\n\t}\n\n\tif (a instanceof Date) return b instanceof Date && a.getTime() === b.getTime()\n\tif (a instanceof RegExp) return b instanceof RegExp && a.toString() === b.toString()\n\n\tif (a instanceof Set) {\n\t\tif (!(b instanceof Set) || a.size !== b.size) return false\n\t\tfor (const val of a) {\n\t\t\tlet found = false\n\t\t\tfor (const bVal of b) {\n\t\t\t\tif (deepCompare(val, bVal, cache)) {\n\t\t\t\t\tfound = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!found) return false\n\t\t}\n\t\treturn true\n\t}\n\tif (a instanceof Map) {\n\t\tif (!(b instanceof Map) || a.size !== b.size) return false\n\t\tfor (const [key, val] of a) {\n\t\t\tif (!b.has(key)) {\n\t\t\t\tlet foundMatch = false\n\t\t\t\tfor (const [bKey, bVal] of b) {\n\t\t\t\t\tif (deepCompare(key, bKey, cache) && deepCompare(val, bVal, cache)) {\n\t\t\t\t\t\tfoundMatch = true\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (!foundMatch) return false\n\t\t\t} else if (!deepCompare(val, b.get(key), cache)) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\treturn true\n\t}\n\n\t// Compare own properties\n\tconst keysA = Object.keys(a)\n\tconst keysB = Object.keys(b)\n\tif (keysA.length !== keysB.length) return false\n\n\tfor (const key of keysA) {\n\t\tif (!Object.hasOwn(b, key) || !deepCompare(a[key], b[key], cache)) return false\n\t}\n\n\treturn true\n}\n\n// Internal use: Used for reactive sets/maps to differentiate between different reactive containers: `x.get('aKey')` vs. `x['aKey']`\nconst contentRefs = new WeakMap<object, any>()\nexport function contentRef(container: object) {\n\tif (!contentRefs.has(container))\n\t\tcontentRefs.set(\n\t\t\tcontainer,\n\t\t\tObject.seal(\n\t\t\t\tObject.create(null, {\n\t\t\t\t\tcontentOf: { value: container, writable: false, configurable: false },\n\t\t\t\t})\n\t\t\t)\n\t\t)\n\treturn contentRefs.get(container)\n}\n\n/**\n * Tags an object with a name\n * @param name - The name to tag the object with\n * @param obj - The object to tag\n * @returns The object with the tag\n */\nexport function tag<T extends object>(name: string, obj: T): T {\n\tObject.defineProperties(obj, {\n\t\t[Symbol.toStringTag]: {\n\t\t\tvalue: name,\n\t\t\twritable: false,\n\t\t\tconfigurable: true,\n\t\t},\n\t\ttoString: {\n\t\t\tvalue: () => name,\n\t\t\twritable: false,\n\t\t\tconfigurable: true,\n\t\t},\n\t})\n\treturn obj\n}\n\n/**\n * Renames a function with a new name\n * @param name - The new name for the function\n * @param fn - The function to rename\n * @returns The function with the new name\n */\nexport function named<T extends Function>(name: string, fn: T): T {\n\tObject.defineProperty(fn, 'name', {\n\t\tvalue: fn.name ? `${fn.name}::${name}` : name,\n\t\twritable: false,\n\t\tconfigurable: true,\n\t})\n\treturn fn\n}\n\nexport function* stringKeys(o: object) {\n\tfor (const key in o) yield key\n}\n\nconst _mode: string =\n\t(typeof process !== 'undefined' && process.env?.NODE_ENV) ||\n\t(typeof import.meta !== 'undefined' && (import.meta as any).env?.MODE) ||\n\t'production'\n\nexport const isDev = _mode === 'development'\nexport const isProd = _mode === 'production'\nexport const isTest = _mode === 'test'\n","// biome-ignore-all lint/suspicious/noConfusingVoidType: We *love* voids\n// Standardized decorator system that works with both Legacy and Modern decorators\n\nimport { isConstructor } from './utils'\n\n/**\n * Error thrown when decorator operations fail\n */\nexport class DecoratorError extends Error {\n\tconstructor(message: string) {\n\t\tsuper(message)\n\t\tthis.name = 'DecoratorException'\n\t}\n}\n//#region all decorator types\n\n// Used for get/set and method decorators\n/**\n * Legacy property decorator type for methods, getters, and setters\n */\nexport type LegacyPropertyDecorator<T> = (\n\ttarget: T,\n\tname: string | symbol,\n\tdescriptor: PropertyDescriptor\n) => any\n\n/**\n * Legacy class decorator type\n */\nexport type LegacyClassDecorator<T> = (target: T) => any\n\n/**\n * Modern method decorator type\n */\nexport type ModernMethodDecorator<T> = (target: T, context: ClassMethodDecoratorContext) => any\n\n/**\n * Modern getter decorator type\n */\nexport type ModernGetterDecorator<T> = (target: T, context: ClassGetterDecoratorContext) => any\n\n/**\n * Modern setter decorator type\n */\nexport type ModernSetterDecorator<T> = (target: T, context: ClassSetterDecoratorContext) => any\n\n/**\n * Modern accessor decorator type\n */\nexport type ModernAccessorDecorator<T> = (target: T, context: ClassAccessorDecoratorContext) => any\n\n/**\n * Modern class decorator type\n */\nexport type ModernClassDecorator<T> = (target: T, context: ClassDecoratorContext) => any\n\n//#endregion\n\ntype DDMethod<T> = (\n\toriginal: (this: T, ...args: any[]) => any,\n\ttarget: any,\n\tname: PropertyKey\n) => ((this: T, ...args: any[]) => any) | void\n\ntype DDGetter<T> = (\n\toriginal: (this: T) => any,\n\ttarget: any,\n\tname: PropertyKey\n) => ((this: T) => any) | void\n\ntype DDSetter<T> = (\n\toriginal: (this: T, value: any) => void,\n\ttarget: any,\n\tname: PropertyKey\n) => ((this: T, value: any) => void) | void\n\ntype DDClass<T> = <Ctor extends new (...args: any[]) => T = new (...args: any[]) => T>(\n\ttarget: Ctor\n) => Ctor | void\n/**\n * Description object for creating decorators that work with both Legacy and Modern decorator proposals\n */\nexport interface DecoratorDescription<T> {\n\t/** Handler for method decorators */\n\tmethod?: DDMethod<T>\n\t/** Handler for class decorators */\n\tclass?: DDClass<T>\n\t/** Handler for getter decorators */\n\tgetter?: DDGetter<T>\n\t/** Handler for setter decorators */\n\tsetter?: DDSetter<T>\n\t/** Default handler for any decorator type not explicitly defined */\n\tdefault?: (...args: any[]) => any\n}\n\n/**\n * Type for decorators that work with both Legacy and Modern decorator proposals\n * Automatically infers the correct decorator type based on the description\n */\nexport type Decorator<T, Description extends DecoratorDescription<T>> = (Description extends {\n\tmethod: DDMethod<T>\n}\n\t? LegacyPropertyDecorator<T> & ModernMethodDecorator<T>\n\t: unknown) &\n\t(Description extends { class: DDClass<new (...args: any[]) => T> }\n\t\t? LegacyClassDecorator<new (...args: any[]) => T> &\n\t\t\t\tModernClassDecorator<new (...args: any[]) => T>\n\t\t: unknown) &\n\t(Description extends { getter: DDGetter<T> }\n\t\t? LegacyPropertyDecorator<T> & ModernGetterDecorator<T> & ModernAccessorDecorator<T>\n\t\t: unknown) &\n\t(Description extends { setter: DDSetter<T> }\n\t\t? LegacyPropertyDecorator<T> & ModernSetterDecorator<T> & ModernAccessorDecorator<T>\n\t\t: unknown) &\n\t(Description extends { default: infer Signature } ? Signature : unknown)\n\n/**\n * Factory type for creating decorators that work with both Legacy and Modern decorator proposals\n */\nexport type DecoratorFactory<T> = <Description extends DecoratorDescription<T>>(\n\tdescription: Description\n) => (Description extends { method: DDMethod<T> }\n\t? LegacyPropertyDecorator<T> & ModernMethodDecorator<T>\n\t: unknown) &\n\t(Description extends { class: DDClass<new (...args: any[]) => T> }\n\t\t? LegacyClassDecorator<new (...args: any[]) => T> &\n\t\t\t\tModernClassDecorator<new (...args: any[]) => T>\n\t\t: unknown) &\n\t(Description extends { getter: DDGetter<T> }\n\t\t? LegacyPropertyDecorator<T> & ModernGetterDecorator<T> & ModernAccessorDecorator<T>\n\t\t: unknown) &\n\t(Description extends { setter: DDSetter<T> }\n\t\t? LegacyPropertyDecorator<T> & ModernSetterDecorator<T> & ModernAccessorDecorator<T>\n\t\t: unknown) &\n\t(Description extends { default: infer Signature } ? Signature : unknown)\n\n/**\n * Creates a decorator that works with Legacy decorator proposals\n * @param description - The decorator description object\n * @returns A decorator function compatible with Legacy decorators\n */\nexport function legacyDecorator<T = any>(description: DecoratorDescription<T>): any {\n\treturn function (\n\t\tthis: any,\n\t\ttarget: any,\n\t\tpropertyKey?: PropertyKey,\n\t\tdescriptor?: PropertyDescriptor,\n\t\t...args: any[]\n\t) {\n\t\tif (propertyKey === undefined) {\n\t\t\tif (isConstructor(target)) {\n\t\t\t\tif (!('class' in description)) throw new Error('Decorator cannot be applied to a class')\n\t\t\t\treturn description.class!(target)\n\t\t\t}\n\t\t} else if (typeof target === 'object' && ['string', 'symbol'].includes(typeof propertyKey)) {\n\t\t\tif (!descriptor) throw new Error('Decorator cannot be applied to a field')\n\t\t\telse if (typeof descriptor === 'object' && 'configurable' in descriptor) {\n\t\t\t\tif ('get' in descriptor || 'set' in descriptor) {\n\t\t\t\t\tif (!('getter' in description || 'setter' in description))\n\t\t\t\t\t\tthrow new Error('Decorator cannot be applied to a getter or setter')\n\t\t\t\t\tif ('getter' in description) {\n\t\t\t\t\t\tconst newGetter = description.getter!(descriptor.get as any, target, propertyKey)\n\t\t\t\t\t\tif (newGetter) descriptor.get = newGetter\n\t\t\t\t\t}\n\t\t\t\t\tif ('setter' in description) {\n\t\t\t\t\t\tconst newSetter = description.setter!(descriptor.set as any, target, propertyKey)\n\t\t\t\t\t\tif (newSetter) descriptor.set = newSetter\n\t\t\t\t\t}\n\t\t\t\t\treturn descriptor\n\t\t\t\t} else if (typeof descriptor.value === 'function') {\n\t\t\t\t\tif (!('method' in description)) throw new Error('Decorator cannot be applied to a method')\n\t\t\t\t\tconst newMethod = description.method!(descriptor.value, target, propertyKey)\n\t\t\t\t\tif (newMethod) descriptor.value = newMethod\n\t\t\t\t\treturn descriptor\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (!('default' in description))\n\t\t\tthrow new Error('Decorator do not have a default implementation')\n\t\treturn description.default!.call(this, target, propertyKey, descriptor, ...args)\n\t}\n}\n\n/**\n * Creates a decorator that works with Modern decorator proposals\n * @param description - The decorator description object\n * @returns A decorator function compatible with Modern decorators\n */\nexport function modernDecorator<T = any>(description: DecoratorDescription<T>): any {\n\t/*return function (target: any, context?: DecoratorContext, ...args: any[]) {*/\n\treturn function (this: any, target: any, context?: DecoratorContext, ...args: any[]) {\n\t\tif (!context?.kind || typeof context.kind !== 'string') {\n\t\t\tif (!('default' in description))\n\t\t\t\tthrow new Error('Decorator do not have a default implementation')\n\t\t\treturn description.default!.call(this, target, context, ...args)\n\t\t}\n\t\tswitch (context.kind) {\n\t\t\tcase 'class':\n\t\t\t\tif (!('class' in description)) throw new Error('Decorator cannot be applied to a class')\n\t\t\t\treturn description.class!(target)\n\t\t\tcase 'field':\n\t\t\t\tthrow new Error('Decorator cannot be applied to a field')\n\t\t\tcase 'getter':\n\t\t\t\tif (!('getter' in description)) throw new Error('Decorator cannot be applied to a getter')\n\t\t\t\treturn description.getter!(target, target, context.name)\n\t\t\tcase 'setter':\n\t\t\t\tif (!('setter' in description)) throw new Error('Decorator cannot be applied to a setter')\n\t\t\t\treturn description.setter!(target, target, context.name)\n\t\t\tcase 'method':\n\t\t\t\tif (!('method' in description)) throw new Error('Decorator cannot be applied to a method')\n\t\t\t\treturn description.method!(target, target, context.name)\n\t\t\tcase 'accessor': {\n\t\t\t\tif (!('getter' in description || 'setter' in description))\n\t\t\t\t\tthrow new Error('Decorator cannot be applied to a getter or setter')\n\t\t\t\tconst rv: Partial<ClassAccessorDecoratorResult<any, any>> = {}\n\t\t\t\tif ('getter' in description) {\n\t\t\t\t\tconst newGetter = description.getter!(target.get, target, context.name)\n\t\t\t\t\tif (newGetter) rv.get = newGetter\n\t\t\t\t}\n\t\t\t\tif ('setter' in description) {\n\t\t\t\t\tconst newSetter = description.setter!(target.set, target, context.name)\n\t\t\t\t\tif (newSetter) rv.set = newSetter\n\t\t\t\t}\n\t\t\t\treturn rv\n\t\t\t}\n\t\t\t//return description.accessor?.(target, context.name, target)\n\t\t}\n\t}\n}\n\n/**\n * Detects if the decorator is being called in modern (Modern) or legacy (Legacy) mode\n * based on the arguments passed to the decorator function\n */\nfunction detectDecoratorMode(\n\t_target: any,\n\tcontextOrKey?: any,\n\t_descriptor?: any\n): 'modern' | 'legacy' {\n\t// Modern decorators have a context object as the second parameter\n\t// Legacy decorators have a string/symbol key as the second parameter\n\tif (\n\t\ttypeof contextOrKey === 'object' &&\n\t\tcontextOrKey !== null &&\n\t\ttypeof contextOrKey.kind === 'string'\n\t) {\n\t\treturn 'modern'\n\t}\n\treturn 'legacy'\n}\n\n/**\n * Main decorator factory that automatically detects and works with both Legacy and Modern decorator proposals\n * @param description - The decorator description object\n * @returns A decorator that works in both Legacy and Modern environments\n */\nexport const decorator: DecoratorFactory<any> = (description: DecoratorDescription<any>) => {\n\tconst modern = modernDecorator(description)\n\tconst legacy = legacyDecorator(description)\n\treturn ((target: any, contextOrKey?: any, ...args: any[]) => {\n\t\tconst mode = detectDecoratorMode(target, contextOrKey, args[0])\n\t\treturn mode === 'modern'\n\t\t\t? modern(target, contextOrKey, ...args)\n\t\t\t: legacy(target, contextOrKey, ...args)\n\t}) as any\n}\n\n/**\n * Generic class decorator type that works with both Legacy and Modern decorator proposals\n */\nexport type GenericClassDecorator<T> = LegacyClassDecorator<abstract new (...args: any[]) => T> &\n\tModernClassDecorator<abstract new (...args: any[]) => T>\n","import { decorator } from './decorator'\n\n// Integrated with `using` statement via Symbol.dispose\nconst fr = new FinalizationRegistry<() => void>((f) => f())\n/**\n * Symbol for marking destructor methods\n */\nexport const destructor = Symbol('destructor')\n/**\n * Symbol for accessing allocated values in destroyable objects\n */\nexport const allocatedValues = Symbol('allocated')\n/**\n * Error thrown when attempting to access a destroyed object\n */\nexport class DestructionError extends Error {\n\tstatic throw<_T = void>(msg: string) {\n\t\treturn () => {\n\t\t\tthrow new DestructionError(msg)\n\t\t}\n\t}\n\tconstructor(msg: string) {\n\t\tsuper(`Object is destroyed. ${msg}`)\n\t\tthis.name = 'DestroyedAccessError'\n\t}\n}\nconst destroyedHandler = {\n\t[Symbol.toStringTag]: 'MutTs Destroyable',\n\tget: DestructionError.throw('Cannot access destroyed object'),\n\tset: DestructionError.throw('Cannot access destroyed object'),\n} as const\n\nabstract class AbstractDestroyable<Allocated> {\n\tabstract [destructor](allocated: Allocated): void\n\t[Symbol.dispose](): void {\n\t\tthis[destructor](this as unknown as Allocated)\n\t}\n}\n\ninterface Destructor<Allocated> {\n\tdestructor(allocated: Allocated): void\n}\n\n/**\n * Creates a destroyable class with a base class and destructor object\n * @param base - The base class to extend\n * @param destructorObj - Object containing the destructor method\n * @returns A destroyable class with static destroy and isDestroyable methods\n */\nexport function Destroyable<\n\tT extends new (\n\t\t...args: any[]\n\t) => any,\n\tAllocated extends Partial<InstanceType<T>>,\n>(\n\tbase: T,\n\tdestructorObj: Destructor<Allocated>\n): (new (\n\t...args: ConstructorParameters<T>\n) => InstanceType<T> & { [allocatedValues]: Allocated }) & {\n\tdestroy(obj: InstanceType<T>): boolean\n\tisDestroyable(obj: InstanceType<T>): boolean\n}\n\n/**\n * Creates a destroyable class with only a destructor object (no base class)\n * @param destructorObj - Object containing the destructor method\n * @returns A destroyable class with static destroy and isDestroyable methods\n */\nexport function Destroyable<Allocated extends Record<PropertyKey, any> = Record<PropertyKey, any>>(\n\tdestructorObj: Destructor<Allocated>\n): (new () => { [allocatedValues]: Allocated }) & {\n\tdestroy(obj: any): boolean\n\tisDestroyable(obj: any): boolean\n}\n\n/**\n * Creates a destroyable class with a base class (requires [destructor] method)\n * @param base - The base class to extend\n * @returns A destroyable class with static destroy and isDestroyable methods\n */\nexport function Destroyable<\n\tT extends new (\n\t\t...args: any[]\n\t) => any,\n\tAllocated extends Record<PropertyKey, any> = Record<PropertyKey, any>,\n>(\n\tbase: T\n): (new (\n\t...args: ConstructorParameters<T>\n) => AbstractDestroyable<Allocated> & InstanceType<T> & { [allocatedValues]: Allocated }) & {\n\tdestroy(obj: InstanceType<T>): boolean\n\tisDestroyable(obj: InstanceType<T>): boolean\n}\n\n/**\n * Creates an abstract destroyable base class\n * @returns An abstract destroyable class with static destroy and isDestroyable methods\n */\nexport function Destroyable<\n\tAllocated extends Record<PropertyKey, any> = Record<PropertyKey, any>,\n>(): abstract new () => (AbstractDestroyable<Allocated> & {\n\t[allocatedValues]: Allocated\n}) & {\n\tdestroy(obj: any): boolean\n\tisDestroyable(obj: any): boolean\n}\n\nexport function Destroyable<\n\tT extends new (\n\t\t...args: any[]\n\t) => any,\n\tAllocated extends Record<PropertyKey, any> = Record<PropertyKey, any>,\n>(base?: T | Destructor<Allocated>, destructorObj?: Destructor<Allocated>) {\n\tif (base && typeof base !== 'function') {\n\t\tdestructorObj = base as Destructor<Allocated>\n\t\tbase = undefined\n\t}\n\tif (!base) {\n\t\tbase = class {} as T\n\t}\n\n\treturn class Destroyable extends (base as T) {\n\t\tstatic readonly destructors = new WeakMap<any, () => void>()\n\t\tstatic destroy(obj: Destroyable) {\n\t\t\tconst destructor = Destroyable.destructors.get(obj)\n\t\t\tif (!destructor) return false\n\t\t\tfr.unregister(obj[allocatedValues])\n\t\t\tDestroyable.destructors.delete(obj)\n\t\t\tObject.setPrototypeOf(obj, new Proxy({}, destroyedHandler))\n\t\t\t// Clear all own properties\n\t\t\tfor (const key of Object.getOwnPropertyNames(obj)) {\n\t\t\t\tdelete (obj as any)[key]\n\t\t\t}\n\t\t\tdestructor()\n\t\t\treturn true\n\t\t}\n\t\tstatic isDestroyable(obj: Destroyable) {\n\t\t\treturn Destroyable.destructors.has(obj)\n\t\t}\n\n\t\t[forwardProperties]!: PropertyKey[]\n\t\treadonly [allocatedValues]: Allocated\n\t\tconstructor(...args: any[]) {\n\t\t\tsuper(...args)\n\t\t\tconst allocated = {} as Allocated\n\t\t\tthis[allocatedValues] = allocated\n\t\t\t// @ts-expect-error `this` is an AbstractDestroyable\n\t\t\tconst myDestructor = destructorObj?.destructor ?? this[destructor]\n\t\t\tif (!myDestructor) {\n\t\t\t\tthrow new DestructionError('Destructor is not defined')\n\t\t\t}\n\t\t\tfunction destruction() {\n\t\t\t\tmyDestructor(allocated)\n\t\t\t}\n\t\t\tDestroyable.destructors.set(this, destruction)\n\t\t\tfr.register(this, destruction, allocated)\n\t\t}\n\t}\n}\n\nconst forwardProperties = Symbol('forwardProperties')\n/**\n * Decorator that marks properties to be stored in the allocated object and passed to the destructor\n * Use with accessor properties or explicit get/set pairs\n */\nexport const allocated = decorator({\n\tsetter(original, _target, propertyKey) {\n\t\treturn function (value) {\n\t\t\tthis[allocatedValues][propertyKey] = value\n\t\t\treturn original.call(this, value)\n\t\t}\n\t},\n})\n\n/**\n * Registers a callback to be called when an object is garbage collected\n * @param cb - The callback function to execute on garbage collection\n * @returns The object whose reference can be collected\n */\nexport function callOnGC(cb: () => void) {\n\tlet called = false\n\tconst forward = () => {\n\t\tif (called) return\n\t\tcalled = true\n\t\tcb()\n\t}\n\tfr.register(forward, cb, cb)\n\treturn forward\n}\n\n/**\n * Context Manager Protocol for `using` statement integration\n * Provides automatic resource cleanup when used with the `using` statement\n */\nexport interface ContextManager<T = any> {\n\t[Symbol.dispose](): void\n\tvalue?: T\n}\n","export interface ArrayDiffResult<T> {\n\tindexA: number\n\tindexB: number\n\tsliceA: T[]\n\tsliceB: T[]\n}\n\n/** Max edit distance before bailing out to a single \"replace all\" patch */\nconst BAILOUT_D = 256\n\n/**\n * Myers' diff producing grouped patches: `{indexA, indexB, sliceA, sliceB}[]`.\n * - O(N) for identical or prefix/suffix-only differences\n * - O(ND) for small D, with a hard bailout at D=BAILOUT_D → single replacement patch\n */\nexport function arrayDiff<T>(A: readonly T[], B: readonly T[]): ArrayDiffResult<T>[] {\n\tlet start = 0\n\tlet endA = A.length\n\tlet endB = B.length\n\n\t// Trim common prefix\n\twhile (start < endA && start < endB && A[start] === B[start]) start++\n\t// Trim common suffix\n\twhile (endA > start && endB > start && A[endA - 1] === B[endB - 1]) {\n\t\tendA--\n\t\tendB--\n\t}\n\n\tconst lenA = endA - start\n\tconst lenB = endB - start\n\n\tif (lenA === 0 && lenB === 0) return []\n\tif (lenA === 0)\n\t\treturn [{ indexA: start, indexB: start, sliceA: [], sliceB: B.slice(start, endB) }]\n\tif (lenB === 0)\n\t\treturn [{ indexA: start, indexB: start, sliceA: A.slice(start, endA), sliceB: [] }]\n\n\t// Myers with bailout\n\tconst maxD = Math.min(lenA + lenB, BAILOUT_D)\n\tconst vSize = 2 * maxD + 1\n\tconst vOffset = maxD\n\tconst V = new Int32Array(vSize)\n\tV[vOffset + 1] = 0\n\tconst history: Int32Array[] = []\n\n\tfor (let d = 0; d <= maxD; d++) {\n\t\tfor (let k = -d; k <= d; k += 2) {\n\t\t\tlet x: number\n\t\t\tif (k === -d || (k !== d && V[vOffset + k - 1] < V[vOffset + k + 1])) {\n\t\t\t\tx = V[vOffset + k + 1]\n\t\t\t} else {\n\t\t\t\tx = V[vOffset + k - 1] + 1\n\t\t\t}\n\t\t\tlet y = x - k\n\t\t\twhile (x < lenA && y < lenB && A[start + x] === B[start + y]) {\n\t\t\t\tx++\n\t\t\t\ty++\n\t\t\t}\n\t\t\tV[vOffset + k] = x\n\t\t\tif (x >= lenA && y >= lenB) return buildPatches(history, A, B, start, x, y, d, k, vOffset)\n\t\t}\n\t\thistory.push(new Int32Array(V))\n\t}\n\n\t// Bailout: too many differences\n\treturn [\n\t\t{ indexA: start, indexB: start, sliceA: A.slice(start, endA), sliceB: B.slice(start, endB) },\n\t]\n}\n\nfunction buildPatches<T>(\n\thistory: Int32Array[],\n\tA: readonly T[],\n\tB: readonly T[],\n\toffset: number,\n\tfinalX: number,\n\tfinalY: number,\n\tfinalD: number,\n\tfinalK: number,\n\tvOffset: number\n): ArrayDiffResult<T>[] {\n\t// Backtrack from (finalX, finalY) at step finalD to step 0, collecting ops in reverse\n\tconst ops: (0 | 1 | 2)[] = [] // 0=eq, 1=ins, 2=del\n\tlet x = finalX\n\tlet y = finalY\n\tlet k = finalK\n\n\tfor (let d = finalD; d > 0; d--) {\n\t\tconst prev = history[d - 1]\n\t\tlet prevK: number\n\t\tlet down: boolean\n\t\tif (k === -d) {\n\t\t\tprevK = k + 1\n\t\t\tdown = true\n\t\t} else if (k === d) {\n\t\t\tprevK = k - 1\n\t\t\tdown = false\n\t\t} else if (prev[vOffset + k - 1] < prev[vOffset + k + 1]) {\n\t\t\tprevK = k + 1\n\t\t\tdown = true\n\t\t} else {\n\t\t\tprevK = k - 1\n\t\t\tdown = false\n\t\t}\n\n\t\tconst prevXEnd = prev[vOffset + prevK]\n\t\tconst prevYEnd = prevXEnd - prevK\n\t\tconst xStart = down ? prevXEnd : prevXEnd + 1\n\t\tconst yStart = down ? prevYEnd + 1 : prevXEnd + 1 - k\n\n\t\t// Diagonal matches (pushed in reverse)\n\t\twhile (x > xStart && y > yStart) {\n\t\t\tops.push(0)\n\t\t\tx--\n\t\t\ty--\n\t\t}\n\t\t// The edit step\n\t\tif (down) {\n\t\t\tops.push(1) // ins\n\t\t\ty--\n\t\t} else {\n\t\t\tops.push(2) // del\n\t\t\tx--\n\t\t}\n\t\tk = prevK\n\t}\n\n\t// Walk ops forward (they were pushed in reverse), grouping contiguous edits\n\tconst patches: ArrayDiffResult<T>[] = []\n\tlet currA = offset\n\tlet currB = offset\n\tlet sliceA: T[] = []\n\tlet sliceB: T[] = []\n\tlet patchA = -1\n\tlet patchB = -1\n\n\tconst flush = () => {\n\t\tif (patchA !== -1) {\n\t\t\tpatches.push({ indexA: patchA, indexB: patchB, sliceA, sliceB })\n\t\t\tsliceA = []\n\t\t\tsliceB = []\n\t\t\tpatchA = -1\n\t\t}\n\t}\n\n\tfor (let i = ops.length - 1; i >= 0; i--) {\n\t\tconst op = ops[i]\n\t\tif (op === 0) {\n\t\t\tflush()\n\t\t\tcurrA++\n\t\t\tcurrB++\n\t\t} else if (op === 1) {\n\t\t\tif (patchA === -1) {\n\t\t\t\tpatchA = currA\n\t\t\t\tpatchB = currB\n\t\t\t}\n\t\t\tsliceB.push(B[currB++])\n\t\t} else {\n\t\t\tif (patchA === -1) {\n\t\t\t\tpatchA = currA\n\t\t\t\tpatchB = currB\n\t\t\t}\n\t\t\tsliceA.push(A[currA++])\n\t\t}\n\t}\n\tflush()\n\treturn patches\n}\n","/**\n * Base type for event maps - all event handlers must be functions\n */\nexport type EventsBase = Record<string, (...args: any[]) => void>\n\nconst events = Symbol('events')\nconst hooks = Symbol('hooks')\n\nconst eventBehavior = {\n\ton<EventType extends keyof EventsBase>(\n\t\teventOrEvents: EventType | Partial<EventsBase>,\n\t\tcb?: EventsBase[EventType]\n\t): (this: Eventful<any>) => void {\n\t\tif (typeof eventOrEvents === 'object') {\n\t\t\tfor (const e of Object.keys(eventOrEvents) as (keyof EventsBase)[]) {\n\t\t\t\tthis.on(e, eventOrEvents[e]!)\n\t\t\t}\n\t\t} else if (cb !== undefined) {\n\t\t\tconst callbacks = this[events].get(eventOrEvents) ?? new Set<EventsBase[EventType]>()\n\t\t\tif (!callbacks.has(cb)) callbacks.add(cb)\n\t\t\tthis[events].set(eventOrEvents, callbacks)\n\t\t}\n\t\treturn () => this.off(eventOrEvents, cb)\n\t},\n\toff<EventType extends keyof EventsBase>(\n\t\teventOrEvents: EventType | Partial<EventsBase>,\n\t\tcb?: EventsBase[EventType]\n\t): void {\n\t\tif (typeof eventOrEvents === 'object') {\n\t\t\tfor (const e of Object.keys(eventOrEvents) as (keyof EventsBase)[]) {\n\t\t\t\tthis.off(e, eventOrEvents[e])\n\t\t\t}\n\t\t} else if (cb !== null && cb !== undefined) {\n\t\t\tconst callbacks = this[events].get(eventOrEvents)\n\t\t\tif (callbacks) {\n\t\t\t\tcallbacks.delete(cb)\n\t\t\t\tif (!callbacks.size) this[events].delete(eventOrEvents)\n\t\t\t}\n\t\t} else {\n\t\t\t// Remove all listeners for this event\n\t\t\tthis[events].delete(eventOrEvents)\n\t\t}\n\t},\n\temit<EventType extends keyof EventsBase>(\n\t\tevent: EventType,\n\t\t...args: Parameters<EventsBase[EventType]>\n\t) {\n\t\tconst callbacks = this[events].get(event)\n\t\tif (callbacks) for (const cb of callbacks) cb.apply(this, args)\n\t\tfor (const cb of this[hooks]) cb.call(this, event, ...args)\n\t},\n}\n\nfunction perEvent(\n\teventful: Eventful<any>,\n\tfct: (event: string, ...args: any[]) => void,\n\tuse?: 'use'\n) {\n\tconst cache = new Map<string, (...args: any[]) => any>()\n\treturn new Proxy(fct, {\n\t\tget(target, prop: PropertyKey) {\n\t\t\tif (typeof prop !== 'string') return target[prop]\n\t\t\tif (use && !eventful[events].has(prop) && !eventful[hooks].size) return () => {}\n\n\t\t\t// Return cached function or create and cache\n\t\t\tlet cached = cache.get(prop)\n\t\t\tif (!cached) {\n\t\t\t\tcached = (...args: any[]) => fct.apply(eventful, [prop, ...args])\n\t\t\t\tcache.set(prop, cached)\n\t\t\t}\n\t\t\treturn cached\n\t\t},\n\t})\n}\n\n/**\n * A type-safe event system that provides a clean API for event handling\n * @template Events - The event map defining event names and their handler signatures\n */\nexport class Eventful<Events extends EventsBase> {\n\tprivate readonly [events] = new Map<keyof Events, Set<(...args: any[]) => void>>()\n\tprivate readonly [hooks] = new Set<(...args: any[]) => void>()\n\n\tpublic hook(\n\t\tcb: <EventType extends keyof Events>(\n\t\t\tevent: EventType,\n\t\t\t...args: Parameters<Events[EventType]>\n\t\t) => void\n\t): () => void {\n\t\tthis[hooks].add(cb)\n\t\treturn () => {\n\t\t\tthis[hooks].delete(cb)\n\t\t}\n\t}\n\n\tpublic on = perEvent(this, eventBehavior.on) as ((events: Partial<Events>) => void) &\n\t\t(<EventType extends keyof Events>(event: EventType, cb: Events[EventType]) => () => void) & {\n\t\t\t[event in keyof Events]: (cb: Events[event]) => () => void\n\t\t}\n\tpublic off = perEvent(this, eventBehavior.off) as ((events: Partial<Events>) => void) &\n\t\t(<EventType extends keyof Events>(event: EventType, cb?: Events[EventType]) => void) & {\n\t\t\t[event in keyof Events]: (cb?: Events[event]) => void\n\t\t}\n\n\tpublic emit = perEvent(this, eventBehavior.emit, 'use') as (<EventType extends keyof Events>(\n\t\tevent: EventType,\n\t\t...args: Parameters<Events[EventType]>\n\t) => void) &\n\t\tEvents\n}\n","/**\n * Creates a flavored (extensible) version of a function with chainable property modifiers.\n *\n * Each property defined in `flavors` returns a new flavored function that transforms\n * how the original function is called. This enables a fluent API where properties\n * create specialized variants of the base function.\n *\n * @param fn - The base function to flavor\n * @param flavors - Object defining the flavor properties (getters or methods)\n * @returns A proxy of the function with the flavor properties attached\n *\n * @example\n * ```typescript\n * function greet(name: string, options?: { loud?: boolean }) {\n * const greeting = `Hello, ${name}!`\n * return options?.loud ? greeting.toUpperCase() : greeting\n * }\n *\n * const flavoredGreet = flavored(greet, {\n * get loud() {\n * return createFlavor(this, (name, opts) => [name, { ...opts, loud: true }])\n * }\n * })\n *\n * flavoredGreet('World') // \"Hello, World!\"\n * flavoredGreet.loud('World') // \"HELLO, WORLD!\"\n * ```\n */\nimport { named } from './utils'\n\n/**\n * Creates a flavored (extensible) version of a function with chainable property modifiers.\n */\nexport function flavored<T extends (...args: any[]) => any, F>(\n\tfn: T,\n\tflavors: F & ThisType<T & F>\n): T & F {\n\t// Store flavors for recursive flavoring\n\t;(fn as any).flavors = flavors\n\n\treturn new Proxy(fn, {\n\t\tget(target, prop, receiver) {\n\t\t\tif (prop in flavors) {\n\t\t\t\treturn Reflect.get(flavors, prop, receiver)\n\t\t\t}\n\t\t\treturn (target as any)[prop]\n\t\t},\n\t}) as T & F\n}\n\n/**\n * Creates a new flavored function that transforms arguments before calling the base.\n *\n * @param fn - The base flavored function\n * @param transform - Function that receives the original arguments and returns transformed arguments\n * @returns A new flavored function with the transformation applied\n *\n * @example\n * ```typescript\n * const loudGreet = createFlavor(greet, (name, opts) => [name, { ...opts, loud: true }])\n * ```\n */\nexport function createFlavor<T extends (...args: any[]) => any>(\n\tfn: T,\n\ttransform: (...args: Parameters<T>) => Parameters<T>,\n\tname?: string\n): T {\n\tconst fct = function flavorWrapper(this: any, ...args: Parameters<T>) {\n\t\treturn fn.apply(this, transform(...args))\n\t}\n\tif (name) named(name, fct)\n\n\treturn flavored(fct as T, (fn as any).flavors || {})\n}\n\n/**\n * Creates a new flavored function that merges options objects at a specific index.\n * By default, uses the function's arity (length) as the index for options.\n *\n * @param fn - The base flavored function\n * @param defaultOptions - Options to merge\n * @param optionsIndex - Optional explicit index for options (defaults to fn.length)\n * @param name - Optional name for the wrapper\n * @returns A new flavored function\n */\nexport function flavorOptions<T extends (...args: any[]) => any>(\n\tfn: T,\n\tdefaultOptions: Record<string, any>,\n\topts: {\n\t\toptionsIndex?: number\n\t\tname?: string\n\t} = {}\n): T {\n\t// If the function is already flavorOptions-wrapped, it might have an index stored\n\tconst targetIndex = opts.optionsIndex ?? (fn as any).optionsIndex ?? fn.length\n\n\tconst fct = function flavorOptionsWrapper(this: any, ...args: any[]) {\n\t\tconst newArgs = [...args]\n\n\t\t// Ensure we have enough arguments to reach the options index\n\t\twhile (newArgs.length <= targetIndex) {\n\t\t\tnewArgs.push(undefined)\n\t\t}\n\n\t\tconst currentOptions = newArgs[targetIndex]\n\t\tconst isObject =\n\t\t\tcurrentOptions !== null &&\n\t\t\ttypeof currentOptions === 'object' &&\n\t\t\t!Array.isArray(currentOptions)\n\n\t\tnewArgs[targetIndex] = isObject ? { ...defaultOptions, ...currentOptions } : defaultOptions\n\n\t\treturn fn.apply(this, newArgs)\n\t}\n\n\tif (opts.name) named(`${fn.name}.${opts.name}`, fct)\n\n\t// Preserve arity and options track\n\tObject.defineProperty(fct, 'length', { value: fn.length })\n\t;(fct as any).optionsIndex = targetIndex\n\n\treturn flavored(fct as T, (fn as any).flavors || {})\n}\n","/**\n * Symbol for defining custom getter logic for numeric index access\n */\nexport const getAt = Symbol('getAt')\n/**\n * Symbol for defining custom setter logic for numeric index access\n */\nexport const setAt = Symbol('setAt')\n\ninterface IndexingAt<Items = any> {\n\t[getAt](index: number): Items\n}\n\ninterface Accessor<T, Items> {\n\tget(this: T, index: number): Items\n\tset?(this: T, index: number, value: Items): void\n\tgetLength?(this: T): number\n\tsetLength?(this: T, value: number): void\n}\n\nabstract class AbstractGetAt<Items = any> {\n\tabstract [getAt](index: number): Items\n}\n\n/**\n * Creates an indexable class with a base class and accessor object\n * @param base - The base class to extend\n * @param accessor - Object containing get/set methods for numeric index access\n * @returns A class that supports numeric index access\n */\nexport function Indexable<Items, Base extends abstract new (...args: any[]) => any>(\n\tbase: Base,\n\taccessor: Accessor<InstanceType<Base>, Items>\n): new (\n\t...args: ConstructorParameters<Base>\n) => InstanceType<Base> & { [x: number]: Items }\n\n/**\n * Creates an indexable class with only an accessor object (no base class)\n * @param accessor - Object containing get/set methods for numeric index access\n * @returns A class that supports numeric index access\n */\nexport function Indexable<Items>(accessor: Accessor<any, Items>): new () => { [x: number]: Items }\n\n/**\n * Creates an indexable class with a base class that has [getAt] method\n * @param base - The base class that implements [getAt] method\n * @returns A class that supports numeric index access using the base class's [getAt] method\n */\nexport function Indexable<Base extends new (...args: any[]) => IndexingAt>(\n\tbase: Base\n): new (\n\t...args: ConstructorParameters<Base>\n) => InstanceType<Base> & { [x: number]: AtReturnType<InstanceType<Base>> }\n\n/**\n * Creates an abstract indexable base class\n * @returns An abstract class that supports numeric index access\n */\nexport function Indexable<Items>(): abstract new (\n\t...args: any[]\n) => AbstractGetAt & { [x: number]: Items }\n\nexport function Indexable<Items, Base extends abstract new (...args: any[]) => any>(\n\tbase?: Base | Accessor<Base, Items>,\n\taccessor?: Accessor<Base, Items>\n) {\n\tif (base && typeof base !== 'function') {\n\t\taccessor = base as Accessor<Base, Items>\n\t\tbase = undefined\n\t}\n\tif (!base) {\n\t\t//@ts-expect-error\n\t\tbase = class {} as Base\n\t}\n\tif (!accessor) {\n\t\taccessor = {\n\t\t\tget(this: any, index: number) {\n\t\t\t\tif (typeof this[getAt] !== 'function') {\n\t\t\t\t\tthrow new Error('Indexable class must have an [getAt] method')\n\t\t\t\t}\n\t\t\t\treturn this[getAt](index)\n\t\t\t},\n\t\t\tset(this: any, index: number, value: Items) {\n\t\t\t\tif (typeof this[setAt] !== 'function') {\n\t\t\t\t\tthrow new Error('Indexable class has read-only numeric index access')\n\t\t\t\t}\n\t\t\t\tthis[setAt](index, value)\n\t\t\t},\n\t\t}\n\t}\n\n\tabstract class Indexable extends (base as Base) {\n\t\t[x: number]: Items\n\t}\n\n\tObject.setPrototypeOf(\n\t\tIndexable.prototype,\n\t\tnew Proxy((base as Base).prototype, {\n\t\t\t//@ts-expect-error\n\t\t\t[Symbol.toStringTag]: 'MutTs Indexable',\n\t\t\tget(target, prop, receiver) {\n\t\t\t\tif (prop in target) {\n\t\t\t\t\tconst getter = Object.getOwnPropertyDescriptor(target, prop)?.get\n\t\t\t\t\treturn getter ? getter.call(receiver) : target[prop]\n\t\t\t\t}\n\t\t\t\tif (typeof prop === 'string') {\n\t\t\t\t\tif (prop === 'length' && accessor.getLength) return accessor.getLength.call(receiver)\n\t\t\t\t\tconst numProp = Number(prop)\n\t\t\t\t\tif (!Number.isNaN(numProp)) {\n\t\t\t\t\t\treturn accessor.get!.call(receiver, numProp) as Items\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn undefined\n\t\t\t},\n\t\t\tset(target, prop, value, receiver) {\n\t\t\t\tif (prop in target) {\n\t\t\t\t\tconst setter = Object.getOwnPropertyDescriptor(target, prop)?.set\n\t\t\t\t\tif (setter) setter.call(receiver, value)\n\t\t\t\t\telse target[prop] = value\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t\tif (typeof prop === 'string') {\n\t\t\t\t\tif (prop === 'length' && accessor.setLength) {\n\t\t\t\t\t\taccessor.setLength.call(receiver, value)\n\t\t\t\t\t\treturn true\n\t\t\t\t\t}\n\t\t\t\t\tconst numProp = Number(prop)\n\t\t\t\t\tif (!Number.isNaN(numProp)) {\n\t\t\t\t\t\tif (!accessor.set) throw new Error('Indexable class has read-only numeric index access')\n\t\t\t\t\t\taccessor.set!.call(receiver, numProp, value)\n\t\t\t\t\t\treturn true\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tObject.defineProperty(receiver, prop, {\n\t\t\t\t\tvalue,\n\t\t\t\t\twritable: true,\n\t\t\t\t\tenumerable: true,\n\t\t\t\t\tconfigurable: true,\n\t\t\t\t})\n\t\t\t\treturn true\n\t\t\t},\n\t\t\thas(target, prop) {\n\t\t\t\tif (prop in target) return true\n\t\t\t\tif (typeof prop === 'string') {\n\t\t\t\t\tif (prop === 'length' && accessor.getLength) return true\n\t\t\t\t\tconst numProp = Number(prop)\n\t\t\t\t\tif (!Number.isNaN(numProp)) return true\n\t\t\t\t}\n\t\t\t\treturn false\n\t\t\t},\n\t\t\townKeys(target) {\n\t\t\t\tconst keys = Reflect.ownKeys(target)\n\t\t\t\tif (accessor.getLength) {\n\t\t\t\t\tkeys.push('length')\n\t\t\t\t\tconst len = accessor.getLength.call(this as any)\n\t\t\t\t\tfor (let i = 0; i < len; i++) keys.push(String(i))\n\t\t\t\t}\n\t\t\t\treturn keys\n\t\t\t},\n\t\t\tgetOwnPropertyDescriptor(target, prop) {\n\t\t\t\tif (prop in target) return Object.getOwnPropertyDescriptor(target, prop)\n\t\t\t\tif (typeof prop === 'string') {\n\t\t\t\t\tif (prop === 'length' && accessor.getLength) {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tenumerable: false,\n\t\t\t\t\t\t\tconfigurable: true,\n\t\t\t\t\t\t\tget: () => accessor.getLength!.call(this as any),\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tconst numProp = Number(prop)\n\t\t\t\t\tif (!Number.isNaN(numProp)) {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tenumerable: true,\n\t\t\t\t\t\t\tconfigurable: true,\n\t\t\t\t\t\t\tget: () => accessor.get!.call(this as any, numProp),\n\t\t\t\t\t\t\tset: accessor.set\n\t\t\t\t\t\t\t\t? (v: any) => accessor.set!.call(this as any, numProp, v)\n\t\t\t\t\t\t\t\t: undefined,\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn undefined\n\t\t\t},\n\t\t})\n\t)\n\treturn Indexable\n}\n\ntype AtReturnType<T> = T extends { [getAt](index: number): infer R } ? R : never\n\n/**\n * Symbol for accessing the forwarded array in ArrayReadForward\n */\nexport const forwardArray = Symbol('forwardArray')\n\n/**\n * A read-only array forwarder that implements all reading/iterating methods of Array\n * but does not implement modification methods.\n *\n * The constructor takes a callback that returns an array, and all methods forward\n * their behavior to the result of that callback.\n */\nexport class ArrayReadForward<T> {\n\tprotected get [forwardArray](): readonly T[] {\n\t\tthrow new Error('ArrayReadForward is not implemented')\n\t}\n\n\t/**\n\t * Get the length of the array\n\t */\n\tget length(): number {\n\t\treturn this[forwardArray].length\n\t}\n\n\t/**\n\t * Get an element at a specific index\n\t */\n\t[index: number]: T | undefined\n\n\t/**\n\t * Iterator protocol support\n\t */\n\t[Symbol.iterator](): Iterator<T> {\n\t\treturn this[forwardArray][Symbol.iterator]()\n\t}\n\n\t// Reading/Iterating methods\n\n\t/**\n\t * Creates a new array with the results of calling a provided function on every element\n\t */\n\tmap<U>(callbackfn: (value: T, index: number, array: readonly T[]) => U, thisArg?: any): U[] {\n\t\treturn this[forwardArray].map(callbackfn, thisArg)\n\t}\n\n\t/**\n\t * Creates a new array with all elements that pass the test implemented by the provided function\n\t */\n\tfilter<S extends T>(\n\t\tpredicate: (value: T, index: number, array: readonly T[]) => value is S,\n\t\tthisArg?: any\n\t): S[]\n\tfilter(predicate: (value: T, index: number, array: readonly T[]) => unknown, thisArg?: any): T[]\n\tfilter(predicate: (value: T, index: number, array: readonly T[]) => unknown, thisArg?: any): T[] {\n\t\treturn this[forwardArray].filter(predicate, thisArg)\n\t}\n\n\t/**\n\t * Executes a reducer function on each element of the array, resulting in a single output value\n\t */\n\treduce(\n\t\tcallbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: readonly T[]) => T\n\t): T\n\treduce(\n\t\tcallbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: readonly T[]) => T,\n\t\tinitialValue: T\n\t): T\n\treduce<U>(\n\t\tcallbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: readonly T[]) => U,\n\t\tinitialValue: U\n\t): U\n\treduce(\n\t\tcallbackfn: (\n\t\t\tpreviousValue: any,\n\t\t\tcurrentValue: T,\n\t\t\tcurrentIndex: number,\n\t\t\tarray: readonly T[]\n\t\t) => any,\n\t\tinitialValue?: any\n\t): any {\n\t\treturn initialValue !== undefined\n\t\t\t? this[forwardArray].reduce(callbackfn, initialValue)\n\t\t\t: this[forwardArray].reduce(callbackfn)\n\t}\n\n\t/**\n\t * Executes a reducer function on each element of the array (right-to-left), resulting in a single output value\n\t */\n\treduceRight(\n\t\tcallbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: readonly T[]) => T\n\t): T\n\treduceRight(\n\t\tcallbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: readonly T[]) => T,\n\t\tinitialValue: T\n\t): T\n\treduceRight<U>(\n\t\tcallbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: readonly T[]) => U,\n\t\tinitialValue: U\n\t): U\n\treduceRight(\n\t\tcallbackfn: (\n\t\t\tpreviousValue: any,\n\t\t\tcurrentValue: T,\n\t\t\tcurrentIndex: number,\n\t\t\tarray: readonly T[]\n\t\t) => any,\n\t\tinitialValue?: any\n\t): any {\n\t\treturn initialValue !== undefined\n\t\t\t? this[forwardArray].reduceRight(callbackfn, initialValue)\n\t\t\t: this[forwardArray].reduceRight(callbackfn)\n\t}\n\n\t/**\n\t * Executes a provided function once for each array element\n\t */\n\tforEach(callbackfn: (value: T, index: number, array: readonly T[]) => void, thisArg?: any): void {\n\t\tthis[forwardArray].forEach(callbackfn, thisArg)\n\t}\n\n\t/**\n\t * Returns the value of the first element in the array that satisfies the provided testing function\n\t */\n\tfind<S extends T>(\n\t\tpredicate: (value: T, index: number, array: readonly T[]) => value is S,\n\t\tthisArg?: any\n\t): S | undefined\n\tfind(\n\t\tpredicate: (value: T, index: number, array: readonly T[]) => unknown,\n\t\tthisArg?: any\n\t): T | undefined\n\tfind(\n\t\tpredicate: (value: T, index: number, array: readonly T[]) => unknown,\n\t\tthisArg?: any\n\t): T | undefined {\n\t\treturn this[forwardArray].find(predicate, thisArg)\n\t}\n\n\t/**\n\t * Returns the index of the first element in the array that satisfies the provided testing function\n\t */\n\tfindIndex(\n\t\tpredicate: (value: T, index: number, array: readonly T[]) => unknown,\n\t\tthisArg?: any\n\t): number {\n\t\treturn this[forwardArray].findIndex(predicate, thisArg)\n\t}\n\n\t/**\n\t * Returns the value of the last element in the array that satisfies the provided testing function\n\t */\n\tfindLast<S extends T>(\n\t\tpredicate: (value: T, index: number, array: readonly T[]) => value is S,\n\t\tthisArg?: any\n\t): S | undefined\n\tfindLast(\n\t\tpredicate: (value: T, index: number, array: readonly T[]) => unknown,\n\t\tthisArg?: any\n\t): T | undefined\n\tfindLast(\n\t\tpredicate: (value: T, index: number, array: readonly T[]) => unknown,\n\t\tthisArg?: any\n\t): T | undefined {\n\t\treturn this[forwardArray].findLast(predicate, thisArg)\n\t}\n\n\t/**\n\t * Returns the index of the last element in the array that satisfies the provided testing function\n\t */\n\tfindLastIndex(\n\t\tpredicate: (value: T, index: number, array: readonly T[]) => unknown,\n\t\tthisArg?: any\n\t): number {\n\t\treturn this[forwardArray].findLastIndex(predicate, thisArg)\n\t}\n\n\t/**\n\t * Determines whether an array includes a certain value among its entries\n\t */\n\tincludes(searchElement: T, fromIndex?: number): boolean {\n\t\treturn this[forwardArray].includes(searchElement, fromIndex)\n\t}\n\n\t/**\n\t * Returns the first index at which a given element can be found in the array\n\t */\n\tindexOf(searchElement: T, fromIndex?: number): number {\n\t\treturn this[forwardArray].indexOf(searchElement, fromIndex)\n\t}\n\n\t/**\n\t * Returns the last index at which a given element can be found in the array\n\t */\n\tlastIndexOf(searchElement: T, fromIndex?: number): number {\n\t\treturn this[forwardArray].lastIndexOf(searchElement, fromIndex)\n\t}\n\n\t/**\n\t * Returns a shallow copy of a portion of an array into a new array object\n\t */\n\tslice(start?: number, end?: number): T[] {\n\t\treturn this[forwardArray].slice(start, end)\n\t}\n\n\t/**\n\t * Returns a new array comprised of this array joined with other array(s) and/or value(s)\n\t */\n\tconcat(...items: ConcatArray<T>[]): T[]\n\tconcat(...items: (T | ConcatArray<T>)[]): T[]\n\tconcat(...items: (T | ConcatArray<T>)[]): T[] {\n\t\treturn this[forwardArray].concat(...items)\n\t}\n\n\t/**\n\t * Tests whether all elements in the array pass the test implemented by the provided function\n\t */\n\tevery(\n\t\tpredicate: (value: T, index: number, array: readonly T[]) => unknown,\n\t\tthisArg?: any\n\t): boolean {\n\t\treturn this[forwardArray].every(predicate, thisArg)\n\t}\n\n\t/**\n\t * Tests whether at least one element in the array passes the test implemented by the provided function\n\t */\n\tsome(\n\t\tpredicate: (value: T, index: number, array: readonly T[]) => unknown,\n\t\tthisArg?: any\n\t): boolean {\n\t\treturn this[forwardArray].some(predicate, thisArg)\n\t}\n\n\t/**\n\t * Joins all elements of an array into a string\n\t */\n\tjoin(separator?: string): string {\n\t\treturn this[forwardArray].join(separator)\n\t}\n\n\t/**\n\t * Returns a new array iterator that contains the keys for each index in the array\n\t */\n\tkeys(): IterableIterator<number> {\n\t\treturn this[forwardArray].keys()\n\t}\n\n\t/**\n\t * Returns a new array iterator that contains the values for each index in the array\n\t */\n\tvalues(): IterableIterator<T> {\n\t\treturn this[forwardArray].values()\n\t}\n\n\t/**\n\t * Returns a new array iterator that contains the key/value pairs for each index in the array\n\t */\n\tentries(): IterableIterator<[number, T]> {\n\t\treturn this[forwardArray].entries()\n\t}\n\n\t/**\n\t * Returns a string representation of the array\n\t */\n\ttoString(): string {\n\t\treturn this[forwardArray].toString()\n\t}\n\n\t/**\n\t * Returns a localized string representing the array\n\t */\n\ttoLocaleString(\n\t\tlocales?: string | string[],\n\t\toptions?: Intl.NumberFormatOptions | Intl.DateTimeFormatOptions\n\t): string {\n\t\treturn this[forwardArray].toLocaleString(locales as string | string[], options)\n\t}\n\n\t/**\n\t * Returns the element at the specified index, or undefined if the index is out of bounds\n\t */\n\tat(index: number): T | undefined {\n\t\treturn this[forwardArray].at(index)\n\t}\n\n\t/**\n\t * Returns a new array with all sub-array elements concatenated into it recursively up to the specified depth\n\t */\n\tflat(depth?: number): T[] {\n\t\treturn this[forwardArray].flat(depth) as T[]\n\t}\n\n\t/**\n\t * Returns a new array formed by applying a given callback function to each element of the array,\n\t * and then flattening the result by one level\n\t */\n\tflatMap<U, This = undefined>(\n\t\tcallback: (this: This, value: T, index: number, array: readonly T[]) => U | ReadonlyArray<U>,\n\t\tthisArg?: This\n\t): U[] {\n\t\treturn this[forwardArray].flatMap(callback as any, thisArg)\n\t}\n\n\t/**\n\t * Returns a new array with elements in reversed order (ES2023)\n\t */\n\ttoReversed(): T[] {\n\t\treturn this[forwardArray].toReversed?.() ?? [...this[forwardArray]].reverse()\n\t}\n\n\t/**\n\t * Returns a new array with elements sorted (ES2023)\n\t */\n\ttoSorted(compareFn?: ((a: T, b: T) => number) | undefined): T[] {\n\t\treturn this[forwardArray].toSorted?.(compareFn) ?? [...this[forwardArray]].sort(compareFn)\n\t}\n\n\t/**\n\t * Returns a new array with some elements removed and/or replaced at a given index (ES2023)\n\t */\n\ttoSpliced(start: number, deleteCount?: number, ...items: T[]): T[] {\n\t\tif (deleteCount === undefined) return this[forwardArray].toSpliced(start)\n\t\treturn this[forwardArray].toSpliced(start, deleteCount, ...items)\n\t}\n\n\t/**\n\t * Returns a new array with the element at the given index replaced with the given value (ES2023)\n\t */\n\twith(index: number, value: T): T[] {\n\t\treturn this[forwardArray].with(index, value)\n\t}\n\tget [Symbol.unscopables]() {\n\t\treturn this[forwardArray][Symbol.unscopables]\n\t}\n}\n","/// <reference lib=\"esnext.collection\" />\n\n/**\n * Uses weak references but still may iterate through them\n * Note: The behavior is highly dependant on the garbage collector - some entries are perhaps deemed to be collected: don't resuscitate them\n */\nexport class IterableWeakMap<K extends WeakKey, V> implements Map<K, V> {\n\tprivate uuids = new WeakMap<K, string>()\n\tprivate refs: Record<string, [WeakRef<K>, any]> = {}\n\tprivate readonly registry: FinalizationRegistry<string>\n\n\tconstructor(entries?: Iterable<[K, V]>) {\n\t\t// Create a FinalizationRegistry to clean up refs when keys are garbage collected\n\t\tthis.registry = new FinalizationRegistry((uuid: string) => {\n\t\t\tdelete this.refs[uuid]\n\t\t})\n\t\tif (entries) for (const [k, v] of entries) this.set(k, v)\n\t}\n\tprivate createIterator<I>(cb: (key: K, value: V) => I): MapIterator<I> {\n\t\tconst { refs } = this\n\t\treturn (function* () {\n\t\t\tfor (const uuid of Object.keys(refs)) {\n\t\t\t\tconst [keyRef, value] = refs[uuid]\n\t\t\t\tconst key = keyRef.deref()\n\t\t\t\tif (key) yield cb(key, value)\n\t\t\t\telse delete refs[uuid]\n\t\t\t}\n\t\t\treturn undefined\n\t\t})()\n\t}\n\tclear(): void {\n\t\t// Unregister all keys from the FinalizationRegistry\n\t\tfor (const uuid of Object.keys(this.refs)) {\n\t\t\tconst key = this.refs[uuid][0].deref()\n\t\t\tif (key) this.registry.unregister(key)\n\t\t}\n\t\tthis.uuids = new WeakMap<K, string>()\n\t\tthis.refs = {}\n\t}\n\tdelete(key: K): boolean {\n\t\tconst uuid = this.uuids.get(key)\n\t\tif (!uuid) return false\n\t\tdelete this.refs[uuid]\n\t\tthis.uuids.delete(key)\n\t\tthis.registry.unregister(key)\n\t\treturn true\n\t}\n\tforEach(callbackfn: (value: V, key: K, map: Map<K, V>) => void, thisArg?: any): void {\n\t\tfor (const [k, v] of this) callbackfn.call(thisArg ?? this, v, k, thisArg ?? this)\n\t}\n\tget(key: K): V | undefined {\n\t\tconst uuid = this.uuids.get(key)\n\t\tif (!uuid) return undefined\n\t\treturn this.refs[uuid][1]\n\t}\n\thas(key: K): boolean {\n\t\treturn this.uuids.has(key)\n\t}\n\tset(key: K, value: V): this {\n\t\tlet uuid = this.uuids.get(key)\n\t\tif (uuid) {\n\t\t\tthis.refs[uuid][1] = value\n\t\t} else {\n\t\t\tuuid = crypto.randomUUID()\n\t\t\tthis.uuids.set(key, uuid)\n\t\t\tthis.refs[uuid] = [new WeakRef(key), value]\n\t\t\t// Register key for cleanup when garbage collected\n\t\t\tthis.registry.register(key, uuid, key)\n\t\t}\n\t\treturn this\n\t}\n\tget size(): number {\n\t\treturn [...this].length\n\t}\n\tentries(): MapIterator<[K, V]> {\n\t\treturn this.createIterator((key, value) => [key, value] as [K, V])\n\t}\n\tkeys(): MapIterator<K> {\n\t\treturn this.createIterator((key, _value) => key)\n\t}\n\tvalues(): MapIterator<V> {\n\t\treturn this.createIterator((_key, value) => value)\n\t}\n\t[Symbol.iterator](): MapIterator<[K, V]> {\n\t\treturn this.entries()\n\t}\n\treadonly [Symbol.toStringTag]: string = 'IterableWeakMap'\n}\n\n/**\n * Uses weak references but still may iterate through them\n * Note: The behavior is highly dependant on the garbage collector - some entries are perhaps deemed to be collected: don't resuscitate them\n */\nexport class IterableWeakSet<K extends WeakKey> implements Set<K> {\n\tprivate uuids = new WeakMap<K, string>()\n\tprivate refs: Record<string, WeakRef<K>> = {}\n\tprivate readonly registry: FinalizationRegistry<string>\n\n\tconstructor(entries?: Iterable<K>) {\n\t\t// Create a FinalizationRegistry to clean up refs when values are garbage collected\n\t\tthis.registry = new FinalizationRegistry((uuid: string) => {\n\t\t\tdelete this.refs[uuid]\n\t\t})\n\t\tif (entries) for (const k of entries) this.add(k)\n\t}\n\tprivate createIterator<I>(cb: (key: K) => I): MapIterator<I> {\n\t\tconst { refs } = this\n\t\treturn (function* () {\n\t\t\tfor (const uuid of Object.keys(refs)) {\n\t\t\t\tconst key = refs[uuid].deref()\n\t\t\t\tif (key) yield cb(key)\n\t\t\t\telse delete refs[uuid]\n\t\t\t}\n\t\t\treturn undefined\n\t\t})()\n\t}\n\n\tclear(): void {\n\t\t// Unregister all values from the FinalizationRegistry\n\t\tfor (const uuid of Object.keys(this.refs)) {\n\t\t\tconst value = this.refs[uuid].deref()\n\t\t\tif (value) this.registry.unregister(value)\n\t\t}\n\t\tthis.uuids = new WeakMap<K, string>()\n\t\tthis.refs = {}\n\t}\n\n\tadd(value: K): this {\n\t\tlet uuid = this.uuids.get(value)\n\t\tif (!uuid) {\n\t\t\tuuid = crypto.randomUUID()\n\t\t\tthis.uuids.set(value, uuid)\n\t\t\tthis.refs[uuid] = new WeakRef(value)\n\t\t\t// Register value for cleanup when garbage collected\n\t\t\tthis.registry.register(value, uuid, value)\n\t\t}\n\t\treturn this\n\t}\n\tdelete(value: K): boolean {\n\t\tconst uuid = this.uuids.get(value)\n\t\tif (!uuid) return false\n\t\tdelete this.refs[uuid]\n\t\tthis.uuids.delete(value)\n\t\tthis.registry.unregister(value)\n\t\treturn true\n\t}\n\n\tforEach(callbackfn: (value: K, value2: K, set: Set<K>) => void, thisArg?: any): void {\n\t\tfor (const value of this) callbackfn.call(thisArg ?? this, value, value, thisArg ?? this)\n\t}\n\n\thas(value: K): boolean {\n\t\treturn this.uuids.has(value)\n\t}\n\tget size(): number {\n\t\treturn [...this].length\n\t}\n\tentries(): SetIterator<[K, K]> {\n\t\treturn this.createIterator((key) => [key, key] as [K, K])\n\t}\n\tkeys(): SetIterator<K> {\n\t\treturn this.createIterator((key) => key)\n\t}\n\tvalues(): SetIterator<K> {\n\t\treturn this.createIterator((key) => key)\n\t}\n\t[Symbol.iterator](): SetIterator<K> {\n\t\treturn this.keys()\n\t}\n\treadonly [Symbol.toStringTag]: string = 'IterableWeakSet'\n\n\tunion<U>(other: ReadonlySetLike<U>): Set<K | U> {\n\t\tconst others = {\n\t\t\t[Symbol.iterator]() {\n\t\t\t\treturn other.keys()\n\t\t\t},\n\t\t}\n\t\tconst that = this\n\t\treturn new Set(\n\t\t\t(function* () {\n\t\t\t\tyield* that\n\t\t\t\tfor (const value of others) if (!that.has(<K>(<unknown>value))) yield value\n\t\t\t})()\n\t\t)\n\t}\n\tintersection<U /**/>(other: ReadonlySetLike<U>): Set<K & U> {\n\t\tconst that = this\n\t\treturn new Set(\n\t\t\t(function* () {\n\t\t\t\tfor (const value of that) if (other.has(<U>(<unknown>value))) yield <K & U>value\n\t\t\t})()\n\t\t)\n\t}\n\tdifference<U>(other: ReadonlySetLike<U>): Set<K> {\n\t\tconst that = this\n\t\treturn new Set(\n\t\t\t(function* () {\n\t\t\t\tfor (const value of that) if (!other.has(<U>(<unknown>value))) yield <K>value\n\t\t\t})()\n\t\t)\n\t}\n\tsymmetricDifference<U>(other: ReadonlySetLike<U>): Set<K | U> {\n\t\tconst others = {\n\t\t\t[Symbol.iterator]() {\n\t\t\t\treturn other.keys()\n\t\t\t},\n\t\t}\n\t\tconst that = this\n\t\treturn new Set(\n\t\t\t(function* () {\n\t\t\t\tfor (const value of that) if (!other.has(<U>(<unknown>value))) yield <K | U>value\n\t\t\t\tfor (const value of others) if (!that.has(<K>(<unknown>value))) yield <K | U>value\n\t\t\t})()\n\t\t)\n\t}\n\tisSubsetOf(other: ReadonlySetLike<unknown>): boolean {\n\t\tfor (const value of this) if (!other.has(value)) return false\n\t\treturn true\n\t}\n\tisSupersetOf(other: ReadonlySetLike<unknown>): boolean {\n\t\tconst others = {\n\t\t\t[Symbol.iterator]() {\n\t\t\t\treturn other.keys()\n\t\t\t},\n\t\t}\n\t\tfor (const value of others) if (!this.has(<K>value)) return false\n\t\treturn true\n\t}\n\tisDisjointFrom(other: ReadonlySetLike<unknown>): boolean {\n\t\tfor (const value of this) if (other.has(value)) return false\n\t\treturn true\n\t}\n}\n","import { FoolProof, isConstructor } from './utils'\n\n/**\n * A mixin function that takes a base class and returns a new class with mixed-in functionality\n * @template Mixed - The functionality to be mixed in\n */\nexport type MixinFunction<Mixed> = <Base>(\n\tbase: new (...args: any[]) => Base\n) => new (\n\t...args: any[]\n) => Base & Mixed\n\n/**\n * A mixin class that can be used both as a base class and as a mixin function\n * @template Mixed - The functionality to be mixed in\n */\nexport type MixinClass<Mixed> = new (...args: any[]) => Mixed\n\n/**\n * Creates a mixin that can be used both as a class (extends) and as a function (mixin)\n *\n * This function supports:\n * - Using mixins as base classes: `class MyClass extends MyMixin`\n * - Using mixins as functions: `class MyClass extends MyMixin(SomeBase)`\n * - Composing mixins: `const Composed = MixinA(MixinB)`\n * - Type-safe property inference for all patterns\n *\n * @param mixinFunction - The function that creates the mixin\n * @param unwrapFunction - Optional function to unwrap reactive objects for method calls\n * @returns A mixin that can be used both as a class and as a function\n */\nexport function mixin<MixinFn extends (base: any) => new (...args: any[]) => any>(\n\tmixinFunction: MixinFn,\n\tunwrapFunction?: (obj: any) => any\n): (new (\n\t...args: any[]\n) => InstanceType<ReturnType<MixinFn>>) &\n\t(<Base>(\n\t\tbase: abstract new (...args: any[]) => Base\n\t) => new (\n\t\t...args: any[]\n\t) => InstanceType<ReturnType<MixinFn>> & Base) {\n\t/**\n\t * Cache for mixin results to ensure the same base class always returns the same mixed class\n\t */\n\tconst mixinCache = new WeakMap<new (...args: any[]) => any, new (...args: any[]) => any>()\n\n\t// Apply the mixin to Object as the base class\n\tconst MixedBase = mixinFunction(Object)\n\tmixinCache.set(Object, MixedBase)\n\n\t// Create the proxy that handles both constructor and function calls\n\treturn new Proxy(MixedBase, {\n\t\t// Handle `MixinClass(SomeBase)` - use as mixin function\n\t\tapply(_target, _thisArg, args) {\n\t\t\tif (args.length === 0) {\n\t\t\t\tthrow new Error('Mixin requires a base class')\n\t\t\t}\n\n\t\t\tconst baseClass = args[0]\n\t\t\tif (typeof baseClass !== 'function') {\n\t\t\t\tthrow new Error('Mixin requires a constructor function')\n\t\t\t}\n\n\t\t\t// Check if it's a valid constructor or a mixin\n\t\t\tif (\n\t\t\t\t!isConstructor(baseClass) &&\n\t\t\t\t!(baseClass && typeof baseClass === 'function' && baseClass.prototype)\n\t\t\t) {\n\t\t\t\tthrow new Error('Mixin requires a valid constructor')\n\t\t\t}\n\n\t\t\t// Check cache first\n\t\t\tconst cached = mixinCache.get(baseClass)\n\t\t\tif (cached) {\n\t\t\t\treturn cached\n\t\t\t}\n\n\t\t\tlet usedBase = baseClass\n\t\t\tif (unwrapFunction) {\n\t\t\t\t// Create a proxied base class that handles method unwrapping\n\t\t\t\tconst ProxiedBaseClass = class extends baseClass {}\n\n\t\t\t\t// Proxy the prototype methods to handle unwrapping\n\t\t\t\tconst originalPrototype = baseClass.prototype\n\t\t\t\tconst proxiedPrototype = new Proxy(originalPrototype, {\n\t\t\t\t\tget(target, prop, receiver) {\n\t\t\t\t\t\tconst value = FoolProof.get(target, prop, receiver)\n\n\t\t\t\t\t\t// Only wrap methods that are likely to access private fields\n\t\t\t\t\t\t// Skip symbols and special properties that the reactive system needs\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\ttypeof value === 'function' &&\n\t\t\t\t\t\t\ttypeof prop === 'string' &&\n\t\t\t\t\t\t\t!['constructor', 'toString', 'valueOf'].includes(prop)\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t// Return a wrapped version that uses unwrapped context\n\t\t\t\t\t\t\treturn function (this: any, ...args: any[]) {\n\t\t\t\t\t\t\t\t// Use the unwrapping function if provided, otherwise use this\n\t\t\t\t\t\t\t\tconst context = unwrapFunction(this as any)\n\t\t\t\t\t\t\t\treturn value.apply(context, args)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\treturn value\n\t\t\t\t\t},\n\t\t\t\t})\n\n\t\t\t\t// Set the proxied prototype\n\t\t\t\tObject.setPrototypeOf(ProxiedBaseClass.prototype, proxiedPrototype)\n\t\t\t\tusedBase = ProxiedBaseClass\n\t\t\t}\n\n\t\t\t// Create the mixed class using the proxied base class\n\t\t\tconst mixedClass = mixinFunction(usedBase)\n\n\t\t\t// Cache the result\n\t\t\tmixinCache.set(baseClass, mixedClass)\n\n\t\t\treturn mixedClass\n\t\t},\n\t}) as MixinFn & (new (...args: any[]) => InstanceType<ReturnType<MixinFn>>)\n}\n","type Resolved<T> =\n\tT extends Promise<infer U>\n\t\t? Resolved<U>\n\t\t: T extends (...args: infer Args) => infer R\n\t\t\t? (...args: Args) => Resolved<R>\n\t\t\t: T extends object\n\t\t\t\t? {\n\t\t\t\t\t\t[k in keyof T]: k extends 'then' | 'catch' | 'finally' ? T[k] : Resolved<T[k]>\n\t\t\t\t\t}\n\t\t\t\t: T\ntype PromiseAnd<T> = Resolved<T> & Promise<Resolved<T>>\n/**\n * Type that transforms promises into chainable objects\n * Allows calling methods directly on promise results without awaiting them first\n */\nexport type PromiseChain<T> = T extends (...args: infer Args) => infer R\n\t? PromiseAnd<(...args: Args) => PromiseChain<Resolved<R>>>\n\t: T extends object\n\t\t? PromiseAnd<{\n\t\t\t\t[k in keyof T]: k extends 'then' | 'catch' | 'finally' ? T[k] : PromiseChain<Resolved<T[k]>>\n\t\t\t}>\n\t\t: Promise<Resolved<T>>\n\nconst forward =\n\t(name: string, target: any) =>\n\t(...args: any[]) => {\n\t\treturn target[name](...args)\n\t}\n\nconst alreadyChained = new WeakMap<any, PromiseChain<any>>()\nconst originals = new WeakMap<Promise<any>, any>()\n\nfunction cache(target: any, rv: PromiseChain<any>) {\n\toriginals.set(rv, target)\n\talreadyChained.set(target, rv)\n}\n\ntype ChainedFunction<T> = ((...args: any[]) => PromiseChain<T>) & {\n\tthen: Promise<T>['then']\n\tcatch: Promise<T>['catch']\n\tfinally: Promise<T>['finally']\n}\n\nconst promiseProxyHandler: ProxyHandler<ChainedFunction<any>> = {\n\t//@ts-expect-error\n\t[Symbol.toStringTag]: 'MutTs PromiseChain function',\n\tget(target, prop) {\n\t\tif (prop === Symbol.toStringTag) return 'PromiseProxy'\n\t\tif (typeof prop === 'string' && ['then', 'catch', 'finally'].includes(prop))\n\t\t\treturn target[prop as keyof typeof target]\n\t\treturn chainPromise(target.then((r) => r[prop as keyof typeof r]))\n\t},\n}\nconst promiseForward = (target: any) => ({\n\t// biome-ignore lint/suspicious/noThenProperty: This one is the whole point\n\tthen: forward('then', target),\n\tcatch: forward('catch', target),\n\tfinally: forward('finally', target),\n})\nconst objectProxyHandler: ProxyHandler<any> = {\n\t//@ts-expect-error\n\t[Symbol.toStringTag]: 'MutTs PromiseChain object',\n\tget(target, prop, receiver) {\n\t\tconst getter = Object.getOwnPropertyDescriptor(target, prop)?.get\n\t\tconst rv = getter ? getter.call(receiver) : target[prop]\n\t\t// Allows fct.call or fct.apply to bypass the chain system\n\t\tif (typeof target === 'function') return rv\n\t\treturn chainPromise(rv)\n\t},\n\tapply(target, thisArg, args) {\n\t\treturn chainPromise(target.apply(thisArg, args))\n\t},\n}\nfunction chainObject<T extends object | Function>(given: T): PromiseChain<T> {\n\tconst rv = new Proxy(given, objectProxyHandler) as PromiseChain<T>\n\tcache(given, rv)\n\treturn rv\n}\n\nfunction chainable(x: any): x is object | Function {\n\treturn x && ['function', 'object'].includes(typeof x)\n}\n/**\n * Transforms a promise or value into a chainable object\n * Allows calling methods directly on promise results without awaiting them first\n * @param given - The promise or value to make chainable\n * @returns A chainable version of the input\n */\nexport function chainPromise<T>(given: Promise<T> | T): PromiseChain<T> {\n\tif (!chainable(given)) return given as PromiseChain<T>\n\tif (alreadyChained.has(given)) return alreadyChained.get(given) as PromiseChain<T>\n\tif (!(given instanceof Promise)) return chainObject(given)\n\t// @ts-expect-error It's ok as we check if it's an object above\n\tgiven = given.then((r) => (chainable(r) ? chainObject(r) : r))\n\tconst target = Object.assign(function (this: any, ...args: any[]) {\n\t\treturn chainPromise(\n\t\t\tgiven.then((r) => {\n\t\t\t\treturn this?.then\n\t\t\t\t\t? this.then((t: any) => (r as any).apply(t, args))\n\t\t\t\t\t: (r as any).apply(this, args)\n\t\t\t})\n\t\t)\n\t}, promiseForward(given)) as ChainedFunction<T>\n\tconst chained = new Proxy(\n\t\ttarget,\n\t\tpromiseProxyHandler as ProxyHandler<ChainedFunction<T>>\n\t) as PromiseChain<T>\n\tcache(given, chained as PromiseChain<any>)\n\treturn chained\n}\n","import type { EffectTrigger, Evolution } from './types'\n\nexport interface DebugHooks {\n\tisDevtoolsEnabled: () => boolean\n\tregisterEffect: (effect: EffectTrigger) => void\n\tgetTriggerChain: (effect: EffectTrigger) => string[]\n\tcaptureStack: (error?: unknown) => unknown\n\tcaptureLineage: (effect?: EffectTrigger, stack?: unknown) => unknown\n\tformatStack: (stack: unknown) => unknown[]\n\trecordTriggerLink: (\n\t\tsource: EffectTrigger | undefined,\n\t\ttarget: EffectTrigger,\n\t\tobj: object,\n\t\tprop: any,\n\t\tevolution: Evolution\n\t) => void\n\tdecorateError: (error: unknown, trigger: EffectTrigger) => void\n}\n\nexport const debugHooks: DebugHooks = {\n\tisDevtoolsEnabled: () => false,\n\tregisterEffect: () => {},\n\tgetTriggerChain: () => [],\n\tcaptureStack: () => [],\n\tcaptureLineage: () => new Error().stack,\n\tformatStack: (stack: unknown) => [stack],\n\trecordTriggerLink: () => {},\n\tdecorateError: () => {},\n}\n\nexport function setDebugHooks(hooks: Partial<DebugHooks>) {\n\tObject.assign(debugHooks, hooks)\n}\n","import { asyncHooks } from './async'\nimport { named, tag } from './utils'\n\ninterface InternalZoneUse<T> {\n\tenter(value?: T): unknown\n\tleave(entered: unknown): void\n}\nfunction isu<T>(z: AZone<T> | InternalZoneUse<T>): InternalZoneUse<T> {\n\treturn z as InternalZoneUse<T>\n}\nexport abstract class AZone<T> {\n\tabstract active?: T\n\tprotected enter(value?: T): unknown {\n\t\tconst prev = this.active\n\t\tthis.active = value\n\t\treturn prev\n\t}\n\tprotected leave(entered: unknown): void {\n\t\tthis.active = entered as T | undefined\n\t}\n\twith<R>(value: T | undefined, fn: () => R): R {\n\t\tconst entered = this.enter(value)\n\t\tlet res: R\n\t\ttry {\n\t\t\tres = fn()\n\t\t} finally {\n\t\t\tthis.leave(entered)\n\t\t}\n\t\t// [HACK]: Sanitization\n\t\t// See BROWSER_ASYNC_POLYFILL.md\n\t\treturn asyncHooks.sanitizePromise(res) as R\n\t}\n\troot<R>(fn: () => R): R {\n\t\tconst prev = this.enter()\n\t\ttry {\n\t\t\treturn fn()\n\t\t} finally {\n\t\t\tthis.leave(prev)\n\t\t}\n\t}\n\tget zoned(): GetterWrapper {\n\t\tconst active = this.active\n\t\treturn named(`${this}@${active}`, (fn) => this.with(active, fn))\n\t}\n}\n\nexport type GetterWrapper = <R>(fn: () => R) => R\n\nexport class Zone<T> extends AZone<T> {\n\tactive: T | undefined\n}\n\nexport type HistoryValue<T> = { present: T | undefined; history: Set<T> }\nexport class ZoneHistory<T> extends AZone<HistoryValue<T>> {\n\tprivate history = new Set<T>()\n\tpublic readonly present: AZone<T>\n\tpublic has(value: T): boolean {\n\t\treturn this.history.has(value)\n\t}\n\tpublic some(predicate: (value: T) => boolean): boolean {\n\t\tfor (const value of this.history) if (predicate(value)) return true\n\t\treturn false\n\t}\n\tconstructor(private controlled: AZone<T> = new Zone<T>()) {\n\t\tsuper()\n\t\tconst self = this\n\t\tthis.present = Object.create(\n\t\t\tcontrolled,\n\t\t\tObject.getOwnPropertyDescriptors({\n\t\t\t\tget active() {\n\t\t\t\t\treturn controlled.active\n\t\t\t\t},\n\t\t\t\tset active(value: T | undefined) {\n\t\t\t\t\tcontrolled.active = value\n\t\t\t\t},\n\t\t\t\tenter(value?: T) {\n\t\t\t\t\tif (value && self.history.has(value))\n\t\t\t\t\t\tthrow new Error('ZoneHistory: re-entering historical zone')\n\t\t\t\t\tif (value !== undefined) self.history.add(value)\n\t\t\t\t\treturn { added: value, entered: isu(controlled).enter(value) }\n\t\t\t\t},\n\t\t\t\tleave(entered: { added: T | undefined; entered: unknown }) {\n\t\t\t\t\tif (entered.added !== undefined) self.history.delete(entered.added)\n\t\t\t\t\treturn isu(controlled).leave(entered.entered)\n\t\t\t\t},\n\t\t\t})\n\t\t)\n\t}\n\tget active() {\n\t\treturn { present: this.controlled.active, history: new Set(this.history) }\n\t}\n\tset active(value: HistoryValue<T> | undefined) {\n\t\tthis.history = value?.history ? new Set(value.history) : new Set()\n\t\tthis.controlled.active = value?.present\n\t}\n}\n\nexport class ZoneAggregator extends AZone<Map<AZone<unknown>, unknown>> {\n\t#zones = new Set<AZone<unknown>>()\n\tconstructor(...zones: AZone<unknown>[]) {\n\t\tsuper()\n\t\tfor (const z of zones) this.#zones.add(z)\n\t}\n\tget active(): Map<AZone<unknown>, unknown> | undefined {\n\t\tconst rv = new Map<AZone<unknown>, unknown>()\n\t\tfor (const z of this.#zones) if (z.active !== undefined) rv.set(z, z.active)\n\t\treturn rv\n\t}\n\tset active(value: Map<AZone<unknown>, unknown> | undefined) {\n\t\tfor (const z of this.#zones) z.active = value?.get(z)\n\t}\n\tenter(value?: Map<AZone<unknown>, unknown> | undefined) {\n\t\tconst entered = new Map<AZone<unknown>, unknown>()\n\t\tfor (const z of this.#zones) {\n\t\t\tconst v = value?.get(z)\n\t\t\tentered.set(z, isu(z).enter(v))\n\t\t}\n\t\treturn entered\n\t}\n\tleave(entered: Map<AZone<unknown>, unknown>): void {\n\t\tfor (const z of this.#zones) isu(z).leave(entered.get(z))\n\t}\n\tadd(z: AZone<unknown>) {\n\t\tthis.#zones.add(z)\n\t}\n\tdelete(z: AZone<unknown>) {\n\t\tthis.#zones.delete(z)\n\t}\n\tclear() {\n\t\tthis.#zones.clear()\n\t}\n}\n\n/**\n * Aggregator of zones that should be preserved across async boundaries.\n * If you add a zone here, it will be preserved across async boundaries.\n *\n * @example\n * ```ts\n * import { Zone, asyncZone } from 'mutts'\n * const userZone = new Zone<User>()\n * asyncZone.add(userZone)\n * ```\n */\nexport const asyncZone = tag('async', new ZoneAggregator())\nasyncHooks.addHook(() => {\n\t// capture state before async boundary\n\tconst zone = asyncZone.active\n\treturn () => {\n\t\t// restore state after async boundary, temporarily\n\t\tconst prev = asyncZone.active\n\t\tasyncZone.active = zone\n\t\treturn () => {\n\t\t\t// restore previous state from before our restore\n\t\t\tasyncZone.active = prev\n\t\t}\n\t}\n})\n","import type { EffectNode, EffectTrigger } from './types'\n\n// Symbol for storing root function on the function itself\nexport const rootFunctionSymbol = Symbol('root-function')\n\n// Track which effects are watching which reactive objects for cleanup\nexport let effectToReactiveObjects = new WeakMap<EffectTrigger, Set<object>>()\n\n// Track effects per reactive object and property\nexport let watchers = new WeakMap<object, Map<any, Set<EffectTrigger>>>()\n\n// Track effect metadata and relationships\nexport let effectNodes = new WeakMap<EffectTrigger, EffectNode>()\n\nexport function getEffectNode(effect: EffectTrigger): EffectNode {\n\tlet node = effectNodes.get(effect)\n\tif (!node) {\n\t\tnode = {}\n\t\teffectNodes.set(effect, node)\n\t}\n\treturn node\n}\n\n// Track reverse mapping to ensure unicity: One Root -> One Function\nlet reverseRoots = new WeakMap<any, WeakRef<Function>>()\n\nexport function resetRegistry() {\n\teffectToReactiveObjects = new WeakMap()\n\twatchers = new WeakMap()\n\teffectNodes = new WeakMap()\n\treverseRoots = new WeakMap()\n}\n\n/**\n * Marks a function with its root function for effect tracking\n * Enforces strict unicity: A root function can only identify ONE function.\n * @param fn - The function to mark\n * @param root - The root function\n * @returns The marked function\n */\nexport function markWithRoot<T extends Function>(fn: T, root: any): T {\n\t// Check for collision\n\tconst existingRef = reverseRoots.get(root)\n\tconst existing = existingRef?.deref()\n\n\tif (existing && existing !== fn) {\n\t\tconst rootName = root.name || 'anonymous'\n\t\tconst existingName = existing.name || 'anonymous'\n\t\tconst fnName = fn.name || 'anonymous'\n\t\tthrow new Error(\n\t\t\t`[reactive] Abusive Shared Root detected: Root '${rootName}' is already identifying function '${existingName}'. ` +\n\t\t\t\t`Cannot reuse it for '${fnName}'. Shared roots cause lost updates and broken identity logic.`\n\t\t)\n\t}\n\n\t// Always update the map so subsequent checks find this one\n\t// (Last writer wins for the check)\n\treverseRoots.set(root, new WeakRef(fn))\n\n\t// Store root mapping as symbol property on the function\n\tfn[rootFunctionSymbol] = getRoot(root)\n\treturn fn\n}\n\n/**\n * Gets the root function of a function for effect tracking\n * @param fn - The function to get the root of\n * @returns The root function\n */\nexport function getRoot<T extends Function | undefined>(fn: T): T {\n\twhile (fn) {\n\t\tconst r = fn[rootFunctionSymbol]\n\t\tif (!r) break\n\t\tfn = r as T\n\t}\n\treturn fn\n}\n","import { tag } from '../utils'\nimport { asyncZone, ZoneAggregator, ZoneHistory } from '../zone'\nimport { getRoot } from './registry'\nimport type { CleanupReason, EffectTrigger, ScopedCallback } from './types'\n\nexport const effectHistory = tag('effectHistory', new ZoneHistory<EffectTrigger>())\ntag('effectHistory.present', effectHistory.present)\nasyncZone.add(effectHistory)\n\n/**\n * Aggregator for zones that need to be tracked along effects.\n * ie. in each effect, the active zone of the given zoning will be the one active at effect's definition\n */\nexport const effectAggregator = tag('effectAggregator', new ZoneAggregator(effectHistory.present))\n\nexport function isRunning(effect: EffectTrigger): boolean {\n\tconst root = getRoot(effect)\n\treturn effectHistory.some((e) => getRoot(e) === root)\n}\n\nexport function getActiveEffect() {\n\treturn effectHistory.present.active\n}\n\nconst cleanups = new WeakMap<object, Set<ScopedCallback | object>>()\n\n/**\n * Attach cleanup dependencies to an object. When `unlink(obj)` is called,\n * each dependency is disposed: functions are invoked with the cleanup reason,\n * objects are recursively `unlink`ed. This forms a cleanup tree.\n *\n * @param obj - The owner object\n * @param cleanupFns - Cleanup callbacks and/or child objects to unlink recursively\n * @returns The owner object (for chaining)\n *\n * @example\n * ```ts\n * // Functions are called with CleanupReason\n * link(parent, () => console.log('disposed'))\n *\n * // Objects are recursively unlinked\n * link(parent, childA, childB)\n *\n * // Mixed\n * link(parent, childObj, () => timer.clear())\n *\n * unlink(parent) // disposes childA, childB, calls the function\n * ```\n */\nexport function link<T extends object>(\n\tobj: T,\n\t...cleanupFns: (ScopedCallback | object | undefined)[]\n): T {\n\tconst set = cleanups.get(obj)\n\tif (!set) cleanups.set(obj, new Set(cleanupFns.filter(Boolean)))\n\telse for (const fn of cleanupFns) if (fn) set.add(fn)\n\treturn obj\n}\n\n/**\n * Dispose an object's cleanup dependencies. Functions are called with the\n * reason; linked objects are recursively unlinked. The cleanup set is removed\n * so calling `unlink` twice is safe (second call is a no-op).\n *\n * @param obj - The object to dispose\n * @param reason - Optional cleanup reason propagated to callbacks\n */\nexport function unlink(obj: object, reason?: CleanupReason): void {\n\tconst set = cleanups.get(obj)\n\tif (set) {\n\t\tcleanups.delete(obj)\n\t\tfor (const fn of set)\n\t\t\tif (typeof fn === 'function') fn(reason)\n\t\t\telse unlink(fn, reason)\n\t}\n}\n","import type { GetterWrapper } from '../zone'\nimport { debugHooks } from './debug-hooks'\n\nexport type EffectAccessEvents = {\n\ttriggered(event: string, ...args: any[]): void\n}\n\n/**\n * Effect access passed to user callbacks within effects/watch\n * Provides functions to track dependencies and information about the effect execution\n */\nexport interface EffectAccess {\n\t/**\n\t * Tracks dependencies in the current effect context\n\t * Use this for normal dependency tracking within the effect\n\t * @example\n\t * ```typescript\n\t * effect(({ tracked }) => {\n\t * // In async context, use tracked to restore dependency tracking\n\t * await someAsyncOperation()\n\t * const value = tracked(() => state.count) // Tracks state.count in this effect\n\t * })\n\t * ```\n\t */\n\ttracked: GetterWrapper\n\t/**\n\t * Tracks dependencies in the parent effect context\n\t * Use this when child effects should track dependencies in the parent,\n\t * allowing parent cleanup to manage child effects while dependencies trigger the parent\n\t * @example\n\t * ```typescript\n\t * effect(({ ascend }) => {\n\t * const length = inputs.length\n\t * if (length > 0) {\n\t * ascend(() => {\n\t * // Dependencies here are tracked in the parent effect\n\t * inputs.forEach(item => console.log(item))\n\t * })\n\t * }\n\t * })\n\t * ```\n\t */\n\tascend: GetterWrapper\n\t/**\n\t * `false` on the first execution, `true` or `CleanupReason` on subsequent runs.\n\t * `true` means this is a re-run but detailed reason gathering is disabled or unavailable.\n\t * A `CleanupReason` describes *why* the previous run was torn down.\n\t * @example\n\t * ```typescript\n\t * effect(({ reaction }) => {\n\t * if (!reaction) {\n\t * // First run — setup\n\t * } else if (reaction !== true && reaction.type === 'propChange') {\n\t * // Re-run due to dependency change (with details)\n\t * for (const { evolution } of reaction.triggers)\n\t * console.log(`${'prop' in evolution ? evolution.prop : evolution.method}: ${evolution.type}`)\n\t * }\n\t * })\n\t * ```\n\t */\n\treaction: boolean | CleanupReason\n\t/**\n\t * AbortSignal that is aborted when the effect is cleaned up or re-runs.\n\t * Use this to cancel async operations (like fetch) when the effect is no longer valid.\n\t */\n\tsignal: AbortSignal\n}\n// Zone-based async context preservation is implemented in zone.ts\n// It automatically preserves effect context across Promise boundaries (.then, .catch, .finally)\n\n/**\n * Base type for effect callbacks - simple function without additional properties\n */\nexport type ScopedCallback = (reason?: CleanupReason) => void\n\nexport const effectMarker = {\n\tenter: 'effect:enter',\n\tleave: 'effect:leave',\n}\n\nexport type PropTrigger = {\n\tobj: object\n\tevolution: Evolution\n\tdependency?: unknown // Stack from when dependency was created\n\ttouch?: unknown // Stack from when touch occurred\n}\n\n/**\n * Reason for an effect cleanup/reaction\n */\nexport type CleanupReason =\n\t| { type: 'propChange'; triggers: PropTrigger[] }\n\t| { type: 'invalidate'; cause: CleanupReason }\n\t| { type: 'stopped'; detail?: string } // explicit stop() call\n\t| { type: 'gc' } // FinalizationRegistry collected the holder\n\t| { type: 'lineage'; parent: CleanupReason } // parent effect cleaned up (recursive)\n\t| { type: 'error'; error: unknown } // error handler chain (reactionCleanup called with error)\n\t| { type: 'multiple'; reasons: CleanupReason[] }\n\nfunction formatTrigger({ obj, evolution, dependency, touch }: PropTrigger): unknown[] {\n\tconst detail = evolution.type === 'bunch' ? evolution.method : String(evolution.prop)\n\tconst parts: unknown[] = [`${evolution.type} ${detail} on`, obj]\n\n\tif (dependency) {\n\t\tparts.push('\\n Dependency created at:')\n\t\tparts.push(...debugHooks.formatStack(dependency))\n\t}\n\n\tif (touch) {\n\t\tparts.push('\\n Touched from:')\n\t\tparts.push(...debugHooks.formatStack(touch))\n\t}\n\n\treturn parts\n}\n\n/**\n * Console-friendly description of a `CleanupReason`.\n * Returns an array of arguments to spread into `console.log` / `console.warn`,\n * mixing strings and raw object references so the console can render them as inspectable values.\n *\n * @example\n * ```typescript\n * effect(({ reaction }) => {\n * if (reaction !== true) console.log(...formatCleanupReason(reaction))\n * })\n * ```\n */\nexport function formatCleanupReason(reason: CleanupReason, depth = 0): unknown[] {\n\tconst indent = depth ? ' '.repeat(depth) : ''\n\tswitch (reason.type) {\n\t\tcase 'propChange': {\n\t\t\tconst parts: unknown[] = [`${indent}propChange:`]\n\t\t\tfor (let i = 0; i < reason.triggers.length; i++) {\n\t\t\t\tif (i > 0) parts.push(',')\n\t\t\t\tparts.push(...formatTrigger(reason.triggers[i]))\n\t\t\t}\n\t\t\treturn parts\n\t\t}\n\t\tcase 'stopped':\n\t\t\treturn [`${indent}stopped`]\n\t\tcase 'gc':\n\t\t\treturn [`${indent}gc`]\n\t\tcase 'error':\n\t\t\treturn [`${indent}error:`, reason.error]\n\t\tcase 'lineage':\n\t\t\treturn [`${indent}lineage ←\\n`, ...formatCleanupReason(reason.parent, depth + 1)]\n\t\tcase 'invalidate':\n\t\t\treturn [`${indent}invalidate ←\\n`, ...formatCleanupReason(reason.cause, depth + 1)]\n\t\tcase 'multiple': {\n\t\t\tconst parts: unknown[] = []\n\t\t\tfor (let i = 0; i < reason.reasons.length; i++) {\n\t\t\t\tif (i > 0) parts.push('\\n')\n\t\t\t\tparts.push(...formatCleanupReason(reason.reasons[i], depth))\n\t\t\t}\n\t\t\treturn parts\n\t\t}\n\t}\n}\n\n/**\n * Type for effect cleanup functions.\n */\nexport type EffectCleanup = ScopedCallback\n\n/**\n * Centralized node for all effect metadata and relationships\n */\nexport interface EffectNode {\n\t// Graph relationships\n\tparent?: EffectTrigger\n\tchildren?: Set<EffectCleanup>\n\n\t// Lifecycle\n\tcleanup?: ScopedCallback\n\tstopped?: boolean\n\t/** The reason why the effect is (re-)executing */\n\tnextReason?: CleanupReason\n\n\t// Error handling\n\tforwardThrow?: CatchFunction\n\tcatchers?: CatchFunction[]\n\n\t// Debug / Metadata\n\tcreationStack?: unknown\n\tdependencyHook?: (obj: any, prop: any) => void\n\n\t// Configuration\n\tisOpaque?: boolean\n\n\t// Pending triggers to be batched into CleanupReason\n\tpendingTriggers?: PropTrigger[]\n}\n\n/**\n * Type for the `runEffect` function of an effect - argument-less function to call to trigger the effect\n */\nexport type EffectTrigger = ScopedCallback\n\n/**\n * Async execution mode for effects\n * - `cancel`: Cancel previous async execution when dependencies change (default)\n * - `queue`: Queue next execution to run after current completes\n * - `ignore`: Ignore new executions while async work is running\n */\nexport type AsyncExecutionMode = 'cancel' | 'queue' | 'ignore'\n\n/**\n * Options for effect creation\n */\nexport interface EffectOptions {\n\t/**\n\t * How to handle async effect executions when dependencies change\n\t * @default 'cancel'\n\t */\n\tasyncMode?: AsyncExecutionMode\n\t/**\n\t * If true, this effect is \"opaque\" to deep optimizations: it sees the object reference itself\n\t * and must be notified when it changes, regardless of deep content similarity.\n\t * Use this for effects that depend on object identity (like memoize).\n\t */\n\topaque?: boolean\n\t/**\n\t * Used for debugging purpose. Provides a callback to be called every time a dependency is created.\n\t */\n\tdependencyHook?: (obj: any, prop: any) => void\n\t/**\n\t * Used for debugging purpose. Provides a name for the effect.\n\t */\n\tname?: string\n}\n\n/**\n * Type for property evolution events\n */\nexport type PropEvolution = {\n\ttype: 'set' | 'del' | 'add' | 'invalidate'\n\tprop: any\n}\n\n/**\n * Type for collection operation evolution events\n */\nexport type BunchEvolution = {\n\ttype: 'bunch'\n\tmethod: string\n}\nexport type Evolution = PropEvolution | BunchEvolution\n\nexport type State =\n\t| {\n\t\t\tevolution: Evolution\n\t\t\tnext: State\n\t }\n\t| {}\n\n// Track native reactivity\n\n/**\n * Symbol to mark class properties as non-reactive\n */\nexport const unreactiveProperties = Symbol('unreactive-properties')\n\n/**\n * Symbol representing all properties in reactive tracking\n */\nexport const allProps = Symbol('all-props')\n\n/**\n * Symbol for structure-only tracking (triggered on key add/delete, not value changes).\n * Used by ownKeys proxy trap — Object.keys(), for..in, Map.keys() depend on this.\n */\nexport const keysOf = Symbol('keys-of')\n\n/**\n * Symbol for accessing projection information on reactive objects\n */\nexport const projectionInfo = Symbol('projection-info')\n\nexport const forwardThrow = Symbol('throw')\n\nexport type EffectCloser = (reason?: CleanupReason) => void\nexport type CatchFunction = (error: unknown) => EffectCloser | undefined | void\n\n/**\n * Context for a running projection item effect\n */\nexport interface ProjectionContext {\n\tsource: any\n\tkey?: any\n\ttarget: any\n\tdepth: number\n\tparent?: ProjectionContext\n}\n\n/**\n * Structured error codes for machine-readable diagnosis\n */\nexport enum ReactiveErrorCode {\n\tCycleDetected = 'Cycle detected',\n\tMaxDepthExceeded = 'Max depth exceeded',\n\tMaxReactionExceeded = 'Max reaction exceeded',\n\tWriteInComputed = 'Write in computed',\n\tTrackingError = 'Tracking error',\n\tBrokenEffects = 'Broken effects',\n}\n\nexport type CycleDebugInfo = {\n\tcode: ReactiveErrorCode.CycleDetected\n\tcycle: string[]\n\tdetails?: string\n\tcausalChain?: string[]\n\tlineage?: unknown\n}\n\nexport type MaxDepthDebugInfo = {\n\tcode: ReactiveErrorCode.MaxDepthExceeded\n\teffectuatedRoots: any[]\n\tcycle: any[] | null\n\ttrace: string\n\tmaxEffectChain: number\n\tqueued: string[]\n\tqueuedCount: number\n\tcausalChain?: string[]\n\tlineage?: unknown\n}\n\nexport type MaxReactionDebugInfo = {\n\tcode: ReactiveErrorCode.MaxReactionExceeded\n\tcount: number\n\teffect: string\n\tcausalChain?: string[]\n\tlineage?: unknown\n}\n\nexport type GenericDebugInfo = {\n\tcode: ReactiveErrorCode\n\tcausalChain?: string[]\n\tlineage?: unknown\n\t[key: string]: any\n}\n\nexport type ReactiveDebugInfo =\n\t| CycleDebugInfo\n\t| MaxDepthDebugInfo\n\t| MaxReactionDebugInfo\n\t| GenericDebugInfo\n\n/**\n * Error class for reactive system errors\n */\nexport class ReactiveError extends Error {\n\tconstructor(\n\t\tmessage: string,\n\t\tpublic debugInfo?: ReactiveDebugInfo\n\t) {\n\t\tsuper(message)\n\t\tthis.name = 'ReactiveError'\n\t}\n\n\tget code(): ReactiveErrorCode | undefined {\n\t\treturn this.debugInfo?.code\n\t}\n\n\tget cause(): any {\n\t\treturn (this.debugInfo as any)?.cause\n\t}\n}\n\n// biome-ignore-start lint/correctness/noUnusedFunctionParameters: Interface declaration with empty defaults\n/**\n * Global options for the reactive system\n */\nexport const options = {\n\t/**\n\t * Debug purpose: called when an effect is entered\n\t * @param effect - The effect that is entered\n\t */\n\tenter: (_effect: Function) => {},\n\t/**\n\t * Debug purpose: called when an effect is left\n\t * @param effect - The effect that is left\n\t */\n\tleave: (_effect: Function) => {},\n\t/**\n\t * Debug purpose: called when an effect is chained\n\t * @param target - The effect that is being triggered\n\t * @param caller - The effect that is calling the target\n\t */\n\tchain: (_targets: Function[], _caller?: Function) => {},\n\t/**\n\t * Debug purpose: called when an effect chain is started\n\t * @param target - The effect that is being triggered\n\t */\n\tbeginChain: (_targets: Function[]) => {},\n\t/**\n\t * Debug purpose: called when an effect chain is ended\n\t */\n\tendChain: () => {},\n\tgarbageCollected: (_fn: Function) => {},\n\t/**\n\t * Debug purpose: called when an object is touched\n\t * @param obj - The object that is touched\n\t * @param evolution - The type of change\n\t * @param props - The properties that changed\n\t * @param deps - The dependencies that changed\n\t */\n\ttouched: (_obj: any, _evolution: Evolution, _props?: any[], _deps?: EffectTrigger[]) => {},\n\t/**\n\t * Debug purpose: called when an effect is skipped because it's already running\n\t * @param effect - The effect that is already running\n\t * @param runningChain - The array of effects from the detected one to the currently running one\n\t */\n\tskipRunningEffect: (_effect: EffectTrigger) => {},\n\t/**\n\t * Debug purpose: called when an effect starts executing.\n\t * @param effect - The effect being executed (root function)\n\t * @param reaction - false for initial creation, true/CleanupReason for subsequent runs\n\t */\n\teffectRun: (_effect: Function, _reaction: boolean | CleanupReason) => {},\n\t/**\n\t * Debug purpose: maximum effect chain (like call stack max depth)\n\t * Used to prevent infinite loops\n\t * @default 100\n\t */\n\tmaxEffectChain: 100,\n\t/**\n\t * Maximum number of times an effect can be triggered by the same cause in a single batch\n\t * Used to detect aggressive re-computation or infinite loops\n\t * @default 10\n\t */\n\tmaxTriggerPerBatch: 10,\n\t/**\n\t * Debug purpose: maximum effect reaction (like call stack max depth)\n\t * Used to prevent infinite loops\n\t * @default 'throw'\n\t */\n\tmaxEffectReaction: 'throw' as 'throw' | 'debug' | 'warn',\n\t/**\n\t * Callback called when a memoization discrepancy is detected (debug only)\n\t * When defined, memoized functions will run a second time (untracked) to verify consistency.\n\t * If the untracked run returns a different value than the cached one, this callback is triggered.\n\t *\n\t * This is the primary tool for detecting missing reactive dependencies in computed values.\n\t *\n\t * @param cached - The value currently in the memoization cache\n\t * @param fresh - The value obtained by re-running the function untracked\n\t * @param fn - The memoized function itself\n\t * @param args - Arguments passed to the function\n\t *\n\t * @example\n\t * ```typescript\n\t * reactiveOptions.onMemoizationDiscrepancy = (cached, fresh, fn, args) => {\n\t * throw new Error(`Memoization discrepancy in ${fn.name}!`);\n\t * };\n\t * ```\n\t */\n\tonMemoizationDiscrepancy: undefined as\n\t\t| ((\n\t\t\t\tcached: any,\n\t\t\t\tfresh: any,\n\t\t\t\tfn: Function,\n\t\t\t\targs: any[],\n\t\t\t\tcause: 'calculation' | 'comparison'\n\t\t ) => void)\n\t\t| undefined,\n\t/**\n\t * How to handle cycles detected in effect batches.\n\t *\n\t * - `'production'` (Default): High-performance mode. Disables dependency graph maintenance and\n\t * Topological Sorting in favor of a simple FIFO queue. Use this for trustworthy, acyclic UI code.\n\t * Cycle detection is heuristic (uses maxEffectChain execution counts).\n\t *\n\t * - `'development'`: Maintains direct dependency graph for early cycle detection during edge creation.\n\t * Catches cycles before effects execute via DFS check when adding edges. Throws immediately with\n\t * basic path information. Good balance of debugging help with moderate overhead.\n\t *\n\t * - `'debug'`: Full diagnostic mode with transitive closures and topological sorting.\n\t * Provides detailed cycle path reporting. Highest overhead but most informative for bug hunting.\n\t *\n\t * @default 'production'\n\t */\n\tcycleHandling: 'development' as 'production' | 'development' | 'debug',\n\t/**\n\t * Internal flag used by memoization discrepancy detector to avoid counting calls in tests\n\t * @warning Do not modify this flag manually, this flag is given by the engine\n\t */\n\tisVerificationRun: false,\n\t/**\n\t * Maximum depth for deep watching traversal\n\t * Used to prevent infinite recursion in circular references\n\t * @default 100\n\t */\n\tmaxDeepWatchDepth: 100,\n\t/**\n\t * Only react on instance members modification (not inherited properties)\n\t * For instance, do not track class methods\n\t * @default true\n\t */\n\tinstanceMembers: true,\n\t/**\n\t * Ignore accessors (getters and setters) and only track direct properties\n\t * @default true\n\t */\n\tignoreAccessors: true,\n\t/**\n\t * Enable recursive touching when objects with the same prototype are replaced\n\t * When enabled, replacing an object with another of the same prototype triggers\n\t * recursive diffing instead of notifying parent effects\n\t * @default true\n\t */\n\trecursiveTouching: true,\n\t/**\n\t * Default async execution mode for effects that return Promises\n\t * - 'cancel': Cancel previous async execution when dependencies change (default, enables async zone)\n\t * - 'queue': Queue next execution to run after current completes (enables async zone)\n\t * - 'ignore': Ignore new executions while async work is running (enables async zone)\n\t * - false: Disable async zone and async mode handling (effects run concurrently)\n\t *\n\t * **When truthy:** Enables async zone (Promise.prototype wrapping) for automatic context\n\t * preservation in Promise callbacks. Warning: This modifies Promise.prototype globally.\n\t * Only enable if no other library modifies Promise.prototype.\n\t *\n\t * **When false:** Async zone is disabled. Use `tracked()` manually in Promise callbacks.\n\t *\n\t * Can be overridden per-effect via EffectOptions\n\t * @default 'cancel'\n\t */\n\tasyncMode: 'cancel' as AsyncExecutionMode | false,\n\t// biome-ignore lint/suspicious/noConsole: This is the whole point here\n\twarn: (...args: any[]) => console.warn(...args),\n\n\t/**\n\t * Introspection and debug aids. Set to `null` to disable all debug overhead in production.\n\t *\n\t * - `gatherReasons`: collect `PropTrigger[]` for `CleanupReason` on effect re-runs (default `true`)\n\t * - `lineages`: what lineages to capture in PropTrigger (default `'touch'`)\n\t * - `logErrors`: log errors with detailed context (default `true`)\n\t * - `enableHistory`: keep a history of mutations (default `true`)\n\t * - `historySize`: number of mutations to keep in history (default `50`)\n\t *\n\t * `enableDevTools()` sets `logErrors` to `true` automatically.\n\t *\n\t * @example\n\t * ```typescript\n\t * // Production: disable all introspection\n\t * reactiveOptions.introspection = null\n\t * ```\n\t */\n\tintrospection: {\n\t\tgatherReasons: { lineages: 'touch' },\n\t\tlogErrors: true,\n\t\tenableHistory: true,\n\t\thistorySize: 50,\n\t} as {\n\t\tgatherReasons: { lineages: 'none' | 'touch' | 'dependency' | 'both' }\n\t\tlogErrors: boolean\n\t\tenableHistory: boolean\n\t\thistorySize: number\n\t} | null,\n}\n// biome-ignore-end lint/correctness/noUnusedFunctionParameters: Interface declaration with empty defaults\n\ntype CallableOption = {\n\t[K in keyof typeof options]: (typeof options)[K] extends ((...args: any[]) => any) | undefined\n\t\t? K\n\t\t: never\n}[keyof typeof options]\n\nexport function optionCall<K extends CallableOption>(\n\tname: K,\n\t...args: NonNullable<(typeof options)[K]> extends (...a: infer A) => unknown ? A : never\n): void {\n\tconst fn = options[name]\n\tif (typeof fn !== 'function') return\n\ttry {\n\t\t;(fn as Function)(...args)\n\t} catch (error) {\n\t\toptions.warn(`options.${name} threw`, error)\n\t}\n}\n\n/** Production preset: no introspection, heuristic cycle detection, minimal overhead */\nexport const prodPreset: Partial<typeof options> = {\n\tmaxEffectReaction: 'throw',\n\tcycleHandling: 'production',\n\tintrospection: null,\n\tonMemoizationDiscrepancy: undefined,\n}\n\n/** Development preset (default): introspection on, early cycle detection, warnings */\nexport const devPreset: Partial<typeof options> = {\n\tmaxEffectReaction: 'warn',\n\tcycleHandling: 'development',\n\tintrospection: {\n\t\tgatherReasons: { lineages: 'touch' },\n\t\tlogErrors: true,\n\t\tenableHistory: true,\n\t\thistorySize: 50,\n\t},\n\tonMemoizationDiscrepancy: undefined,\n}\n\n/** Debug preset: full diagnostics, throws on violations, rich lineage capture */\nexport const debugPreset: Partial<typeof options> = {\n\tmaxEffectReaction: 'debug',\n\tcycleHandling: 'debug',\n\tintrospection: {\n\t\tgatherReasons: { lineages: 'both' },\n\t\tlogErrors: true,\n\t\tenableHistory: true,\n\t\thistorySize: 200,\n\t},\n}\n\n// --- Proxy State (Merged from proxy-state.ts) ---\n\nexport const objectToProxy = new WeakMap<object, object>()\nexport const proxyToObject = new WeakMap<object, object>()\n\nexport function storeProxyRelationship(target: object, proxy: object) {\n\tobjectToProxy.set(target, proxy)\n\tproxyToObject.set(proxy, target)\n}\n\nexport function getExistingProxy<T extends object>(target: T): T | undefined {\n\treturn objectToProxy.get(target) as T | undefined\n}\n\nexport function trackProxyObject(proxy: object, target: object) {\n\tproxyToObject.set(proxy, target)\n}\n\nexport function unwrap<T>(obj: T): T {\n\tif (!obj || typeof obj !== 'object') return obj\n\treturn (proxyToObject.get(obj as object) as T) || obj\n}\n\nexport function isReactive(obj: any): boolean {\n\treturn proxyToObject.has(obj)\n}\n","import { debugHooks } from './debug-hooks'\nimport { getActiveEffect } from './effect-context'\nimport { effectToReactiveObjects, getEffectNode, watchers } from './registry'\nimport { allProps, type EffectTrigger, keysOf, options, unwrap } from './types'\n\n// Track dependency stacks per (obj, prop, effect)\nlet dependencyStacks = new WeakMap<object, Map<any, Map<EffectTrigger, unknown>>>()\nlet assertUntrackedFlag = false\n\nexport function resetTracking() {\n\tdependencyStacks = new WeakMap()\n}\n\n/**\n * Executes a function and throws if any reactive dependencies are tracked during execution.\n * Used to assert that code runs in an untracked context.\n */\nexport function assertUntracked<T>(fn: () => T): T {\n\tif (assertUntrackedFlag) {\n\t\tthrow new Error('assertUntracked: nested calls are not supported')\n\t}\n\tassertUntrackedFlag = true\n\ttry {\n\t\treturn fn()\n\t} finally {\n\t\tassertUntrackedFlag = false\n\t}\n}\n\nfunction getDependencyStack(effect: EffectTrigger, obj: object, prop: any): unknown | undefined {\n\tconst objStacks = dependencyStacks.get(obj)\n\tif (!objStacks) return undefined\n\treturn objStacks.get(prop)?.get(effect) ?? objStacks.get(allProps)?.get(effect)\n}\n\nexport { getDependencyStack }\n\n/**\n * Marks a property as a dependency of the current effect\n * @param obj - The object containing the property\n * @param prop - The property name (defaults to allProps)\n */\nexport function dependant(obj: any, prop: any = allProps) {\n\tif (assertUntrackedFlag) {\n\t\tthrow new Error(\n\t\t\t`Reactive dependency tracking detected in assertUntracked context: ${String(prop)} on ${obj}`\n\t\t)\n\t}\n\tobj = unwrap(obj)\n\tconst currentActiveEffect = getActiveEffect()\n\n\t// Early return if no active effect, tracking disabled, or invalid prop\n\tif (!currentActiveEffect || (typeof prop === 'symbol' && prop !== allProps && prop !== keysOf))\n\t\treturn\n\n\tconst node = getEffectNode(currentActiveEffect)\n\tif ('dependencyHook' in node) {\n\t\tnode.dependencyHook(obj, prop)\n\t}\n\tlet objectWatchers = watchers.get(obj)\n\tif (!objectWatchers) {\n\t\tobjectWatchers = new Map<PropertyKey, Set<EffectTrigger>>()\n\t\twatchers.set(obj, objectWatchers)\n\t}\n\tlet deps = objectWatchers.get(prop)\n\tif (!deps) {\n\t\tdeps = new Set<EffectTrigger>()\n\t\tobjectWatchers.set(prop, deps)\n\t}\n\tdeps.add(currentActiveEffect)\n\n\t// Track which reactive objects this effect is watching\n\tconst effectObjects = effectToReactiveObjects.get(currentActiveEffect)\n\tif (effectObjects) {\n\t\teffectObjects.add(obj)\n\t} else {\n\t\teffectToReactiveObjects.set(currentActiveEffect, new Set([obj]))\n\t}\n\n\t// Store dependency stack if introspection is enabled\n\tconst gatherReasons = options.introspection?.gatherReasons\n\tif (gatherReasons) {\n\t\tconst lineageConfig = gatherReasons.lineages\n\t\tif (lineageConfig === 'dependency' || lineageConfig === 'both') {\n\t\t\tlet objStacks = dependencyStacks.get(obj)\n\t\t\tif (!objStacks) {\n\t\t\t\tobjStacks = new Map()\n\t\t\t\tdependencyStacks.set(obj, objStacks)\n\t\t\t}\n\t\t\tlet propStacks = objStacks.get(prop)\n\t\t\tif (!propStacks) {\n\t\t\t\tpropStacks = new Map()\n\t\t\t\tobjStacks.set(prop, propStacks)\n\t\t\t}\n\t\t\tpropStacks.set(currentActiveEffect, debugHooks.captureLineage())\n\t\t}\n\t}\n}\n","import { decorator } from '../decorator'\nimport { flavored, flavorOptions } from '../flavored'\nimport { IterableWeakSet } from '../iterableWeak'\nimport { named } from '../utils'\nimport type { HistoryValue } from '../zone'\nimport { debugHooks } from './debug-hooks'\nimport { effectAggregator, effectHistory, getActiveEffect } from './effect-context'\nimport {\n\teffectToReactiveObjects,\n\tgetEffectNode,\n\tgetRoot,\n\tmarkWithRoot,\n\tresetRegistry,\n\twatchers,\n} from './registry'\nimport { resetTracking } from './tracking'\nimport {\n\ttype CatchFunction,\n\ttype CleanupReason,\n\ttype EffectAccess,\n\ttype EffectCleanup,\n\ttype EffectCloser,\n\ttype EffectOptions,\n\ttype EffectTrigger,\n\ttype Evolution,\n\teffectMarker,\n\toptionCall,\n\toptions,\n\t// type AsyncExecutionMode,\n\ttype PropTrigger,\n\tReactiveError,\n\tReactiveErrorCode,\n\ttype ScopedCallback,\n\tunwrap,\n} from './types'\n\n/**\n * Finds a cycle in a sequence of functions by looking for the first repetition\n */\nfunction findCycleInChain(roots: Function[]): Function[] | null {\n\tconst seen = new Map<Function, number>()\n\tfor (let i = 0; i < roots.length; i++) {\n\t\tconst root = roots[i]\n\t\tif (seen.has(root)) {\n\t\t\treturn roots.slice(seen.get(root)!)\n\t\t}\n\t\tseen.set(root, i)\n\t}\n\treturn null\n}\n\n/**\n * Formats a list of function roots into a readable trace\n */\nfunction formatRoots(roots: Function[], limit = 20): string {\n\tconst names = roots.map((r) => r.name || '<anonymous>')\n\tif (names.length <= limit) return names.join(' → ')\n\tconst start = names.slice(0, 5)\n\tconst end = names.slice(-10)\n\treturn `${start.join(' → ')} ... (${names.length - 15} more) ... ${end.join(' → ')}`\n}\n\nexport interface ActivationRecord {\n\teffect: EffectTrigger\n\tobj: any\n\tevolution: Evolution\n\tprop: any\n\tbatchId: number\n}\n\n// Nested map structure for efficient counting and batch cleanup\n// batchId -> effect root -> obj -> prop -> count\nlet activationRegistry: Map<Function, Map<any, Map<any, number>>> | undefined\n\nexport const activationLog: Omit<ActivationRecord, 'batchId'>[] = new Array(100)\n\n/**\n * Returns the activation log containing recent effect activations for debugging.\n * The log is a circular buffer of the last 100 activations.\n *\n * @returns Array of activation records\n */\nexport function getActivationLog() {\n\treturn activationLog\n}\n\nexport function recordActivation(effect: EffectTrigger, obj: any, evolution: Evolution, prop: any) {\n\tconst root = getRoot(effect)\n\n\tif (!activationRegistry) return\n\tlet effectData = activationRegistry.get(root)\n\tif (!effectData) {\n\t\teffectData = new Map()\n\t\tactivationRegistry.set(root, effectData)\n\t}\n\tlet objData = effectData.get(obj)\n\tif (!objData) {\n\t\tobjData = new Map()\n\t\teffectData.set(obj, objData)\n\t}\n\tconst count = (objData.get(prop) ?? 0) + 1\n\tobjData.set(prop, count)\n\n\t// Keep a limited history for diagnostics\n\tactivationLog.unshift({\n\t\teffect,\n\t\tobj,\n\t\tevolution,\n\t\tprop,\n\t})\n\tactivationLog.pop()\n\n\tif (count >= options.maxTriggerPerBatch) {\n\t\tconst effectName = root.name\n\t\tconst message = `Aggressive trigger detected: effect \"${effectName}\" triggered ${count} times in the batch by the same cause.`\n\t\tif (options.maxEffectReaction === 'throw') {\n\t\t\tthrow new ReactiveError(message, {\n\t\t\t\tcode: ReactiveErrorCode.MaxReactionExceeded,\n\t\t\t\tcount,\n\t\t\t\teffect: root,\n\t\t\t})\n\t\t}\n\t\toptions.warn(`[reactive] ${message}`)\n\t}\n}\n\nexport function caught(onThrow: CatchFunction, effect?: EffectTrigger) {\n\teffect ??= getActiveEffect()\n\tif (!effect) throw new Error('Tracking an effect throw while not in an effect')\n\tconst node = getEffectNode(effect)\n\tif (!node.catchers) node.catchers = [onThrow]\n\telse node.catchers.push(onThrow)\n}\n/** @deprecated Use `caught` instead */\nexport const onEffectThrow = caught\n\n// Dependency graph: tracks which effects trigger which other effects\n// Uses roots (Function) as keys for consistency\nlet effectTriggers = new WeakMap<Function, IterableWeakSet<Function>>()\nlet effectTriggeredBy = new WeakMap<Function, IterableWeakSet<Function>>()\n\n// Transitive closures: track all indirect relationships\n// causesClosure: for each effect, all effects that trigger it (directly or indirectly)\n// consequencesClosure: for each effect, all effects that it triggers (directly or indirectly)\nlet causesClosure = new WeakMap<Function, IterableWeakSet<Function>>()\nlet consequencesClosure = new WeakMap<Function, IterableWeakSet<Function>>()\n\n// Batch re-entrance depth and broken state\nlet broken = false\n\n// Debug: Capture where an effect was created\nexport const effectCreationStacks = new WeakMap<Function, unknown[]>()\n\n/**\n * Gets or creates an IterableWeakSet for a closure map\n */\nfunction getOrCreateClosure(\n\tclosure: WeakMap<Function, IterableWeakSet<Function>>,\n\troot: Function\n): IterableWeakSet<Function> {\n\tlet set = closure.get(root)\n\tif (!set) {\n\t\tset = new IterableWeakSet()\n\t\tclosure.set(root, set)\n\t}\n\treturn set\n}\n\n/**\n * Adds an edge to the dependency graph: callerRoot → targetRoot\n * Also maintains transitive closures\n * @param callerRoot - Root function of the effect that triggers\n * @param targetRoot - Root function of the effect being triggered\n */\nfunction addGraphEdge(callerRoot: Function, targetRoot: Function) {\n\tif (options.cycleHandling === 'production') return\n\t// Add to forward graph: callerRoot → targetRoot\n\tconst triggers = effectTriggers.get(callerRoot)\n\n\tif (!triggers) {\n\t\tconst newTriggers = new IterableWeakSet<Function>()\n\t\tnewTriggers.add(targetRoot)\n\t\teffectTriggers.set(callerRoot, newTriggers)\n\t} else {\n\t\ttriggers.add(targetRoot)\n\t}\n\n\t// Add to reverse graph: targetRoot ← callerRoot\n\tlet triggeredBy = effectTriggeredBy.get(targetRoot)\n\tif (!triggeredBy) {\n\t\ttriggeredBy = new IterableWeakSet()\n\t\teffectTriggeredBy.set(targetRoot, triggeredBy)\n\t}\n\ttriggeredBy.add(callerRoot)\n\n\t// Update transitive closures\n\t// When U→V is added, we need to propagate the relationship:\n\t// 1. Add U to causesClosure(V) and V to consequencesClosure(U) (direct relationship)\n\t// 2. For each X in causesClosure(U): add V to consequencesClosure(X) and X to causesClosure(V)\n\t// 3. For each Y in consequencesClosure(V): add U to causesClosure(Y) and Y to consequencesClosure(U)\n\t// Note: Self-loops (U→U) are not added to closures - if an effect appears in its own closure,\n\t// it means there's an indirect cycle that should be detected\n\n\t// Self-loops are explicitly ignored - an effect reading and writing the same property\n\t// (e.g., obj.prop++) should not create a dependency relationship or appear in closures\n\tif (callerRoot === targetRoot) {\n\t\treturn\n\t}\n\n\tconst uConsequences = getOrCreateClosure(consequencesClosure, callerRoot)\n\tconst vCauses = getOrCreateClosure(causesClosure, targetRoot)\n\n\t// 1. Add direct relationship\n\tuConsequences.add(targetRoot)\n\tvCauses.add(callerRoot)\n\n\t// 2. For each X in causesClosure(U): X→U→V means X→V\n\tconst uCausesSet = causesClosure.get(callerRoot)\n\tif (uCausesSet) {\n\t\tfor (const x of uCausesSet) {\n\t\t\t// Skip if this would create a self-loop\n\t\t\tif (x === targetRoot) continue\n\t\t\tconst xConsequences = getOrCreateClosure(consequencesClosure, x)\n\t\t\txConsequences.add(targetRoot)\n\t\t\tvCauses.add(x)\n\t\t}\n\t}\n\n\t// 3. For each Y in consequencesClosure(V): U→V→Y means U→Y\n\tconst vConsequencesSet = consequencesClosure.get(targetRoot)\n\tif (vConsequencesSet) {\n\t\tfor (const y of vConsequencesSet) {\n\t\t\t// Skip if this would create a self-loop\n\t\t\tif (y === callerRoot) continue\n\t\t\tconst yCauses = getOrCreateClosure(causesClosure, y)\n\t\t\tyCauses.add(callerRoot)\n\t\t\tuConsequences.add(y)\n\t\t}\n\t}\n\n\t// 4. Cross-product: for each X in causesClosure(U) and Y in consequencesClosure(V): X→Y\n\tif (uCausesSet?.size && vConsequencesSet?.size) {\n\t\tfor (const x of uCausesSet) {\n\t\t\tconst xConsequences = getOrCreateClosure(consequencesClosure, x)\n\t\t\tfor (const y of vConsequencesSet) {\n\t\t\t\t// Skip if this would create a self-loop\n\t\t\t\tif (x === y) continue\n\t\t\t\txConsequences.add(y)\n\t\t\t\tconst yCauses = getOrCreateClosure(causesClosure, y)\n\t\t\t\tyCauses.add(x)\n\t\t\t}\n\t\t}\n\t}\n}\n\n/**\n * Checks if there's a path from start to end in the dependency graph, excluding a specific node\n * Uses BFS to find any path that doesn't go through the excluded node\n * @param start - Starting node\n * @param end - Target node\n * @param exclude - Node to exclude from the path\n * @returns true if a path exists without going through the excluded node\n */\nfunction hasPathExcluding(start: Function, end: Function, exclude: Function): boolean {\n\tif (start === end) return true\n\tif (start === exclude) return false\n\n\tconst visited = new Set<Function>()\n\tconst queue: Function[] = [start]\n\tvisited.add(start)\n\tvisited.add(exclude) // Pre-mark excluded node as visited to skip it\n\n\twhile (queue.length > 0) {\n\t\tconst current = queue.shift()!\n\t\tconst triggers = effectTriggers.get(current)\n\t\tif (!triggers) continue\n\n\t\tfor (const next of triggers) {\n\t\t\tif (next === end) return true\n\t\t\tif (!visited.has(next)) {\n\t\t\t\tvisited.add(next)\n\t\t\t\tqueue.push(next)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn false\n}\n\n/**\n * Removes all edges involving the given effect from the dependency graph\n * Also cleans up transitive closures by propagating cleanup to all affected effects\n * Called when an effect is stopped/cleaned up\n * @param effect - The effect being cleaned up\n */\nfunction cleanupEffectFromGraph(effect: EffectTrigger) {\n\tif (options.cycleHandling === 'production') return\n\tconst root = getRoot(effect)\n\n\t// Get closures before removing direct edges (needed for propagation)\n\tconst rootCauses = causesClosure.get(root)\n\tconst rootConsequences = consequencesClosure.get(root)\n\n\t// Remove from effectTriggers (outgoing edges)\n\tconst triggers = effectTriggers.get(root)\n\tif (triggers) {\n\t\t// Remove this root from all targets' effectTriggeredBy sets\n\t\tfor (const targetRoot of triggers) {\n\t\t\tconst triggeredBy = effectTriggeredBy.get(targetRoot)\n\t\t\ttriggeredBy?.delete(root)\n\t\t}\n\t\teffectTriggers.delete(root)\n\t}\n\n\t// Remove from effectTriggeredBy (incoming edges)\n\tconst triggeredBy = effectTriggeredBy.get(root)\n\tif (triggeredBy) {\n\t\t// Remove this root from all sources' effectTriggers sets\n\t\tfor (const sourceRoot of triggeredBy) {\n\t\t\tconst triggers = effectTriggers.get(sourceRoot)\n\t\t\ttriggers?.delete(root)\n\t\t}\n\t\teffectTriggeredBy.delete(root)\n\t}\n\n\t// Propagate closure cleanup to all affected effects\n\t// When removing B from A → B → C:\n\t// - Remove B from causesClosure(C) and consequencesClosure(A)\n\t// - For each X in causesClosure(B): remove C from consequencesClosure(X) if B was the only path\n\t// - For each Y in consequencesClosure(B): remove A from causesClosure(Y) if B was the only path\n\t// - Remove transitive relationships that depended on B\n\n\tif (rootCauses) {\n\t\t// For each X that triggers root: remove root from X's consequences\n\t\t// Only remove root's consequences if no alternate path exists\n\t\tfor (const causeRoot of rootCauses) {\n\t\t\tconst causeConsequences = consequencesClosure.get(causeRoot)\n\t\t\tif (causeConsequences) {\n\t\t\t\t// Remove root itself (it's being cleaned up)\n\t\t\t\tcauseConsequences.delete(root)\n\t\t\t\t// Only remove consequences of root if there's no alternate path from causeRoot to them\n\t\t\t\tif (rootConsequences) {\n\t\t\t\t\tfor (const consequence of rootConsequences) {\n\t\t\t\t\t\t// Check if causeRoot can still reach consequence without going through root\n\t\t\t\t\t\tif (!hasPathExcluding(causeRoot, consequence, root)) {\n\t\t\t\t\t\t\tcauseConsequences.delete(consequence)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif (rootConsequences) {\n\t\t// For each Y that root triggers: remove root from Y's causes\n\t\t// Only remove root's causes if no alternate path exists\n\t\tfor (const consequenceRoot of rootConsequences) {\n\t\t\tconst consequenceCauses = causesClosure.get(consequenceRoot)\n\t\t\tif (consequenceCauses) {\n\t\t\t\t// Remove root itself (it's being cleaned up)\n\t\t\t\tconsequenceCauses.delete(root)\n\t\t\t\t// Only remove causes of root if there's no alternate path from them to consequenceRoot\n\t\t\t\tif (rootCauses) {\n\t\t\t\t\tfor (const cause of rootCauses) {\n\t\t\t\t\t\t// Check if cause can still reach consequenceRoot without going through root\n\t\t\t\t\t\tif (!hasPathExcluding(cause, consequenceRoot, root)) {\n\t\t\t\t\t\t\tconsequenceCauses.delete(cause)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Cross-product cleanup: for each X in causesClosure(B) and Y in consequencesClosure(B),\n\t// remove X→Y if B was the only path connecting them\n\tif (rootCauses && rootConsequences) {\n\t\tfor (const x of rootCauses) {\n\t\t\tconst xConsequences = consequencesClosure.get(x)\n\t\t\tif (xConsequences) {\n\t\t\t\tfor (const y of rootConsequences) {\n\t\t\t\t\t// Check if there's still a path from X to Y without going through root\n\t\t\t\t\t// Use BFS to find any path that doesn't include root\n\t\t\t\t\tif (!hasPathExcluding(x, y, root)) {\n\t\t\t\t\t\txConsequences.delete(y)\n\t\t\t\t\t\tconst yCauses = causesClosure.get(y)\n\t\t\t\t\t\tyCauses?.delete(x)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Finally, delete the closures for this effect\n\tcausesClosure.delete(root)\n\tconsequencesClosure.delete(root)\n}\n\n// Batch queue structure - optimized with cached in-degrees\ninterface BatchQueue {\n\t// All effects in the current batch that still need to be executed (todos)\n\tall: Map<Function, EffectTrigger> // root → effect\n\t// Cached in-degrees for each effect in the batch (number of causes in batch)\n\tinDegrees: Map<Function, number> // root → in-degree count\n\t// Deferred callbacks to run after this batch completes (populated by defer())\n\tdeferreds: Set<ScopedCallback>\n}\n\n// Track currently executing effects to prevent re-execution\n// These are all the effects triggered under `activeEffect`\n// Batch stack - handles nested batches by giving each its own queue\nconst batchStack: BatchQueue[] = []\nexport function hasBatched(effect: EffectTrigger) {\n\tconst root = getRoot(effect)\n\treturn batchStack.some((bs) => bs.all.has(root))\n}\n// DEV: stack of currently-executing effects (push on enter, pop on leave)\nconst executingStack: EffectTrigger[] = []\nexport function getExecutingStack(): readonly EffectTrigger[] {\n\treturn executingStack\n}\n\n/**\n * Computes and caches in-degrees for all effects in the batch\n * Called once when batch starts or when new effects are added\n */\nfunction computeAllInDegrees(batch: BatchQueue): void {\n\tif (options.cycleHandling === 'production') return\n\tconst activeEffect = getActiveEffect()\n\tconst activeRoot = activeEffect ? getRoot(activeEffect) : null\n\n\t// Reset all in-degrees\n\tbatch.inDegrees.clear()\n\n\tfor (const [root] of batch.all) {\n\t\tlet inDegree = 0\n\t\tconst causes = causesClosure.get(root)\n\t\tif (causes) {\n\t\t\tfor (const causeRoot of causes) {\n\t\t\t\t// Only count if it's in the batch and not the active/self effect\n\t\t\t\tif (batch.all.has(causeRoot) && causeRoot !== activeRoot && causeRoot !== root) {\n\t\t\t\t\tinDegree++\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tbatch.inDegrees.set(root, inDegree)\n\t}\n}\n\n/**\n * Decrements in-degrees of all effects that depend on the executed effect\n * Called after an effect is executed to update the cached in-degrees\n */\nfunction decrementInDegreesForExecuted(batch: BatchQueue, executedRoot: Function): void {\n\t// Get all effects that this executed effect triggers\n\tconst consequences = consequencesClosure.get(executedRoot)\n\tif (!consequences) return\n\n\tfor (const consequenceRoot of consequences) {\n\t\t// Only update if it's still in the batch\n\t\tif (batch.all.has(consequenceRoot)) {\n\t\t\tconst currentDegree = batch.inDegrees.get(consequenceRoot) ?? 0\n\t\t\tif (currentDegree > 0) {\n\t\t\t\tbatch.inDegrees.set(consequenceRoot, currentDegree - 1)\n\t\t\t}\n\t\t}\n\t}\n}\n\n/**\n * Finds a path from startRoot to endRoot in the dependency graph\n * Uses DFS to find the path through direct edges\n * @param startRoot - Starting effect root\n * @param endRoot - Target effect root\n * @param visited - Set of visited nodes (for recursion)\n * @param path - Current path being explored\n * @returns Path from startRoot to endRoot, or empty array if no path exists\n */\nfunction findPath(\n\tstartRoot: Function,\n\tendRoot: Function,\n\tvisited: Set<Function> = new Set(),\n\tpath: Function[] = []\n): Function[] {\n\tif (startRoot === endRoot) {\n\t\treturn [...path, endRoot]\n\t}\n\n\tif (visited.has(startRoot)) {\n\t\treturn []\n\t}\n\n\tvisited.add(startRoot)\n\tconst newPath = [...path, startRoot]\n\n\tconst triggers = effectTriggers.get(startRoot)\n\tif (triggers) {\n\t\tfor (const targetRoot of triggers) {\n\t\t\tconst result = findPath(targetRoot, endRoot, visited, newPath)\n\t\t\tif (result.length > 0) {\n\t\t\t\treturn result\n\t\t\t}\n\t\t}\n\t}\n\n\treturn []\n}\n\n/**\n * Gets the cycle path when adding an edge would create a cycle\n * @param callerRoot - Root of the effect that triggers\n * @param targetRoot - Root of the effect being triggered\n * @returns Array of effect roots forming the cycle, or empty array if no cycle\n */\nfunction getCyclePathForEdge(callerRoot: Function, targetRoot: Function): Function[] {\n\t// Find path from targetRoot back to callerRoot (this is the existing path)\n\t// Then adding callerRoot -> targetRoot completes the cycle\n\tconst path = findPath(targetRoot, callerRoot)\n\tif (path.length > 0) {\n\t\t// The cycle is: callerRoot -> targetRoot -> ... -> callerRoot\n\t\treturn [callerRoot, ...path]\n\t}\n\treturn []\n}\n\n/**\n * Checks if adding an edge would create a cycle\n * Uses causesClosure to check if callerRoot is already a cause of targetRoot\n * Self-loops (callerRoot === targetRoot) are explicitly ignored and return false\n *\n * **Note**: This is the primary optimization benefit of the transitive closure system.\n * It allows detecting cycles in O(1) time before they are executed.\n *\n * @param callerRoot - Root of the effect that triggers\n * @param targetRoot - Root of the effect being triggered\n * @returns true if adding this edge would create a cycle\n */\nfunction wouldCreateCycle(callerRoot: Function, targetRoot: Function): boolean {\n\t// Self-loops are explicitly ignored - an effect reading and writing the same property\n\t// (e.g., obj.prop++) should not create a dependency relationship\n\tif (callerRoot === targetRoot) {\n\t\treturn false\n\t}\n\n\t// Check if targetRoot already triggers callerRoot (directly or indirectly)\n\t// This would create a cycle: callerRoot -> targetRoot -> ... -> callerRoot\n\t// Using consequencesClosure: if targetRoot triggers callerRoot, then callerRoot is in consequencesClosure(targetRoot)\n\tconst targetConsequences = consequencesClosure.get(targetRoot)\n\tif (targetConsequences?.has(callerRoot)) {\n\t\treturn true // Cycle detected: targetRoot -> ... -> callerRoot, and we're adding callerRoot -> targetRoot\n\t}\n\n\treturn false\n}\n\n/**\n * Adds an effect to the batch queue\n * @param effect - The effect to add\n * @param caller - The active effect that triggered this one (optional)\n * @param immediate - If true, don't create edges in the dependency graph\n */\nfunction addToBatch(\n\teffect: EffectTrigger,\n\tcaller?: EffectTrigger,\n\timmediate?: boolean,\n\treason?: CleanupReason\n) {\n\tconst node = getEffectNode(effect)\n\tconst currentBatch = batchStack[batchStack.length - 1]\n\n\tif (!currentBatch) {\n\t\treturn\n\t}\n\n\tconst root = getRoot(effect)\n\n\t// Build reason from pending triggers if not provided\n\tif (!reason && node.pendingTriggers) {\n\t\treason = { type: 'propChange', triggers: node.pendingTriggers }\n\t}\n\tnode.pendingTriggers = undefined\n\n\tif (reason) {\n\t\tconst existing = node.nextReason\n\t\tif (!existing) {\n\t\t\tnode.nextReason = reason\n\t\t} else {\n\t\t\tconst mergePropChange = (\n\t\t\t\tinto: CleanupReason,\n\t\t\t\tfrom: { type: 'propChange'; triggers: PropTrigger[] }\n\t\t\t): boolean => {\n\t\t\t\tif (into.type === 'propChange') {\n\t\t\t\t\tinto.triggers.push(...from.triggers)\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t\tif (into.type === 'multiple') {\n\t\t\t\t\tconst target = into.reasons.find((r) => r.type === 'propChange') as\n\t\t\t\t\t\t| { type: 'propChange'; triggers: PropTrigger[] }\n\t\t\t\t\t\t| undefined\n\t\t\t\t\tif (target) {\n\t\t\t\t\t\ttarget.triggers.push(...from.triggers)\n\t\t\t\t\t\treturn true\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\tif (reason.type === 'propChange') {\n\t\t\t\tif (!mergePropChange(existing, reason)) {\n\t\t\t\t\tif (existing.type === 'multiple') {\n\t\t\t\t\t\texisting.reasons.push(reason)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tnode.nextReason = { type: 'multiple', reasons: [existing, reason] }\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else if (existing.type === 'multiple') {\n\t\t\t\texisting.reasons.push(reason)\n\t\t\t} else {\n\t\t\t\tnode.nextReason = { type: 'multiple', reasons: [existing, reason] }\n\t\t\t}\n\t\t}\n\t}\n\n\t// 1. Add to batch first (needed for cycle detection)\n\t// TODO: Check if it's the correct way to do (these different behavior in function of dev/production)\n\tif (options.cycleHandling === 'production') {\n\t\t// Production mode: FIFO (delete and re-add to move to end)\n\t\tif (currentBatch.all.has(root)) {\n\t\t\tcurrentBatch.all.delete(root)\n\t\t}\n\t} else {\n\t\t// Dev mode: skip if already queued — the existing entry will re-run\n\t\tif (currentBatch.all.has(root)) {\n\t\t\treturn\n\t\t}\n\t}\n\n\t// If the effect was stopped during cleanup (e.g. lazy memoization), don't add it to the batch\n\tif (node.stopped) return\n\n\tcurrentBatch.all.set(root, effect)\n\n\tif (caller && !immediate && options.cycleHandling !== 'production') {\n\t\tconst callerRoot = getRoot(caller)\n\t\t// const root = getRoot(effect) // Already have root\n\n\t\t// Check for cycle BEFORE adding edge\n\t\tif (wouldCreateCycle(callerRoot, root)) {\n\t\t\tconst cyclePath = getCyclePathForEdge(callerRoot, root)\n\t\t\tconst cycleMessage =\n\t\t\t\tcyclePath.length > 0\n\t\t\t\t\t? `Cycle detected: ${cyclePath.map((r) => r.name || r.toString()).join(' → ')}`\n\t\t\t\t\t: `Cycle detected: ${callerRoot.name || callerRoot.toString()} → ${root.name || root.toString()} (and back)`\n\n\t\t\tcurrentBatch.all.delete(root)\n\t\t\tconst causalChain = debugHooks.getTriggerChain(effect)\n\t\t\tconst lineage = getEffectNode(effect).creationStack\n\n\t\t\tthrow new ReactiveError(`[reactive] ${cycleMessage}`, {\n\t\t\t\tcode: ReactiveErrorCode.CycleDetected,\n\t\t\t\tcycle: cyclePath.map((r) => r.name || r.toString()),\n\t\t\t\tdetails: cycleMessage,\n\t\t\t\tcausalChain,\n\t\t\t\tlineage,\n\t\t\t})\n\t\t}\n\n\t\taddGraphEdge(callerRoot, root)\n\t}\n}\n\n/**\n * Adds a cleanup function to be called when the current batch of effects completes\n * @param cleanup - The cleanup function to add\n */\nexport function addBatchCleanup(cleanup: EffectCleanup) {\n\tconst currentBatch = batchStack[batchStack.length - 1]\n\tif (!currentBatch) cleanup()\n\telse currentBatch.deferreds.add(cleanup)\n}\n\n/**\n * Semantic alias for `addBatchCleanup` - defers work to the end of the current reactive batch.\n *\n * Use this when an effect needs to perform an action that would modify state the effect depends on,\n * which would create a reactive cycle. The deferred callback runs after all effects complete.\n *\n * @param callback - The callback to defer until after the current batch completes\n *\n * @example\n * ```typescript\n * effect(() => {\n * processData()\n *\n * // Defer to avoid cycle (createMovement modifies state this effect reads)\n * defer(() => {\n * createMovement(data)\n * })\n * })\n * ```\n */\nexport const defer = addBatchCleanup\n\n/**\n * Gets a cycle path for debugging\n * Uses DFS to find cycles in the batch\n * @param batch - The batch queue\n * @returns Array of effect roots forming a cycle\n */\nfunction getCyclePath(batch: BatchQueue): Function[] {\n\t// If all effects have in-degree > 0, there must be a cycle\n\t// Use DFS to find it\n\tconst visited = new Set<Function>()\n\tconst recursionStack = new Set<Function>()\n\tconst path: Function[] = []\n\n\tfor (const [root] of batch.all) {\n\t\tif (visited.has(root)) continue\n\t\tconst cycle = findCycle(root, visited, recursionStack, path, batch)\n\t\tif (cycle.length > 0) {\n\t\t\treturn cycle\n\t\t}\n\t}\n\n\treturn []\n}\n\nfunction findCycle(\n\troot: Function,\n\tvisited: Set<Function>,\n\trecursionStack: Set<Function>,\n\tpath: Function[],\n\tbatch: BatchQueue\n): Function[] {\n\tif (recursionStack.has(root)) {\n\t\t// Found a cycle! Return the path from the cycle start to root\n\t\tconst cycleStart = path.indexOf(root)\n\t\treturn path.slice(cycleStart).concat([root])\n\t}\n\n\tif (visited.has(root)) {\n\t\treturn []\n\t}\n\n\tvisited.add(root)\n\trecursionStack.add(root)\n\tpath.push(root)\n\n\t// Follow edges to effects in the batch\n\t// Use direct edges (effectTriggers) for cycle detection\n\tconst triggers = effectTriggers.get(root)\n\tif (triggers) {\n\t\tfor (const targetRoot of triggers) {\n\t\t\tif (batch.all.has(targetRoot)) {\n\t\t\t\tconst cycle = findCycle(targetRoot, visited, recursionStack, path, batch)\n\t\t\t\tif (cycle.length > 0) {\n\t\t\t\t\treturn cycle\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tpath.pop()\n\trecursionStack.delete(root)\n\treturn []\n}\n\n/**\n * Executes the next effect in dependency order (using cached in-degrees)\n * Finds an effect with in-degree 0 and executes it\n * @returns The return value of the executed effect, or null if batch is complete\n */\nfunction executeNext(effectuatedRoots: Function[]): any {\n\tconst currentBatch = batchStack[batchStack.length - 1]\n\tif (!currentBatch) return null\n\n\t// Find an effect with in-degree 0 using cached values\n\tlet nextEffect: EffectTrigger | null = null\n\tlet nextRoot: Function | null = null\n\n\tif (options.cycleHandling === 'production') {\n\t\t// In flat mode, we just take the first effect in the queue (FIFO)\n\t\tconst first = currentBatch.all.entries().next().value\n\t\tif (first) {\n\t\t\t;[nextRoot, nextEffect] = first\n\t\t}\n\t} else {\n\t\t// Find an effect with in-degree 0 (no dependencies in batch that still need execution)\n\t\t// Using cached in-degrees for O(n) lookup instead of O(n²)\n\t\tfor (const [root, effect] of currentBatch.all) {\n\t\t\tconst inDegree = currentBatch.inDegrees.get(root) ?? 0\n\t\t\tif (inDegree === 0) {\n\t\t\t\tnextEffect = effect\n\t\t\t\tnextRoot = root\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tif (!nextEffect) {\n\t\t// No effect with in-degree 0 - there must be a cycle\n\t\t// If all effects have dependencies, it means there's a circular dependency\n\t\tif (currentBatch.all.size > 0) {\n\t\t\tlet cycle = getCyclePath(currentBatch)\n\t\t\t// If we couldn't find a cycle path using direct edges, try using closures\n\t\t\t// (transitive relationships) - if all effects have in-degree > 0, there must be a cycle\n\t\t\tif (cycle.length === 0) {\n\t\t\t\t// Try to find a cycle using consequencesClosure (transitive relationships)\n\t\t\t\t// Note: Self-loops are ignored - we only look for cycles between different effects\n\t\t\t\tfor (const [root] of currentBatch.all) {\n\t\t\t\t\tconst consequences = consequencesClosure.get(root)\n\t\t\t\t\tif (consequences) {\n\t\t\t\t\t\t// Check if any consequence in the batch also has root as a consequence\n\t\t\t\t\t\tfor (const consequence of consequences) {\n\t\t\t\t\t\t\t// Skip self-loops - they are ignored\n\t\t\t\t\t\t\tif (consequence === root) continue\n\t\t\t\t\t\t\tif (currentBatch.all.has(consequence)) {\n\t\t\t\t\t\t\t\tconst consequenceConsequences = consequencesClosure.get(consequence)\n\t\t\t\t\t\t\t\tif (consequenceConsequences?.has(root)) {\n\t\t\t\t\t\t\t\t\t// Found cycle: root -> consequence -> root\n\t\t\t\t\t\t\t\t\tcycle = [root, consequence, root]\n\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (cycle.length > 0) break\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst cycleMessage =\n\t\t\t\tcycle.length > 0\n\t\t\t\t\t? `Cycle detected: ${cycle.map((r) => r.name || '<anonymous>').join(' → ')}`\n\t\t\t\t\t: 'Cycle detected in effect batch - all effects have dependencies that prevent execution'\n\n\t\t\tthrow new ReactiveError(`[reactive] ${cycleMessage}`, {\n\t\t\t\tcode: ReactiveErrorCode.CycleDetected,\n\t\t\t\tcycle: cycle.map((r) => r.name || r.toString()),\n\t\t\t\tdetails: cycleMessage,\n\t\t\t})\n\t\t}\n\t\treturn null // Batch complete\n\t}\n\n\teffectuatedRoots.push(getRoot(nextEffect))\n\t// Execute the effect\n\texecutingStack.push(nextEffect)\n\tlet result: any\n\ttry {\n\t\tconst node = getEffectNode(nextEffect)\n\t\tconst reason = node.nextReason\n\t\tif (node.cleanup) {\n\t\t\tconst cleanup = node.cleanup\n\t\t\tnode.cleanup = undefined\n\t\t\tcleanup(reason)\n\t\t}\n\t\tresult = nextEffect()\n\t} finally {\n\t\texecutingStack.pop()\n\t}\n\n\t// Remove from ALL batches in the stack and update in-degrees of dependents\n\tfor (let i = batchStack.length - 1; i >= 0; i--) {\n\t\tconst batch = batchStack[i]\n\t\tif (batch.all.has(nextRoot!)) {\n\t\t\tbatch.all.delete(nextRoot!)\n\t\t\tbatch.inDegrees.delete(nextRoot!)\n\t\t\tdecrementInDegreesForExecuted(batch, nextRoot!)\n\t\t}\n\t}\n\n\treturn result\n}\n\n// Track which sub-effects have been executed to prevent infinite loops\n// These are all the effects triggered under `activeEffect` and all their sub-effects\nexport function batch(effect: EffectTrigger | EffectTrigger[], immediate?: 'immediate') {\n\tif (broken) {\n\t\tthrow new ReactiveError(\n\t\t\t'[reactive] Reactive system is broken after an unrecoverable error. Call reset() to recover.',\n\t\t\t{ code: ReactiveErrorCode.BrokenEffects }\n\t\t)\n\t}\n\tif (!Array.isArray(effect)) effect = [effect]\n\tconst roots = effect.map(getRoot)\n\n\tconst isNewBatch = batchStack.length === 0\n\tif (isNewBatch) {\n\t\tif (!activationRegistry) activationRegistry = new Map()\n\t\telse throw new Error('Activation registry already exists')\n\t\toptionCall('beginChain', roots)\n\t}\n\n\t// TODO: Consider this has been produced but was useless - it might be more correct ?const caller = executingStack.length > 0 ? getActiveEffect() : undefined\n\tconst caller = getActiveEffect()\n\n\t// Optimization: If nested and NOT immediate, just join the existing batch\n\tif (!isNewBatch && !immediate) {\n\t\tfor (let i = 0; i < effect.length; i++) {\n\t\t\taddToBatch(effect[i], caller, false)\n\t\t}\n\t\treturn\n\t}\n\n\tconst currentBatch: BatchQueue = {\n\t\tall: new Map(),\n\t\tinDegrees: new Map(),\n\t\tdeferreds: new Set(),\n\t}\n\tbatchStack.push(currentBatch)\n\n\tlet success = false\n\ttry {\n\t\tconst effectuatedRoots: Function[] = []\n\t\tconst firstReturn: { value?: any } = {}\n\n\t\tif (immediate) {\n\t\t\t// Execute initial effects in providing order\n\t\t\tfor (let i = 0; i < effect.length; i++) {\n\t\t\t\texecutingStack.push(effect[i])\n\t\t\t\ttry {\n\t\t\t\t\tconst node = getEffectNode(effect[i])\n\t\t\t\t\tconst reason = node.nextReason\n\t\t\t\t\tif (node.cleanup) {\n\t\t\t\t\t\tconst cleanup = node.cleanup\n\t\t\t\t\t\tnode.cleanup = undefined\n\t\t\t\t\t\tcleanup(reason)\n\t\t\t\t\t}\n\t\t\t\t\tconst rv = effect[i]()\n\t\t\t\t\tif (rv !== undefined && !('value' in firstReturn)) firstReturn.value = rv\n\t\t\t\t} finally {\n\t\t\t\t\texecutingStack.pop()\n\t\t\t\t\tcurrentBatch.all.delete(getRoot(effect[i]))\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\t// Add initial effects to batch and compute dependencies\n\t\t\tfor (let i = 0; i < effect.length; i++) {\n\t\t\t\taddToBatch(effect[i], caller, false)\n\t\t\t}\n\t\t\tcomputeAllInDegrees(currentBatch)\n\t\t}\n\n\t\t// Process the current batch queue\n\t\twhile (currentBatch.all.size > 0 || currentBatch.deferreds.size > 0) {\n\t\t\tif (currentBatch.all.size > 0) {\n\t\t\t\tif (effectuatedRoots.length > options.maxEffectChain) {\n\t\t\t\t\tconst cycle = findCycleInChain(effectuatedRoots as any)\n\t\t\t\t\tconst trace = formatRoots(effectuatedRoots as any)\n\t\t\t\t\tconst message = cycle\n\t\t\t\t\t\t? `Max effect chain reached (cycle detected: ${formatRoots(cycle)})`\n\t\t\t\t\t\t: `Max effect chain reached (trace: ${trace})`\n\n\t\t\t\t\tconst queuedRoots = Array.from(currentBatch.all.keys())\n\t\t\t\t\tconst queued = queuedRoots.map((r) => r.name || '<anonymous>')\n\t\t\t\t\tconst debugInfo = {\n\t\t\t\t\t\tcode: ReactiveErrorCode.MaxDepthExceeded,\n\t\t\t\t\t\teffectuatedRoots,\n\t\t\t\t\t\tcycle,\n\t\t\t\t\t\ttrace,\n\t\t\t\t\t\tmaxEffectChain: options.maxEffectChain,\n\t\t\t\t\t\tqueued: queued.slice(0, 50),\n\t\t\t\t\t\tqueuedCount: queued.length,\n\t\t\t\t\t\tcausalChain:\n\t\t\t\t\t\t\teffectuatedRoots.length > 0\n\t\t\t\t\t\t\t\t? debugHooks.getTriggerChain(\n\t\t\t\t\t\t\t\t\t\tcurrentBatch.all.get(effectuatedRoots[effectuatedRoots.length - 1])!\n\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t: [],\n\t\t\t\t\t}\n\t\t\t\t\tswitch (options.maxEffectReaction) {\n\t\t\t\t\t\tcase 'throw':\n\t\t\t\t\t\t\tthrow new ReactiveError(`[reactive] ${message}`, debugInfo)\n\t\t\t\t\t\tcase 'debug':\n\t\t\t\t\t\t\t// biome-ignore lint/suspicious/noDebugger: This is the whole point here\n\t\t\t\t\t\t\tdebugger\n\t\t\t\t\t\t\tthrow new ReactiveError(`[reactive] ${message}`, debugInfo)\n\t\t\t\t\t\tcase 'warn':\n\t\t\t\t\t\t\toptions.warn(\n\t\t\t\t\t\t\t\t`[reactive] ${message} (queued: ${queued.slice(0, 10).join(', ')}${queued.length > 10 ? ', …' : ''})`\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tconst rv = executeNext(effectuatedRoots)\n\t\t\t\tif (rv !== undefined && !('value' in firstReturn)) firstReturn.value = rv\n\t\t\t} else {\n\t\t\t\t// Process deferreds for this batch.\n\t\t\t\tconst deferreds = Array.from(currentBatch.deferreds)\n\t\t\t\tcurrentBatch.deferreds.clear()\n\t\t\t\tfor (const deferred of deferreds) deferred()\n\t\t\t}\n\t\t}\n\t\tsuccess = true\n\t\treturn firstReturn.value\n\t} finally {\n\t\tif (!success && batchStack.length === 1) {\n\t\t\tbroken = true\n\t\t}\n\t\tbatchStack.pop()\n\t\tif (batchStack.length === 0) {\n\t\t\tactivationRegistry = undefined\n\t\t\toptionCall('endChain')\n\t\t}\n\t}\n}\n\n/**\n * Resets the reactive system to a consistent state.\n * Call this after an unrecoverable error has set the system to \"broken\".\n * This clears all batch state, effect dependency graphs, and watcher registrations.\n * All existing effects become orphaned and must be recreated.\n */\nexport function reset() {\n\tbroken = false\n\tactivationRegistry = undefined\n\tbatchStack.length = 0\n\teffectTriggers = new WeakMap()\n\teffectTriggeredBy = new WeakMap()\n\tcausesClosure = new WeakMap()\n\tconsequencesClosure = new WeakMap()\n\tresetRegistry()\n\tresetTracking()\n\teffectHistory.present.active = undefined\n}\n\nexport { reset as resetBatchQueueForTest }\n\n// Inject batch function to allow atomic game loops in requestAnimationFrame/setTimeout/...\n// Note: Automatic batching of async callbacks (setTimeout, Promise.then, etc.) is NOT implemented.\n// Rationale: (1) asyncHooks.addHook API doesn't support knowing when callbacks complete (needed for batching),\n// (2) hooking all callback-creating functions adds overhead without guaranteed benefit,\n// (3) incomplete coverage in Node (async_hooks misses user-land patterns).\n// Solution: Use explicit @atomic decorator or manual batch() calls where optimization is needed.\n\n/**\n * Decorator that makes methods atomic - batches all effects triggered within the method\n */\nexport const atomic = decorator({\n\tmethod(original) {\n\t\treturn function (this: any, ...args: any[]) {\n\t\t\tconst atomicEffect = () => original.apply(this, args)\n\t\t\t// Debug: helpful to have a name\n\t\t\tObject.defineProperty(atomicEffect, 'name', { value: `atomic(${original.name})` })\n\t\t\treturn batch(atomicEffect as EffectTrigger, 'immediate')\n\t\t}\n\t},\n\tdefault<Args extends any[], Return>(\n\t\toriginal: (...args: Args) => Return\n\t): (...args: Args) => Return {\n\t\treturn function (this: any, ...args: Args) {\n\t\t\tconst atomicEffect = () => original.apply(this, args)\n\t\t\t// Debug: helpful to have a name\n\t\t\tObject.defineProperty(atomicEffect, 'name', { value: `atomic(${original.name})` })\n\t\t\treturn batch(atomicEffect as EffectTrigger, 'immediate')\n\t\t}\n\t},\n})\n\n/**\n * Wraps `fn` so it runs within `effect`'s zone context when invoked later.\n *\n * Useful for deferred callbacks (event listeners, `DOMContentLoaded`, etc.)\n * that need sub-effects parented to the original effect.\n *\n * @param prev - The effect whose context should be restored, or `undefined` for root context\n * @param fn - The function to wrap\n * @returns A function with the same signature that restores the effect context before calling `fn`\n */\nexport function captured<Args extends any[], Return>(\n\tprev: HistoryValue<EffectTrigger> | undefined,\n\tfn: (...args: Args) => Return\n): (...args: Args) => Return {\n\tprev ??= effectHistory.active\n\treturn named(effectMarker.leave, (...args: Args) => {\n\t\treturn effectHistory.with(prev, () => fn(...args))\n\t})\n}\n\n/**\n * Runs `fn` atomically and **always immediately**, batching all reactive effects\n * triggered inside it so they fire only once after `fn` completes.\n *\n * Unlike `atomic(fn)` which **wraps** a function for later invocation,\n * `atom(fn)` **executes** the function right away.\n *\n * @example\n * ```ts\n * const state = reactive({ a: 0, b: 0 })\n * effect(() => console.log(state.a, state.b)) // logs once after atom completes\n *\n * atom(() => {\n * state.a = 1\n * state.b = 2\n * })\n * ```\n */\nexport function atom<T>(fn: () => T) {\n\treturn batch(fn, 'immediate')\n}\n\nconst fr = new FinalizationRegistry<() => void>((f) => f())\n\n/**\n * @param fn - The effect function to run - provides the cleaner\n * @returns The cleanup function\n */\n/**\n * Reactive effect function with chainable flavor modifiers.\n */\nexport interface Effect {\n\t(\n\t\tfn: (access: EffectAccess) => EffectCloser | undefined | void | Promise<any>,\n\t\teffectOptions?: EffectOptions\n\t): EffectCleanup\n\t/** Opaque flavor: bypasses deep-touch optimizations */\n\treadonly opaque: Effect\n\t/** Named flavor: assigns a debug name */\n\tnamed(name: string): Effect\n}\n\n/**\n * Creates a reactive effect that automatically re-runs when dependencies change\n * @param fn - The effect function that provides dependencies and may return a cleanup function or Promise\n * @param options - Options for effect execution\n * @returns A cleanup function to stop the effect\n */\nexport const effect: Effect = named(\n\teffectMarker.leave,\n\tflavored(\n\t\tfunction effect(\n\t\t\tfn: (access: EffectAccess) => EffectCloser | undefined | void | Promise<any>,\n\t\t\teffectOptions: EffectOptions = {}\n\t\t): EffectCleanup {\n\t\t\tif (effectOptions?.name) Object.defineProperty(fn, 'name', { value: effectOptions.name })\n\t\t\t// Use per-effect asyncMode or fall back to global option\n\t\t\tconst asyncMode = effectOptions?.asyncMode ?? options.asyncMode ?? 'cancel'\n\n\t\t\t// Create the effect function - naming it for debug\n\t\t\tconst runEffect: EffectTrigger = () => {\n\t\t\t\tconst node = getEffectNode(runEffect)\n\t\t\t\t// Clear previous dependencies\n\t\t\t\tif (node.cleanup) {\n\t\t\t\t\tconst prevCleanup = node.cleanup\n\t\t\t\t\tnode.cleanup = undefined\n\t\t\t\t\ttry {\n\t\t\t\t\t\tuntracked(() => prevCleanup(node.nextReason || { type: 'stopped' }))\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t// If we want to report them, we could use options.warn or similar\n\t\t\t\t\t\toptions.warn('Error during effect cleanup', error)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Handle async modes when effect is retriggered\n\t\t\t\tif (runningPromise) {\n\t\t\t\t\tif (asyncMode === 'cancel' && cancelPrevious) {\n\t\t\t\t\t\t// Cancel previous execution\n\t\t\t\t\t\tabort()\n\t\t\t\t\t\tcancelPrevious()\n\t\t\t\t\t\tcancelPrevious = null\n\t\t\t\t\t\trunningPromise = null\n\t\t\t\t\t} else if (asyncMode === 'ignore') {\n\t\t\t\t\t\t// Ignore new execution while async work is running\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\t// Note: 'queue' mode not yet implemented\n\t\t\t\t}\n\n\t\t\t\t// The effect has been stopped after having been planned\n\t\t\t\tif (effectStopped) return\n\n\t\t\t\tlet reactionCleanup: EffectCloser | undefined\n\t\t\t\tfunction cleanupReaction(reason?: CleanupReason) {\n\t\t\t\t\tconst toCleanup = reactionCleanup\n\t\t\t\t\treactionCleanup = undefined\n\t\t\t\t\ttoCleanup?.(reason)\n\t\t\t\t}\n\t\t\t\t// Set reaction reason for the upcoming run\n\t\t\t\taccess.reaction = node.nextReason || access.reaction\n\t\t\t\tnode.nextReason = undefined\n\n\t\t\t\toptionCall('enter', getRoot(fn))\n\t\t\t\toptionCall('effectRun', getRoot(fn), access.reaction)\n\t\t\t\tlet result: any\n\t\t\t\tlet caught = 0\n\n\t\t\t\t// Define bubbling thrower\n\t\t\t\tconst thrower: CatchFunction = (error: any) => {\n\t\t\t\t\tconst catches = node.catchers\n\t\t\t\t\tconst reason: CleanupReason = { type: 'error', error }\n\t\t\t\t\tif (catches)\n\t\t\t\t\t\twhile (caught < catches.length) {\n\t\t\t\t\t\t\tcleanupReaction(reason)\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\treactionCleanup = catches[caught](error) as EffectCloser\n\t\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t\t} catch (_e) {\n\t\t\t\t\t\t\t\tcaught++\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\tif (parent) {\n\t\t\t\t\t\tconst parentNode = getEffectNode(parent)\n\t\t\t\t\t\tif (parentNode.forwardThrow) parentNode.forwardThrow(error)\n\t\t\t\t\t\telse throw error\n\t\t\t\t\t} else throw error\n\t\t\t\t}\n\t\t\t\tnode.forwardThrow = thrower\n\n\t\t\t\tlet errorToThrow: Error | undefined\n\t\t\t\ttry {\n\t\t\t\t\tresult = tracked(named(effectMarker.enter, () => fn.call(null, access)))\n\t\t\t\t\taccess.reaction = true\n\t\t\t\t\toptionCall('leave', fn)\n\t\t\t\t\tif (\n\t\t\t\t\t\tresult &&\n\t\t\t\t\t\ttypeof result !== 'function' &&\n\t\t\t\t\t\t(typeof result !== 'object' || !('then' in result))\n\t\t\t\t\t)\n\t\t\t\t\t\tthrow new ReactiveError(`[reactive] Effect returned a non-function value: ${result}`)\n\t\t\t\t\t// Check if result is a Promise (async effect)\n\t\t\t\t\tif (result && typeof result === 'object' && typeof result.then === 'function') {\n\t\t\t\t\t\tconst originalPromise = result as Promise<any>\n\n\t\t\t\t\t\t// Create a cancellation promise that we can reject\n\t\t\t\t\t\tlet cancelReject: ((reason: any) => void) | null = null\n\t\t\t\t\t\tconst cancelPromise = new Promise<never>((_, reject) => {\n\t\t\t\t\t\t\tcancelReject = reject\n\t\t\t\t\t\t})\n\n\t\t\t\t\t\tconst cancelError = new ReactiveError(\n\t\t\t\t\t\t\t'[reactive] Effect canceled due to dependency change'\n\t\t\t\t\t\t)\n\n\t\t\t\t\t\t// Race between the actual promise and cancellation\n\t\t\t\t\t\t// If canceled, the race rejects, which will propagate through any promise chain\n\t\t\t\t\t\trunningPromise = Promise.race([originalPromise, cancelPromise])\n\n\t\t\t\t\t\t// Store the cancellation function\n\t\t\t\t\t\tcancelPrevious = () => {\n\t\t\t\t\t\t\tif (cancelReject) {\n\t\t\t\t\t\t\t\tcancelReject(cancelError)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Wrap the original promise chain so cancellation propagates\n\t\t\t\t\t\t// This ensures that when we cancel, the original promise's .catch() handlers are triggered\n\t\t\t\t\t\t// We do this by rejecting the race promise, which makes the original promise chain see the rejection\n\t\t\t\t\t\t// through the zone-wrapped .then()/.catch() handlers\n\t\t\t\t\t\trunningPromise = runningPromise.catch((error) => {\n\t\t\t\t\t\t\t// Propagate async errors to the effect's error handler\n\t\t\t\t\t\t\t// This ensures onEffectThrow handlers are triggered for async errors\n\t\t\t\t\t\t\tif (error !== cancelError) {\n\t\t\t\t\t\t\t\tthrower(error)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t// If thrower didn't throw (handled), we absorb the error.\n\t\t\t\t\t\t\t// If thrower threw (unhandled), it propagates as a new unhandled rejection, which is correct.\n\t\t\t\t\t\t})\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// Synchronous result - treat as cleanup function\n\t\t\t\t\t\treactionCleanup = result as undefined | EffectCloser\n\t\t\t\t\t}\n\t\t\t\t} catch (error) {\n\t\t\t\t\tdebugHooks.decorateError(error, runEffect)\n\t\t\t\t\t// catcher:self`\n\t\t\t\t\terrorToThrow = error\n\t\t\t\t}\n\n\t\t\t\t// Create cleanup function for next run\n\t\t\t\tnode.cleanup = (reason?: CleanupReason) => {\n\t\t\t\t\tnode.cleanup = undefined\n\t\t\t\t\tabort()\n\t\t\t\t\tcleanupReaction(reason)\n\t\t\t\t\tdelete node.catchers\n\t\t\t\t\t// Remove this effect from all reactive objects it's watching\n\t\t\t\t\tconst effectObjects = effectToReactiveObjects.get(runEffect)\n\t\t\t\t\tif (effectObjects) {\n\t\t\t\t\t\tfor (const reactiveObj of effectObjects) {\n\t\t\t\t\t\t\tconst objectWatchers = watchers.get(reactiveObj)\n\t\t\t\t\t\t\tif (objectWatchers) {\n\t\t\t\t\t\t\t\tfor (const [prop, deps] of objectWatchers.entries()) {\n\t\t\t\t\t\t\t\t\tdeps.delete(runEffect)\n\t\t\t\t\t\t\t\t\tif (deps.size === 0) objectWatchers.delete(prop)\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (objectWatchers.size === 0) watchers.delete(reactiveObj)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\teffectToReactiveObjects.delete(runEffect)\n\t\t\t\t\t}\n\t\t\t\t\t// Invoke all child stops (recursive via subEffectCleanup calling its own mainCleanup)\n\t\t\t\t\tconst children = node.children\n\t\t\t\t\tif (children) {\n\t\t\t\t\t\tconst childReason: CleanupReason = reason\n\t\t\t\t\t\t\t? reason.type === 'lineage'\n\t\t\t\t\t\t\t\t? reason\n\t\t\t\t\t\t\t\t: { type: 'lineage', parent: reason }\n\t\t\t\t\t\t\t: { type: 'stopped' }\n\t\t\t\t\t\tfor (const childCleanup of children) childCleanup(childReason)\n\t\t\t\t\t\tdelete node.children\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (errorToThrow) thrower(errorToThrow)\n\t\t\t}\n\n\t\t\t// Initialize metadata node\n\t\t\tconst node = getEffectNode(runEffect)\n\n\t\t\tif (debugHooks.isDevtoolsEnabled()) {\n\t\t\t\tconst stack = debugHooks.captureStack() // Robustly skips internal mutts frames\n\t\t\t\tif (Array.isArray(stack) && stack.length > 0) {\n\t\t\t\t\tnode.creationStack = stack\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst tracked = effectHistory.present.with(runEffect, () =>\n\t\t\t\tnamed(effectMarker.leave, effectAggregator.zoned)\n\t\t\t)\n\t\t\tconst ascended = named(effectMarker.leave, effectHistory.zoned)\n\t\t\tconst parent = effectHistory.present.active\n\t\t\t// Set parent relationship in node\n\t\t\tnode.parent = parent\n\n\t\t\t// let thrower: CatchFunction | undefined // Moved inside runEffect\n\t\t\tlet effectStopped = false\n\t\t\tlet abortController: AbortController | undefined\n\n\t\t\tconst access: EffectAccess = {\n\t\t\t\ttracked,\n\t\t\t\tascend: named(effectMarker.leave, (fn) =>\n\t\t\t\t\tascended(named(effectMarker.enter, () => fn.call(null)))\n\t\t\t\t),\n\t\t\t\t//named(effectMarker.enter, (fn) => ascended(fn)),\n\t\t\t\treaction: false,\n\t\t\t\tget signal() {\n\t\t\t\t\tif (!abortController) {\n\t\t\t\t\t\tabortController = new AbortController()\n\t\t\t\t\t}\n\t\t\t\t\treturn abortController.signal\n\t\t\t\t},\n\t\t\t}\n\t\t\tlet runningPromise: Promise<any> | null = null\n\t\t\tlet cancelPrevious: (() => void) | null = null\n\t\t\tif (effectOptions?.dependencyHook) node.dependencyHook = effectOptions.dependencyHook\n\t\t\t// Mark the runEffect callback with the original function as its root\n\t\t\tmarkWithRoot(runEffect, fn)\n\n\t\t\t// Register strict mode if enabled\n\t\t\tif (effectOptions?.opaque) {\n\t\t\t\tnode.isOpaque = true\n\t\t\t}\n\n\t\t\tif (debugHooks.isDevtoolsEnabled()) {\n\t\t\t\tdebugHooks.registerEffect(runEffect)\n\t\t\t}\n\n\t\t\t// Store parent relationship for hierarchy traversal - ALREADY DONE ABOVE via getEffectNode\n\n\t\t\tconst abort = () => {\n\t\t\t\tif (abortController) {\n\t\t\t\t\tabortController.abort(\n\t\t\t\t\t\tnew ReactiveError('[reactive] Effect aborted due to dependency change or stop')\n\t\t\t\t\t)\n\t\t\t\t\tabortController = undefined\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tbatch(runEffect, 'immediate')\n\t\t\t// Only ROOT effects are registered for GC cleanup and zone tracking\n\t\t\tconst isRootEffect = !parent\n\n\t\t\tconst stopEffect = (reason?: CleanupReason): void => {\n\t\t\t\tif (effectStopped) return\n\t\t\t\teffectStopped = true\n\t\t\t\tnode.stopped = true\n\t\t\t\t// Cancel any running async work\n\t\t\t\tabort()\n\t\t\t\tif (cancelPrevious) {\n\t\t\t\t\tcancelPrevious()\n\t\t\t\t\tcancelPrevious = null\n\t\t\t\t\trunningPromise = null\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tnode.cleanup?.(reason || { type: 'stopped' })\n\t\t\t\t} catch (error) {\n\t\t\t\t\t// Cleanup errors should basically be ignored or at least not stop the world\n\t\t\t\t\t// If we want to report them, we could use options.warn or similar\n\t\t\t\t\toptions.warn('Error during effect cleanup', error)\n\t\t\t\t}\n\t\t\t\t// Clean up dependency graph edges\n\t\t\t\tcleanupEffectFromGraph(runEffect)\n\t\t\t\tfr.unregister(stopEffect)\n\t\t\t}\n\t\t\tif (isRootEffect) {\n\t\t\t\tconst callIfCollected = (reason) => stopEffect(reason)\n\t\t\t\tfr.register(\n\t\t\t\t\tcallIfCollected,\n\t\t\t\t\t() => {\n\t\t\t\t\t\tstopEffect({ type: 'gc' })\n\t\t\t\t\t\toptionCall('garbageCollected', fn)\n\t\t\t\t\t},\n\t\t\t\t\tstopEffect\n\t\t\t\t)\n\t\t\t\treturn callIfCollected\n\t\t\t}\n\t\t\t// Register this effect to be stopped when the parent effect is cleaned up\n\t\t\tif (parent) {\n\t\t\t\tconst parentNode = getEffectNode(parent)\n\t\t\t\tif (!parentNode.children) {\n\t\t\t\t\tparentNode.children = new Set()\n\t\t\t\t}\n\t\t\t\tconst children = parentNode.children\n\n\t\t\t\tconst subEffectCleanup = (reason) => {\n\t\t\t\t\tchildren.delete(subEffectCleanup)\n\t\t\t\t\t// Execute this child effect cleanup (which triggers its own mainCleanup)\n\t\t\t\t\tstopEffect(reason)\n\t\t\t\t}\n\t\t\t\tchildren.add(subEffectCleanup)\n\t\t\t\treturn subEffectCleanup\n\t\t\t}\n\t\t\t// Should not be reachable given isRootEffect check, but for type safety\n\t\t\treturn (reason) => stopEffect(reason)\n\t\t},\n\t\t{\n\t\t\tget opaque() {\n\t\t\t\treturn flavorOptions(this, { opaque: true }, { name: 'opaque' })\n\t\t\t},\n\t\t\tnamed(name: string) {\n\t\t\t\treturn flavorOptions(this, { name }, { name: 'named' })\n\t\t\t},\n\t\t}\n\t)\n) as Effect\n\n/**\n * Executes a function without tracking dependencies but maintains parent cleanup relationship\n * Effects created inside will still be cleaned up when the parent effect is destroyed\n * @param fn - The function to execute\n */\nexport function untracked<T>(fn: () => T): T {\n\treturn effectHistory.present.root(fn)\n}\n\n/**\n * Executes a function from a virgin/root context - no parent effect, no tracking\n * Creates completely independent effects that won't be cleaned up by any parent\n * @param fn - The function to execute\n */\nexport function root<T>(fn: () => T): T {\n\treturn effectHistory.root(fn)\n}\n\n/**\n * Creates a bidirectional binding between a reactive value and a non-reactive external value\n * Prevents infinite loops by automatically suppressing circular notifications\n *\n * @param received - Function called when the reactive value changes (external setter)\n * @param get - Getter for the reactive value OR an object with `{ get, set }` properties\n * @param set - Setter for the reactive value (required if `get` is a function)\n * @returns A function to manually provide updates from the external side\n *\n * @example\n * ```typescript\n * const model = reactive({ value: '' })\n * const input = { value: '' }\n *\n * // Bidirectional binding\n * const provide = biDi(\n * (v) => input.value = v, // external setter\n * () => model.value, // reactive getter\n * (v) => model.value = v // reactive setter\n * )\n *\n * // External notification (e.g., from input event)\n * provide('new value') // Updates model.value, doesn't trigger circular loop\n * ```\n *\n * @example Using object syntax\n * ```typescript\n * const provide = biDi(\n * (v) => setHTMLValue(v),\n * { get: () => reactiveObj.value, set: (v) => reactiveObj.value = v }\n * )\n * ```\n */\nexport function biDi<T>(\n\treceived: (value: T) => void,\n\tvalue: { get: () => T; set: (value: T) => void }\n): (value: T) => void\nexport function biDi<T>(\n\treceived: (value: T) => void,\n\tget: () => T,\n\tset: (value: T) => void\n): (value: T) => void\nexport function biDi<T>(\n\treceived: (value: T) => void,\n\tget: (() => T) | { get: () => T; set: (value: T) => void },\n\tset?: (value: T) => void\n): (value: T) => void {\n\tif (typeof get !== 'function') {\n\t\tset = get.set\n\t\tget = get.get\n\t}\n\tlet programmaticallySetValue: any = Symbol()\n\teffect.named('biDi')(\n\t\tmarkWithRoot(() => {\n\t\t\tconst newValue = get()\n\t\t\tconst pValue = programmaticallySetValue\n\t\t\tprogrammaticallySetValue = Symbol()\n\t\t\tif (unwrap(newValue) !== pValue) received(newValue)\n\t\t}, received)\n\t)\n\treturn set\n\t\t? atomic((value: T) => {\n\t\t\t\tprogrammaticallySetValue = unwrap(value)\n\t\t\t\tset(value)\n\t\t\t})\n\t\t: () => {}\n}\n","import { debugHooks } from './debug-hooks'\nimport { batch } from './effects'\nimport { getEffectNode } from './registry'\nimport { getDependencyStack } from './tracking'\nimport { allProps, type EffectTrigger, type Evolution, options } from './types'\n\n// Track which objects contain which other objects (back-references)\nexport const objectParents = new WeakMap<object, Set<{ parent: object; prop: PropertyKey }>>()\n\n// Track which objects have deep watchers\nexport const objectsWithDeepWatchers = new WeakSet<object>()\nlet deepWatcherCount = 0\nexport function registerDeepWatcher() {\n\tdeepWatcherCount++\n}\n\n// Track deep watchers per object\nexport const deepWatchers = new WeakMap<object, Set<EffectTrigger>>()\n\n// Track which effects are doing deep watching\nexport const effectToDeepWatchedObjects = new WeakMap<EffectTrigger, Set<object>>()\n\n/**\n * Add a back-reference from child to parent\n */\nexport function addBackReference(child: object, parent: object, prop: any) {\n\tlet parents = objectParents.get(child)\n\tif (!parents) {\n\t\tparents = new Set()\n\t\tobjectParents.set(child, parents)\n\t}\n\tparents.add({ parent, prop })\n}\n\n/**\n * Remove a back-reference from child to parent\n */\nexport function removeBackReference(child: object, parent: object, prop: any) {\n\tconst parents = objectParents.get(child)\n\tif (parents) {\n\t\tfor (const entry of parents) {\n\t\t\tif (entry.parent === parent && entry.prop === prop) {\n\t\t\t\tparents.delete(entry)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif (parents.size === 0) {\n\t\t\tobjectParents.delete(child)\n\t\t}\n\t}\n}\n\n/**\n * Check if an object needs back-references (has deep watchers or parents with deep watchers)\n */\nexport function needsBackReferences(obj: object): boolean {\n\t// Fast path: if no deep watchers exist anywhere, skip entirely\n\tif (!deepWatcherCount) return false // fast path: no deep watchers anywhere\n\t// Check if object itself has deep watchers\n\tif (objectsWithDeepWatchers.has(obj)) return true\n\t// Slow path: check if any parent has deep watchers (recursive)\n\treturn hasParentWithDeepWatchers(obj)\n}\n\n/**\n * Bubble up changes through the back-reference chain\n */\nexport function bubbleUpChange(changedObject: object, evolution: Evolution) {\n\tconst parents = objectParents.get(changedObject)\n\tif (!parents) return\n\n\tfor (const { parent } of parents) {\n\t\t// Trigger deep watchers on parent\n\t\tconst parentDeepWatchers = deepWatchers.get(parent)\n\t\tif (parentDeepWatchers) {\n\t\t\tif (options.introspection?.gatherReasons) {\n\t\t\t\tconst gatherReasons = options.introspection.gatherReasons\n\t\t\t\tconst lineageConfig = gatherReasons.lineages\n\n\t\t\t\tlet touchLineage: unknown | undefined\n\t\t\t\tif (lineageConfig === 'touch' || lineageConfig === 'both') {\n\t\t\t\t\ttouchLineage = debugHooks.captureLineage()\n\t\t\t\t}\n\n\t\t\t\tfor (const watcher of parentDeepWatchers) {\n\t\t\t\t\tconst dependencyStack =\n\t\t\t\t\t\tlineageConfig === 'dependency' || lineageConfig === 'both'\n\t\t\t\t\t\t\t? getDependencyStack(watcher, parent, allProps)\n\t\t\t\t\t\t\t: undefined\n\n\t\t\t\t\tconst node = getEffectNode(watcher)\n\t\t\t\t\tif (!node.pendingTriggers) node.pendingTriggers = []\n\t\t\t\t\tnode.pendingTriggers.push({\n\t\t\t\t\t\tobj: parent,\n\t\t\t\t\t\tevolution,\n\t\t\t\t\t\tdependency: dependencyStack,\n\t\t\t\t\t\ttouch: touchLineage,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (const watcher of parentDeepWatchers) batch(watcher)\n\t\t}\n\n\t\t// Continue bubbling up\n\t\tbubbleUpChange(parent, evolution)\n\t}\n}\n\nfunction hasParentWithDeepWatchers(obj: object): boolean {\n\tconst parents = objectParents.get(obj)\n\tif (!parents) return false\n\n\tfor (const { parent } of parents) {\n\t\tif (objectsWithDeepWatchers.has(parent)) return true\n\t\tif (hasParentWithDeepWatchers(parent)) return true\n\t}\n\treturn false\n}\n","import { debugHooks } from './debug-hooks'\nimport { bubbleUpChange, objectsWithDeepWatchers } from './deep-watch-state'\nimport { getActiveEffect, isRunning } from './effect-context'\nimport { batch, hasBatched, recordActivation } from './effects'\nimport { getEffectNode, watchers } from './registry'\nimport { getDependencyStack } from './tracking'\nimport {\n\tallProps,\n\ttype EffectTrigger,\n\ttype Evolution,\n\tkeysOf,\n\toptionCall,\n\toptions,\n\ttype State,\n\tunwrap,\n} from './types'\n\nconst states = new WeakMap<object, State>()\n\nexport function addState(obj: any, evolution: Evolution) {\n\tobj = unwrap(obj)\n\tconst next = {}\n\tconst state = getState(obj)\n\tif (state) Object.assign(state, { evolution, next })\n\tstates.set(obj, next)\n}\n\n/**\n * Gets the current state of a reactive object for evolution tracking\n * @param obj - The reactive object\n * @returns The current state object\n */\nexport function getState(obj: any) {\n\tobj = unwrap(obj)\n\tlet state = states.get(obj)\n\tif (!state) {\n\t\tstate = {}\n\t\tstates.set(obj, state)\n\t}\n\treturn state\n}\n\nexport function collectEffects(\n\tobj: any,\n\tevolution: Evolution,\n\teffects: Map<EffectTrigger, unknown>,\n\tobjectWatchers: Map<any, Set<EffectTrigger>>,\n\t...keyChains: Iterable<any>[]\n) {\n\tconst sourceEffect = getActiveEffect()\n\tfor (const keys of keyChains)\n\t\tfor (const key of keys) {\n\t\t\tconst deps = objectWatchers.get(key)\n\t\t\tif (deps) {\n\t\t\t\t// Make sure `some.prop++` does not keep a dependency to `some.props`\n\t\t\t\tdeps.delete(sourceEffect)\n\t\t\t\tfor (const effect of deps) {\n\t\t\t\t\tconst runningChain = isRunning(effect)\n\t\t\t\t\tif (runningChain) {\n\t\t\t\t\t\toptionCall('skipRunningEffect', effect)\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tif (!effects.has(effect)) {\n\t\t\t\t\t\teffects.set(effect, getDependencyStack(effect, obj, key))\n\t\t\t\t\t\tif (!hasBatched(effect)) recordActivation(effect, obj, evolution, key)\n\t\t\t\t\t}\n\t\t\t\t\tdebugHooks.recordTriggerLink(sourceEffect, effect, obj, key, evolution)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n}\n\n/**\n * Triggers effects for a single property change\n * @param obj - The object that changed\n * @param evolution - The type of change\n * @param prop - The property that changed\n */\nexport function touched1(obj: any, evolution: Evolution, prop: any) {\n\ttouched(obj, evolution, [prop])\n}\n\n/**\n * Triggers effects for property changes\n * @param obj - The object that changed\n * @param evolution - The type of change\n * @param props - The properties that changed\n */\nexport function touched(obj: any, evolution: Evolution, props?: Iterable<any>) {\n\tobj = unwrap(obj)\n\taddState(obj, evolution)\n\tconst objectWatchers = watchers.get(obj)\n\tif (objectWatchers) {\n\t\t// Note: we have to collect effects to remove duplicates in the specific case when no batch is running\n\t\tconst effects = new Map<EffectTrigger, unknown>()\n\t\tconst structural = !['set', 'invalidate'].includes(evolution.type)\n\t\tconst broad = structural ? [allProps, keysOf] : [allProps]\n\t\tif (props) collectEffects(obj, evolution, effects, objectWatchers, broad, props)\n\t\telse collectEffects(obj, evolution, effects, objectWatchers, objectWatchers.keys())\n\t\tconst triggers = Array.from(effects.keys())\n\t\toptionCall('touched', obj, evolution, props as any[] | undefined, triggers)\n\t\t// Store pending triggers for CleanupReason before batching\n\t\tif (options.introspection?.gatherReasons) {\n\t\t\tconst gatherReasons = options.introspection.gatherReasons\n\t\t\tconst lineageConfig = gatherReasons.lineages\n\n\t\t\tlet touchLineage: unknown | undefined\n\t\t\tif (lineageConfig === 'touch' || lineageConfig === 'both') {\n\t\t\t\ttouchLineage = debugHooks.captureLineage()\n\t\t\t}\n\n\t\t\tfor (const [effect, dependencyStack] of effects) {\n\t\t\t\tconst node = getEffectNode(effect)\n\t\t\t\tif (!node.pendingTriggers) node.pendingTriggers = []\n\t\t\t\tnode.pendingTriggers.push({\n\t\t\t\t\tobj,\n\t\t\t\t\tevolution,\n\t\t\t\t\tdependency: dependencyStack,\n\t\t\t\t\ttouch: touchLineage,\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t\tbatch(triggers)\n\t}\n\n\t// Bubble up changes if this object has deep watchers\n\tif (objectsWithDeepWatchers.has(obj)) {\n\t\tbubbleUpChange(obj, evolution)\n\t}\n}\n\n/**\n * Triggers only opaque effects for property changes\n * Used by deep-touch to ensure opaque listeners are notified even when deep optimization is active\n */\nexport function touchedOpaque(obj: any, evolution: Evolution, prop: any) {\n\tobj = unwrap(obj)\n\tconst objectWatchers = watchers.get(obj)\n\tif (!objectWatchers) return\n\n\tconst deps = objectWatchers.get(prop)\n\tif (!deps) return\n\n\tconst effects = new Set<EffectTrigger>()\n\tconst sourceEffect = getActiveEffect()\n\n\tconst gather = options.introspection?.gatherReasons\n\n\tif (gather) {\n\t\tconst lineageConfig = gather.lineages\n\n\t\tfor (const effect of deps) {\n\t\t\tconst node = getEffectNode(effect)\n\t\t\tif (!node.isOpaque) continue\n\n\t\t\tconst runningChain = isRunning(effect)\n\t\t\tif (runningChain) {\n\t\t\t\toptionCall('skipRunningEffect', effect)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\teffects.add(effect)\n\t\t\tif (gather) {\n\t\t\t\tlet touchLineage: unknown | undefined\n\t\t\t\tlet dependencyStack: unknown | undefined\n\n\t\t\t\tif (lineageConfig === 'touch' || lineageConfig === 'both') {\n\t\t\t\t\ttouchLineage = debugHooks.captureLineage()\n\t\t\t\t}\n\t\t\t\tif (lineageConfig === 'dependency' || lineageConfig === 'both') {\n\t\t\t\t\tdependencyStack = getDependencyStack(effect, obj, prop)\n\t\t\t\t}\n\n\t\t\t\tif (!node.pendingTriggers) node.pendingTriggers = []\n\t\t\t\tnode.pendingTriggers.push({\n\t\t\t\t\tobj,\n\t\t\t\t\tevolution,\n\t\t\t\t\tdependency: dependencyStack,\n\t\t\t\t\ttouch: touchLineage,\n\t\t\t\t})\n\t\t\t}\n\t\t\trecordActivation(effect, obj, evolution, prop)\n\t\t\tdebugHooks.recordTriggerLink(sourceEffect, effect, obj, prop, evolution)\n\t\t}\n\t} else {\n\t\t// When not gathering reasons, process effects normally\n\t\tfor (const effect of deps) {\n\t\t\tconst node = getEffectNode(effect)\n\t\t\tif (!node.isOpaque) continue\n\n\t\t\tconst runningChain = isRunning(effect)\n\t\t\tif (runningChain) {\n\t\t\t\toptionCall('skipRunningEffect', effect)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\teffects.add(effect)\n\t\t\trecordActivation(effect, obj, evolution, prop)\n\t\t\tdebugHooks.recordTriggerLink(sourceEffect, effect, obj, prop, evolution)\n\t\t}\n\t}\n\n\tif (effects.size > 0) {\n\t\toptionCall('touched', obj, evolution, [prop], Array.from(effects))\n\t\tbatch(Array.from(effects))\n\t}\n}\n","import { unreactiveProperties } from './types'\nexport const absent = Symbol('absent')\n\n/**\n * Add unreactive properties to a prototype.\n * If no set is provided, marks the entire object/prototype as non-reactive (sets [unreactiveProperties] = true).\n * If a set is provided, merges with existing unreactive properties (never overrides true).\n */\nexport function addUnreactiveProps<T extends object>(proto: T, set?: Iterable<PropertyKey>): T {\n\tif (unreactiveProperties in proto) {\n\t\tconst existing = (proto as any)[unreactiveProperties]\n\t\t// If already fully unreactive, don't change\n\t\tif (existing === true) return proto\n\t\t// If no set provided, upgrade to fully unreactive\n\t\tif (!set) {\n\t\t\t;(proto as any)[unreactiveProperties] = true\n\t\t\treturn proto\n\t\t}\n\t\t// Merge sets\n\t\tset = (proto as any)[unreactiveProperties] = new Set<PropertyKey>(\n\t\t\t(proto as any)[unreactiveProperties]\n\t\t)\n\t\tfor (const p of set) existing.add(p)\n\t}\n\t// If no set, mark as fully unreactive, otherwise create set\n\telse proto[unreactiveProperties] = set ? new Set<PropertyKey>(set) : true\n\treturn proto\n}\n\n/** Check if a property is marked unreactive on obj or any of its prototypes (trap-free) */\nexport function isUnreactiveProp(obj: object, prop: PropertyKey): boolean {\n\tif (typeof prop === 'symbol' || prop === 'constructor') return true\n\tconst marker = obj[unreactiveProperties]\n\treturn (\n\t\tmarker === true || // Fully unreactive\n\t\tmarker?.has?.(prop) || // Property is unreactive\n\t\tfalse\n\t)\n}\n\nexport function nonReactive<T extends object[]>(...obj: T): T[0] {\n\tfor (const o of obj) {\n\t\t;(o as any)[unreactiveProperties] = true\n\t}\n\treturn obj[0]\n}\n\nexport function nonReactiveClass<T extends (new (...args: any[]) => any)[]>(...cls: T): T[0] {\n\tfor (const c of cls) if (c) (c.prototype as any)[unreactiveProperties] = true\n\treturn cls[0]\n}\n\nexport function isNonReactive(obj: any): boolean {\n\treturn !obj || obj[unreactiveProperties] === true\n}\n\nnonReactiveClass(Date, RegExp, Error, Promise, Function)\nif (typeof window !== 'undefined') {\n\tnonReactive(window, document)\n\tnonReactiveClass(Node, Element, HTMLElement, EventTarget, HTMLCollection, NodeList)\n}\n","import { addState, collectEffects, touched1, touchedOpaque } from './change'\nimport { debugHooks } from './debug-hooks'\nimport { bubbleUpChange, objectsWithDeepWatchers } from './deep-watch-state'\nimport { batch, untracked } from './effects'\nimport { isNonReactive } from './non-reactive'\nimport { effectToReactiveObjects, getEffectNode, watchers } from './registry'\nimport { getDependencyStack } from './tracking'\nimport {\n\tallProps,\n\ttype EffectCleanup,\n\ttype EffectTrigger,\n\ttype Evolution,\n\tkeysOf,\n\toptionCall,\n\toptions,\n\tunwrap,\n} from './types'\n\nfunction getPrototypeToken(value: any): object | null | undefined {\n\tif (Array.isArray(value)) return Array.prototype\n\tif (typeof value !== 'object') return undefined\n\ttry {\n\t\treturn value.constructor\n\t} catch {\n\t\treturn undefined\n\t}\n}\n\nexport function shouldRecurseTouch(oldValue: any, newValue: any): boolean {\n\tif (oldValue === newValue) return false\n\tif (\n\t\t(typeof oldValue !== 'object' && !Array.isArray(oldValue)) ||\n\t\t(typeof newValue !== 'object' && !Array.isArray(newValue))\n\t)\n\t\treturn false\n\tif (isNonReactive(oldValue) /*|| isNonReactive(newValue)*/) return false\n\treturn getPrototypeToken(oldValue) === getPrototypeToken(newValue)\n}\n\n/**\n * Migrate all watcher registrations from oldRef to newRef.\n * Called when deep touch replaces an object identity without any child value differences,\n * to prevent watcher orphaning (effects still pointing at the discarded old object).\n */\nfunction migrateWatchers(oldRef: object, newRef: object) {\n\tconst oldMap = watchers.get(oldRef)\n\tif (!oldMap) return\n\t// Move the entire watcher map\n\twatchers.set(newRef, oldMap)\n\twatchers.delete(oldRef)\n\t// Update the reverse map (effect → objects it watches)\n\tfor (const deps of oldMap.values()) {\n\t\tfor (const effect of deps) {\n\t\t\tconst objects = effectToReactiveObjects.get(effect)\n\t\t\tif (objects) {\n\t\t\t\tobjects.delete(oldRef)\n\t\t\t\tobjects.add(newRef)\n\t\t\t}\n\t\t}\n\t}\n}\n\n/**\n * Centralized function to handle property change notifications with optional recursive touch\n * @param targetObj - The object whose property changed\n * @param prop - The property that changed\n * @param oldValue - The old value (before change)\n * @param newValue - The new value (after change)\n * @param hadProperty - Whether the property existed before (for add vs set)\n */\nexport function notifyPropertyChange(\n\ttargetObj: any,\n\tprop: any,\n\toldValue: any,\n\tnewValue: any,\n\thadProperty: boolean\n) {\n\tconst evolution: Evolution = { type: hadProperty ? 'set' : 'add', prop }\n\n\tif (\n\t\toptions.recursiveTouching &&\n\t\toldValue !== undefined &&\n\t\tshouldRecurseTouch(oldValue, newValue)\n\t) {\n\t\tconst unwrappedObj = unwrap(targetObj)\n\t\tconst origin = { obj: unwrappedObj, prop }\n\t\t// Deep touch: only notify nested property changes with origin filtering\n\t\t// Don't notify direct property change - the whole point is to avoid parent effects re-running\n\n\t\tconst changes = untracked(() => recursiveTouch(oldValue, newValue, new WeakMap(), [], origin))\n\n\t\t// When deep touch found no child differences, the object identity still changed.\n\t\t// Migrate watchers from old → new so the dependency chain is preserved.\n\t\tif (changes.length === 0) {\n\t\t\tmigrateWatchers(unwrap(oldValue), unwrap(newValue))\n\t\t} else {\n\t\t\tdispatchNotifications(changes)\n\t\t}\n\n\t\t// Notify opaque listeners (like memoize) that always want to know about identity changes\n\t\ttouchedOpaque(targetObj, evolution, prop)\n\t} else {\n\t\ttouched1(targetObj, evolution, prop)\n\t}\n}\n\ntype VisitedPairs = WeakMap<object, WeakSet<object>>\ntype PendingNotification = {\n\ttarget: any\n\tevolution: Evolution\n\tprop: any\n\torigin?: { obj: object; prop: PropertyKey } // The property access that triggered this deep touch\n}\n\nfunction hasVisitedPair(visited: VisitedPairs, oldObj: object, newObj: object): boolean {\n\tlet mapped = visited.get(oldObj)\n\tif (!mapped) {\n\t\tmapped = new WeakSet<object>()\n\t\tvisited.set(oldObj, mapped)\n\t}\n\tif (mapped.has(newObj)) return true\n\tmapped.add(newObj)\n\treturn false\n}\n\nfunction collectObjectKeys(obj: any): Set<PropertyKey> {\n\tconst keys = new Set<PropertyKey>(Reflect.ownKeys(obj))\n\tlet proto = Object.getPrototypeOf(obj)\n\t// Continue walking while prototype exists and doesn't have its own constructor\n\t// This stops at Object.prototype (has own constructor) and class prototypes (have own constructor)\n\t// but continues for data prototypes (Object.create({}), Object.create(instance), etc.)\n\twhile (proto && !Object.hasOwn(proto, 'constructor')) {\n\t\tfor (const key of Reflect.ownKeys(proto)) keys.add(key)\n\t\tproto = Object.getPrototypeOf(proto)\n\t}\n\treturn keys\n}\n\nexport function recursiveTouch(\n\toldValue: any,\n\tnewValue: any,\n\tvisited: VisitedPairs = new WeakMap(),\n\tnotifications: PendingNotification[] = [],\n\torigin?: { obj: object; prop: PropertyKey }\n): PendingNotification[] {\n\tif (!shouldRecurseTouch(oldValue, newValue)) return notifications\n\tif (\n\t\t(typeof oldValue !== 'object' && !Array.isArray(oldValue)) ||\n\t\t(typeof newValue !== 'object' && !Array.isArray(newValue))\n\t)\n\t\treturn notifications\n\tif (hasVisitedPair(visited, oldValue, newValue)) return notifications\n\n\tif (Array.isArray(oldValue) && Array.isArray(newValue)) {\n\t\tdiffArrayElements(oldValue, newValue, visited, notifications, origin)\n\t\treturn notifications\n\t}\n\n\tdiffObjectProperties(oldValue, newValue, visited, notifications, origin)\n\treturn notifications\n}\n\nfunction diffArrayElements(\n\toldArray: any[] | readonly any[],\n\tnewArray: any[] | readonly any[],\n\t_visited: VisitedPairs,\n\tnotifications: PendingNotification[],\n\torigin?: { obj: object; prop: PropertyKey }\n) {\n\tconst local: PendingNotification[] = []\n\tconst oldLength = oldArray.length\n\tconst newLength = newArray.length\n\tconst max = Math.max(oldLength, newLength)\n\n\tfor (let index = 0; index < max; index++) {\n\t\tconst hasOld = index < oldLength\n\t\tconst hasNew = index < newLength\n\t\tif (hasOld && !hasNew) {\n\t\t\tlocal.push({ target: oldArray, evolution: { type: 'del', prop: index }, prop: index, origin })\n\t\t\tcontinue\n\t\t}\n\t\tif (!hasOld && hasNew) {\n\t\t\tlocal.push({ target: oldArray, evolution: { type: 'add', prop: index }, prop: index, origin })\n\t\t\tcontinue\n\t\t}\n\t\tif (!hasOld || !hasNew) continue\n\t\tconst oldEntry = unwrap(oldArray[index])\n\t\tconst newEntry = unwrap(newArray[index])\n\t\tif (!Object.is(oldEntry, newEntry)) {\n\t\t\tlocal.push({ target: oldArray, evolution: { type: 'set', prop: index }, prop: index, origin })\n\t\t}\n\t}\n\n\tif (oldLength !== newLength)\n\t\tlocal.push({\n\t\t\ttarget: oldArray,\n\t\t\tevolution: { type: 'set', prop: 'length' },\n\t\t\tprop: 'length',\n\t\t\torigin,\n\t\t})\n\n\tnotifications.push(...local)\n}\n\nfunction diffObjectProperties(\n\toldObj: any,\n\tnewObj: any,\n\tvisited: VisitedPairs,\n\tnotifications: PendingNotification[],\n\torigin?: { obj: object; prop: PropertyKey }\n) {\n\tconst oldKeys = collectObjectKeys(oldObj)\n\tconst newKeys = collectObjectKeys(newObj)\n\tconst local: PendingNotification[] = []\n\n\tfor (const key of oldKeys)\n\t\tif (!newKeys.has(key))\n\t\t\tlocal.push({ target: oldObj, evolution: { type: 'del', prop: key }, prop: key, origin })\n\n\tfor (const key of newKeys) {\n\t\tif (!oldKeys.has(key)) {\n\t\t\tlocal.push({ target: oldObj, evolution: { type: 'add', prop: key }, prop: key, origin })\n\t\t\tcontinue\n\t\t}\n\t\tconst oldEntry = unwrap((oldObj as any)[key])\n\t\tconst newEntry = unwrap((newObj as any)[key])\n\t\tif (shouldRecurseTouch(oldEntry, newEntry)) {\n\t\t\trecursiveTouch(oldEntry, newEntry, visited, notifications, origin)\n\t\t} else if (!Object.is(oldEntry, newEntry)) {\n\t\t\tlocal.push({ target: oldObj, evolution: { type: 'set', prop: key }, prop: key, origin })\n\t\t}\n\t}\n\n\tnotifications.push(...local)\n}\n\n/**\n * Checks if an effect or any of its ancestors is in the allowed set\n */\nfunction hasAncestorInSet(\n\teffect: EffectTrigger | EffectCleanup,\n\tallowedSet: Set<EffectTrigger | EffectCleanup>\n): boolean {\n\tlet current: EffectTrigger | EffectCleanup | undefined = effect\n\tconst visited = new WeakSet<EffectTrigger | EffectCleanup>()\n\twhile (current && !visited.has(current)) {\n\t\tvisited.add(current)\n\t\tif (allowedSet.has(current)) return true\n\t\tconst node = getEffectNode(current as EffectTrigger)\n\t\tcurrent = node.parent\n\t}\n\treturn false\n}\n\nexport function dispatchNotifications(notifications: PendingNotification[]) {\n\tif (!notifications.length) return\n\tconst combinedEffects = new Set<EffectTrigger>()\n\tconst effectCauses = new Map<EffectTrigger, PendingNotification[]>()\n\n\t// Extract origin from first notification (all should have the same origin from a single deep touch)\n\tconst origin = notifications[0]?.origin\n\tlet allowedEffects: Set<EffectTrigger> | undefined\n\n\t// If origin exists, compute allowed effects (those that depend on origin.obj[origin.prop])\n\tif (origin) {\n\t\tallowedEffects = new Set<EffectTrigger>()\n\t\tconst originWatchers = watchers.get(origin.obj)\n\t\tif (originWatchers) {\n\t\t\tconst originEffects = new Map<EffectTrigger, unknown>()\n\t\t\tcollectEffects(\n\t\t\t\torigin.obj,\n\t\t\t\t{ type: 'set', prop: origin.prop },\n\t\t\t\toriginEffects,\n\t\t\t\toriginWatchers,\n\t\t\t\t[allProps],\n\t\t\t\t[origin.prop]\n\t\t\t)\n\t\t\tallowedEffects = new Set(originEffects.keys())\n\t\t}\n\t\t// If no allowed effects, skip all notifications (no one should be notified)\n\t\tif (!allowedEffects?.size) return\n\t}\n\n\tfor (const notification of notifications) {\n\t\tconst { target, evolution, prop } = notification\n\t\tif (typeof target !== 'object' && !Array.isArray(target)) continue\n\t\tconst obj = unwrap(target)\n\t\taddState(obj, evolution)\n\t\tconst objectWatchers = watchers.get(obj)\n\t\tlet currentEffects: Map<EffectTrigger, unknown> | undefined\n\t\tconst propsArray = [prop]\n\t\tif (objectWatchers) {\n\t\t\tcurrentEffects = new Map<EffectTrigger, unknown>()\n\t\t\tconst broad = evolution.type !== 'set' ? [allProps, keysOf] : [allProps]\n\t\t\tcollectEffects(obj, evolution, currentEffects, objectWatchers, broad, propsArray)\n\n\t\t\t// Filter effects by ancestor chain if origin exists\n\t\t\t// Include effects that either directly depend on origin or have an ancestor that does\n\t\t\tif (origin && allowedEffects) {\n\t\t\t\tconst filteredEffects = new Map<EffectTrigger, unknown>()\n\t\t\t\tfor (const [effect, associated] of currentEffects) {\n\t\t\t\t\t// Check if effect itself is allowed OR has an ancestor that is allowed\n\t\t\t\t\tif (allowedEffects.has(effect) || hasAncestorInSet(effect, allowedEffects)) {\n\t\t\t\t\t\tfilteredEffects.set(effect, associated)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcurrentEffects = filteredEffects\n\t\t\t}\n\n\t\t\tfor (const effect of currentEffects.keys()) {\n\t\t\t\tcombinedEffects.add(effect)\n\t\t\t\tlet causes = effectCauses.get(effect)\n\t\t\t\tif (!causes) {\n\t\t\t\t\tcauses = []\n\t\t\t\t\teffectCauses.set(effect, causes)\n\t\t\t\t}\n\t\t\t\tcauses.push(notification)\n\t\t\t}\n\t\t}\n\t\tif (currentEffects) {\n\t\t\toptionCall('touched', obj, evolution, propsArray, Array.from(currentEffects.keys()))\n\t\t}\n\t\tif (objectsWithDeepWatchers.has(obj)) bubbleUpChange(obj, evolution)\n\t}\n\tif (combinedEffects.size) {\n\t\tif (options.introspection?.gatherReasons) {\n\t\t\tconst gatherReasons = options.introspection.gatherReasons\n\t\t\tconst lineageConfig = gatherReasons.lineages\n\n\t\t\tlet touchLineage: unknown | undefined\n\t\t\tif (lineageConfig === 'touch' || lineageConfig === 'both') {\n\t\t\t\ttouchLineage = debugHooks.captureLineage()\n\t\t\t}\n\n\t\t\tfor (const effect of combinedEffects) {\n\t\t\t\tconst node = getEffectNode(effect)\n\t\t\t\tif (!node.pendingTriggers) node.pendingTriggers = []\n\t\t\t\tfor (const { target, evolution, prop } of effectCauses.get(effect)!) {\n\t\t\t\t\tconst dependencyStack =\n\t\t\t\t\t\tlineageConfig === 'dependency' || lineageConfig === 'both'\n\t\t\t\t\t\t\t? getDependencyStack(effect, unwrap(target), prop ?? allProps)\n\t\t\t\t\t\t\t: undefined\n\t\t\t\t\tnode.pendingTriggers.push({\n\t\t\t\t\t\tobj: unwrap(target),\n\t\t\t\t\t\tevolution,\n\t\t\t\t\t\tdependency: dependencyStack,\n\t\t\t\t\t\ttouch: touchLineage,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tbatch([...combinedEffects])\n\t}\n}\n","import { decorator } from '../decorator'\nimport { mixin } from '../mixins'\nimport { FoolProof, isOwnAccessor } from '../utils'\nimport { touched1 } from './change'\nimport { notifyPropertyChange } from './deep-touch'\nimport {\n\taddBackReference,\n\tbubbleUpChange,\n\tneedsBackReferences,\n\tobjectsWithDeepWatchers,\n\tremoveBackReference,\n} from './deep-watch-state'\nimport { absent, isNonReactive, isUnreactiveProp } from './non-reactive'\nimport { dependant } from './tracking'\nimport {\n\tgetExistingProxy,\n\tisReactive,\n\tkeysOf,\n\toptions,\n\tproxyToObject,\n\tReactiveError,\n\tReactiveErrorCode,\n\tstoreProxyRelationship,\n\tunwrap,\n} from './types'\nexport const metaProtos = new WeakMap()\nexport const wrapProtos = new WeakMap()\nconst arrayLengths = new WeakMap<unknown[], number>()\nconst hasReentry = new Set<PropertyKey>()\nexport type SubProxy = {\n\tget?(obj: any, prop: PropertyKey, receiver: any): any\n\thas?(obj: any, prop: PropertyKey): boolean\n\townKeys?(obj: any): ArrayLike<string | symbol>\n\tgetOwnPropertyDescriptor?(obj: any, prop: PropertyKey): PropertyDescriptor | undefined\n}\n// Sub-proxy registration for custom reactive behaviors\nconst subsRegister = new WeakMap<any, SubProxy>()\n// Internal untracked flag for setter/getter operations - only used when testing oldValue while setting a value\n// TODO: `touched` trigger also compares to old value and should use the internalUntracked flag\nlet internalUntracked = false\n\nconst reactiveHandlers: ProxyHandler<any> & Record<symbol, unknown> = {\n\t[Symbol.toStringTag]: 'MutTs Reactive',\n\tget(obj, prop, receiver) {\n\t\tif (internalUntracked) return FoolProof.get(obj, prop, receiver)\n\t\tif (obj && typeof obj === 'object' && prop !== Symbol.toStringTag) {\n\t\t\tconst metaProto = metaProtos.get(obj.constructor)\n\t\t\tif (metaProto && Object.hasOwn(metaProto, prop)) {\n\t\t\t\tconst desc = Object.getOwnPropertyDescriptor(metaProto, prop)!\n\t\t\t\tif (desc.get) {\n\t\t\t\t\tif (!Object.hasOwn(obj, prop)) return desc.get.call(obj)\n\t\t\t\t\t// For own properties (e.g., array length): only override if writable/configurable\n\t\t\t\t\tconst ownDesc = Object.getOwnPropertyDescriptor(obj, prop)!\n\t\t\t\t\tif (ownDesc.configurable || ownDesc.writable || ownDesc.get) return desc.get.call(obj)\n\t\t\t\t} else if (!Object.hasOwn(obj, prop)) return (...args: any[]) => desc.value.apply(obj, args)\n\t\t\t}\n\t\t\tconst wrapProto = wrapProtos.get(obj.constructor)\n\t\t\tif (wrapProto && Object.hasOwn(wrapProto, prop)) return wrapProto[prop]\n\t\t}\n\t\t// Symbols: fast-path — no reactivity tracking\n\t\tif (typeof prop === 'symbol' || prop === 'constructor' || isUnreactiveProp(obj, prop))\n\t\t\treturn FoolProof.get(obj, prop, receiver)\n\n\t\t// Check if property exists using a trap-free walk to avoid triggering\n\t\t// the has-trap cascade on prototype chains of reactive proxies.\n\t\tconst isOwnProp = Object.hasOwn(obj, prop)\n\n\t\t// For accessor properties, check the unwrapped object to see if it's an accessor\n\t\t// This ensures ignoreAccessors works correctly even after operations like Object.setPrototypeOf\n\t\t// Skip for null-proto objects (pounce scopes) — they never have accessors\n\t\tconst shouldIgnoreAccessor =\n\t\t\toptions.ignoreAccessors &&\n\t\t\tisOwnProp &&\n\t\t\tObject.getPrototypeOf(obj) !== null &&\n\t\t\t(isOwnAccessor(receiver, prop) || isOwnAccessor(obj, prop))\n\n\t\t// Check if property exists using a trap-free walk to avoid triggering\n\t\t// the has-trap cascade on prototype chains of reactive proxies.\n\t\tlet hasProp = isOwnProp\n\t\tlet owner: any = isOwnProp ? obj : undefined\n\t\tif (!isOwnProp) {\n\t\t\tlet raw = Object.getPrototypeOf(obj)\n\t\t\twhile (raw && raw !== Object.prototype) {\n\t\t\t\tif (Object.hasOwn(raw, prop)) {\n\t\t\t\t\thasProp = true\n\t\t\t\t\towner = raw\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\traw = Object.getPrototypeOf(raw)\n\t\t\t}\n\t\t}\n\t\tconst isInheritedAccess = hasProp && !isOwnProp\n\n\t\t// Depend if...\n\t\tif (\n\t\t\t!hasProp ||\n\t\t\t(!(options.instanceMembers && isInheritedAccess && obj instanceof Object) &&\n\t\t\t\t!shouldIgnoreAccessor)\n\t\t)\n\t\t\tdependant(obj, prop)\n\n\t\t// Two-Point Tracking: for inherited access on null-proto chains, also track\n\t\t// the owning ancestor so that writing directly to it triggers dependent effects.\n\t\tif (isInheritedAccess && owner && (!options.instanceMembers || !(obj instanceof Object))) {\n\t\t\tdependant(owner, prop)\n\t\t}\n\t\t// For arrays, use FoolProof.get (Indexer path) for numeric index reactivity.\n\t\t// For all other objects, inline Reflect.get directly (skips 3 function calls).\n\t\tconst value = (subsRegister.get(obj)?.get || FoolProof.get)(obj, prop, receiver)\n\t\tif (!isReactive(value) && typeof value === 'object' && value !== null) {\n\t\t\tconst reactiveValue = reactiveObject(value)\n\n\t\t\t// Only create back-references if this object needs them\n\t\t\tif (needsBackReferences(obj)) {\n\t\t\t\taddBackReference(reactiveValue, obj, prop)\n\t\t\t}\n\n\t\t\treturn reactiveValue\n\t\t}\n\t\treturn value\n\t},\n\tset(obj, prop, value, receiver) {\n\t\tconst unwrapped = unwrap(receiver)\n\t\tif (obj !== unwrapped)\n\t\t\treturn Object.defineProperty(unwrapped, prop, {\n\t\t\t\tvalue,\n\t\t\t\tconfigurable: true,\n\t\t\t\twritable: true,\n\t\t\t\tenumerable: true,\n\t\t\t})\n\t\tif (internalUntracked)\n\t\t\tthrow new Error('Internal untracked: setting a value in an getter in a set operation')\n\t\t//return FoolProof.set(obj, prop, value, receiver)\n\n\t\t// Check if this property is marked as unreactive\n\t\tif (isUnreactiveProp(obj, prop)) return FoolProof.set(obj, prop, value, receiver)\n\t\tconst newValue = unwrap(value)\n\t\t// metaProto setter dispatch (e.g., reactive array length)\n\t\tif (obj && typeof obj === 'object' && prop !== Symbol.toStringTag) {\n\t\t\tconst metaProto = obj.constructor && metaProtos.get(obj.constructor)\n\t\t\tif (metaProto && Object.hasOwn(metaProto, prop)) {\n\t\t\t\tconst desc = Object.getOwnPropertyDescriptor(metaProto, prop)!\n\t\t\t\tif (desc.set) {\n\t\t\t\t\tdesc.set.call(obj, newValue)\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// Read old value, using withEffect(undefined, ...) for getter-only accessors to avoid\n\t\t// breaking memoization dependency tracking during SET operations\n\t\tlet oldVal = absent\n\t\tconst isArrayLength = prop === 'length' && Array.isArray(obj)\n\t\tinternalUntracked = true\n\t\ttry {\n\t\t\tif (Reflect.has(obj, prop)) {\n\t\t\t\toldVal = isArrayLength\n\t\t\t\t\t? arrayLengths.get(obj) === newValue\n\t\t\t\t\t\t? newValue\n\t\t\t\t\t\t: absent\n\t\t\t\t\t: Reflect.get(obj, prop, receiver)\n\t\t\t}\n\t\t} finally {\n\t\t\tinternalUntracked = false\n\t\t}\n\t\tif (objectsWithDeepWatchers.has(obj)) {\n\t\t\tif (typeof oldVal === 'object' && oldVal !== null) {\n\t\t\t\tremoveBackReference(oldVal, obj, prop)\n\t\t\t}\n\t\t\tif (typeof newValue === 'object' && newValue !== null) {\n\t\t\t\tconst reactiveValue = reactiveObject(newValue)\n\t\t\t\taddBackReference(reactiveValue, obj, prop)\n\t\t\t}\n\t\t}\n\t\tif (oldVal !== newValue) {\n\t\t\t// For getter-only accessors, Reflect.set() may fail, but we still return true\n\t\t\t// to avoid throwing errors. Only proceed with change notifications if set succeeded.\n\t\t\tif (FoolProof.set(obj, prop, newValue, receiver)) {\n\t\t\t\tif (isArrayLength) arrayLengths.set(obj, newValue)\n\t\t\t\tnotifyPropertyChange(obj, prop, oldVal, newValue, oldVal !== absent)\n\t\t\t}\n\t\t}\n\t\treturn true\n\t},\n\thas(obj, prop) {\n\t\tif (hasReentry.has(obj))\n\t\t\tthrow new ReactiveError(\n\t\t\t\t`[reactive] Circular dependency detected in 'has' check for property '${String(prop)}'`,\n\t\t\t\t{\n\t\t\t\t\tcode: ReactiveErrorCode.CycleDetected,\n\t\t\t\t\tcycle: [], // We don't have the full cycle here, but we know it involves obj\n\t\t\t\t}\n\t\t\t)\n\t\thasReentry.add(obj)\n\t\tif (!internalUntracked && !isUnreactiveProp(obj, prop)) dependant(obj, prop)\n\t\tconst rv = (subsRegister.get(obj)?.has || Reflect.has)(obj, prop)\n\t\thasReentry.delete(obj)\n\t\treturn rv\n\t},\n\tdeleteProperty(obj, prop) {\n\t\tif (!Object.hasOwn(obj, prop)) return false\n\n\t\tconst oldVal = (obj as any)[prop]\n\n\t\t// Remove back-references if this object has deep watchers\n\t\tif (objectsWithDeepWatchers.has(obj) && typeof oldVal === 'object' && oldVal !== null) {\n\t\t\tremoveBackReference(oldVal, obj, prop)\n\t\t}\n\n\t\tdelete (obj as any)[prop]\n\t\ttouched1(obj, { type: 'del', prop }, prop)\n\n\t\t// Bubble up changes if this object has deep watchers\n\t\tif (objectsWithDeepWatchers.has(obj)) {\n\t\t\tbubbleUpChange(obj, { type: 'del', prop })\n\t\t}\n\n\t\treturn true\n\t},\n\townKeys(obj) {\n\t\tdependant(obj, keysOf)\n\t\treturn subsRegister.get(obj)?.ownKeys?.(obj) || Reflect.ownKeys(obj)\n\t},\n\tgetOwnPropertyDescriptor(obj, prop) {\n\t\treturn (\n\t\t\tsubsRegister.get(obj)?.getOwnPropertyDescriptor?.(obj, prop) ||\n\t\t\tReflect.getOwnPropertyDescriptor(obj, prop)\n\t\t)\n\t},\n}\n\nconst reactiveClasses = new WeakSet<Function>()\n\n// Create the ReactiveBase mixin\n/**\n * Base mixin for reactive classes that provides proper constructor reactivity\n * Solves constructor reactivity issues in complex inheritance trees\n */\nexport const ReactiveBase = mixin((base) => {\n\tclass ReactiveMixin extends base {\n\t\tconstructor(...args: any[]) {\n\t\t\tsuper(...args)\n\t\t\t// Only apply reactive transformation if the class is marked with @reactive\n\t\t\t// This allows the mixin to work properly with method inheritance\n\t\t\t// biome-ignore lint/correctness/noConstructorReturn: This is the whole point here\n\t\t\treturn reactiveClasses.has(new.target) ? reactive(this) : this\n\t\t}\n\t}\n\treturn ReactiveMixin\n})\nfunction reactiveObject<T>(anyTarget: T, subProxy?: SubProxy): T {\n\tif (!anyTarget || typeof anyTarget !== 'object') return anyTarget\n\tconst target = anyTarget as any\n\t// If target is already a proxy, return it\n\tif (isNonReactive(target)) return target as T\n\tconst isProxy = proxyToObject.has(target)\n\tif (isProxy) return target as T\n\n\t// If we already have a proxy for this object, return it (optimized: get returns undefined if not found)\n\tconst existing = getExistingProxy(target)\n\tif (existing !== undefined) return existing as T\n\n\tif (subProxy) subsRegister.set(target, subProxy)\n\tconst proxy = new Proxy(target, reactiveHandlers)\n\tif (Array.isArray(target)) arrayLengths.set(target, target.length)\n\t// Store the relationships\n\tstoreProxyRelationship(target, proxy)\n\treturn proxy as T\n}\n\n/**\n * Main decorator for making classes reactive\n * Automatically makes class instances reactive when created\n */\nexport const reactive = decorator({\n\tclass(original) {\n\t\tif (original.prototype instanceof ReactiveBase) {\n\t\t\treactiveClasses.add(original)\n\t\t\treturn original\n\t\t}\n\n\t\tclass Reactive extends original {\n\t\t\tconstructor(...args: any[]) {\n\t\t\t\tsuper(...args)\n\t\t\t\tif (new.target !== Reactive && !reactiveClasses.has(new.target))\n\t\t\t\t\toptions.warn(\n\t\t\t\t\t\t`${(original as any).name} has been inherited by ${this.constructor.name} that is not reactive.\n@reactive decorator must be applied to the leaf class OR classes have to extend ReactiveBase.`\n\t\t\t\t\t)\n\t\t\t\t// biome-ignore lint/correctness/noConstructorReturn: This is the whole point here\n\t\t\t\treturn reactive(this)\n\t\t\t}\n\t\t}\n\t\tObject.defineProperty(Reactive, 'name', {\n\t\t\tvalue: `Reactive<${original.name}>`,\n\t\t})\n\t\treturn Reactive as any\n\t},\n\tget(original: any) {\n\t\treturn reactiveObject(original)\n\t},\n\tdefault: reactiveObject,\n})\n","import { arrayDiff } from '../diff'\nimport { flavored } from '../flavored'\nimport type { GetterWrapper } from '../zone'\nimport { getState, touched, touched1 } from './change'\nimport { link } from './effect-context'\nimport { effect } from './effects'\nimport { reactive } from './proxy'\nimport { markWithRoot } from './registry'\nimport { dependant } from './tracking'\nimport {\n\ttype CleanupReason,\n\ttype EffectAccess,\n\ttype EffectCloser,\n\tisReactive,\n\tkeysOf,\n\ttype ScopedCallback,\n\ttype State,\n} from './types'\n\n/**\n * Reactively attends to each entry of a collection or each key yielded by an\n * enumeration callback. For each key, an inner effect runs the callback. When a\n * key disappears, its inner effect is disposed. The callback may return a cleanup\n * (like a regular effect closer).\n *\n * Accepts arrays, records, Maps, Sets, or a raw `() => Iterable<Key>` callback.\n *\n * @example\n * ```typescript\n * // Record shorthand\n * attend(record, (key) => { console.log(key, record[key]) })\n *\n * // Array shorthand\n * attend(array, (index) => { console.log(index, array[index]) })\n *\n * // Raw enumeration callback\n * attend(() => Object.keys(record), (key) => { ... })\n * ```\n */\nexport function attend<T>(\n\tsource: readonly T[],\n\tcallback: (index: number, access: EffectAccess) => EffectCloser | void\n): ScopedCallback\nexport function attend<K, V>(\n\tsource: Map<K, V>,\n\tcallback: (key: K, access: EffectAccess) => EffectCloser | void\n): ScopedCallback\nexport function attend<T>(\n\tsource: Set<T>,\n\tcallback: (value: T, access: EffectAccess) => EffectCloser | void\n): ScopedCallback\nexport function attend<S extends object>(\n\tsource: S,\n\tcallback: (key: keyof S & string, access: EffectAccess) => EffectCloser | void\n): ScopedCallback\nexport function attend<Key>(\n\tenumerate: () => Iterable<Key>,\n\tcallback: (key: Key, access: EffectAccess) => EffectCloser | void\n): ScopedCallback\nexport function attend(\n\tsource: any,\n\tcallback: (key: any, access: EffectAccess) => EffectCloser | void\n): ScopedCallback {\n\tconst enumerate: () => Iterable<any> =\n\t\ttypeof source === 'function'\n\t\t\t? source\n\t\t\t: Array.isArray(source)\n\t\t\t\t? () => Array.from({ length: source.length }, (_, i) => i)\n\t\t\t\t: source instanceof Map\n\t\t\t\t\t? () => source.keys()\n\t\t\t\t\t: source instanceof Set\n\t\t\t\t\t\t? () => source.values()\n\t\t\t\t\t\t: () => Object.keys(source)\n\n\tconst keyEffects = new Map<any, ScopedCallback>()\n\n\tconst outer = effect.named('attend')(({ ascend }) => {\n\t\tconst keys = new Set<any>()\n\t\tfor (const key of enumerate()) keys.add(key)\n\n\t\tfor (const key of keys) {\n\t\t\tif (keyEffects.has(key)) continue\n\t\t\tkeyEffects.set(\n\t\t\t\tkey,\n\t\t\t\tascend(() => effect.named(`attend:${key}`)((access) => callback(key, access)))\n\t\t\t)\n\t\t}\n\n\t\tfor (const key of Array.from(keyEffects.keys())) {\n\t\t\tif (!keys.has(key)) {\n\t\t\t\tkeyEffects.get(key)!()\n\t\t\t\tkeyEffects.delete(key)\n\t\t\t}\n\t\t}\n\t})\n\n\treturn (reason?: CleanupReason) => {\n\t\touter(reason)\n\t\tfor (const stop of keyEffects.values()) stop(reason)\n\t\tkeyEffects.clear()\n\t}\n}\n\n/**\n * Lifts a callback that returns an array into a reactive array that automatically\n * synchronizes with the source array returned by the callback.\n *\n * The returned reactive array will update whenever the callback's dependencies change,\n * efficiently syncing only the elements that differ from the previous result.\n *\n * @example\n * ```typescript\n * const items = reactive([1, 2, 3])\n * const doubled = lift(() => items.map(x => x * 2))\n *\n * console.log([...doubled]) // [2, 4, 6]\n *\n * items.push(4)\n * console.log([...doubled]) // [2, 4, 6, 8]\n * ```\n *\n * @param cb Callback function that returns an array\n * @returns A reactive array synchronized with the callback's result, with a [cleanup] property to stop tracking\n */\nexport function lift<Output extends any[]>(cb: (access: EffectAccess) => Output): Output\n\n/**\n * Lifts a callback that returns an object into a reactive object that automatically\n * synchronizes with the source object returned by the callback.\n *\n * The returned reactive object will update whenever the callback's dependencies change,\n * efficiently syncing only the properties that differ from the previous result using\n * Object.assign(). Properties that no longer exist in the source are automatically removed.\n *\n * @example\n * ```typescript\n * const user = reactive({ name: 'John', age: 30 })\n * const profile = lift(() => ({\n * displayName: user.name.toUpperCase(),\n * isAdult: user.age >= 18,\n * description: `${user.name} is ${user.age} years old`\n * }))\n *\n * console.log(profile.displayName) // JOHN\n * console.log(profile.isAdult) // true\n *\n * user.name = 'Jane'\n * console.log(profile.displayName) // JANE\n * console.log(profile.description) // Jane is 30 years old\n * ```\n *\n * @param cb Callback function that returns an object\n * @returns A reactive object synchronized with the callback's result, with a [cleanup] property to stop tracking\n */\nexport function lift<Output extends object>(cb: (access: EffectAccess) => Output): Output\nexport function lift<Output extends any[] | object>(cb: (access: EffectAccess) => Output): Output {\n\tlet result!: Output\n\tlet rawResult!: Output\n\tconst liftCleanup = effect.named(`lift:${cb.name}`)(\n\t\tmarkWithRoot((access) => {\n\t\t\tconst source = cb(access)\n\t\t\tif (!source || typeof source !== 'object')\n\t\t\t\tthrow new Error('lift callback must return an array or object')\n\t\t\tconst sourceProto = Object.getPrototypeOf(source)\n\t\t\tif (!result) {\n\t\t\t\trawResult = Array.isArray(source) ? [] : Object.create(sourceProto)\n\t\t\t\tresult = reactive(rawResult)\n\t\t\t}\n\t\t\tif (sourceProto !== Object.getPrototypeOf(result))\n\t\t\t\tthrow new Error('lift callback must return the same type as the previous result')\n\n\t\t\tif (Array.isArray(source)) {\n\t\t\t\tconst res = result as unknown[]\n\t\t\t\tfor (const { indexA, sliceA, sliceB } of arrayDiff(res, source).sort(\n\t\t\t\t\t(a, b) => a.indexA - b.indexA\n\t\t\t\t))\n\t\t\t\t\tres.splice(indexA, sliceA.length, ...sliceB)\n\t\t\t} else {\n\t\t\t\tfor (const key of Object.keys(source)) {\n\t\t\t\t\tconst had = key in rawResult\n\t\t\t\t\tconst newDesc = Object.getOwnPropertyDescriptor(source, key)!\n\t\t\t\t\tif (had) {\n\t\t\t\t\t\tconst oldDesc = Object.getOwnPropertyDescriptor(rawResult, key)\n\t\t\t\t\t\tconst sameAccessor = oldDesc && newDesc.get && oldDesc.get === newDesc.get\n\t\t\t\t\t\tObject.defineProperty(rawResult, key, newDesc)\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t!sameAccessor &&\n\t\t\t\t\t\t\trawResult[key] !==\n\t\t\t\t\t\t\t\t(oldDesc ? (oldDesc.get ? oldDesc.get() : oldDesc.value) : undefined)\n\t\t\t\t\t\t)\n\t\t\t\t\t\t\ttouched1(rawResult, { type: 'set', prop: key }, key)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tObject.defineProperty(rawResult, key, newDesc)\n\t\t\t\t\t\ttouched1(rawResult, { type: 'add', prop: key }, key)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfor (const key of Object.keys(rawResult))\n\t\t\t\t\tif (!(key in source)) {\n\t\t\t\t\t\tdelete rawResult[key]\n\t\t\t\t\t\ttouched1(rawResult, { type: 'del', prop: key }, key)\n\t\t\t\t\t}\n\t\t\t}\n\t\t}, cb)\n\t)\n\treturn link(result, liftCleanup)\n}\n\n/**\n * Options for `morph` and its variants.\n *\n * @property pure - When `true`, the mapping function is assumed pure (no reactive reads inside `fn`).\n * Per-item effects are skipped and items are computed eagerly. When a predicate `(i) => boolean`,\n * purity is evaluated per item — pure items skip the effect wrapper, non-pure items get their own.\n */\nexport type MorphOptions<I> = { pure?: boolean | ((i: I) => boolean) }\n\n/**\n * Reactively maps an array source through `fn`, producing a lazy reactive output array.\n *\n * Each source item gets its own isolated effect (via `root()`) so that changes to one item\n * only recompute that item's projection. Structural changes (push, splice, reorder) are detected\n * via `arrayDiff` and surgically applied to the output cache.\n *\n * The source can be a reactive array or a function returning an array. When a function is provided,\n * the function is re-evaluated inside an effect whenever its dependencies change.\n *\n * Output elements are computed lazily — accessing `result[i]` triggers computation if not yet cached.\n *\n * @param source - A reactive array or a function returning an array\n * @param fn - Mapping function applied to each element\n * @param options - Optional purity hints to skip per-item effects\n * @returns A readonly reactive array with a `[cleanup]` method to dispose all effects\n */\nexport function morphArray<I, O>(\n\tsource: readonly I[] | (() => readonly I[]),\n\tfn: (arg: I, access?: EffectAccess) => O,\n\toptions?: MorphOptions<I>\n): readonly O[] {\n\tif (typeof source !== 'function' && !isReactive(source) && options?.pure === true) {\n\t\treturn source.map((i) => fn(i)) as any\n\t}\n\n\tlet track!: GetterWrapper\n\tconst itemEffects = new Map<any, { stop: ScopedCallback; index: { value: number } }>()\n\tconst cache = [] as O[]\n\tlet input: readonly I[] = []\n\n\tfunction stopItem(key: any) {\n\t\tconst entry = itemEffects.get(key)\n\t\tif (entry) {\n\t\t\tentry.stop({ type: 'stopped' })\n\t\t\titemEffects.delete(key)\n\t\t}\n\t}\n\n\tfunction computeItem(key: number, input: I) {\n\t\tconst isPure =\n\t\t\toptions?.pure === true || (typeof options?.pure === 'function' && options.pure(input))\n\t\tif (isPure) {\n\t\t\ttrack(() => {\n\t\t\t\tcache[key] = fn(input)\n\t\t\t})\n\t\t} else {\n\t\t\tconst indexRef = { value: key }\n\t\t\tconst stop = track(() =>\n\t\t\t\teffect.named(`morph:${fn.name}:${key}`).opaque((access) => {\n\t\t\t\t\tcache[indexRef.value] = fn(input, access)\n\t\t\t\t\treturn (reason) => {\n\t\t\t\t\t\tdelete cache[indexRef.value]\n\t\t\t\t\t\ttouched1(cache, { type: 'invalidate', prop: 'morph' }, String(key))\n\t\t\t\t\t\tstop?.({ type: 'invalidate', cause: reason })\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t)\n\t\t\titemEffects.set(key, { stop, index: indexRef })\n\t\t}\n\t}\n\n\tconst proxy = reactive(cache, {\n\t\tget(cache, prop) {\n\t\t\tconst n = typeof prop === 'string' ? Number(prop) : NaN\n\t\t\tif (Number.isNaN(n)) return cache[prop]\n\t\t\tif (!(n in cache)) computeItem(n, input[n])\n\t\t\treturn cache[n]\n\t\t},\n\t\thas(_cache, prop) {\n\t\t\treturn Reflect.has(input, prop)\n\t\t},\n\t})\n\n\tconst stopMain = effect.named(`morph:${fn.name}`)(({ ascend }) => {\n\t\ttrack = ascend\n\t\tconst newInput = [...(typeof source === 'function' ? source() : source)]\n\t\tconst diffs = arrayDiff(input, newInput).toSorted((a, b) => b.indexA - a.indexA)\n\n\t\tif (diffs.length > 0) {\n\t\t\tfor (const diff of diffs) {\n\t\t\t\t// Stop items in removed range\n\t\t\t\tfor (let i = diff.indexA; i < diff.indexA + diff.sliceA.length; i++) stopItem(i)\n\n\t\t\t\t// Shift existing itemEffects in the Map to match the new indices\n\t\t\t\tconst shift = diff.sliceB.length - diff.sliceA.length\n\t\t\t\tif (shift !== 0) {\n\t\t\t\t\t// We need to move entries in the Map.\n\t\t\t\t\tconst entries = Array.from(itemEffects.entries()).sort((a, b) => a[0] - b[0])\n\t\t\t\t\t// Remove entries that will be shifted\n\t\t\t\t\tfor (const [idx, _entry] of entries) {\n\t\t\t\t\t\tif (idx >= diff.indexA + diff.sliceA.length) {\n\t\t\t\t\t\t\titemEffects.delete(idx)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t// Re-add them with shifted indices\n\t\t\t\t\tfor (const [idx, entry] of entries) {\n\t\t\t\t\t\tif (idx >= diff.indexA + diff.sliceA.length) {\n\t\t\t\t\t\t\tconst newIdx = idx + shift\n\t\t\t\t\t\t\tentry.index.value = newIdx\n\t\t\t\t\t\t\titemEffects.set(newIdx, entry)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Splice the cache\n\t\t\t\tcache.splice(\n\t\t\t\t\tdiff.indexA,\n\t\t\t\t\tdiff.sliceA.length,\n\t\t\t\t\t...new Array(diff.sliceB.length).fill(undefined)\n\t\t\t\t)\n\n\t\t\t\t// Make holes for lazy computation\n\t\t\t\tfor (let i = diff.indexA; i < diff.indexA + diff.sliceB.length; i++) delete cache[i]\n\t\t\t}\n\n\t\t\tconst invalidates = new Set<PropertyKey>([keysOf])\n\t\t\tif (input.length !== newInput.length) invalidates.add('length')\n\t\t\tfor (const diff of diffs) {\n\t\t\t\tconst max = Math.max(diff.sliceA.length, diff.sliceB.length)\n\t\t\t\tfor (let i = 0; i < max; i++) invalidates.add(String(diff.indexA + i))\n\t\t\t}\n\t\t\ttouched(cache, { type: 'bunch', method: 'morph-input' }, invalidates)\n\t\t}\n\n\t\tinput = newInput\n\t})\n\n\treturn link(proxy, (reason) => {\n\t\tstopMain(reason)\n\t\tfor (const entry of itemEffects.values()) entry.stop(reason)\n\t\titemEffects.clear()\n\t})\n}\n\n/**\n * Reactively maps a `Map` source through `fn`, producing a reactive output Map.\n *\n * Each key gets its own isolated effect so that value changes for one key only recompute\n * that key's projection. Key additions and removals are tracked via `keysOf` dependency.\n *\n * @param source - A reactive Map\n * @param fn - Mapping function applied to each value\n * @param options - Optional purity hints to skip per-key effects\n * @returns A reactive Map with a `[cleanup]` method to dispose all effects\n */\nexport function morphMap<K, V, O>(\n\tsource: Map<K, V>,\n\tfn: (arg: V, key: K, access?: EffectAccess) => O,\n\toptions?: MorphOptions<V>\n): Map<K, O> {\n\tif (!isReactive(source) && options?.pure === true) {\n\t\tconst res = new Map<K, O>()\n\t\tfor (const [k, v] of source) res.set(k, fn(v, k))\n\t\treturn res as any\n\t}\n\n\tlet track!: GetterWrapper\n\tconst itemEffects = new Map<any, ScopedCallback>()\n\tconst cache = new Map<K, O>()\n\tObject.defineProperty(cache, 'constructor', { value: Object, enumerable: false })\n\n\tfunction stopItem(key: any) {\n\t\tconst stop = itemEffects.get(key)\n\t\tif (stop) {\n\t\t\tstop({ type: 'stopped' })\n\t\t\titemEffects.delete(key)\n\t\t}\n\t}\n\n\tfunction computeItem(key: any, val: any) {\n\t\tconst isPure =\n\t\t\toptions?.pure === true || (typeof options?.pure === 'function' && options.pure(val))\n\t\tif (isPure) {\n\t\t\tcache.set(\n\t\t\t\tkey,\n\t\t\t\ttrack(() => fn(val, key))\n\t\t\t)\n\t\t} else {\n\t\t\tconst stop = track(() =>\n\t\t\t\teffect.named(`morph:${fn.name}:${key}`).opaque((access) => {\n\t\t\t\t\tcache.set(key, fn(source.get(key), key, access))\n\t\t\t\t\treturn (reason) => {\n\t\t\t\t\t\tcache.delete(key)\n\t\t\t\t\t\ttouched1(cache, { type: 'invalidate', prop: 'morph' }, String(key))\n\t\t\t\t\t\tstop?.({ type: 'invalidate', cause: reason })\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t)\n\t\t\titemEffects.set(key, stop)\n\t\t}\n\t}\n\n\tconst proxy = reactive(cache, {\n\t\tget(cache, prop) {\n\t\t\tif (prop === 'get')\n\t\t\t\treturn (key: any) => {\n\t\t\t\t\tif (!cache.has(key) && source.has(key)) computeItem(key, source.get(key))\n\t\t\t\t\treturn cache.get(key)\n\t\t\t\t}\n\t\t\tif (prop === 'has')\n\t\t\t\treturn (key: any) => {\n\t\t\t\t\treturn source.has(key)\n\t\t\t\t}\n\t\t\tif (prop === 'keys')\n\t\t\t\treturn () => {\n\t\t\t\t\treturn source.keys()\n\t\t\t\t}\n\t\t\tif (prop === 'values')\n\t\t\t\treturn function* () {\n\t\t\t\t\tfor (const key of source.keys()) {\n\t\t\t\t\t\tyield proxy.get(key)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tif (prop === 'entries')\n\t\t\t\treturn function* () {\n\t\t\t\t\tfor (const key of source.keys()) {\n\t\t\t\t\t\tyield [key, proxy.get(key)]\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tif (prop === Symbol.iterator)\n\t\t\t\treturn function* () {\n\t\t\t\t\tfor (const key of source.keys()) {\n\t\t\t\t\t\tyield [key, proxy.get(key)]\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\treturn (cache as any)[prop]\n\t\t},\n\t}) as any\n\n\tlet stateSnapshot: State = getState(source)\n\tconst stopMain = effect.named(`morph:${fn.name}`)(({ ascend }) => {\n\t\ttrack = ascend\n\t\tdependant(source, keysOf)\n\t\twhile ('evolution' in stateSnapshot) {\n\t\t\tconst { evolution } = stateSnapshot\n\t\t\tstateSnapshot = stateSnapshot.next\n\t\t\tif (evolution.type === 'add') {\n\t\t\t\ttouched1(cache, evolution, evolution.prop)\n\t\t\t} else if (evolution.type === 'del') {\n\t\t\t\tstopItem(evolution.prop)\n\t\t\t\tcache.delete(evolution.prop)\n\t\t\t\ttouched1(cache, evolution, evolution.prop)\n\t\t\t}\n\t\t}\n\t})\n\n\treturn link(proxy, (reason) => {\n\t\tstopMain(reason)\n\t\tfor (const stop of itemEffects.values()) stop(reason)\n\t\titemEffects.clear()\n\t})\n}\n\n/**\n * Reactively maps a record/object source through `fn`, producing a reactive output record.\n *\n * Each key gets its own isolated effect so that value changes for one key only recompute\n * that key's projection. Key additions and removals are tracked automatically.\n *\n * @param source - A reactive record\n * @param fn - Mapping function applied to each value\n * @param options - Optional purity hints to skip per-key effects\n * @returns A reactive record with a `[cleanup]` method to dispose all effects\n */\nexport function morphRecord<S extends Record<PropertyKey, any>, O>(\n\tsource: S,\n\tfn: (arg: S[keyof S], key: keyof S, access?: EffectAccess) => O,\n\toptions?: MorphOptions<S[keyof S]>\n): { [K in keyof S]: O } {\n\tif (!isReactive(source) && options?.pure === true) {\n\t\tconst res = {} as any\n\t\tfor (const k of Object.keys(source)) res[k] = fn(source[k], k)\n\t\treturn res\n\t}\n\n\tlet track!: GetterWrapper\n\tconst itemEffects = new Map<any, ScopedCallback>()\n\tconst cache = {} as any\n\n\tfunction stopItem(key: any) {\n\t\tconst stop = itemEffects.get(key)\n\t\tif (stop) {\n\t\t\tstop({ type: 'stopped' })\n\t\t\titemEffects.delete(key)\n\t\t}\n\t}\n\n\tfunction computeItem(key: any, val: any) {\n\t\tconst isPure =\n\t\t\toptions?.pure === true || (typeof options?.pure === 'function' && options.pure(val))\n\t\tif (isPure) {\n\t\t\tcache[key] = track(() => fn(val, key))\n\t\t} else {\n\t\t\tconst stop = track(() =>\n\t\t\t\teffect.named(`morph:${fn.name}:${key}`).opaque((access) => {\n\t\t\t\t\tcache[key] = fn(source[key], key, access)\n\t\t\t\t\treturn (reason) => {\n\t\t\t\t\t\tdelete cache[key]\n\t\t\t\t\t\ttouched1(cache, { type: 'invalidate', prop: 'morph' }, String(key))\n\t\t\t\t\t\tstop?.({ type: 'invalidate', cause: reason })\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t)\n\t\t\titemEffects.set(key, stop)\n\t\t}\n\t}\n\tfunction get(prop: PropertyKey) {\n\t\tif (!(prop in cache) && prop in source) computeItem(prop, source[prop])\n\t\treturn cache[prop]\n\t}\n\tconst proxy = reactive(cache, {\n\t\tget(_, prop) {\n\t\t\treturn get(prop)\n\t\t},\n\t\thas(_, prop) {\n\t\t\treturn prop in source\n\t\t},\n\t\townKeys() {\n\t\t\treturn Reflect.ownKeys(source)\n\t\t},\n\t\tgetOwnPropertyDescriptor(_cache, prop) {\n\t\t\tif (prop in source) return { configurable: true, enumerable: true, get: () => get(prop) }\n\t\t},\n\t})\n\n\tlet stateSnapshot: State = getState(source)\n\tconst stopMain = effect.named(`morph:${fn.name}`)(({ ascend }) => {\n\t\ttrack = ascend\n\t\t// Track only structural changes on source\n\t\tdependant(source, keysOf)\n\t\twhile ('evolution' in stateSnapshot) {\n\t\t\tconst { evolution } = stateSnapshot\n\t\t\tstateSnapshot = stateSnapshot.next\n\t\t\tif (evolution.type === 'add') {\n\t\t\t\ttouched1(cache, evolution, evolution.prop)\n\t\t\t} else if (evolution.type === 'del') {\n\t\t\t\tstopItem(evolution.prop)\n\t\t\t\tdelete cache[evolution.prop]\n\t\t\t\ttouched1(cache, evolution, evolution.prop)\n\t\t\t}\n\t\t}\n\t})\n\n\treturn link(proxy, (reason) => {\n\t\tstopMain(reason)\n\t\tfor (const stop of itemEffects.values()) stop(reason)\n\t\titemEffects.clear()\n\t})\n}\n\n/**\n * Unified reactive collection mapper. Dispatches to `morphArray`, `morphMap`, or `morphRecord`\n * based on the source type. Access `morph.pure(source, fn)` for the `{ pure: true }` shorthand.\n *\n * @see morphArray\n * @see morphMap\n * @see morphRecord\n */\nexport type Morph = {\n\t<I, O>(\n\t\tsource: readonly I[] | (() => readonly I[]),\n\t\tfn: (arg: I, access?: EffectAccess) => O,\n\t\toptions?: MorphOptions<I>\n\t): readonly O[]\n\n\t<K, V, O>(\n\t\tsource: Map<K, V>,\n\t\tfn: (arg: V, key: K, access?: EffectAccess) => O,\n\t\toptions?: MorphOptions<V>\n\t): Map<K, O>\n\n\t<S extends Record<PropertyKey, any>, O>(\n\t\tsource: S,\n\t\tfn: (arg: S[keyof S], key: keyof S, access?: EffectAccess) => O,\n\t\toptions?: MorphOptions<S[keyof S]>\n\t): { [K in keyof S]: O }\n\n\tpure: Morph\n}\n\n/**\n * Reactively maps a collection (array, Map, or record) through a per-entry function.\n *\n * Each entry in the source gets its own reactive context — when only one entry's dependencies\n * change, only that entry's projection recomputes. Structural changes (additions, removals,\n * reorders) are detected via diffing and applied surgically.\n *\n * Use `morph.pure(source, fn)` when `fn` has no reactive reads (skips per-item effects).\n *\n * @example\n * ```ts\n * const users = reactive([{ name: 'John' }, { name: 'Jane' }])\n * const names = morph(users, u => u.name.toUpperCase())\n * // names[0] = 'JOHN', names[1] = 'JANE'\n * // Changing users[0].name only recomputes names[0]\n * ```\n */\nexport const morph = flavored(\n\tfunction morph(source: any, fn: any, options?: any): any {\n\t\tif (Array.isArray(source) || typeof source === 'function')\n\t\t\treturn morphArray(source, fn, options)\n\t\tif (source instanceof Map) return morphMap(source, fn, options)\n\t\treturn morphRecord(source, fn, options)\n\t},\n\t{\n\t\tget pure() {\n\t\t\treturn (source: any, fn: any, _opt) => this(source, fn, { pure: true })\n\t\t},\n\t}\n) as Morph\n","import {\n\tdeepWatchers,\n\teffectToDeepWatchedObjects,\n\tobjectsWithDeepWatchers,\n\tregisterDeepWatcher,\n} from './deep-watch-state'\nimport { effect, untracked } from './effects'\nimport { isNonReactive } from './non-reactive'\nimport { reactive } from './proxy'\nimport { markWithRoot } from './registry'\nimport { dependant } from './tracking'\nimport { type EffectCleanup, type EffectTrigger, options, unwrap } from './types'\n\n/**\n * Deep watch an object and all its nested properties\n * @param target - The object to watch deeply\n * @param callback - The callback to call when any nested property changes\n * @param options - Options for the deep watch\n * @returns A cleanup function to stop watching\n */\n/**\n * Sets up deep watching for an object, tracking all nested property changes\n * @param target - The object to watch\n * @param callback - The callback to call when changes occur\n * @param options - Options for deep watching\n * @returns A cleanup function to stop deep watching\n */\nexport function deepWatch<T extends object>(\n\ttarget: T,\n\tcallback: (value: T) => void,\n\t{ immediate = false } = {}\n): EffectCleanup | undefined {\n\tif (target === null || target === undefined) return undefined\n\tif (typeof target !== 'object') throw new Error('Target of deep watching must be an object')\n\t// Create a wrapper callback that matches EffectTrigger signature\n\tconst wrappedCallback: EffectTrigger = markWithRoot(\n\t\t(() => callback(target)) as EffectTrigger,\n\t\tcallback\n\t)\n\n\tregisterDeepWatcher()\n\n\t// Use the existing effect system to register dependencies\n\treturn effect.named('deepWatch')(() => {\n\t\t// Mark the target object as having deep watchers\n\t\tobjectsWithDeepWatchers.add(target)\n\n\t\t// Track which objects this effect is watching for cleanup\n\t\tlet effectObjects = effectToDeepWatchedObjects.get(wrappedCallback)\n\t\tif (!effectObjects) {\n\t\t\teffectObjects = new Set()\n\t\t\teffectToDeepWatchedObjects.set(wrappedCallback, effectObjects)\n\t\t}\n\t\teffectObjects!.add(target)\n\n\t\t// Traverse the object graph and register dependencies\n\t\t// This will re-run every time the effect runs, ensuring we catch all changes\n\t\tconst visited = new WeakSet()\n\t\tfunction traverseAndTrack(obj: any, depth = 0) {\n\t\t\t// Prevent infinite recursion and excessive depth\n\t\t\tif (!obj || visited.has(obj) || typeof obj !== 'object' || depth > options.maxDeepWatchDepth)\n\t\t\t\treturn\n\t\t\t// Do not traverse into unreactive objects\n\t\t\tif (isNonReactive(obj)) return\n\t\t\tvisited.add(obj)\n\n\t\t\t// Mark this object as having deep watchers\n\t\t\tobjectsWithDeepWatchers.add(obj)\n\t\t\teffectObjects!.add(obj)\n\n\t\t\t// Traverse all properties to register dependencies\n\t\t\t// unwrap to avoid kicking dependency\n\t\t\tfor (const key in unwrap(obj)) {\n\t\t\t\tif (Object.hasOwn(obj, key)) {\n\t\t\t\t\t// Access the property to register dependency\n\t\t\t\t\tconst value = (obj as any)[key]\n\t\t\t\t\t// Make the value reactive if it's an object\n\t\t\t\t\tconst reactiveValue =\n\t\t\t\t\t\ttypeof value === 'object' && value !== null ? reactive(value) : value\n\t\t\t\t\ttraverseAndTrack(reactiveValue, depth + 1)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Also handle array indices and length\n\t\t\t// Handle arrays and collections using iterators to ensure proxy tracking is triggered\n\t\t\tif (typeof obj[Symbol.iterator] === 'function') {\n\t\t\t\t// Access the iterator to track additions/removals/collection changes\n\t\t\t\tfor (const value of obj) {\n\t\t\t\t\t// Make the value reactive if it's an object\n\t\t\t\t\tconst reactiveValue =\n\t\t\t\t\t\ttypeof value === 'object' && value !== null ? reactive(value) : value\n\t\t\t\t\ttraverseAndTrack(reactiveValue, depth + 1)\n\t\t\t\t}\n\n\t\t\t\t// Explicitly depend on length so array mutations changing count trigger re-evaluation\n\t\t\t\tif ('length' in obj) {\n\t\t\t\t\tdependant(obj, 'length')\n\t\t\t\t}\n\n\t\t\t\t// For Maps, also ensure we track values explicitly if the iterator yields entries\n\t\t\t\tif (obj instanceof Map) {\n\t\t\t\t\tfor (const value of obj.values()) {\n\t\t\t\t\t\tconst reactiveValue =\n\t\t\t\t\t\t\ttypeof value === 'object' && value !== null ? reactive(value) : value\n\t\t\t\t\t\ttraverseAndTrack(reactiveValue, depth + 1)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Note: WeakSet and WeakMap cannot be iterated, so we can't deep watch their contents\n\t\t\t// They will only trigger when the collection itself is replaced\n\t\t}\n\n\t\t// Traverse the target object to register all dependencies\n\t\t// This will register dependencies on all current properties and array elements\n\t\ttraverseAndTrack(target)\n\n\t\t// Only call the callback if immediate is true or if it's not the first run\n\t\tif (immediate) {\n\t\t\tuntracked(() => callback(target))\n\t\t}\n\t\timmediate = true\n\n\t\t// Return a cleanup function that properly removes deep watcher tracking\n\t\treturn () => {\n\t\t\t// Get the objects this effect was watching\n\t\t\tconst effectObjects = effectToDeepWatchedObjects.get(wrappedCallback)\n\t\t\tif (effectObjects) {\n\t\t\t\t// Remove deep watcher tracking from all objects this effect was watching\n\t\t\t\tfor (const obj of effectObjects) {\n\t\t\t\t\t// Check if this object still has other deep watchers\n\t\t\t\t\tconst watchers = deepWatchers.get(obj)\n\t\t\t\t\tif (watchers) {\n\t\t\t\t\t\t// Remove this effect's callback from the watchers\n\t\t\t\t\t\twatchers.delete(wrappedCallback)\n\n\t\t\t\t\t\t// If no more watchers, remove the object from deep watchers tracking\n\t\t\t\t\t\tif (watchers.size === 0) {\n\t\t\t\t\t\t\tdeepWatchers.delete(obj)\n\t\t\t\t\t\t\tobjectsWithDeepWatchers.delete(obj)\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// No watchers found, remove from deep watchers tracking\n\t\t\t\t\t\tobjectsWithDeepWatchers.delete(obj)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Clean up the tracking data\n\t\t\t\teffectToDeepWatchedObjects.delete(wrappedCallback)\n\t\t\t}\n\t\t}\n\t})\n}\n","import { decorator } from '../decorator'\nimport { flavored } from '../flavored'\nimport { deepCompare, named } from '../utils'\nimport { touched1 } from './change'\nimport { effect, root, untracked } from './effects'\nimport { getRoot, markWithRoot, rootFunctionSymbol } from './registry'\nimport { dependant } from './tracking'\nimport { type CleanupReason, optionCall, options, proxyToObject } from './types'\n\nexport type MemoizableArgument = object | any[] | ((...args: any[]) => any)\nexport type Memoizable = ((...args: MemoizableArgument[]) => unknown) | Record<string, any>\n\ntype MemoCacheTree<Result> = {\n\tresult?: Result\n\tcleanup?: (reason?: CleanupReason) => void\n\tbranches?: WeakMap<MemoizableArgument, MemoCacheTree<Result>>\n}\n\nconst memoizedRegistry = new WeakMap<any, Memoizable>()\nconst wrapperRegistry = new WeakMap<Function, (that: object) => unknown>()\n\nfunction getBranch<Result>(\n\ttree: MemoCacheTree<Result>,\n\tkey: MemoizableArgument\n): MemoCacheTree<Result> {\n\ttree.branches ??= new WeakMap()\n\tlet branch = tree.branches.get(key)\n\tif (!branch) {\n\t\tbranch = {}\n\t\ttree.branches.set(key, branch)\n\t}\n\treturn branch\n}\n\nfunction memoizeFunction<Result, Args extends MemoizableArgument[]>(\n\tfn: (...args: Args) => Result,\n\topts?: {\n\t\tlenient?: boolean\n\t}\n): (...args: Args) => Result {\n\tconst fnRoot = getRoot(fn)\n\tconst existing = memoizedRegistry.get(fnRoot)\n\tif (existing) return existing as (...args: Args) => Result\n\n\tconst cacheRoot: MemoCacheTree<Result> = {}\n\tconst memoized = markWithRoot(function memoized(...args: Args): Result {\n\t\tif (args.some((arg) => !(arg && ['object', 'symbol', 'function'].includes(typeof arg)))) {\n\t\t\tif (opts?.lenient) return fn.apply(this, args)\n\t\t\tthrow new Error('memoize expects non-null object arguments')\n\t\t}\n\n\t\tlet node: MemoCacheTree<Result> = cacheRoot\n\t\t// Note: decorators add `this` as first argument\n\t\tfor (const arg of args) {\n\t\t\tnode = getBranch(node, arg)\n\t\t}\n\n\t\tdependant(node, 'memoize')\n\t\tif ('result' in node) {\n\t\t\tif (options.onMemoizationDiscrepancy) {\n\t\t\t\tconst wasVerification = options.isVerificationRun\n\t\t\t\toptions.isVerificationRun = true\n\t\t\t\ttry {\n\t\t\t\t\tconst fresh = untracked(() => fn.apply(this, args))\n\t\t\t\t\tif (!deepCompare(node.result, fresh)) {\n\t\t\t\t\t\toptionCall('onMemoizationDiscrepancy', node.result, fresh, fn, args, 'calculation')\n\t\t\t\t\t}\n\t\t\t\t} finally {\n\t\t\t\t\toptions.isVerificationRun = wasVerification\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn node.result!\n\t\t}\n\n\t\t// Create memoize internal effect to track dependencies and invalidate cache\n\t\t// Use untracked to prevent the effect creation from being affected by parent effects\n\t\tnode.cleanup = root(() =>\n\t\t\teffect.named('memoize')(\n\t\t\t\t() => {\n\t\t\t\t\t// Execute the function and track its dependencies\n\t\t\t\t\t// The function execution will automatically track dependencies on reactive objects\n\t\t\t\t\tnode.result = fn.apply(this, args)\n\t\t\t\t\treturn (reason) => {\n\t\t\t\t\t\t// When dependencies change, clear the cache and notify consumers\n\t\t\t\t\t\tdelete node.result\n\t\t\t\t\t\ttouched1(node, { type: 'invalidate', prop: args }, 'memoize')\n\t\t\t\t\t\t// Lazy memoization: stop the effect so it doesn't re-run immediately.\n\t\t\t\t\t\t// It will be re-created on next access.\n\t\t\t\t\t\tif (node.cleanup) {\n\t\t\t\t\t\t\tnode.cleanup({ type: 'invalidate', cause: reason })\n\t\t\t\t\t\t\tnode.cleanup = undefined\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t{ opaque: true }\n\t\t\t)\n\t\t)\n\n\t\tif (options.onMemoizationDiscrepancy) {\n\t\t\tconst wasVerification = options.isVerificationRun\n\t\t\toptions.isVerificationRun = true\n\t\t\ttry {\n\t\t\t\tconst fresh = untracked(() => fn.apply(this, args))\n\t\t\t\tif (!deepCompare(node.result, fresh)) {\n\t\t\t\t\toptionCall('onMemoizationDiscrepancy', node.result, fresh, fn, args, 'comparison')\n\t\t\t\t}\n\t\t\t} finally {\n\t\t\t\toptions.isVerificationRun = wasVerification\n\t\t\t}\n\t\t}\n\n\t\treturn node.result!\n\t}, fn)\n\n\tmemoizedRegistry.set(fnRoot, memoized)\n\tmemoizedRegistry.set(memoized, memoized)\n\treturn memoized as (...args: Args) => Result\n}\n\nfunction memoizeObject<T extends Record<string, any>>(target: T, opts?: { lenient?: boolean }): T {\n\tconst existing = memoizedRegistry.get(target)\n\tif (existing) return existing as T\n\n\tconst proxy = new Proxy(target, {\n\t\tget(source, prop, receiver) {\n\t\t\t// 1. Walk prototype chain to find descriptor\n\t\t\tlet current = source\n\t\t\tlet desc: PropertyDescriptor | undefined\n\t\t\twhile (current) {\n\t\t\t\tdesc = Object.getOwnPropertyDescriptor(current, prop)\n\t\t\t\tif (desc) break\n\t\t\t\tcurrent = Object.getPrototypeOf(current)\n\t\t\t}\n\t\t\tif (!desc) return Reflect.get(source, prop, receiver)\n\t\t\t// 2. If getter, memoize\n\t\t\tif (desc.get) {\n\t\t\t\tconst originalGetter = desc.get\n\t\t\t\tlet wrapper = wrapperRegistry.get(originalGetter)\n\t\t\t\tif (!wrapper) {\n\t\t\t\t\twrapper = markWithRoot(\n\t\t\t\t\t\tnamed(\n\t\t\t\t\t\t\t`${String(source?.constructor?.name ?? 'Object')}.${String(prop)}`,\n\t\t\t\t\t\t\t(that: any) => {\n\t\t\t\t\t\t\t\treturn originalGetter.call(that)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t),\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tpropertyKey: prop,\n\t\t\t\t\t\t}\n\t\t\t\t\t)\n\t\t\t\t\tconst origRoot = originalGetter[rootFunctionSymbol]\n\t\t\t\t\tif (origRoot) wrapper[rootFunctionSymbol] = origRoot\n\t\t\t\t\twrapperRegistry.set(originalGetter, wrapper)\n\t\t\t\t}\n\t\t\t\tconst memoized = memoizeFunction(wrapper, opts)\n\t\t\t\treturn memoized(receiver)\n\t\t\t}\n\n\t\t\t// 3. Otherwise forward\n\t\t\treturn Reflect.get(source, prop, receiver)\n\t\t},\n\t\t// Forward set to the target (source) to ensure it acts as the receiver for reactivity notifications\n\t\tset(source, prop, value, _receiver) {\n\t\t\t// By strictly passing `source` as receiver, we ensure that if `source` is a reactive proxy,\n\t\t\t// it recognizes itself and triggers change notifications.\n\t\t\treturn Reflect.set(source, prop, value, source)\n\t\t},\n\t})\n\n\tproxyToObject.set(proxy, target)\n\tmemoizedRegistry.set(target, proxy)\n\treturn proxy\n}\n\n/**\n * Decorator and function wrapper for memoizing computed values based on reactive dependencies.\n *\n * When used as a decorator on getters or methods, it caches the result and automatically\n * invalidates the cache when reactive dependencies change.\n *\n * When used as a function wrapper, it memoizes based on object arguments (WeakMap-based cache).\n *\n * @example\n * ```typescript\n * class User {\n * @memoize\n * get fullName() {\n * return `${this.firstName} ${this.lastName}`\n * }\n * }\n *\n * // Or as a function wrapper\n * const expensive = memoize((obj: SomeObject) => {\n * return heavyComputation(obj)\n * })\n * ```\n */\nfunction makeMemoizeDecorator(memoizeOpts?: { lenient?: boolean }) {\n\treturn decorator({\n\t\tgetter(original, target, propertyKey) {\n\t\t\treturn function (this: any) {\n\t\t\t\tlet wrapper = wrapperRegistry.get(original)\n\t\t\t\tif (!wrapper) {\n\t\t\t\t\twrapper = markWithRoot(\n\t\t\t\t\t\tnamed(\n\t\t\t\t\t\t\t`${String(target?.constructor?.name ?? target?.name ?? 'Object')}.${String(propertyKey)}`,\n\t\t\t\t\t\t\t(that: object) => {\n\t\t\t\t\t\t\t\treturn original.call(that)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t),\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tmethod: original,\n\t\t\t\t\t\t\tpropertyKey,\n\t\t\t\t\t\t}\n\t\t\t\t\t)\n\t\t\t\t\tconst origRoot = original[rootFunctionSymbol]\n\t\t\t\t\tif (origRoot) wrapper[rootFunctionSymbol] = origRoot\n\t\t\t\t\twrapperRegistry.set(original, wrapper)\n\t\t\t\t}\n\t\t\t\tconst memoized = memoizeFunction(wrapper as any, memoizeOpts)\n\t\t\t\treturn memoized(this)\n\t\t\t}\n\t\t},\n\t\tmethod(original, target, name) {\n\t\t\treturn function (this: any, ...args: object[]) {\n\t\t\t\tlet wrapper = wrapperRegistry.get(original)\n\t\t\t\tif (!wrapper) {\n\t\t\t\t\twrapper = markWithRoot(\n\t\t\t\t\t\tnamed(\n\t\t\t\t\t\t\t`${String(target?.constructor?.name ?? target?.name ?? 'Object')}.${String(name)}`,\n\t\t\t\t\t\t\t(that: object, ...args: object[]) => {\n\t\t\t\t\t\t\t\treturn original.call(that, ...args)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t),\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tmethod: original,\n\t\t\t\t\t\t\tpropertyKey: name,\n\t\t\t\t\t\t}\n\t\t\t\t\t)\n\t\t\t\t\tconst origRoot = original[rootFunctionSymbol]\n\t\t\t\t\tif (origRoot) wrapper[rootFunctionSymbol] = origRoot\n\t\t\t\t\twrapperRegistry.set(original, wrapper)\n\t\t\t\t}\n\t\t\t\tconst memoized = memoizeFunction(wrapper as any, memoizeOpts) as (\n\t\t\t\t\t...args: object[]\n\t\t\t\t) => unknown\n\t\t\t\treturn memoized(this, ...args)\n\t\t\t}\n\t\t},\n\t\tdefault: <T extends Memoizable>(target: T): T =>\n\t\t\ttypeof target === 'object'\n\t\t\t\t? (memoizeObject(target, memoizeOpts) as T)\n\t\t\t\t: (memoizeFunction(target, memoizeOpts) as T),\n\t})\n}\n\nexport const memoize: ReturnType<typeof makeMemoizeDecorator> & {\n\treadonly lenient: ReturnType<typeof makeMemoizeDecorator>\n} = flavored(makeMemoizeDecorator(), {\n\tget lenient() {\n\t\treturn makeMemoizeDecorator({ lenient: true })\n\t},\n})\n","import { decorator, type GenericClassDecorator } from '../decorator'\nimport { flavored, flavorOptions } from '../flavored'\nimport { deepWatch } from './deep-watch'\nimport { effectHistory, link } from './effect-context'\nimport { captured, effect, untracked } from './effects'\nimport { addUnreactiveProps, isNonReactive } from './non-reactive'\nimport { reactive } from './proxy'\nimport { markWithRoot } from './registry'\nimport { dependant } from './tracking'\nimport {\n\ttype EffectAccess,\n\ttype EffectCleanup,\n\ttype ScopedCallback,\n\tunreactiveProperties,\n\tunwrap,\n} from './types'\n\n//#region watch\n\nconst unsetYet = Symbol('unset-yet')\n/**\n * Options for the watch function\n */\nexport interface WatchOptions {\n\t/** Whether to call the callback immediately */\n\timmediate?: boolean\n\t/** Whether to watch nested properties */\n\tdeep?: boolean\n}\n\n/**\n * Watches a reactive value and calls a callback when it changes\n */\nexport interface Watch {\n\t<T>(\n\t\tvalue: (dep: EffectAccess) => T,\n\t\tchanged: (value: T, oldValue?: T) => void,\n\t\toptions?: Omit<WatchOptions, 'deep'> & { deep?: false }\n\t): EffectCleanup\n\t/**\n\t * Watches a reactive value with deep watching enabled\n\t */\n\t<T extends object | any[]>(\n\t\tvalue: (dep: EffectAccess) => T,\n\t\tchanged: (value: T, oldValue?: T) => void,\n\t\toptions?: Omit<WatchOptions, 'deep'> & { deep: true }\n\t): EffectCleanup\n\t/**\n\t * Watches a reactive object directly\n\t */\n\t<T extends object | any[]>(\n\t\tvalue: T,\n\t\tchanged: (value: T) => void,\n\t\toptions?: WatchOptions\n\t): EffectCleanup\n\n\t/** Deep watch flavor */\n\tget deep(): Watch\n\t/** Immediate watch flavor */\n\tget immediate(): Watch\n}\n\nexport const watch = flavored(\n\tfunction watch(\n\t\tvalue: any, //object | ((dep: DependencyAccess) => object),\n\t\tchanged: (value?: object, oldValue?: object) => void,\n\t\toptions: any = {}\n\t) {\n\t\treturn typeof value === 'function'\n\t\t\t? watchCallBack(value, changed, options)\n\t\t\t: typeof value === 'object' && value !== null\n\t\t\t\t? watchObject(value, changed, options)\n\t\t\t\t: (() => {\n\t\t\t\t\t\tthrow new Error('watch: value must be a function or an object')\n\t\t\t\t\t})()\n\t},\n\t{\n\t\tget deep() {\n\t\t\treturn flavorOptions(this, { deep: true })\n\t\t},\n\t\tget immediate() {\n\t\t\treturn flavorOptions(this, { immediate: true })\n\t\t},\n\t}\n) as Watch\n\nfunction watchObject(\n\tvalue: object,\n\tchanged: (value: object) => void,\n\t{ immediate = false, deep = false } = {}\n): EffectCleanup {\n\tif (deep) return deepWatch(value, changed, { immediate })!\n\treturn effect.named('watch:object')(() => {\n\t\tdependant(value)\n\t\tif (immediate) changed(value)\n\t\timmediate = true\n\t})\n}\n\nfunction watchCallBack<T>(\n\tvalue: (dep: EffectAccess) => T,\n\tchanged: (value: T, oldValue?: T) => void,\n\t{ immediate = false, deep = false } = {}\n): EffectCleanup {\n\tlet oldValue: T | typeof unsetYet = unsetYet\n\tlet deepCleanup: EffectCleanup | undefined\n\tconst cbCleanup = effect.named('watch:callback')(\n\t\tmarkWithRoot((access) => {\n\t\t\tconst newValue = value(access)\n\t\t\tif (oldValue !== newValue) {\n\t\t\t\tconst old = oldValue\n\t\t\t\tif (old === unsetYet) {\n\t\t\t\t\tif (immediate) untracked(() => changed(newValue))\n\t\t\t\t} else untracked(() => changed(newValue, old as T))\n\t\t\t}\n\t\t\toldValue = newValue\n\t\t\tif (deep) {\n\t\t\t\tif (deepCleanup) deepCleanup()\n\t\t\t\tdeepCleanup = deepWatch(newValue as object, (value) => changed(value as T, value as T))\n\t\t\t}\n\t\t}, value)\n\t)\n\treturn (() => {\n\t\tcbCleanup()\n\t\tif (deepCleanup) deepCleanup()\n\t}) as EffectCleanup\n}\n\n//#endregion\n\n//#region when\n\n/**\n * Returns a promise that resolves when the predicate returns a truthy value.\n * The predicate is evaluated reactively — it re-runs whenever its dependencies change.\n * @param predicate - Reactive function that returns a value; resolves when truthy\n * @param timeout - Optional timeout in milliseconds — rejects if condition is not met within this duration\n * @returns Promise that resolves with the first truthy return value\n */\nexport function when<T>(predicate: (dep: EffectAccess) => T, timeout?: number): Promise<T> {\n\treturn new Promise<T>((resolve, reject) => {\n\t\tlet timer: ReturnType<typeof setTimeout> | undefined\n\t\tconst stop = effect.named('watch:when')((access) => {\n\t\t\ttry {\n\t\t\t\tconst value = predicate(access)\n\t\t\t\tif (value) {\n\t\t\t\t\tif (timer !== undefined) clearTimeout(timer)\n\t\t\t\t\ttimer = undefined\n\t\t\t\t\tqueueMicrotask(() => stop())\n\t\t\t\t\tresolve(value)\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tif (timer !== undefined) clearTimeout(timer)\n\t\t\t\ttimer = undefined\n\t\t\t\treject(error)\n\t\t\t}\n\t\t})\n\t\tif (timeout !== undefined) {\n\t\t\ttimer = setTimeout(() => {\n\t\t\t\tstop()\n\t\t\t\ttimer = undefined\n\t\t\t\treject(new Error(`when: timed out after ${timeout}ms`))\n\t\t\t}, timeout)\n\t\t}\n\t})\n}\n\n//#endregion\n\n//#region nonReactive\n\n/**\n * Mark an object as non-reactive. This object and all its properties will never be made reactive.\n * @param obj - The object to mark as non-reactive\n */\nfunction shallowNonReactive<T>(obj: T): T {\n\tobj = unwrap(obj)\n\tif (isNonReactive(obj)) return obj\n\t;(obj as any)[unreactiveProperties] = true\n\treturn obj\n}\nfunction unreactiveApplication<T extends object>(...args: (keyof T)[]): GenericClassDecorator<T>\nfunction unreactiveApplication<T extends object>(obj: T): T\nfunction unreactiveApplication<T extends object>(\n\targ1: T | keyof T,\n\t...args: (keyof T)[]\n): GenericClassDecorator<T> | T {\n\treturn typeof arg1 === 'object'\n\t\t? shallowNonReactive(arg1)\n\t\t: (((original) => {\n\t\t\t\t// Copy the parent's unreactive properties if they exist\n\t\t\t\tconst parentMarker = (original.prototype as any)[unreactiveProperties]\n\t\t\t\t// If parent is fully unreactive, child is too\n\t\t\t\tif (parentMarker === true) {\n\t\t\t\t\t;(original.prototype as any)[unreactiveProperties] = true\n\t\t\t\t} else {\n\t\t\t\t\tconst set = new Set<PropertyKey>(parentMarker || [])\n\t\t\t\t\t// Add all arguments (including the first one)\n\t\t\t\t\tset.add(arg1)\n\t\t\t\t\tfor (const arg of args) set.add(arg)\n\t\t\t\t\taddUnreactiveProps(original.prototype, set)\n\t\t\t\t}\n\t\t\t\treturn original // Return the class\n\t\t\t}) as GenericClassDecorator<T>)\n}\n/**\n * Decorator that marks classes or properties as non-reactive\n * Prevents objects from being made reactive\n */\nexport const unreactive = decorator({\n\tclass(original) {\n\t\t// Called without arguments, mark entire class as non-reactive\n\t\t;(original.prototype as any)[unreactiveProperties] = true\n\t},\n\tdefault: unreactiveApplication,\n})\n\n//#endregion\n\n//#region resource\n\nexport function lazyInit<T extends object>(resource: T, load: ScopedCallback) {\n\tconst creation = effectHistory.active\n\tlet fresh = true\n\treturn new Proxy(resource, {\n\t\t[Symbol.toStringTag]: 'LazyInit',\n\t\tget(target, prop) {\n\t\t\tif (fresh) {\n\t\t\t\tcaptured(creation, load)()\n\t\t\t\tfresh = false\n\t\t\t}\n\t\t\treturn target[prop]\n\t\t},\n\t} as ProxyHandler<T>)\n}\n\nexport interface Resource<T> {\n\tvalue: T | undefined\n\tloading: boolean\n\terror: any\n\tlatest: T | undefined\n\treload(): void\n\tpromise: Promise<void>\n}\n\n/**\n * Creates a reactive resource that automatically tracks async state.\n * @param fetcher - Async function that returns the value. Reactive dependencies are tracked.\n * @param options - Resource options (initialValue)\n * @returns Reactive Resource object with value, loading, error, latest properties\n */\nexport function resource<T>(\n\tfetcher: (access: EffectAccess) => Promise<T> | T,\n\toptions: { initialValue?: T } = {}\n): Resource<T> {\n\tconst resource: Partial<Resource<T>> = reactive({\n\t\tvalue: options.initialValue,\n\t\tloading: true,\n\t\terror: undefined as any,\n\t\tlatest: options.initialValue,\n\t\treload() {\n\t\t\treloadSignal.value++\n\t\t},\n\t})\n\n\tconst reloadSignal = reactive({ value: 0 })\n\t// Solve race conditions: make sure a new fast request is not overloaded by a slow old one\n\tlet counter = 0\n\n\treturn lazyInit(resource as Resource<T>, () => {\n\t\tlink(\n\t\t\tresource,\n\t\t\teffect.named('watch:resource')((access) => {\n\t\t\t\t// Track reload signal to enable manual reloading\n\t\t\t\tvoid reloadSignal.value\n\n\t\t\t\tconst id = ++counter\n\t\t\t\tresource.loading = true\n\t\t\t\tresource.error = undefined\n\n\t\t\t\ttry {\n\t\t\t\t\tconst result = fetcher(access)\n\n\t\t\t\t\tif (result instanceof Promise) {\n\t\t\t\t\t\tresource.promise = result\n\t\t\t\t\t\t\t.then((val) => {\n\t\t\t\t\t\t\t\tif (id === counter) {\n\t\t\t\t\t\t\t\t\tresource.value = val\n\t\t\t\t\t\t\t\t\tresource.latest = val\n\t\t\t\t\t\t\t\t\tresource.loading = false\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t.catch((err) => {\n\t\t\t\t\t\t\t\tif (id === counter) {\n\t\t\t\t\t\t\t\t\tresource.error = err\n\t\t\t\t\t\t\t\t\tresource.loading = false\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t})\n\t\t\t\t\t} else {\n\t\t\t\t\t\tresource.promise = Promise.resolve()\n\t\t\t\t\t\tresource.value = result\n\t\t\t\t\t\tresource.latest = result\n\t\t\t\t\t\tresource.loading = false\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tresource.promise = Promise.reject(err)\n\t\t\t\t\tresource.error = err\n\t\t\t\t\tresource.loading = false\n\t\t\t\t}\n\t\t\t})\n\t\t) as Resource<T>\n\t})\n}\n\n//#endregion\n","import { reactive } from './proxy'\n\n/**\n * Converts an iterator to a generator that yields reactive values\n */\nexport function* makeReactiveIterator<T>(iterator: Iterator<T>): Generator<T> {\n\tlet result = iterator.next()\n\twhile (!result.done) {\n\t\tyield reactive(result.value)\n\t\tresult = iterator.next()\n\t}\n}\n\n/**\n * Converts an iterator of key-value pairs to a generator that yields reactive key-value pairs\n */\nexport function* makeReactiveEntriesIterator<K, V>(iterator: Iterator<[K, V]>): Generator<[K, V]> {\n\tlet result = iterator.next()\n\twhile (!result.done) {\n\t\tconst [key, value] = result.value\n\t\tyield [reactive(key), reactive(value)]\n\t\tresult = iterator.next()\n\t}\n}\n","import { FoolProof } from '../utils'\nimport { touched } from './change'\nimport { atomic } from './effects'\nimport { makeReactiveEntriesIterator, makeReactiveIterator } from './iterator-helpers'\nimport { reactive } from './proxy'\nimport { dependant } from './tracking'\nimport { keysOf, unwrap } from './types'\n\nfunction* index(i: number, { length = true } = {}): IterableIterator<number | 'length'> {\n\tif (length) yield 'length'\n\tyield i\n}\nexport abstract class Indexer extends Array {\n\tget(i: number): any {\n\t\tdependant(this, i)\n\t\treturn reactive(this[i])\n\t}\n\t// Returns undefined intentionally: signals the proxy handler that notifications\n\t// were already dispatched via touched(), preventing double notification\n\tset(i: number, value: any) {\n\t\tconst added = i >= this.length\n\t\tthis[i] = value\n\t\ttouched(this, { type: 'set', prop: i }, index(i, { length: added }))\n\t}\n}\nconst indexLess = { get: FoolProof.get, set: FoolProof.set }\n// Fast numeric-string check: first char is a digit (0-9)\nfunction asIndex(prop: string): number {\n\tconst c = prop.charCodeAt(0)\n\tif (c < 48 || c > 57) return -1 // not 0-9\n\tconst n = +prop // coerce — faster than parseInt, handles \"0\", \"12\", etc.\n\treturn n === (n | 0) && n >= 0 ? n : -1\n}\nObject.assign(FoolProof, {\n\tget(obj: any, prop: any, receiver: any) {\n\t\tif (Array.isArray(obj) && typeof prop === 'string') {\n\t\t\tconst i = asIndex(prop)\n\t\t\tif (i >= 0) return Indexer.prototype.get.call(obj, i)\n\t\t}\n\t\treturn indexLess.get(obj, prop, receiver)\n\t},\n\tset(obj: any, prop: any, value: any, receiver: any) {\n\t\tif (Array.isArray(obj) && typeof prop === 'string') {\n\t\t\tconst i = asIndex(prop)\n\t\t\tif (i >= 0) return Indexer.prototype.set.call(obj, i, value)\n\t\t}\n\t\treturn indexLess.set(obj, prop, value, receiver)\n\t},\n})\n\nexport abstract class ReactiveArray extends Array {\n\ttoJSON() {\n\t\treturn this\n\t}\n}\n/**\n * This is a wrapper class for Array that adds reactive behavior.\n * It extends Array and overrides methods to add reactive behavior, while making sure that the internal representation is not reactive.\n */\nexport abstract class ReactiveArrayWrapper extends Array {\n\tat(index: number): any {\n\t\treturn reactive(super.at(index))\n\t}\n\n\tconcat(...items: any[]): any[] {\n\t\treturn reactive(super.concat(...items.map(unwrap)))\n\t}\n\n\tentries(): any {\n\t\tdependant(this, keysOf)\n\t\treturn makeReactiveEntriesIterator(super.entries())\n\t}\n\n\tevery<S>(\n\t\tpredicate: (value: any, index: number, array: any[]) => value is S,\n\t\tthisArg?: any\n\t): this is S[]\n\tevery(predicate: (value: any, index: number, array: any[]) => unknown, thisArg?: any): boolean\n\tevery(predicate: (value: any, index: number, array: any[]) => any, thisArg?: any): any {\n\t\treturn super.every((v, i, a) => predicate.call(thisArg, reactive(v), i, a), thisArg)\n\t}\n\n\t@atomic\n\tfill(value: any, start?: number, end?: number): this {\n\t\treturn super.fill(unwrap(value), start, end) as this\n\t}\n\n\t@atomic\n\tcopyWithin(target: number, start: number, end?: number): this {\n\t\treturn super.copyWithin(target, start, end) as this\n\t}\n\n\tfilter<S>(predicate: (value: any, index: number, array: any[]) => value is S, thisArg?: any): S[]\n\tfilter(predicate: (value: any, index: number, array: any[]) => unknown, thisArg?: any): any[]\n\tfilter(predicate: (value: any, index: number, array: any[]) => unknown, thisArg?: any): any {\n\t\treturn reactive(super.filter((v, i, a) => predicate.call(thisArg, reactive(v), i, a), thisArg))\n\t}\n\n\tfind<S>(\n\t\tpredicate: (value: any, index: number, array: any[]) => value is S,\n\t\tthisArg?: any\n\t): S | undefined\n\tfind(\n\t\tpredicate: (value: any, index: number, array: any[]) => unknown,\n\t\tthisArg?: any\n\t): any | undefined\n\tfind(predicate: (value: any, index: number, array: any[]) => unknown, thisArg?: any): any {\n\t\treturn reactive(super.find((v, i, a) => predicate.call(thisArg, reactive(v), i, a), thisArg))\n\t}\n\n\tfindIndex(\n\t\tpredicate: (value: any, index: number, array: any[]) => unknown,\n\t\tthisArg?: any\n\t): number {\n\t\treturn super.findIndex((v, i, a) => predicate.call(thisArg, reactive(v), i, a), thisArg)\n\t}\n\n\tfindLast<S>(\n\t\tpredicate: (value: any, index: number, array: any[]) => value is S,\n\t\tthisArg?: any\n\t): S | undefined\n\tfindLast(\n\t\tpredicate: (value: any, index: number, array: any[]) => unknown,\n\t\tthisArg?: any\n\t): any | undefined\n\tfindLast(predicate: (value: any, index: number, array: any[]) => unknown, thisArg?: any): any {\n\t\treturn reactive(\n\t\t\tsuper.findLast((v, i, a) => predicate.call(thisArg, reactive(v), i, a), thisArg)\n\t\t)\n\t}\n\n\tfindLastIndex(\n\t\tpredicate: (value: any, index: number, array: any[]) => unknown,\n\t\tthisArg?: any\n\t): number {\n\t\treturn super.findLastIndex((v, i, a) => predicate.call(thisArg, reactive(v), i, a), thisArg)\n\t}\n\n\tflat(depth?: number): any[] {\n\t\treturn reactive(super.flat(depth))\n\t}\n\n\tflatMap(callbackfn: (value: any, index: number, array: any[]) => any, thisArg?: any): any[] {\n\t\treturn reactive(\n\t\t\tsuper.flatMap((v, i, a) => unwrap(callbackfn.call(thisArg, reactive(v), i, a)), thisArg)\n\t\t)\n\t}\n\n\tforEach(callbackfn: (value: any, index: number, array: any[]) => void, thisArg?: any): void {\n\t\tsuper.forEach((v, i, a) => {\n\t\t\tcallbackfn.call(thisArg, reactive(v), i, a)\n\t\t}, thisArg)\n\t}\n\n\tincludes(searchElement: any, fromIndex?: number): boolean {\n\t\treturn arguments.length > 1\n\t\t\t? super.includes(unwrap(searchElement), fromIndex)\n\t\t\t: super.includes(unwrap(searchElement))\n\t}\n\n\tindexOf(searchElement: any, fromIndex?: number): number {\n\t\treturn arguments.length > 1\n\t\t\t? super.indexOf(unwrap(searchElement), fromIndex)\n\t\t\t: super.indexOf(unwrap(searchElement))\n\t}\n\n\tjoin(separator?: string): string {\n\t\treturn super.join(separator)\n\t}\n\n\tkeys(): any {\n\t\tdependant(this, 'length')\n\t\treturn super.keys()\n\t}\n\n\tlastIndexOf(searchElement: any, fromIndex?: number): number {\n\t\treturn arguments.length > 1\n\t\t\t? super.lastIndexOf(unwrap(searchElement), fromIndex)\n\t\t\t: super.lastIndexOf(unwrap(searchElement))\n\t}\n\n\tmap<U>(callbackfn: (value: any, index: number, array: any[]) => U, thisArg?: any): U[] {\n\t\treturn reactive(\n\t\t\tsuper.map((v, i, a) => unwrap(callbackfn.call(thisArg, reactive(v), i, a)), thisArg)\n\t\t)\n\t}\n\n\t@atomic\n\tpop(): any {\n\t\treturn reactive(super.pop())\n\t}\n\n\t@atomic\n\tpush(...items: any[]): number {\n\t\treturn super.push(...items.map(unwrap))\n\t}\n\n\treduce(\n\t\tcallbackfn: (acc: any, value: any, index: number, array: any[]) => any,\n\t\tinitialValue?: any\n\t): any {\n\t\treturn reactive(\n\t\t\targuments.length > 1\n\t\t\t\t? super.reduce((acc, v, i, a) => unwrap(callbackfn(acc, reactive(v), i, a)), initialValue)\n\t\t\t\t: super.reduce((acc, v, i, a) => unwrap(callbackfn(acc, reactive(v), i, a)))\n\t\t)\n\t}\n\n\treduceRight(\n\t\tcallbackfn: (acc: any, value: any, index: number, array: any[]) => any,\n\t\tinitialValue?: any\n\t): any {\n\t\treturn reactive(\n\t\t\targuments.length > 1\n\t\t\t\t? super.reduceRight(\n\t\t\t\t\t\t(acc, v, i, a) => unwrap(callbackfn(acc, reactive(v), i, a)),\n\t\t\t\t\t\tinitialValue\n\t\t\t\t\t)\n\t\t\t\t: super.reduceRight((acc, v, i, a) => unwrap(callbackfn(acc, reactive(v), i, a)))\n\t\t)\n\t}\n\n\t@atomic\n\treverse(): any[] {\n\t\treturn reactive(super.reverse())\n\t}\n\n\t@atomic\n\tshift(): any {\n\t\treturn reactive(super.shift())\n\t}\n\n\tslice(start?: number, end?: number): any[] {\n\t\treturn reactive(super.slice(start, end))\n\t}\n\n\tsome<S>(\n\t\tpredicate: (value: any, index: number, array: any[]) => value is S,\n\t\tthisArg?: any\n\t): this is S[]\n\tsome(predicate: (value: any, index: number, array: any[]) => unknown, thisArg?: any): boolean\n\tsome(predicate: (value: any, index: number, array: any[]) => any, thisArg?: any): any {\n\t\treturn super.some((v, i, a) => predicate.call(thisArg, reactive(v), i, a), thisArg)\n\t}\n\n\t@atomic\n\tsort(compareFn?: (a: any, b: any) => number): this {\n\t\tconst wrappedCompare = compareFn\n\t\t\t? (a: any, b: any) => compareFn(reactive(a), reactive(b))\n\t\t\t: undefined\n\t\treturn super.sort(wrappedCompare) as this\n\t}\n\n\t@atomic\n\tsplice(start: number, deleteCount?: number, ...items: any[]): any {\n\t\tif (arguments.length > 2)\n\t\t\treturn reactive(super.splice(start, deleteCount!, ...items.map(unwrap)))\n\t\tif (arguments.length === 2) return reactive(super.splice(start, deleteCount!))\n\t\tif (arguments.length === 1) return reactive(super.splice(start))\n\t\treturn reactive([])\n\t}\n\n\t@atomic\n\tunshift(...items: any[]): number {\n\t\treturn super.unshift(...items.map(unwrap))\n\t}\n\n\tvalues(): any {\n\t\tdependant(this, keysOf)\n\t\treturn makeReactiveIterator(super.values())\n\t}\n\n\t[Symbol.iterator](): any {\n\t\tdependant(this, keysOf)\n\t\treturn makeReactiveIterator(super[Symbol.iterator]())\n\t}\n\n\ttoReversed(): any[] {\n\t\treturn reactive(super.toReversed())\n\t}\n\n\ttoSorted(compareFn?: (a: any, b: any) => number): any[] {\n\t\tconst wrappedCompare = compareFn\n\t\t\t? (a: any, b: any) => compareFn(reactive(a), reactive(b))\n\t\t\t: undefined\n\t\treturn reactive(super.toSorted(wrappedCompare))\n\t}\n\n\ttoSpliced(start: number, deleteCount?: number, ...items: any[]): any {\n\t\tif (arguments.length > 2)\n\t\t\treturn reactive(super.toSpliced(start, deleteCount!, ...items.map(unwrap)))\n\t\tif (arguments.length === 2) return reactive(super.toSpliced(start, deleteCount!))\n\t\tif (arguments.length === 1) return reactive(super.toSpliced(start))\n\t\treturn reactive([...this])\n\t}\n\n\twith(index: number, value: any): any[] {\n\t\treturn reactive(super.with(index, unwrap(value)))\n\t}\n}\n","import { contentRef } from '../utils'\nimport { touched, touched1 } from './change'\nimport { notifyPropertyChange } from './deep-touch'\nimport { batch } from './effects'\nimport { makeReactiveEntriesIterator, makeReactiveIterator } from './iterator-helpers'\nimport { reactive } from './proxy'\nimport { dependant } from './tracking'\nimport { keysOf } from './types'\n\n/**\n * Reactive wrapper around JavaScript's WeakMap class\n * Only tracks individual key operations, no size tracking (WeakMap limitation)\n */\nexport abstract class ReactiveWeakMap<K extends object, V> extends WeakMap<K, V> {\n\t// Implement WeakMap interface methods with reactivity\n\tdelete(key: K): boolean {\n\t\tconst hadKey = this.has(key)\n\t\tconst result = super.delete(key)\n\n\t\tif (hadKey) touched1(contentRef(this), { type: 'del', prop: key }, key)\n\n\t\treturn result\n\t}\n\n\tget(key: K): V | undefined {\n\t\tdependant(contentRef(this), key)\n\t\treturn reactive(super.get(key))\n\t}\n\n\thas(key: K): boolean {\n\t\tdependant(contentRef(this), key)\n\t\treturn super.has(key)\n\t}\n\n\tset(key: K, value: V): this {\n\t\tconst hadKey = this.has(key)\n\t\tconst oldValue = this.get(key)\n\t\tconst reactiveValue = reactive(value)\n\t\tthis.set(key, reactiveValue)\n\n\t\tif (!hadKey || oldValue !== reactiveValue) {\n\t\t\tnotifyPropertyChange(contentRef(this), key, oldValue, reactiveValue, hadKey)\n\t\t}\n\n\t\treturn this\n\t}\n}\n\n/**\n * Reactive wrapper around JavaScript's Map class\n * Tracks size changes, individual key operations, and collection-wide operations\n */\nexport abstract class ReactiveMap<K, V> extends Map<K, V> {\n\t// Implement Map interface methods with reactivity\n\tget size(): number {\n\t\tdependant(this, 'size') // The ReactiveMap instance still goes through proxy\n\t\treturn super.size\n\t}\n\n\tclear(): void {\n\t\tconst hadEntries = this.size > 0\n\t\tsuper.clear()\n\n\t\tif (hadEntries) {\n\t\t\tconst evolution = { type: 'bunch', method: 'clear' } as const\n\t\t\t// Clear triggers all effects since all keys are affected\n\t\t\tbatch(() => {\n\t\t\t\ttouched1(this, evolution, 'size')\n\t\t\t\ttouched(contentRef(this), evolution)\n\t\t\t})\n\t\t}\n\t}\n\n\tentries(): Generator<[K, V]> {\n\t\tdependant(contentRef(this))\n\t\treturn makeReactiveEntriesIterator(this.entries())\n\t}\n\n\tforEach(callbackfn: (value: V, key: K, map: Map<K, V>) => void, thisArg?: any): void {\n\t\tdependant(contentRef(this))\n\t\tthis.forEach(callbackfn, thisArg)\n\t}\n\n\tkeys(): MapIterator<K> {\n\t\tdependant(contentRef(this), keysOf)\n\t\treturn this.keys()\n\t}\n\n\tvalues(): Generator<V> {\n\t\tdependant(contentRef(this))\n\t\treturn makeReactiveIterator(this.values())\n\t}\n\n\t[Symbol.iterator](): MapIterator<[K, V]> {\n\t\tdependant(contentRef(this))\n\t\tconst it: MapIterator<[K, V]> = Map.prototype[Symbol.iterator].call(this)\n\t\tconst nativeNext = it.next.bind(it)\n\t\tit.next = () => {\n\t\t\tconst result = nativeNext()\n\t\t\tif (result.done) return result\n\t\t\tconst [key, value] = result.value\n\t\t\treturn { value: [reactive(key), reactive(value)], done: false }\n\t\t}\n\t\treturn it\n\t}\n\n\t// Implement Map methods with reactivity\n\tdelete(key: K): boolean {\n\t\tconst hadKey = this.has(key)\n\t\tconst result = super.delete(key)\n\n\t\tif (hadKey) {\n\t\t\tconst evolution = { type: 'del', prop: key } as const\n\t\t\tbatch(() => {\n\t\t\t\ttouched1(contentRef(this), evolution, key)\n\t\t\t\ttouched1(this, evolution, 'size')\n\t\t\t})\n\t\t}\n\n\t\treturn result\n\t}\n\n\tget(key: K): V | undefined {\n\t\tdependant(contentRef(this), key)\n\t\treturn reactive(super.get(key))\n\t}\n\n\thas(key: K): boolean {\n\t\tdependant(contentRef(this), key)\n\t\treturn super.has(key)\n\t}\n\n\tset(key: K, value: V): this {\n\t\tconst hadKey = this.has(key)\n\t\tconst oldValue = this.get(key)\n\t\tconst reactiveValue = reactive(value)\n\t\tsuper.set(key, reactiveValue)\n\n\t\tif (!hadKey || oldValue !== reactiveValue) {\n\t\t\tbatch(() => {\n\t\t\t\tnotifyPropertyChange(contentRef(this), key, oldValue, reactiveValue, hadKey)\n\t\t\t\t// Also notify size change for Map (WeakMap doesn't track size)\n\t\t\t\tconst evolution = { type: hadKey ? 'set' : 'add', prop: key } as const\n\t\t\t\ttouched1(this, evolution, 'size')\n\t\t\t})\n\t\t}\n\n\t\treturn this\n\t}\n}\n","import { contentRef } from '../utils'\nimport { touched, touched1 } from './change'\nimport { batch } from './effects'\nimport { makeReactiveEntriesIterator, makeReactiveIterator } from './iterator-helpers'\nimport { reactive } from './proxy'\nimport { dependant } from './tracking'\n\n/**\n * Reactive wrapper around JavaScript's WeakSet class\n * Only tracks individual value operations, no size tracking (WeakSet limitation)\n */\nexport abstract class ReactiveWeakSet<T extends object> extends WeakSet<T> {\n\tadd(value: T): this {\n\t\tconst had = this.has(value)\n\t\tsuper.add(value)\n\t\tif (!had) {\n\t\t\t// touch the specific value and the collection view\n\t\t\ttouched1(contentRef(this), { type: 'add', prop: value }, value)\n\t\t\t// no size/allProps for WeakSet\n\t\t}\n\t\treturn this\n\t}\n\n\tdelete(value: T): boolean {\n\t\tconst had = this.has(value)\n\t\tconst res = super.delete(value)\n\t\tif (had) touched1(contentRef(this), { type: 'del', prop: value }, value)\n\t\treturn res\n\t}\n\n\thas(value: T): boolean {\n\t\tdependant(contentRef(this), value)\n\t\treturn super.has(value)\n\t}\n}\n\n/**\n * Reactive wrapper around JavaScript's Set class\n * Tracks size changes, individual value operations, and collection-wide operations\n */\nexport abstract class ReactiveSet<T> extends Set<T> {\n\tget size(): number {\n\t\t// size depends on the wrapper instance, like Map counterpart\n\t\tdependant(this, 'size')\n\t\treturn this.size\n\t}\n\n\tadd(value: T): this {\n\t\tconst had = this.has(value)\n\t\tconst reactiveValue = reactive(value)\n\t\tsuper.add(reactiveValue)\n\t\tif (!had) {\n\t\t\tconst evolution = { type: 'add', prop: reactiveValue } as const\n\t\t\t// touch for value-specific and aggregate dependencies\n\t\t\tbatch(() => {\n\t\t\t\ttouched1(contentRef(this), evolution, reactiveValue)\n\t\t\t\ttouched1(this, evolution, 'size')\n\t\t\t})\n\t\t}\n\t\treturn this\n\t}\n\n\tclear(): void {\n\t\tconst hadEntries = this.size > 0\n\t\tsuper.clear()\n\t\tif (hadEntries) {\n\t\t\tconst evolution = { type: 'bunch', method: 'clear' } as const\n\t\t\tbatch(() => {\n\t\t\t\ttouched1(this, evolution, 'size')\n\t\t\t\ttouched(contentRef(this), evolution)\n\t\t\t})\n\t\t}\n\t}\n\n\tdelete(value: T): boolean {\n\t\tconst had = this.has(value)\n\t\tconst res = super.delete(value)\n\t\tif (had) {\n\t\t\tconst evolution = { type: 'del', prop: value } as const\n\t\t\tbatch(() => {\n\t\t\t\ttouched1(contentRef(this), evolution, value)\n\t\t\t\ttouched1(this, evolution, 'size')\n\t\t\t})\n\t\t}\n\t\treturn res\n\t}\n\n\thas(value: T): boolean {\n\t\tdependant(contentRef(this), value)\n\t\treturn this.has(value)\n\t}\n\n\tentries(): Generator<[T, T]> {\n\t\tdependant(contentRef(this))\n\t\treturn makeReactiveEntriesIterator(this.entries())\n\t}\n\n\tforEach(callbackfn: (value: T, value2: T, set: Set<T>) => void, thisArg?: any): void {\n\t\tdependant(contentRef(this))\n\t\tthis.forEach(callbackfn, thisArg)\n\t}\n\n\tkeys(): Generator<T> {\n\t\tdependant(contentRef(this))\n\t\treturn makeReactiveIterator(this.keys())\n\t}\n\n\tvalues(): Generator<T> {\n\t\tdependant(contentRef(this))\n\t\treturn makeReactiveIterator(this.values())\n\t}\n\n\t[Symbol.iterator](): SetIterator<T> {\n\t\tdependant(contentRef(this))\n\t\tconst it: SetIterator<T> = Set.prototype[Symbol.iterator].call(this)\n\t\tconst nativeNext = it.next.bind(it)\n\t\tit.next = () => {\n\t\t\tconst result = nativeNext()\n\t\t\tif (result.done) return result\n\t\t\treturn { value: reactive(result.value), done: false }\n\t\t}\n\t\treturn it\n\t}\n}\n","export { attend, lift, morph, morph as project } from './buffer'\nexport { getState, touched, touched1 } from './change'\nexport { deepWatch } from './deep-watch'\nexport { effectAggregator, getActiveEffect, link, unlink } from './effect-context'\nexport {\n\taddBatchCleanup,\n\tatom,\n\tatomic,\n\t//batch, - NEVER export batch, it deals with EffectTriggers who are internal types - mutts consumers use `atomic` or `atom`\n\tbiDi,\n\tcaptured,\n\tcaught,\n\tdefer,\n\teffect,\n\tgetActivationLog,\n\tonEffectThrow,\n\treset,\n\troot,\n\tuntracked,\n} from './effects'\nexport { type Memoizable, type MemoizableArgument, memoize } from './memoize'\nexport { addUnreactiveProps, isNonReactive } from './non-reactive'\nexport { ReactiveBase, reactive } from './proxy'\nexport { organize, organized } from './record'\nexport { type Resource, resource, unreactive, watch, when } from './satellite'\nexport { assertUntracked } from './tracking'\nexport {\n\ttype CleanupReason,\n\tdebugPreset,\n\tdevPreset,\n\ttype EffectAccess,\n\ttype EffectCleanup,\n\ttype EffectCloser,\n\ttype EffectOptions,\n\ttype EffectTrigger,\n\ttype Evolution,\n\tformatCleanupReason,\n\tisReactive,\n\tobjectToProxy,\n\toptions as reactiveOptions,\n\ttype PropTrigger,\n\tprodPreset,\n\tproxyToObject,\n\tReactiveError,\n\tReactiveErrorCode,\n\ttype ScopedCallback,\n\tunwrap,\n} from './types'\n\nimport { ReactiveArray, ReactiveArrayWrapper } from './array'\nimport {\n\tdeepWatchers,\n\teffectToDeepWatchedObjects,\n\tobjectParents,\n\tobjectsWithDeepWatchers,\n} from './deep-watch-state'\nimport { ReactiveMap, ReactiveWeakMap } from './map'\nimport { metaProtos, wrapProtos } from './proxy'\nimport { effectToReactiveObjects, watchers } from './registry'\nimport { ReactiveSet, ReactiveWeakSet } from './set'\nimport { objectToProxy, proxyToObject } from './types'\n\n// Register native collection types to use specialized reactive wrappers\nmetaProtos.set(Array, ReactiveArray.prototype)\nmetaProtos.set(Set, ReactiveSet.prototype)\nmetaProtos.set(WeakSet, ReactiveWeakSet.prototype)\nmetaProtos.set(Map, ReactiveMap.prototype)\nmetaProtos.set(WeakMap, ReactiveWeakMap.prototype)\nwrapProtos.set(Array, ReactiveArrayWrapper.prototype)\n\n/**\n * Object containing internal reactive system state for debugging and profiling\n */\nexport const profileInfo: any = {\n\tobjectToProxy,\n\tproxyToObject,\n\teffectToReactiveObjects,\n\twatchers,\n\tobjectParents,\n\tobjectsWithDeepWatchers,\n\tdeepWatchers,\n\teffectToDeepWatchedObjects,\n}\n","import { decorator, type GenericClassDecorator } from './decorator'\nimport { flavored } from './flavored'\nimport { options } from './reactive/types'\n\n// In order to avoid async re-entrance, we could use zone.js or something like that.\nconst syncCalculating: { object: object; prop: PropertyKey }[] = []\n/**\n * Decorator that caches the result of a getter method and only recomputes when dependencies change\n * Prevents circular dependencies and provides automatic cache invalidation\n */\nexport const cached = decorator({\n\tgetter(original, _target, propertyKey) {\n\t\treturn function (this: any) {\n\t\t\tconst alreadyCalculating = syncCalculating.findIndex(\n\t\t\t\t(c) => c.object === this && c.prop === propertyKey\n\t\t\t)\n\t\t\tif (alreadyCalculating > -1)\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Circular dependency detected: ${syncCalculating\n\t\t\t\t\t\t.slice(alreadyCalculating)\n\t\t\t\t\t\t.map((c) => `${c.object.constructor.name}.${String(c.prop)}`)\n\t\t\t\t\t\t.join(' -> ')} -> again`\n\t\t\t\t)\n\t\t\tsyncCalculating.push({ object: this, prop: propertyKey })\n\t\t\ttry {\n\t\t\t\tconst rv = original.call(this)\n\t\t\t\tcache(this, propertyKey, rv)\n\t\t\t\treturn rv\n\t\t\t} finally {\n\t\t\t\tsyncCalculating.pop()\n\t\t\t}\n\t\t}\n\t},\n})\n\n/**\n * Checks if a property is cached (has a cached value)\n * @param object - The object to check\n * @param propertyKey - The property key to check\n * @returns True if the property has a cached value\n */\nexport function isCached(object: Object, propertyKey: PropertyKey) {\n\treturn !!Object.getOwnPropertyDescriptor(object, propertyKey)\n}\n\n/**\n * Caches a value for a property on an object\n * @param object - The object to cache the value on\n * @param propertyKey - The property key to cache\n * @param value - The value to cache\n */\nexport function cache(object: Object, propertyKey: PropertyKey, value: any) {\n\tObject.defineProperty(object, propertyKey, { value })\n}\n\n/**\n * Creates a decorator that modifies property descriptors for specified properties\n * @param descriptor - The descriptor properties to apply\n * @returns A class decorator that applies the descriptor to specified properties\n */\nexport const descriptor = flavored(\n\tfunction descriptor(descriptor: {\n\t\tenumerable?: boolean\n\t\tconfigurable?: boolean // Not modifiable once the property has been defined\n\t\twritable?: boolean\n\t}) {\n\t\treturn <T>(...properties: (keyof T)[]): GenericClassDecorator<T> =>\n\t\t\t(Base) => {\n\t\t\t\treturn class extends Base {\n\t\t\t\t\tconstructor(...args: any[]) {\n\t\t\t\t\t\tsuper(...args)\n\t\t\t\t\t\tfor (const key of properties) {\n\t\t\t\t\t\t\tconst existing = Object.getOwnPropertyDescriptor(this, key)\n\t\t\t\t\t\t\tObject.defineProperty(this, key, Object.assign(existing || {}, descriptor))\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t},\n\t{\n\t\t/**\n\t\t * enumerable: true\n\t\t */\n\t\tget enumerable() {\n\t\t\treturn descriptor({ enumerable: true })\n\t\t},\n\t\t/**\n\t\t * enumerable: false\n\t\t */\n\t\tget hidden() {\n\t\t\treturn descriptor({ enumerable: false })\n\t\t},\n\t\t/**\n\t\t * configurable: true\n\t\t */\n\t\tget configurable() {\n\t\t\treturn descriptor({ configurable: true })\n\t\t},\n\t\t/**\n\t\t * configurable: false\n\t\t */\n\t\tget frozen() {\n\t\t\treturn descriptor({ configurable: false })\n\t\t},\n\t\t/**\n\t\t * writable: true\n\t\t */\n\t\tget writable() {\n\t\t\treturn descriptor({ writable: true })\n\t\t},\n\t\t/**\n\t\t * writable: false\n\t\t */\n\t\tget readonly() {\n\t\t\treturn descriptor({ writable: false })\n\t\t},\n\t}\n)\n\n/**\n * Decorator that marks methods, properties, or classes as deprecated\n * Provides warning messages when deprecated items are used\n */\nexport const deprecated = Object.assign(\n\tdecorator({\n\t\tmethod(original, _target, propertyKey) {\n\t\t\treturn function (this: any, ...args: any[]) {\n\t\t\t\tdeprecated.warn(this, propertyKey)\n\t\t\t\treturn original.apply(this, args)\n\t\t\t}\n\t\t},\n\t\tgetter(original, _target, propertyKey) {\n\t\t\treturn function (this: any) {\n\t\t\t\tdeprecated.warn(this, propertyKey)\n\t\t\t\treturn original.call(this)\n\t\t\t}\n\t\t},\n\t\tsetter(original, _target, propertyKey) {\n\t\t\treturn function (this: any, value: any) {\n\t\t\t\tdeprecated.warn(this, propertyKey)\n\t\t\t\treturn original.call(this, value)\n\t\t\t}\n\t\t},\n\t\tclass(original) {\n\t\t\treturn class extends original {\n\t\t\t\tconstructor(...args: any[]) {\n\t\t\t\t\tsuper(...args)\n\t\t\t\t\tdeprecated.warn(this, 'constructor')\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\tdefault(message: string) {\n\t\t\treturn decorator({\n\t\t\t\tmethod(original, _target, propertyKey) {\n\t\t\t\t\treturn function (this: any, ...args: any[]) {\n\t\t\t\t\t\tdeprecated.warn(this, propertyKey, message)\n\t\t\t\t\t\treturn original.apply(this, args)\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\tgetter(original, _target, propertyKey) {\n\t\t\t\t\treturn function (this: any) {\n\t\t\t\t\t\tdeprecated.warn(this, propertyKey, message)\n\t\t\t\t\t\treturn original.call(this)\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\tsetter(original, _target, propertyKey) {\n\t\t\t\t\treturn function (this: any, value: any) {\n\t\t\t\t\t\tdeprecated.warn(this, propertyKey, message)\n\t\t\t\t\t\treturn original.call(this, value)\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\tclass(original) {\n\t\t\t\t\treturn class extends original {\n\t\t\t\t\t\tconstructor(...args: any[]) {\n\t\t\t\t\t\t\tsuper(...args)\n\t\t\t\t\t\t\tdeprecated.warn(this, 'constructor', message)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t})\n\t\t},\n\t}),\n\t{\n\t\twarn: (target: any, propertyKey: PropertyKey, message?: string) => {\n\t\t\toptions.warn(\n\t\t\t\t`${target.constructor.name}.${String(propertyKey)} is deprecated${message ? `: ${message}` : ''}`\n\t\t\t)\n\t\t},\n\t}\n)\n\n/**\n * Creates a debounced method decorator that delays execution until after the delay period has passed\n * @param delay - The delay in milliseconds\n * @returns A method decorator that debounces method calls\n */\nexport function debounce(delay: number) {\n\treturn decorator({\n\t\tmethod(original, _target, _propertyKey) {\n\t\t\tlet timeoutId: ReturnType<typeof setTimeout> | null = null\n\n\t\t\treturn function (this: any, ...args: any[]) {\n\t\t\t\t// Clear existing timeout\n\t\t\t\tif (timeoutId) {\n\t\t\t\t\tclearTimeout(timeoutId)\n\t\t\t\t}\n\n\t\t\t\t// Set new timeout\n\t\t\t\ttimeoutId = setTimeout(() => {\n\t\t\t\t\toriginal.apply(this, args)\n\t\t\t\t\ttimeoutId = null\n\t\t\t\t}, delay)\n\t\t\t}\n\t\t},\n\t})\n}\n\n/**\n * Creates a throttled method decorator that limits execution to once per delay period\n * @param delay - The delay in milliseconds\n * @returns A method decorator that throttles method calls\n */\nexport function throttle(delay: number) {\n\treturn decorator({\n\t\tmethod(original, _target, _propertyKey) {\n\t\t\tlet lastCallTime = 0\n\t\t\tlet timeoutId: ReturnType<typeof setTimeout> | null = null\n\n\t\t\treturn function (this: any, ...args: any[]) {\n\t\t\t\tconst now = Date.now()\n\n\t\t\t\t// If enough time has passed since last call, execute immediately\n\t\t\t\tif (now - lastCallTime >= delay) {\n\t\t\t\t\t// Clear any pending timeout since we're executing now\n\t\t\t\t\tif (timeoutId) {\n\t\t\t\t\t\tclearTimeout(timeoutId)\n\t\t\t\t\t\ttimeoutId = null\n\t\t\t\t\t}\n\t\t\t\t\tlastCallTime = now\n\t\t\t\t\treturn original.apply(this, args)\n\t\t\t\t}\n\n\t\t\t\t// Otherwise, schedule execution for when the delay period ends\n\t\t\t\tif (!timeoutId) {\n\t\t\t\t\tconst remainingTime = delay - (now - lastCallTime)\n\t\t\t\t\tconst scheduledArgs = [...args] // Capture args at scheduling time\n\t\t\t\t\ttimeoutId = setTimeout(() => {\n\t\t\t\t\t\tlastCallTime = Date.now()\n\t\t\t\t\t\toriginal.apply(this, scheduledArgs)\n\t\t\t\t\t\ttimeoutId = null\n\t\t\t\t\t}, remainingTime)\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t})\n}\n","export * from './async'\nexport * from './decorator'\nexport * from './destroyable'\nexport * from './diff'\nexport * from './eventful'\nexport * from './flavored'\nexport * from './indexable'\nexport * from './iterableWeak'\nexport * from './mixins'\nexport * from './promiseChain'\nexport * from './reactive'\nexport * from './std-decorators'\nexport {\n\tarrayEquals,\n\tdeepCompare,\n\tisConstructor,\n\tisDev,\n\tisObject,\n\tisProd,\n\tisTest,\n\tnamed,\n\ttag,\n\tzip,\n} from './utils'\nexport * from './zone'\n\n// Important: let it here!\nimport pkg from '../package.json'\n\nconst { version } = pkg\n\nconst GLOBAL_MUTTS_KEY = '__MUTTS_INSTANCE__'\nconst globalScope = (\n\ttypeof globalThis !== 'undefined'\n\t\t? globalThis\n\t\t: typeof window !== 'undefined'\n\t\t\t? window\n\t\t\t: typeof global !== 'undefined'\n\t\t\t\t? global\n\t\t\t\t: false\n) as any\nif (globalScope) {\n\tlet source = 'mutts/index'\n\ttry {\n\t\tif (typeof __filename !== 'undefined') source = __filename\n\t\telse if (typeof import.meta !== 'undefined' && import.meta.url) {\n\t\t\tsource = import.meta.url\n\t\t}\n\t} catch (_e) {}\n\n\tconst currentSourceInfo = { version, source, timestamp: Date.now() }\n\n\tif (globalScope[GLOBAL_MUTTS_KEY]) {\n\t\tconst existing = globalScope[GLOBAL_MUTTS_KEY]\n\t\tthrow new Error(\n\t\t\t`[Mutts] Multiple instances detected!\\n` +\n\t\t\t\t`Existing instance: ${JSON.stringify(existing, null, 2)}\\n` +\n\t\t\t\t`New instance: ${JSON.stringify(currentSourceInfo, null, 2)}\\n` +\n\t\t\t\t`This usually happens when 'mutts' is both installed as a dependency and bundled, ` +\n\t\t\t\t`or when different versions are loaded. ` +\n\t\t\t\t`Please check your build configuration (aliases, externals) to ensure a single source of truth.`\n\t\t)\n\t}\n\tglobalScope[GLOBAL_MUTTS_KEY] = currentSourceInfo\n}\n","import { FoolProof } from '../utils'\nimport { attend } from './buffer'\nimport { touched1 } from './change'\nimport { link } from './effect-context'\nimport { reactive } from './proxy'\nimport type { CleanupReason, EffectCloser } from './types'\n\n/**\n * Provides type-safe access to a source object's property within the organized callback.\n * @template Source - The type of the source object\n * @template Key - The type of the property key in the source object\n */\nexport type OrganizedAccess<Source extends Record<PropertyKey, any>, Key extends keyof Source> = {\n\t/** The property key being accessed */\n\treadonly key: Key\n\n\t/**\n\t * Gets the current value of the property from the source object\n\t * @returns The current value of the property\n\t */\n\tget(): Source[Key]\n\n\t/**\n\t * Updates the property value in the source object\n\t * @param value - The new value to set\n\t * @returns {boolean} True if the update was successful\n\t */\n\tset(value: Source[Key]): boolean\n\n\t/**\n\t * The current value of the property (equivalent to using get()/set() directly)\n\t */\n\tvalue: Source[Key]\n}\n\n/**\n * Callback function type for the organized function that processes each source property.\n * @template Source - The type of the source object\n * @template Target - The type of the target object\n */\nexport type OrganizedCallback<Source extends Record<PropertyKey, any>, Target extends object> = <\n\tKey extends keyof Source,\n>(\n\t/**\n\t * Accessor object for the current source property\n\t */\n\taccess: OrganizedAccess<Source, Key>,\n\n\t/**\n\t * The target object where organized data will be stored\n\t */\n\ttarget: Target\n) => EffectCloser | undefined\n\n/**\n * The result type of the organized function, combining the target object with cleanup capability.\n * @template Target - The type of the target object\n */\nexport type OrganizedResult<Target extends object> = Target\n\n/**\n * Organizes a source object's properties into a target object using a callback function.\n * This creates a reactive mapping between source properties and a target object,\n * automatically handling property additions, updates, and removals.\n *\n * @template Source - The type of the source object\n * @template Target - The type of the target object (defaults to Record<PropertyKey, any>)\n *\n * @param {Source} source - The source object to organize\n * @param {OrganizedCallback<Source, Target>} apply - Callback function that defines how each source property is mapped to the target\n * @param {Target} [baseTarget={}] - Optional base target object to use (will be made reactive if not already)\n *\n * @returns {OrganizedResult<Target>} The target object with cleanup capability\n *\n * @example\n * // Organize user permissions into role-based access\n * const user = reactive({ isAdmin: true, canEdit: false });\n * const permissions = organized(\n * user,\n * (access, target) => {\n * if (access.key === 'isAdmin') {\n * target.hasFullAccess = access.value;\n * }\n * target[`can${access.key.charAt(0).toUpperCase() + access.key.slice(1)}`] = access.value;\n * }\n * );\n *\n * @example\n * // Transform object structure with cleanup\n * const source = reactive({ firstName: 'John', lastName: 'Doe' });\n * const formatted = organized(\n * source,\n * (access, target) => {\n * if (access.key === 'firstName' || access.key === 'lastName') {\n * target.fullName = `${source.firstName} ${source.lastName}`.trim();\n * }\n * }\n * );\n *\n * @example\n * // Using with cleanup in a component\n * effect(() => {\n * const data = fetchData();\n * const organizedData = organized(data, (access, target) => {\n * // Transform data\n * });\n *\n * // The cleanup will be called automatically when the effect is disposed\n * return () => organizedData[cleanup]();\n * });\n */\nexport function organized<\n\tSource extends Record<PropertyKey, any>,\n\tTarget extends object = Record<PropertyKey, any>,\n>(\n\tsource: Source,\n\tapply: OrganizedCallback<Source, Target>,\n\tbaseTarget: Target = {} as Target\n): OrganizedResult<Target> {\n\tconst observedSource = reactive(source) as Source\n\tconst target = reactive(baseTarget) as Target\n\n\tconst stop = attend(\n\t\t() => {\n\t\t\tconst keys: PropertyKey[] = []\n\t\t\tfor (const key in observedSource) keys.push(key)\n\t\t\treturn keys\n\t\t},\n\t\t(key) => {\n\t\t\tconst sourceKey = key as keyof Source\n\t\t\tconst accessBase = {\n\t\t\t\tkey: sourceKey,\n\t\t\t\tget: () => FoolProof.get(observedSource, sourceKey, observedSource),\n\t\t\t\tset: (value: Source[typeof sourceKey]) =>\n\t\t\t\t\tFoolProof.set(observedSource, sourceKey, value, observedSource),\n\t\t\t}\n\t\t\tObject.defineProperty(accessBase, 'value', {\n\t\t\t\tget: accessBase.get,\n\t\t\t\tset: accessBase.set,\n\t\t\t\tconfigurable: true,\n\t\t\t\tenumerable: true,\n\t\t\t})\n\t\t\treturn apply(accessBase as OrganizedAccess<Source, typeof sourceKey>, target)\n\t\t}\n\t)\n\n\treturn link(target, (reason?: CleanupReason) => stop(reason)) as OrganizedResult<Target>\n}\n\n/**\n * Organizes a property on a target object\n * Shortcut for defineProperty/delete with touched signal\n * @param target - The target object\n * @param property - The property to organize\n * @param access - The access object\n * @returns The property descriptor\n */\nexport function organize<T>(\n\ttarget: object,\n\tproperty: PropertyKey,\n\taccess: { get?(): T; set?(value: T): boolean }\n) {\n\tObject.defineProperty(target, property, {\n\t\tget: access.get,\n\t\tset: access.set,\n\t\tconfigurable: true,\n\t\tenumerable: true,\n\t})\n\ttouched1(target, { type: 'set', prop: property }, property)\n\treturn () => delete (target as any)[property]\n}\n"],"names":["hooks","Set","asyncHooks","addHook","hook","add","delete","sanitizePromise","p","promiseContexts","WeakMap","captureRestorers","restorers","restorer","wrap","fn","capturedRestorers","args","undoers","restore","push","apply","this","res","then","Promise","resolve","reject","setTimeout","GLOBAL_ORIGINALS","Symbol","for","GLOBAL_PROMISE","originals","OriginalPromise","patchedThen","onFulfilled","onRejected","context","get","nextPromise","call","size","set","PatchedPromise","executor","wrappedResolve","wrappedReject","globalThis","prototype","catch","finally","all","allSettled","race","any","setInterval","setImmediate","requestAnimationFrame","queueMicrotask","Object","assign","value","has","reason","values","onFinally","defineProperty","species","configurable","_e","callback","nativeConstructors","Array","Date","Function","Map","WeakSet","Error","TypeError","ReferenceError","SyntaxError","RangeError","URIError","EvalError","Reflect","Proxy","RegExp","String","Number","Boolean","isConstructor","toString","startsWith","hasNode","Node","FoolProof","obj","prop","receiver","isOwnAccessor","opd","getOwnPropertyDescriptor","deepCompare","a","b","cache","getPrototypeOf","compared","isArray","length","i","getTime","val","found","bVal","key","foundMatch","bKey","keysA","keys","keysB","hasOwn","contentRefs","contentRef","container","seal","create","contentOf","writable","tag","name","defineProperties","toStringTag","named","_mode","process","env","NODE_ENV","undefined","isDev","isProd","isTest","DecoratorError","constructor","message","super","legacyDecorator","description","target","propertyKey","descriptor","class","includes","newGetter","getter","newSetter","setter","newMethod","method","default","modernDecorator","kind","rv","decorator","modern","legacy","contextOrKey","mode","_target","detectDecoratorMode","fr","FinalizationRegistry","f","destructor","allocatedValues","DestructionError","msg","destroyedHandler","throw","allocated","original","arrayDiff","A","B","start","endA","endB","lenA","lenB","indexA","indexB","sliceA","sliceB","slice","maxD","Math","min","vOffset","V","Int32Array","history","d","k","x","y","buildPatches","offset","finalX","finalY","finalD","finalK","ops","prev","prevK","down","prevXEnd","xStart","yStart","patches","currA","currB","patchA","patchB","flush","op","events","eventBehavior","on","eventOrEvents","cb","e","callbacks","off","emit","event","perEvent","eventful","fct","use","cached","flavored","flavors","flavorOptions","defaultOptions","opts","targetIndex","optionsIndex","newArgs","currentOptions","isObject","_a","getAt","setAt","forwardArray","ArrayReadForward","iterator","map","callbackfn","thisArg","filter","predicate","reduce","initialValue","reduceRight","forEach","find","findIndex","findLast","findLastIndex","searchElement","fromIndex","indexOf","lastIndexOf","end","concat","items","every","some","join","separator","entries","toLocaleString","locales","options","at","index","flat","depth","flatMap","toReversed","reverse","toSorted","compareFn","sort","toSpliced","deleteCount","with","unscopables","IterableWeakMap","uuids","refs","registry","uuid","v","createIterator","keyRef","deref","clear","unregister","crypto","randomUUID","WeakRef","register","_value","_key","IterableWeakSet","_b","union","other","others","that","intersection","difference","symmetricDifference","isSubsetOf","isSupersetOf","isDisjointFrom","mixin","mixinFunction","unwrapFunction","mixinCache","MixedBase","_thisArg","baseClass","usedBase","ProxiedBaseClass","originalPrototype","proxiedPrototype","setPrototypeOf","mixedClass","forward","alreadyChained","promiseProxyHandler","chainPromise","r","promiseForward","objectProxyHandler","chainObject","given","chainable","t","chained","debugHooks","stack","isu","z","AZone","enter","active","leave","entered","root","zoned","Zone","ZoneHistory","controlled","self","present","getOwnPropertyDescriptors","added","ZoneAggregator","zones","_ZoneAggregator_zones","__classPrivateFieldGet","asyncZone","zone","rootFunctionSymbol","effectToReactiveObjects","watchers","effectNodes","getEffectNode","effect","node","reverseRoots","markWithRoot","existingRef","existing","rootName","existingName","fnName","getRoot","effectHistory","effectAggregator","isRunning","getActiveEffect","cleanups","link","cleanupFns","effectMarker","formatTrigger","evolution","dependency","touch","detail","type","parts","unreactiveProperties","allProps","keysOf","ReactiveErrorCode","ReactiveError","debugInfo","code","cause","_effect","chain","_targets","_caller","beginChain","endChain","garbageCollected","_fn","touched","_obj","_evolution","_props","_deps","skipRunningEffect","effectRun","_reaction","maxEffectChain","maxTriggerPerBatch","maxEffectReaction","onMemoizationDiscrepancy","cycleHandling","isVerificationRun","maxDeepWatchDepth","instanceMembers","ignoreAccessors","recursiveTouching","asyncMode","warn","introspection","gatherReasons","lineages","logErrors","enableHistory","historySize","optionCall","error","prodPreset","devPreset","objectToProxy","proxyToObject","unwrap","isReactive","activationRegistry","dependencyStacks","assertUntrackedFlag","getDependencyStack","objStacks","dependant","currentActiveEffect","dependencyHook","objectWatchers","deps","effectObjects","lineageConfig","propStacks","findCycleInChain","roots","seen","formatRoots","limit","names","activationLog","recordActivation","effectData","objData","count","unshift","pop","MaxReactionExceeded","caught","onThrow","catchers","onEffectThrow","effectTriggers","effectTriggeredBy","causesClosure","consequencesClosure","broken","getOrCreateClosure","closure","hasPathExcluding","exclude","visited","queue","current","shift","triggers","next","batchStack","hasBatched","bs","executingStack","decrementInDegreesForExecuted","batch","executedRoot","consequences","consequenceRoot","currentDegree","inDegrees","findPath","startRoot","endRoot","path","newPath","targetRoot","result","getCyclePathForEdge","callerRoot","addToBatch","caller","immediate","currentBatch","pendingTriggers","nextReason","mergePropChange","into","from","reasons","stopped","targetConsequences","wouldCreateCycle","cyclePath","cycleMessage","causalChain","lineage","creationStack","CycleDetected","cycle","details","newTriggers","triggeredBy","uConsequences","vCauses","uCausesSet","vConsequencesSet","xConsequences","addGraphEdge","addBatchCleanup","cleanup","deferreds","defer","findCycle","recursionStack","cycleStart","executeNext","effectuatedRoots","nextEffect","nextRoot","first","getCyclePath","consequence","consequenceConsequences","BrokenEffects","isNewBatch","success","firstReturn","activeEffect","activeRoot","inDegree","causes","causeRoot","computeAllInDegrees","trace","queued","MaxDepthExceeded","queuedCount","deferred","atomic","atomicEffect","captured","effectOptions","runEffect","prevCleanup","untracked","runningPromise","cancelPrevious","abort","effectStopped","reactionCleanup","cleanupReaction","toCleanup","access","reaction","thrower","catches","parent","parentNode","forwardThrow","errorToThrow","tracked","originalPromise","cancelReject","cancelPromise","_","cancelError","reactiveObj","children","childReason","childCleanup","ascended","abortController","ascend","signal","AbortController","opaque","isOpaque","stopEffect","rootCauses","rootConsequences","sourceRoot","causeConsequences","consequenceCauses","yCauses","cleanupEffectFromGraph","callIfCollected","subEffectCleanup","objectParents","objectsWithDeepWatchers","deepWatcherCount","deepWatchers","effectToDeepWatchedObjects","addBackReference","child","parents","removeBackReference","entry","needsBackReferences","hasParentWithDeepWatchers","bubbleUpChange","changedObject","parentDeepWatchers","touchLineage","watcher","dependencyStack","states","addState","state","getState","collectEffects","effects","keyChains","sourceEffect","touched1","props","structural","absent","addUnreactiveProps","proto","isUnreactiveProp","marker","nonReactiveClass","cls","c","isNonReactive","getPrototypeToken","shouldRecurseTouch","oldValue","newValue","notifyPropertyChange","targetObj","hadProperty","origin","changes","recursiveTouch","oldRef","newRef","oldMap","objects","migrateWatchers","notifications","combinedEffects","effectCauses","allowedEffects","originWatchers","originEffects","notification","currentEffects","propsArray","filteredEffects","associated","hasAncestorInSet","dispatchNotifications","gather","touchedOpaque","collectObjectKeys","ownKeys","oldObj","newObj","mapped","hasVisitedPair","oldArray","newArray","_visited","local","oldLength","newLength","max","hasOld","hasNew","oldEntry","newEntry","is","diffArrayElements","oldKeys","newKeys","diffObjectProperties","allowedSet","window","o","nonReactive","document","Element","HTMLElement","EventTarget","HTMLCollection","NodeList","metaProtos","wrapProtos","arrayLengths","hasReentry","subsRegister","internalUntracked","reactiveHandlers","metaProto","desc","ownDesc","wrapProto","isOwnProp","shouldIgnoreAccessor","hasProp","owner","raw","isInheritedAccess","reactiveValue","reactiveObject","unwrapped","enumerable","oldVal","isArrayLength","deleteProperty","reactiveClasses","ReactiveBase","base","reactive","anyTarget","subProxy","getExistingProxy","proxy","storeProxyRelationship","Reactive","attend","source","enumerate","keyEffects","outer","stop","morphRecord","pure","track","itemEffects","stopItem","computeItem","_cache","stateSnapshot","stopMain","morph","input","indexRef","n","NaN","isNaN","newInput","diffs","diff","idx","_entry","newIdx","splice","fill","invalidates","morphArray","morphMap","_opt","deepWatch","wrappedCallback","traverseAndTrack","memoizedRegistry","wrapperRegistry","getBranch","tree","branches","branch","memoizeFunction","fnRoot","cacheRoot","memoized","arg","lenient","wasVerification","fresh","makeMemoizeDecorator","memoizeOpts","wrapper","origRoot","originalGetter","_receiver","memoizeObject","memoize","unsetYet","watch","changed","deep","deepCleanup","cbCleanup","old","watchCallBack","watchObject","unreactive","arg1","parentMarker","makeReactiveIterator","done","makeReactiveEntriesIterator","Indexer","indexLess","asIndex","charCodeAt","ReactiveArrayWrapper","_classSuper","copyWithin","arguments","acc","wrappedCompare","_fill_decorators","_pop_decorators","_push_decorators","_shift_decorators","_sort_decorators","_unshift_decorators","__runInitializers","_instanceExtraInitializers","__esDecorate","static","private","metadata","_metadata","_copyWithin_decorators","_reverse_decorators","_splice_decorators","ReactiveWeakMap","hadKey","ReactiveMap","hadEntries","it","nativeNext","bind","ReactiveWeakSet","had","ReactiveSet","toJSON","profileInfo","syncCalculating","alreadyCalculating","object","properties","Base","hidden","frozen","readonly","deprecated","version","pkg","GLOBAL_MUTTS_KEY","globalScope","global","__filename","url","location","require","pathToFileURL","href","_documentCurrentScript","tagName","toUpperCase","src","URL","baseURI","currentSourceInfo","timestamp","now","JSON","stringify","destructorObj","destroy","destructors","getOwnPropertyNames","isDestroyable","myDestructor","destruction","accessor","Indexable","getLength","numProp","setLength","len","received","programmaticallySetValue","pValue","called","transform","delay","_propertyKey","timeoutId","clearTimeout","formatCleanupReason","indent","repeat","rawResult","liftCleanup","sourceProto","newDesc","oldDesc","sameAccessor","property","baseTarget","observedSource","sourceKey","accessBase","fetcher","resource","loading","latest","reload","reloadSignal","counter","load","creation","lazyInit","id","promise","err","lastCallTime","remainingTime","scheduledArgs","unlink","timeout","timer","maxLength","arr","tuple"],"mappings":"2SAIO,MAAMA,EAAQ,IAAIC,IAEZC,EAAa,CACzBC,QAAQC,IACPJ,EAAMK,IAAID,GACH,IAAMJ,EAAMM,OAAOF,IAO3BG,gBAAgBC,GACRA,GCfHC,EAAkB,IAAIC,QAkB5B,SAASC,IACR,MAAMC,E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AAImD,MAAM,yBAAyBk3B,SACxCA,KAGN,qBzB5J0D/6B,GACzD,IAAKA,EAAK6F,OAAQ,MAAO,GACzB,MAAMo1B,EAAY9vB,KAAKmgB,OAAOtrB,EAAKgP,IAAKksB,GAAQA,EAAIr1B,SAEpD,IAAK,IAAIC,EAAI,EAAGA,EAAIm1B,EAAWn1B,IAAK,CACnC,MAAMq1B,EAAQn7B,EAAKgP,IAAKksB,GAAQA,EAAIp1B,UAC9Bq1B,CACP,CACD"}
|
|
1
|
+
{"version":3,"file":"mutts.umd.min.js","sources":["../src/async/index.ts","../src/async/browser.ts","../src/utils.ts","../src/decorator.ts","../src/destroyable.ts","../src/diff.ts","../src/eventful.ts","../src/flavored.ts","../src/indexable.ts","../src/iterableWeak.ts","../src/mixins.ts","../src/promiseChain.ts","../src/reactive/debug-hooks.ts","../src/zone.ts","../src/reactive/registry.ts","../src/reactive/effect-context.ts","../src/reactive/types.ts","../src/reactive/tracking.ts","../src/reactive/effects.ts","../src/reactive/deep-watch-state.ts","../src/reactive/change.ts","../src/reactive/non-reactive.ts","../src/reactive/deep-touch.ts","../src/reactive/proxy.ts","../src/reactive/buffer.ts","../src/reactive/deep-watch.ts","../src/reactive/memoize.ts","../src/reactive/satellite.ts","../src/reactive/iterator-helpers.ts","../src/reactive/array.ts","../src/reactive/map.ts","../src/reactive/set.ts","../src/reactive/index.ts","../src/std-decorators.ts","../src/index.ts","../src/reactive/record.ts"],"sourcesContent":["export type Restorer = () => () => void\nexport type Hook = () => Restorer\n\n// Queue for hooks registered before the environment is ready (circular dependency fix)\nexport const hooks = new Set<Hook>()\n\nexport const asyncHooks = {\n\taddHook(hook: Hook): () => void {\n\t\thooks.add(hook)\n\t\treturn () => hooks.delete(hook)\n\t},\n\t/**\n\t * [Hack] Sanitize a promise (or value) to prevent context leaks.\n\t * Default: Identity function.\n\t * Browser: Uses Macrotask wrapping to break microtask chains.\n\t */\n\tsanitizePromise(p: any): any {\n\t\treturn p\n\t},\n}\n\n/**\n * Register a hook that will be called whenever an asynchronous operation is initiated.\n * The hook should return a restorer function which will be called just before the async callback runs.\n * That restorer should in turn return an undoer function which will be called just after the async callback finishes.\n */\nexport const asyncHook = (hook: Hook) => asyncHooks.addHook(hook)\n","import { asyncHooks, hooks, type Restorer } from '.'\n\nconst promiseContexts = new WeakMap<Promise<any>, Set<Restorer>>()\n\n// [HACK]: Sanitization\n// If a Promise is created inside the zone, it carries the \"Sticky\" zone context.\n// If returned to the outer scope, that context leaks. We wrap it in a new Promise\n// created here (in the outer scope) to break the chain and sanitize the return value.\n// See BROWSER_ASYNC_POLYFILL.md for full details.\nasyncHooks.sanitizePromise = (res: any) => {\n\tif (res && typeof (res as any).then === 'function') {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tsetTimeout(() => {\n\t\t\t\t;(res as any).then(resolve, reject)\n\t\t\t}, 0)\n\t\t})\n\t}\n\treturn res\n}\n\nfunction captureRestorers() {\n\tconst restorers = new Set<Restorer>()\n\tfor (const hook of hooks) {\n\t\tconst restorer = hook()\n\t\tif (restorer) restorers.add(restorer)\n\t}\n\treturn restorers\n}\n\nfunction wrap<Args extends any[], R>(\n\tfn: ((...args: Args) => R) | null | undefined,\n\tcapturedRestorers?: Set<Restorer>\n) {\n\tif (typeof fn !== 'function') return fn\n\tconst restorers = capturedRestorers || captureRestorers()\n\treturn function (this: any, ...args: Args) {\n\t\tconst undoers: (() => void)[] = []\n\t\tfor (const restore of restorers) undoers.push(restore())\n\t\ttry {\n\t\t\treturn fn.apply(this, args)\n\t\t} finally {\n\t\t\t/* cf BROWSER_ASYNC_POLYFILL.md\n\t\t\t// Note: my fear about this code: in between 2~3~4 microtask waits, some other microtasks might have started, stopped, ...\n\t\t\t// We might be in the middle of another promise hook trying to setup the zone\n\t\t\t// TODO We might wish to have a flag :asyncZone.acquired - like a semaphore - that we falsify here and set back when we setup the zone\n\t\t\t// - but this might perhaps be an overkill creating more problems than it solves\n\t\t\tif (originals.queueMicrotask) {\n\t\t\t\t// Double microtask ensures we run after the first await resumption microtask\n\t\t\t\toriginals.queueMicrotask.call(globalThis, () => {\n\t\t\t\t\toriginals.queueMicrotask.call(globalThis, () => {\n\t\t\t\t\t\toriginals.queueMicrotask.call(globalThis, () => {\n\t\t\t\t\t\t\tfor (let i = undoers.length - 1; i >= 0; i--) undoers[i]()\n\t\t\t\t\t\t})\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t} else {\n\t\t\t\tfor (let i = undoers.length - 1; i >= 0; i--) undoers[i]()\n\t\t\t}*/\n\t\t}\n\t}\n}\n\nconst GLOBAL_ORIGINALS = Symbol.for('mutts.originals')\nconst GLOBAL_PROMISE = Symbol.for('mutts.OriginalPromise')\n\nlet originals: any\nlet OriginalPromise: any\n\nif ((globalThis as any)[GLOBAL_ORIGINALS]) {\n\toriginals = (globalThis as any)[GLOBAL_ORIGINALS]\n\tOriginalPromise = (globalThis as any)[GLOBAL_PROMISE]\n} else {\n\tOriginalPromise = globalThis.Promise\n\toriginals = {\n\t\t// biome-ignore lint/suspicious/noThenProperty: Intentional Promise.prototype patching\n\t\tthen: OriginalPromise.prototype.then,\n\t\tcatch: OriginalPromise.prototype.catch,\n\t\tfinally: OriginalPromise.prototype.finally,\n\t\tresolve: OriginalPromise.resolve,\n\t\treject: OriginalPromise.reject,\n\t\tall: OriginalPromise.all,\n\t\tallSettled: (OriginalPromise as any).allSettled,\n\t\trace: OriginalPromise.race,\n\t\tany: (OriginalPromise as any).any,\n\t\tsetTimeout: globalThis.setTimeout,\n\t\tsetInterval: globalThis.setInterval,\n\t\tsetImmediate: (globalThis as any).setImmediate,\n\t\trequestAnimationFrame: (globalThis as any).requestAnimationFrame,\n\t\tqueueMicrotask: globalThis.queueMicrotask,\n\t}\n\t;(globalThis as any)[GLOBAL_ORIGINALS] = originals\n\t;(globalThis as any)[GLOBAL_PROMISE] = OriginalPromise\n}\n\n// Ensure modern statics are captured even if originals was cached from an older version\nif (!originals.allSettled) originals.allSettled = (OriginalPromise as any).allSettled\nif (!originals.any) originals.any = (OriginalPromise as any).any\nif (!originals.race) originals.race = OriginalPromise.race\n\nfunction patchedThen(this: any, onFulfilled: any, onRejected: any) {\n\tconst context = promiseContexts.get(this) || captureRestorers()\n\tconst nextPromise = originals.then.call(\n\t\tthis,\n\t\twrap(onFulfilled, context),\n\t\twrap(onRejected, context)\n\t)\n\tif (context.size > 0) promiseContexts.set(nextPromise, context)\n\treturn nextPromise\n}\n\nfunction patchedCatch(this: any, onRejected: any) {\n\tconst context = promiseContexts.get(this) || captureRestorers()\n\tconst nextPromise = originals.catch.call(this, wrap(onRejected, context))\n\tif (context.size > 0) promiseContexts.set(nextPromise, context)\n\treturn nextPromise\n}\n\nfunction patchedFinally(this: any, onFinally: any) {\n\tconst context = promiseContexts.get(this) || captureRestorers()\n\tconst nextPromise = originals.finally.call(this, wrap(onFinally, context))\n\tif (context.size > 0) promiseContexts.set(nextPromise, context)\n\treturn nextPromise\n}\n\nfunction PatchedPromise<T>(\n\tthis: any,\n\texecutor: (resolve: (value: T | PromiseLike<T>) => void, reject: (reason?: any) => void) => void\n) {\n\tif (typeof executor === 'function') {\n\t\tconst p = new OriginalPromise((resolve, reject) => {\n\t\t\tconst wrappedResolve = wrap(resolve)\n\t\t\tconst wrappedReject = wrap(reject)\n\t\t\texecutor(wrappedResolve, wrappedReject)\n\t\t})\n\t\tconst context = captureRestorers()\n\t\tpromiseContexts.set(p, context) // Always set, even if empty (Sticky Root)\n\t\treturn p\n\t}\n\treturn new OriginalPromise(executor)\n}\n\n// Copy statics\nObject.assign(PatchedPromise, OriginalPromise as any)\n\n// Inherit prototype for instanceof checks\nPatchedPromise.prototype = OriginalPromise.prototype\n\nPatchedPromise.resolve = (<T>(value?: T | PromiseLike<T>): Promise<T> => {\n\tconst p = originals.resolve.call(OriginalPromise, value) as Promise<T>\n\tconst context = captureRestorers()\n\t// Ensure we don't overwrite if it already has context (e.g. from constructor)\n\tif (context.size > 0 && !promiseContexts.has(p)) promiseContexts.set(p, context)\n\treturn p\n}) as any\n\nPatchedPromise.reject = (<T = never>(reason?: any): Promise<T> => {\n\tconst p = originals.reject.call(OriginalPromise, reason) as Promise<T>\n\tconst context = captureRestorers()\n\tif (context.size > 0) promiseContexts.set(p, context)\n\treturn p\n}) as any\n\nPatchedPromise.all = (<T>(values: Iterable<T | PromiseLike<T>>): Promise<Awaited<T>[]> => {\n\tconst p = originals.all.call(OriginalPromise, values) as Promise<Awaited<T>[]>\n\tconst context = captureRestorers()\n\tif (context.size > 0) promiseContexts.set(p, context)\n\treturn p\n}) as any\n\nPatchedPromise.allSettled = (<T>(\n\tvalues: Iterable<T | PromiseLike<T>>\n): Promise<PromiseSettledResult<Awaited<T>>[]> => {\n\tconst p = (originals.allSettled as any).call(OriginalPromise, values)\n\tconst context = captureRestorers()\n\tif (context.size > 0) promiseContexts.set(p, context)\n\treturn p\n}) as any\n\nPatchedPromise.race = (<T>(values: Iterable<T | PromiseLike<T>>): Promise<Awaited<T>> => {\n\tconst p = originals.race.call(OriginalPromise, values) as Promise<Awaited<T>>\n\tconst context = captureRestorers()\n\tif (context.size > 0) promiseContexts.set(p, context)\n\treturn p\n}) as any\n\nPatchedPromise.any = (<T>(values: Iterable<T | PromiseLike<T>>): Promise<Awaited<T>> => {\n\tconst p = (originals.any as any).call(OriginalPromise, values)\n\tconst context = captureRestorers()\n\tif (context.size > 0) promiseContexts.set(p, context)\n\treturn p\n}) as any\n\n// Only apply patches if not already applied (or re-apply safely)\n// Note: OriginalPromise.prototype might be shared if we used the global one.\n// We must ensure we don't patch it twice if it's the SAME object.\nif (OriginalPromise.prototype.then !== patchedThen) {\n\t// biome-ignore lint/suspicious/noThenProperty: Intentional Promise.prototype patching\n\tOriginalPromise.prototype.then = patchedThen as any\n\tOriginalPromise.prototype.catch = patchedCatch as any\n\tOriginalPromise.prototype.finally = patchedFinally as any\n}\n\ntry {\n\tObject.defineProperty(OriginalPromise, Symbol.species, {\n\t\tget: () => PatchedPromise,\n\t\tconfigurable: true,\n\t})\n} catch (_e) {}\n\n;(globalThis as any).Promise = PatchedPromise\n\nglobalThis.setTimeout = ((callback: Function, ...args: any[]) => {\n\treturn originals.setTimeout.call(globalThis, wrap(callback as any), ...args)\n}) as any\n\nglobalThis.setInterval = ((callback: Function, ...args: any[]) => {\n\treturn originals.setInterval.call(globalThis, wrap(callback as any), ...args)\n}) as any\n\nif (originals.setImmediate) {\n\t;(globalThis as any).setImmediate = ((callback: Function, ...args: any[]) => {\n\t\treturn originals.setImmediate.call(globalThis, wrap(callback as any), ...args)\n\t}) as any\n}\n\nif (originals.requestAnimationFrame) {\n\tglobalThis.requestAnimationFrame = (callback: FrameRequestCallback) => {\n\t\treturn originals.requestAnimationFrame.call(globalThis, wrap(callback))\n\t}\n}\n\nif (originals.queueMicrotask) {\n\tglobalThis.queueMicrotask = (callback: VoidFunction): void => {\n\t\toriginals.queueMicrotask.call(globalThis, wrap(callback))\n\t}\n}\n","type ElementTypes<T extends readonly unknown[]> = {\n\t[K in keyof T]: T[K] extends readonly (infer U)[] ? U : T[K]\n}\n\n/**\n * Yields tuples containing elements from each input array, stopping at the longest array length\n * @param args - Arrays to zip together\n * @returns Generator yielding tuples containing elements from each input array\n */\nexport function* zip<T extends (readonly unknown[])[]>(...args: T): Generator<ElementTypes<T>> {\n\tif (!args.length) return []\n\tconst maxLength = Math.max(...args.map((arr) => arr.length))\n\n\tfor (let i = 0; i < maxLength; i++) {\n\t\tconst tuple = args.map((arr) => arr[i]) as ElementTypes<T>\n\t\tyield tuple\n\t}\n}\n\n/**\n * Checks if two arrays are strictly equal (shallow comparison)\n * @param a - First value\n * @param b - Second value\n * @returns True if arrays are equal or values are strictly equal\n */\nexport function arrayEquals(a: any, b: any): boolean {\n\tif (!Array.isArray(a) || !Array.isArray(b)) return false\n\tif (a === b) return true\n\tif (a.length !== b.length) return false\n\tfor (let i = 0; i < a.length; i++) {\n\t\tif (a[i] !== b[i]) return false\n\t}\n\treturn true\n}\n\nconst nativeConstructors = new Set<Function>([\n\tObject,\n\tArray,\n\tDate,\n\tFunction,\n\tSet,\n\tMap,\n\tWeakMap,\n\tWeakSet,\n\tPromise,\n\tError,\n\tTypeError,\n\tReferenceError,\n\tSyntaxError,\n\tRangeError,\n\tURIError,\n\tEvalError,\n\tReflect,\n\tProxy,\n\tRegExp,\n\tString,\n\tNumber,\n\tBoolean,\n] as Function[])\n/**\n * Checks if a function is a constructor (class or constructor function)\n * @param fn - The function to check\n * @returns True if the function is a constructor\n */\nexport function isConstructor(fn: Function): boolean {\n\treturn (\n\t\tfn &&\n\t\ttypeof fn === 'function' &&\n\t\t(nativeConstructors.has(fn) || fn.toString?.().startsWith('class '))\n\t)\n}\n\n/**\n * Checks if a value is an object\n * @param value - The value to check\n * @returns True if the value is an object\n */\nexport function isObject(value: any): value is object {\n\treturn (\n\t\ttypeof value === 'object' &&\n\t\tvalue !== null &&\n\t\t!Array.isArray(value) &&\n\t\t!(\n\t\t\tvalue instanceof Date ||\n\t\t\tvalue instanceof RegExp ||\n\t\t\tvalue instanceof Error ||\n\t\t\tvalue instanceof Set ||\n\t\t\tvalue instanceof Map ||\n\t\t\tvalue instanceof WeakSet ||\n\t\t\tvalue instanceof WeakMap ||\n\t\t\tvalue instanceof Promise ||\n\t\t\tvalue instanceof Function\n\t\t)\n\t)\n}\n\nconst hasNode = typeof Node !== 'undefined'\nexport const FoolProof = {\n\tget(obj: any, prop: any, receiver: any) {\n\t\tif (hasNode && obj instanceof Node) return (obj as any)[prop]\n\t\treturn Reflect.get(obj, prop, receiver)\n\t},\n\tset(obj: any, prop: any, value: any, receiver: any) {\n\t\tif (hasNode && obj instanceof Node) {\n\t\t\t;(obj as any)[prop] = value\n\t\t\treturn true\n\t\t} /*\n\t\tif (!(obj instanceof Object) && !Object.hasOwn(obj, prop)) {\n\t\t\tObject.defineProperty(obj, prop, {\n\t\t\t\tvalue,\n\t\t\t\tconfigurable: true,\n\t\t\t\twritable: true,\n\t\t\t\tenumerable: true,\n\t\t\t})\n\t\t\treturn true\n\t\t}*/\n\t\treturn Reflect.set(obj, prop, value, receiver)\n\t},\n}\n\nexport function isOwnAccessor(obj: any, prop: any) {\n\tconst opd = Object.getOwnPropertyDescriptor(obj, prop)\n\treturn !!(opd?.get || opd?.set)\n}\n\n/**\n * Symbol used to provide custom comparison logic for an object.\n */\nexport const CompareSymbol = Symbol.for('mutts.compare')\n\n/**\n */\nexport function deepCompare(a: any, b: any, cache = new Map<object, Set<object>>()): boolean {\n\tif (a === b) return true\n\n\tif (typeof a !== 'object' || a === null || typeof b !== 'object' || b === null) {\n\t\treturn a === b\n\t}\n\n\t// Custom comparison support\n\tif (typeof (a as any)[CompareSymbol] === 'function') {\n\t\treturn (a as any)[CompareSymbol](b, (x: any, y: any) => deepCompare(x, y, cache))\n\t}\n\tif (typeof (b as any)[CompareSymbol] === 'function') {\n\t\treturn (b as any)[CompareSymbol](a, (x: any, y: any) => deepCompare(x, y, cache))\n\t}\n\n\t// Prototype check\n\tif (Object.getPrototypeOf(a) !== Object.getPrototypeOf(b)) return false\n\n\t// Circular reference protection\n\tlet compared = cache.get(a)\n\tif (compared?.has(b)) return true\n\tif (!compared) {\n\t\tcompared = new Set()\n\t\tcache.set(a, compared)\n\t}\n\tcompared.add(b)\n\n\t// Handle specific object types\n\tif (Array.isArray(a)) {\n\t\tif (!Array.isArray(b) || a.length !== b.length) return false\n\t\tfor (let i = 0; i < a.length; i++) {\n\t\t\tif (!deepCompare(a[i], b[i], cache)) return false\n\t\t}\n\t\treturn true\n\t}\n\n\tif (a instanceof Date) return b instanceof Date && a.getTime() === b.getTime()\n\tif (a instanceof RegExp) return b instanceof RegExp && a.toString() === b.toString()\n\n\tif (a instanceof Set) {\n\t\tif (!(b instanceof Set) || a.size !== b.size) return false\n\t\tfor (const val of a) {\n\t\t\tlet found = false\n\t\t\tfor (const bVal of b) {\n\t\t\t\tif (deepCompare(val, bVal, cache)) {\n\t\t\t\t\tfound = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!found) return false\n\t\t}\n\t\treturn true\n\t}\n\tif (a instanceof Map) {\n\t\tif (!(b instanceof Map) || a.size !== b.size) return false\n\t\tfor (const [key, val] of a) {\n\t\t\tif (!b.has(key)) {\n\t\t\t\tlet foundMatch = false\n\t\t\t\tfor (const [bKey, bVal] of b) {\n\t\t\t\t\tif (deepCompare(key, bKey, cache) && deepCompare(val, bVal, cache)) {\n\t\t\t\t\t\tfoundMatch = true\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (!foundMatch) return false\n\t\t\t} else if (!deepCompare(val, b.get(key), cache)) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\treturn true\n\t}\n\n\t// Compare own properties\n\tconst keysA = Object.keys(a)\n\tconst keysB = Object.keys(b)\n\tif (keysA.length !== keysB.length) return false\n\n\tfor (const key of keysA) {\n\t\tif (!Object.hasOwn(b, key) || !deepCompare(a[key], b[key], cache)) return false\n\t}\n\n\treturn true\n}\n\n// Internal use: Used for reactive sets/maps to differentiate between different reactive containers: `x.get('aKey')` vs. `x['aKey']`\nconst contentRefs = new WeakMap<object, any>()\nexport function contentRef(container: object) {\n\tif (!contentRefs.has(container))\n\t\tcontentRefs.set(\n\t\t\tcontainer,\n\t\t\tObject.seal(\n\t\t\t\tObject.create(null, {\n\t\t\t\t\tcontentOf: { value: container, writable: false, configurable: false },\n\t\t\t\t})\n\t\t\t)\n\t\t)\n\treturn contentRefs.get(container)\n}\n\n/**\n * Tags an object with a name\n * @param name - The name to tag the object with\n * @param obj - The object to tag\n * @returns The object with the tag\n */\nexport function tag<T extends object>(name: string, obj: T): T {\n\tObject.defineProperties(obj, {\n\t\t[Symbol.toStringTag]: {\n\t\t\tvalue: name,\n\t\t\twritable: false,\n\t\t\tconfigurable: true,\n\t\t},\n\t\ttoString: {\n\t\t\tvalue: () => name,\n\t\t\twritable: false,\n\t\t\tconfigurable: true,\n\t\t},\n\t})\n\treturn obj\n}\n\n/**\n * Renames a function with a new name\n * @param name - The new name for the function\n * @param fn - The function to rename\n * @returns The function with the new name\n */\nexport function named<T extends Function>(name: string, fn: T): T {\n\tObject.defineProperty(fn, 'name', {\n\t\tvalue: fn.name ? `${fn.name}::${name}` : name,\n\t\twritable: false,\n\t\tconfigurable: true,\n\t})\n\treturn fn\n}\n\nexport function* stringKeys(o: object) {\n\tfor (const key in o) yield key\n}\n\nconst runtimeGlobals = globalThis as typeof globalThis & {\n\tprocess?: {\n\t\tenv?: {\n\t\t\tNODE_ENV?: string\n\t\t}\n\t}\n}\n\nconst _mode: string =\n\truntimeGlobals.process?.env?.NODE_ENV ||\n\t(typeof import.meta !== 'undefined' && (import.meta as any).env?.MODE) ||\n\t'production'\n\nexport const isDev = _mode === 'development'\nexport const isProd = _mode === 'production'\nexport const isTest = _mode === 'test'\n","// biome-ignore-all lint/suspicious/noConfusingVoidType: We *love* voids\n// Standardized decorator system that works with both Legacy and Modern decorators\n\nimport { isConstructor } from './utils'\n\n/**\n * Error thrown when decorator operations fail\n */\nexport class DecoratorError extends Error {\n\tconstructor(message: string) {\n\t\tsuper(message)\n\t\tthis.name = 'DecoratorException'\n\t}\n}\n//#region all decorator types\n\n// Used for get/set and method decorators\n/**\n * Legacy property decorator type for methods, getters, and setters\n */\nexport type LegacyPropertyDecorator<T> = (\n\ttarget: T,\n\tname: string | symbol,\n\tdescriptor: PropertyDescriptor\n) => any\n\n/**\n * Legacy class decorator type\n */\nexport type LegacyClassDecorator<T> = (target: T) => any\n\n/**\n * Modern method decorator type\n */\nexport type ModernMethodDecorator<T> = (target: T, context: ClassMethodDecoratorContext) => any\n\n/**\n * Modern getter decorator type\n */\nexport type ModernGetterDecorator<T> = (target: T, context: ClassGetterDecoratorContext) => any\n\n/**\n * Modern setter decorator type\n */\nexport type ModernSetterDecorator<T> = (target: T, context: ClassSetterDecoratorContext) => any\n\n/**\n * Modern accessor decorator type\n */\nexport type ModernAccessorDecorator<T> = (target: T, context: ClassAccessorDecoratorContext) => any\n\n/**\n * Modern class decorator type\n */\nexport type ModernClassDecorator<T> = (target: T, context: ClassDecoratorContext) => any\n\n//#endregion\n\ntype DDMethod<T> = (\n\toriginal: (this: T, ...args: any[]) => any,\n\ttarget: any,\n\tname: PropertyKey\n) => ((this: T, ...args: any[]) => any) | void\n\ntype DDGetter<T> = (\n\toriginal: (this: T) => any,\n\ttarget: any,\n\tname: PropertyKey\n) => ((this: T) => any) | void\n\ntype DDSetter<T> = (\n\toriginal: (this: T, value: any) => void,\n\ttarget: any,\n\tname: PropertyKey\n) => ((this: T, value: any) => void) | void\n\ntype DDClass<T> = <Ctor extends new (...args: any[]) => T = new (...args: any[]) => T>(\n\ttarget: Ctor\n) => Ctor | void\n/**\n * Description object for creating decorators that work with both Legacy and Modern decorator proposals\n */\nexport interface DecoratorDescription<T> {\n\t/** Handler for method decorators */\n\tmethod?: DDMethod<T>\n\t/** Handler for class decorators */\n\tclass?: DDClass<T>\n\t/** Handler for getter decorators */\n\tgetter?: DDGetter<T>\n\t/** Handler for setter decorators */\n\tsetter?: DDSetter<T>\n\t/** Default handler for any decorator type not explicitly defined */\n\tdefault?: (...args: any[]) => any\n}\n\n/**\n * Type for decorators that work with both Legacy and Modern decorator proposals\n * Automatically infers the correct decorator type based on the description\n */\nexport type Decorator<T, Description extends DecoratorDescription<T>> = (Description extends {\n\tmethod: DDMethod<T>\n}\n\t? LegacyPropertyDecorator<T> & ModernMethodDecorator<T>\n\t: unknown) &\n\t(Description extends { class: DDClass<new (...args: any[]) => T> }\n\t\t? LegacyClassDecorator<new (...args: any[]) => T> &\n\t\t\t\tModernClassDecorator<new (...args: any[]) => T>\n\t\t: unknown) &\n\t(Description extends { getter: DDGetter<T> }\n\t\t? LegacyPropertyDecorator<T> & ModernGetterDecorator<T> & ModernAccessorDecorator<T>\n\t\t: unknown) &\n\t(Description extends { setter: DDSetter<T> }\n\t\t? LegacyPropertyDecorator<T> & ModernSetterDecorator<T> & ModernAccessorDecorator<T>\n\t\t: unknown) &\n\t(Description extends { default: infer Signature } ? Signature : unknown)\n\n/**\n * Factory type for creating decorators that work with both Legacy and Modern decorator proposals\n */\nexport type DecoratorFactory<T> = <Description extends DecoratorDescription<T>>(\n\tdescription: Description\n) => (Description extends { method: DDMethod<T> }\n\t? LegacyPropertyDecorator<T> & ModernMethodDecorator<T>\n\t: unknown) &\n\t(Description extends { class: DDClass<new (...args: any[]) => T> }\n\t\t? LegacyClassDecorator<new (...args: any[]) => T> &\n\t\t\t\tModernClassDecorator<new (...args: any[]) => T>\n\t\t: unknown) &\n\t(Description extends { getter: DDGetter<T> }\n\t\t? LegacyPropertyDecorator<T> & ModernGetterDecorator<T> & ModernAccessorDecorator<T>\n\t\t: unknown) &\n\t(Description extends { setter: DDSetter<T> }\n\t\t? LegacyPropertyDecorator<T> & ModernSetterDecorator<T> & ModernAccessorDecorator<T>\n\t\t: unknown) &\n\t(Description extends { default: infer Signature } ? Signature : unknown)\n\n/**\n * Creates a decorator that works with Legacy decorator proposals\n * @param description - The decorator description object\n * @returns A decorator function compatible with Legacy decorators\n */\nexport function legacyDecorator<T = any>(description: DecoratorDescription<T>): any {\n\treturn function (\n\t\tthis: any,\n\t\ttarget: any,\n\t\tpropertyKey?: PropertyKey,\n\t\tdescriptor?: PropertyDescriptor,\n\t\t...args: any[]\n\t) {\n\t\tif (propertyKey === undefined) {\n\t\t\tif (isConstructor(target)) {\n\t\t\t\tif (!('class' in description)) throw new Error('Decorator cannot be applied to a class')\n\t\t\t\treturn description.class!(target)\n\t\t\t}\n\t\t} else if (typeof target === 'object' && ['string', 'symbol'].includes(typeof propertyKey)) {\n\t\t\tif (!descriptor) throw new Error('Decorator cannot be applied to a field')\n\t\t\telse if (typeof descriptor === 'object' && 'configurable' in descriptor) {\n\t\t\t\tif ('get' in descriptor || 'set' in descriptor) {\n\t\t\t\t\tif (!('getter' in description || 'setter' in description))\n\t\t\t\t\t\tthrow new Error('Decorator cannot be applied to a getter or setter')\n\t\t\t\t\tif ('getter' in description) {\n\t\t\t\t\t\tconst newGetter = description.getter!(descriptor.get as any, target, propertyKey)\n\t\t\t\t\t\tif (newGetter) descriptor.get = newGetter\n\t\t\t\t\t}\n\t\t\t\t\tif ('setter' in description) {\n\t\t\t\t\t\tconst newSetter = description.setter!(descriptor.set as any, target, propertyKey)\n\t\t\t\t\t\tif (newSetter) descriptor.set = newSetter\n\t\t\t\t\t}\n\t\t\t\t\treturn descriptor\n\t\t\t\t} else if (typeof descriptor.value === 'function') {\n\t\t\t\t\tif (!('method' in description)) throw new Error('Decorator cannot be applied to a method')\n\t\t\t\t\tconst newMethod = description.method!(descriptor.value, target, propertyKey)\n\t\t\t\t\tif (newMethod) descriptor.value = newMethod\n\t\t\t\t\treturn descriptor\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (!('default' in description))\n\t\t\tthrow new Error('Decorator do not have a default implementation')\n\t\treturn description.default!.call(this, target, propertyKey, descriptor, ...args)\n\t}\n}\n\n/**\n * Creates a decorator that works with Modern decorator proposals\n * @param description - The decorator description object\n * @returns A decorator function compatible with Modern decorators\n */\nexport function modernDecorator<T = any>(description: DecoratorDescription<T>): any {\n\t/*return function (target: any, context?: DecoratorContext, ...args: any[]) {*/\n\treturn function (this: any, target: any, context?: DecoratorContext, ...args: any[]) {\n\t\tif (!context?.kind || typeof context.kind !== 'string') {\n\t\t\tif (!('default' in description))\n\t\t\t\tthrow new Error('Decorator do not have a default implementation')\n\t\t\treturn description.default!.call(this, target, context, ...args)\n\t\t}\n\t\tswitch (context.kind) {\n\t\t\tcase 'class':\n\t\t\t\tif (!('class' in description)) throw new Error('Decorator cannot be applied to a class')\n\t\t\t\treturn description.class!(target)\n\t\t\tcase 'field':\n\t\t\t\tthrow new Error('Decorator cannot be applied to a field')\n\t\t\tcase 'getter':\n\t\t\t\tif (!('getter' in description)) throw new Error('Decorator cannot be applied to a getter')\n\t\t\t\treturn description.getter!(target, target, context.name)\n\t\t\tcase 'setter':\n\t\t\t\tif (!('setter' in description)) throw new Error('Decorator cannot be applied to a setter')\n\t\t\t\treturn description.setter!(target, target, context.name)\n\t\t\tcase 'method':\n\t\t\t\tif (!('method' in description)) throw new Error('Decorator cannot be applied to a method')\n\t\t\t\treturn description.method!(target, target, context.name)\n\t\t\tcase 'accessor': {\n\t\t\t\tif (!('getter' in description || 'setter' in description))\n\t\t\t\t\tthrow new Error('Decorator cannot be applied to a getter or setter')\n\t\t\t\tconst rv: Partial<ClassAccessorDecoratorResult<any, any>> = {}\n\t\t\t\tif ('getter' in description) {\n\t\t\t\t\tconst newGetter = description.getter!(target.get, target, context.name)\n\t\t\t\t\tif (newGetter) rv.get = newGetter\n\t\t\t\t}\n\t\t\t\tif ('setter' in description) {\n\t\t\t\t\tconst newSetter = description.setter!(target.set, target, context.name)\n\t\t\t\t\tif (newSetter) rv.set = newSetter\n\t\t\t\t}\n\t\t\t\treturn rv\n\t\t\t}\n\t\t\t//return description.accessor?.(target, context.name, target)\n\t\t}\n\t}\n}\n\n/**\n * Detects if the decorator is being called in modern (Modern) or legacy (Legacy) mode\n * based on the arguments passed to the decorator function\n */\nfunction detectDecoratorMode(\n\t_target: any,\n\tcontextOrKey?: any,\n\t_descriptor?: any\n): 'modern' | 'legacy' {\n\t// Modern decorators have a context object as the second parameter\n\t// Legacy decorators have a string/symbol key as the second parameter\n\tif (\n\t\ttypeof contextOrKey === 'object' &&\n\t\tcontextOrKey !== null &&\n\t\ttypeof contextOrKey.kind === 'string'\n\t) {\n\t\treturn 'modern'\n\t}\n\treturn 'legacy'\n}\n\n/**\n * Main decorator factory that automatically detects and works with both Legacy and Modern decorator proposals\n * @param description - The decorator description object\n * @returns A decorator that works in both Legacy and Modern environments\n */\nexport const decorator: DecoratorFactory<any> = (description: DecoratorDescription<any>) => {\n\tconst modern = modernDecorator(description)\n\tconst legacy = legacyDecorator(description)\n\treturn ((target: any, contextOrKey?: any, ...args: any[]) => {\n\t\tconst mode = detectDecoratorMode(target, contextOrKey, args[0])\n\t\treturn mode === 'modern'\n\t\t\t? modern(target, contextOrKey, ...args)\n\t\t\t: legacy(target, contextOrKey, ...args)\n\t}) as any\n}\n\n/**\n * Generic class decorator type that works with both Legacy and Modern decorator proposals\n */\nexport type GenericClassDecorator<T> = LegacyClassDecorator<abstract new (...args: any[]) => T> &\n\tModernClassDecorator<abstract new (...args: any[]) => T>\n","import { decorator } from './decorator'\n\n// Integrated with `using` statement via Symbol.dispose\nconst fr = new FinalizationRegistry<() => void>((f) => f())\n/**\n * Symbol for marking destructor methods\n */\nexport const destructor = Symbol('destructor')\n/**\n * Symbol for accessing allocated values in destroyable objects\n */\nexport const allocatedValues = Symbol('allocated')\n/**\n * Error thrown when attempting to access a destroyed object\n */\nexport class DestructionError extends Error {\n\tstatic throw<_T = void>(msg: string) {\n\t\treturn () => {\n\t\t\tthrow new DestructionError(msg)\n\t\t}\n\t}\n\tconstructor(msg: string) {\n\t\tsuper(`Object is destroyed. ${msg}`)\n\t\tthis.name = 'DestroyedAccessError'\n\t}\n}\nconst destroyedHandler = {\n\t[Symbol.toStringTag]: 'MutTs Destroyable',\n\tget: DestructionError.throw('Cannot access destroyed object'),\n\tset: DestructionError.throw('Cannot access destroyed object'),\n} as const\n\nabstract class AbstractDestroyable<Allocated> {\n\tabstract [destructor](allocated: Allocated): void\n\t[Symbol.dispose](): void {\n\t\tthis[destructor](this as unknown as Allocated)\n\t}\n}\n\ninterface Destructor<Allocated> {\n\tdestructor(allocated: Allocated): void\n}\n\n/**\n * Creates a destroyable class with a base class and destructor object\n * @param base - The base class to extend\n * @param destructorObj - Object containing the destructor method\n * @returns A destroyable class with static destroy and isDestroyable methods\n */\nexport function Destroyable<\n\tT extends new (\n\t\t...args: any[]\n\t) => any,\n\tAllocated extends Partial<InstanceType<T>>,\n>(\n\tbase: T,\n\tdestructorObj: Destructor<Allocated>\n): (new (\n\t...args: ConstructorParameters<T>\n) => InstanceType<T> & { [allocatedValues]: Allocated }) & {\n\tdestroy(obj: InstanceType<T>): boolean\n\tisDestroyable(obj: InstanceType<T>): boolean\n}\n\n/**\n * Creates a destroyable class with only a destructor object (no base class)\n * @param destructorObj - Object containing the destructor method\n * @returns A destroyable class with static destroy and isDestroyable methods\n */\nexport function Destroyable<Allocated extends Record<PropertyKey, any> = Record<PropertyKey, any>>(\n\tdestructorObj: Destructor<Allocated>\n): (new () => { [allocatedValues]: Allocated }) & {\n\tdestroy(obj: any): boolean\n\tisDestroyable(obj: any): boolean\n}\n\n/**\n * Creates a destroyable class with a base class (requires [destructor] method)\n * @param base - The base class to extend\n * @returns A destroyable class with static destroy and isDestroyable methods\n */\nexport function Destroyable<\n\tT extends new (\n\t\t...args: any[]\n\t) => any,\n\tAllocated extends Record<PropertyKey, any> = Record<PropertyKey, any>,\n>(\n\tbase: T\n): (new (\n\t...args: ConstructorParameters<T>\n) => AbstractDestroyable<Allocated> & InstanceType<T> & { [allocatedValues]: Allocated }) & {\n\tdestroy(obj: InstanceType<T>): boolean\n\tisDestroyable(obj: InstanceType<T>): boolean\n}\n\n/**\n * Creates an abstract destroyable base class\n * @returns An abstract destroyable class with static destroy and isDestroyable methods\n */\nexport function Destroyable<\n\tAllocated extends Record<PropertyKey, any> = Record<PropertyKey, any>,\n>(): abstract new () => (AbstractDestroyable<Allocated> & {\n\t[allocatedValues]: Allocated\n}) & {\n\tdestroy(obj: any): boolean\n\tisDestroyable(obj: any): boolean\n}\n\nexport function Destroyable<\n\tT extends new (\n\t\t...args: any[]\n\t) => any,\n\tAllocated extends Record<PropertyKey, any> = Record<PropertyKey, any>,\n>(base?: T | Destructor<Allocated>, destructorObj?: Destructor<Allocated>) {\n\tif (base && typeof base !== 'function') {\n\t\tdestructorObj = base as Destructor<Allocated>\n\t\tbase = undefined\n\t}\n\tif (!base) {\n\t\tbase = class {} as T\n\t}\n\n\treturn class Destroyable extends (base as T) {\n\t\tstatic readonly destructors = new WeakMap<any, () => void>()\n\t\tstatic destroy(obj: Destroyable) {\n\t\t\tconst destructor = Destroyable.destructors.get(obj)\n\t\t\tif (!destructor) return false\n\t\t\tfr.unregister(obj[allocatedValues])\n\t\t\tDestroyable.destructors.delete(obj)\n\t\t\tObject.setPrototypeOf(obj, new Proxy({}, destroyedHandler))\n\t\t\t// Clear all own properties\n\t\t\tfor (const key of Object.getOwnPropertyNames(obj)) {\n\t\t\t\tdelete (obj as any)[key]\n\t\t\t}\n\t\t\tdestructor()\n\t\t\treturn true\n\t\t}\n\t\tstatic isDestroyable(obj: Destroyable) {\n\t\t\treturn Destroyable.destructors.has(obj)\n\t\t}\n\n\t\t[forwardProperties]!: PropertyKey[]\n\t\treadonly [allocatedValues]: Allocated\n\t\tconstructor(...args: any[]) {\n\t\t\tsuper(...args)\n\t\t\tconst allocated = {} as Allocated\n\t\t\tthis[allocatedValues] = allocated\n\t\t\t// @ts-expect-error `this` is an AbstractDestroyable\n\t\t\tconst myDestructor = destructorObj?.destructor ?? this[destructor]\n\t\t\tif (!myDestructor) {\n\t\t\t\tthrow new DestructionError('Destructor is not defined')\n\t\t\t}\n\t\t\tfunction destruction() {\n\t\t\t\tmyDestructor(allocated)\n\t\t\t}\n\t\t\tDestroyable.destructors.set(this, destruction)\n\t\t\tfr.register(this, destruction, allocated)\n\t\t}\n\t}\n}\n\nconst forwardProperties = Symbol('forwardProperties')\n/**\n * Decorator that marks properties to be stored in the allocated object and passed to the destructor\n * Use with accessor properties or explicit get/set pairs\n */\nexport const allocated = decorator({\n\tsetter(original, _target, propertyKey) {\n\t\treturn function (value) {\n\t\t\tthis[allocatedValues][propertyKey] = value\n\t\t\treturn original.call(this, value)\n\t\t}\n\t},\n})\n\n/**\n * Registers a callback to be called when an object is garbage collected\n * @param cb - The callback function to execute on garbage collection\n * @returns The object whose reference can be collected\n */\nexport function callOnGC(cb: () => void) {\n\tlet called = false\n\tconst forward = () => {\n\t\tif (called) return\n\t\tcalled = true\n\t\tcb()\n\t}\n\tfr.register(forward, cb, cb)\n\treturn forward\n}\n\n/**\n * Context Manager Protocol for `using` statement integration\n * Provides automatic resource cleanup when used with the `using` statement\n */\nexport interface ContextManager<T = any> {\n\t[Symbol.dispose](): void\n\tvalue?: T\n}\n","export interface ArrayDiffResult<T> {\n\tindexA: number\n\tindexB: number\n\tsliceA: T[]\n\tsliceB: T[]\n}\n\n/** Max edit distance before bailing out to a single \"replace all\" patch */\nconst BAILOUT_D = 256\n\n/**\n * Myers' diff producing grouped patches: `{indexA, indexB, sliceA, sliceB}[]`.\n * - O(N) for identical or prefix/suffix-only differences\n * - O(ND) for small D, with a hard bailout at D=BAILOUT_D → single replacement patch\n */\nexport function arrayDiff<T>(A: readonly T[], B: readonly T[]): ArrayDiffResult<T>[] {\n\tlet start = 0\n\tlet endA = A.length\n\tlet endB = B.length\n\n\t// Trim common prefix\n\twhile (start < endA && start < endB && A[start] === B[start]) start++\n\t// Trim common suffix\n\twhile (endA > start && endB > start && A[endA - 1] === B[endB - 1]) {\n\t\tendA--\n\t\tendB--\n\t}\n\n\tconst lenA = endA - start\n\tconst lenB = endB - start\n\n\tif (lenA === 0 && lenB === 0) return []\n\tif (lenA === 0)\n\t\treturn [{ indexA: start, indexB: start, sliceA: [], sliceB: B.slice(start, endB) }]\n\tif (lenB === 0)\n\t\treturn [{ indexA: start, indexB: start, sliceA: A.slice(start, endA), sliceB: [] }]\n\n\t// Myers with bailout\n\tconst maxD = Math.min(lenA + lenB, BAILOUT_D)\n\tconst vSize = 2 * maxD + 1\n\tconst vOffset = maxD\n\tconst V = new Int32Array(vSize)\n\tV[vOffset + 1] = 0\n\tconst history: Int32Array[] = []\n\n\tfor (let d = 0; d <= maxD; d++) {\n\t\tfor (let k = -d; k <= d; k += 2) {\n\t\t\tlet x: number\n\t\t\tif (k === -d || (k !== d && V[vOffset + k - 1] < V[vOffset + k + 1])) {\n\t\t\t\tx = V[vOffset + k + 1]\n\t\t\t} else {\n\t\t\t\tx = V[vOffset + k - 1] + 1\n\t\t\t}\n\t\t\tlet y = x - k\n\t\t\twhile (x < lenA && y < lenB && A[start + x] === B[start + y]) {\n\t\t\t\tx++\n\t\t\t\ty++\n\t\t\t}\n\t\t\tV[vOffset + k] = x\n\t\t\tif (x >= lenA && y >= lenB) return buildPatches(history, A, B, start, x, y, d, k, vOffset)\n\t\t}\n\t\thistory.push(new Int32Array(V))\n\t}\n\n\t// Bailout: too many differences\n\treturn [\n\t\t{ indexA: start, indexB: start, sliceA: A.slice(start, endA), sliceB: B.slice(start, endB) },\n\t]\n}\n\nfunction buildPatches<T>(\n\thistory: Int32Array[],\n\tA: readonly T[],\n\tB: readonly T[],\n\toffset: number,\n\tfinalX: number,\n\tfinalY: number,\n\tfinalD: number,\n\tfinalK: number,\n\tvOffset: number\n): ArrayDiffResult<T>[] {\n\t// Backtrack from (finalX, finalY) at step finalD to step 0, collecting ops in reverse\n\tconst ops: (0 | 1 | 2)[] = [] // 0=eq, 1=ins, 2=del\n\tlet x = finalX\n\tlet y = finalY\n\tlet k = finalK\n\n\tfor (let d = finalD; d > 0; d--) {\n\t\tconst prev = history[d - 1]\n\t\tlet prevK: number\n\t\tlet down: boolean\n\t\tif (k === -d) {\n\t\t\tprevK = k + 1\n\t\t\tdown = true\n\t\t} else if (k === d) {\n\t\t\tprevK = k - 1\n\t\t\tdown = false\n\t\t} else if (prev[vOffset + k - 1] < prev[vOffset + k + 1]) {\n\t\t\tprevK = k + 1\n\t\t\tdown = true\n\t\t} else {\n\t\t\tprevK = k - 1\n\t\t\tdown = false\n\t\t}\n\n\t\tconst prevXEnd = prev[vOffset + prevK]\n\t\tconst prevYEnd = prevXEnd - prevK\n\t\tconst xStart = down ? prevXEnd : prevXEnd + 1\n\t\tconst yStart = down ? prevYEnd + 1 : prevXEnd + 1 - k\n\n\t\t// Diagonal matches (pushed in reverse)\n\t\twhile (x > xStart && y > yStart) {\n\t\t\tops.push(0)\n\t\t\tx--\n\t\t\ty--\n\t\t}\n\t\t// The edit step\n\t\tif (down) {\n\t\t\tops.push(1) // ins\n\t\t\ty--\n\t\t} else {\n\t\t\tops.push(2) // del\n\t\t\tx--\n\t\t}\n\t\tk = prevK\n\t}\n\n\t// Walk ops forward (they were pushed in reverse), grouping contiguous edits\n\tconst patches: ArrayDiffResult<T>[] = []\n\tlet currA = offset\n\tlet currB = offset\n\tlet sliceA: T[] = []\n\tlet sliceB: T[] = []\n\tlet patchA = -1\n\tlet patchB = -1\n\n\tconst flush = () => {\n\t\tif (patchA !== -1) {\n\t\t\tpatches.push({ indexA: patchA, indexB: patchB, sliceA, sliceB })\n\t\t\tsliceA = []\n\t\t\tsliceB = []\n\t\t\tpatchA = -1\n\t\t}\n\t}\n\n\tfor (let i = ops.length - 1; i >= 0; i--) {\n\t\tconst op = ops[i]\n\t\tif (op === 0) {\n\t\t\tflush()\n\t\t\tcurrA++\n\t\t\tcurrB++\n\t\t} else if (op === 1) {\n\t\t\tif (patchA === -1) {\n\t\t\t\tpatchA = currA\n\t\t\t\tpatchB = currB\n\t\t\t}\n\t\t\tsliceB.push(B[currB++])\n\t\t} else {\n\t\t\tif (patchA === -1) {\n\t\t\t\tpatchA = currA\n\t\t\t\tpatchB = currB\n\t\t\t}\n\t\t\tsliceA.push(A[currA++])\n\t\t}\n\t}\n\tflush()\n\treturn patches\n}\n","/**\n * Base type for event maps - all event handlers must be functions\n */\nexport type EventsBase = Record<string, (...args: any[]) => void>\n\nconst events = Symbol('events')\nconst hooks = Symbol('hooks')\n\ntype EventfulStore = {\n\t[events]: Map<PropertyKey, Set<(...args: any[]) => void>>\n\t[hooks]: Set<(...args: any[]) => void>\n}\n\nfunction getEventMap(target: object): EventfulStore[typeof events] {\n\treturn (target as EventfulStore)[events]\n}\n\nfunction getHookSet(target: object): EventfulStore[typeof hooks] {\n\treturn (target as EventfulStore)[hooks]\n}\n\nconst eventBehavior = {\n\ton<EventType extends keyof EventsBase>(\n\t\teventOrEvents: EventType | Partial<EventsBase>,\n\t\tcb?: EventsBase[EventType]\n\t): (this: Eventful<any>) => void {\n\t\tconst self = this as Eventful<any>\n\t\tconst eventMap = getEventMap(self)\n\t\tif (typeof eventOrEvents === 'object') {\n\t\t\tfor (const e of Object.keys(eventOrEvents) as (keyof EventsBase)[]) {\n\t\t\t\tthis.on(e, eventOrEvents[e]!)\n\t\t\t}\n\t\t} else if (cb !== undefined) {\n\t\t\tconst callbacks = eventMap.get(eventOrEvents) ?? new Set<EventsBase[EventType]>()\n\t\t\tif (!callbacks.has(cb)) callbacks.add(cb)\n\t\t\teventMap.set(eventOrEvents, callbacks)\n\t\t}\n\t\treturn () => this.off(eventOrEvents, cb)\n\t},\n\toff<EventType extends keyof EventsBase>(\n\t\teventOrEvents: EventType | Partial<EventsBase>,\n\t\tcb?: EventsBase[EventType]\n\t): void {\n\t\tconst self = this as Eventful<any>\n\t\tconst eventMap = getEventMap(self)\n\t\tif (typeof eventOrEvents === 'object') {\n\t\t\tfor (const e of Object.keys(eventOrEvents) as (keyof EventsBase)[]) {\n\t\t\t\tthis.off(e, eventOrEvents[e])\n\t\t\t}\n\t\t} else if (cb !== null && cb !== undefined) {\n\t\t\tconst callbacks = eventMap.get(eventOrEvents)\n\t\t\tif (callbacks) {\n\t\t\t\tcallbacks.delete(cb)\n\t\t\t\tif (!callbacks.size) eventMap.delete(eventOrEvents)\n\t\t\t}\n\t\t} else {\n\t\t\t// Remove all listeners for this event\n\t\t\teventMap.delete(eventOrEvents)\n\t\t}\n\t},\n\temit<EventType extends keyof EventsBase>(\n\t\tevent: EventType,\n\t\t...args: Parameters<EventsBase[EventType]>\n\t) {\n\t\tconst self = this as Eventful<any>\n\t\tconst callbacks = getEventMap(self).get(event)\n\t\tif (callbacks) for (const cb of callbacks) cb.apply(this, args)\n\t\tfor (const cb of getHookSet(self)) cb.call(this, event, ...args)\n\t},\n}\n\nfunction perEvent(\n\teventful: Eventful<any>,\n\tfct: (event: string, ...args: any[]) => void,\n\tuse?: 'use'\n) {\n\tconst cache = new Map<string, (...args: any[]) => any>()\n\treturn new Proxy(fct, {\n\t\tget(target, prop: PropertyKey) {\n\t\t\tif (typeof prop !== 'string')\n\t\t\t\treturn (target as typeof target & Record<PropertyKey, unknown>)[prop]\n\t\t\tif (use && !getEventMap(eventful).has(prop) && !getHookSet(eventful).size) return () => {}\n\n\t\t\t// Return cached function or create and cache\n\t\t\tlet cached = cache.get(prop)\n\t\t\tif (!cached) {\n\t\t\t\tcached = (...args: any[]) => fct.apply(eventful, [prop, ...args])\n\t\t\t\tcache.set(prop, cached)\n\t\t\t}\n\t\t\treturn cached\n\t\t},\n\t})\n}\n\n/**\n * A type-safe event system that provides a clean API for event handling\n * @template Events - The event map defining event names and their handler signatures\n */\nexport class Eventful<Events extends EventsBase> {\n\tprivate readonly [events] = new Map<keyof Events, Set<(...args: any[]) => void>>()\n\tprivate readonly [hooks] = new Set<(...args: any[]) => void>()\n\n\tpublic hook(\n\t\tcb: <EventType extends keyof Events>(\n\t\t\tevent: EventType,\n\t\t\t...args: Parameters<Events[EventType]>\n\t\t) => void\n\t): () => void {\n\t\tthis[hooks].add(cb)\n\t\treturn () => {\n\t\t\tthis[hooks].delete(cb)\n\t\t}\n\t}\n\n\tpublic on = perEvent(this, eventBehavior.on) as ((events: Partial<Events>) => void) &\n\t\t(<EventType extends keyof Events>(event: EventType, cb: Events[EventType]) => () => void) & {\n\t\t\t[event in keyof Events]: (cb: Events[event]) => () => void\n\t\t}\n\tpublic off = perEvent(this, eventBehavior.off) as ((events: Partial<Events>) => void) &\n\t\t(<EventType extends keyof Events>(event: EventType, cb?: Events[EventType]) => void) & {\n\t\t\t[event in keyof Events]: (cb?: Events[event]) => void\n\t\t}\n\n\tpublic emit = perEvent(this, eventBehavior.emit, 'use') as (<EventType extends keyof Events>(\n\t\tevent: EventType,\n\t\t...args: Parameters<Events[EventType]>\n\t) => void) &\n\t\tEvents\n}\n","/**\n * Creates a flavored (extensible) version of a function with chainable property modifiers.\n *\n * Each property defined in `flavors` returns a new flavored function that transforms\n * how the original function is called. This enables a fluent API where properties\n * create specialized variants of the base function.\n *\n * @param fn - The base function to flavor\n * @param flavors - Object defining the flavor properties (getters or methods)\n * @returns A proxy of the function with the flavor properties attached\n *\n * @example\n * ```typescript\n * function greet(name: string, options?: { loud?: boolean }) {\n * const greeting = `Hello, ${name}!`\n * return options?.loud ? greeting.toUpperCase() : greeting\n * }\n *\n * const flavoredGreet = flavored(greet, {\n * get loud() {\n * return createFlavor(this, (name, opts) => [name, { ...opts, loud: true }])\n * }\n * })\n *\n * flavoredGreet('World') // \"Hello, World!\"\n * flavoredGreet.loud('World') // \"HELLO, WORLD!\"\n * ```\n */\nimport { named } from './utils'\n\ntype AnyFunction = (...args: any[]) => any\ntype CaptionedOptions<T extends AnyFunction> = {\n\tcallbackIndex?: number\n\tname?: string\n\trename?: (caption: string, callback: Function) => unknown\n\twarn?: (message: string) => void\n\tshouldWarnAnonymous?: (callback: Function, args: Parameters<T>) => boolean\n}\ntype ResolvedCaptionedOptions<T extends AnyFunction> = {\n\tcallbackIndex: number\n\tname: string\n\trename: NonNullable<CaptionedOptions<T>['rename']>\n\twarn: NonNullable<CaptionedOptions<T>['warn']>\n\tshouldWarnAnonymous?: CaptionedOptions<T>['shouldWarnAnonymous']\n}\n\nconst captionedOptionsSymbol = Symbol('mutts.captioned.options')\n\nexport type Captioned<T extends AnyFunction> = T &\n\t((strings: TemplateStringsArray, ...values: readonly unknown[]) => T)\n\nfunction isTemplateStringsArray(value: unknown): value is TemplateStringsArray {\n\treturn (\n\t\tArray.isArray(value) &&\n\t\tObject.hasOwn(value, 'raw') &&\n\t\tArray.isArray((value as unknown as TemplateStringsArray).raw)\n\t)\n}\n\nfunction renderTemplate(strings: TemplateStringsArray, values: readonly unknown[]) {\n\tlet result = strings[0] ?? ''\n\tfor (let i = 0; i < values.length; i++) result += String(values[i]) + (strings[i + 1] ?? '')\n\treturn result\n}\n\nfunction renameCallback<T extends Function>(caption: string, callback: T): T {\n\tObject.defineProperty(callback, 'name', {\n\t\tvalue: caption,\n\t\twritable: false,\n\t\tconfigurable: true,\n\t})\n\treturn callback\n}\n\nfunction isAnonymousCallback(callback: Function) {\n\treturn !callback.name || callback.name === 'anonymous'\n}\n\n/**\n * Wraps a callback-first function so it also accepts a tagged-template call form.\n *\n * The template caption is applied to one callback argument before the base\n * function runs. By default, `captioned` targets the first argument, but\n * `callbackIndex` can point to any callback position.\n *\n * This is intended for APIs such as `effect`, `lift`, or `watch` where naming\n * is useful but should remain separate from the flavor system.\n *\n * Plain calls still work:\n * `run(callback)`\n *\n * Captioned calls add a runtime name to the first callback:\n * `` run`task:${id}`(callback) ``\n *\n * Anonymous uncaptioned callbacks may trigger a warning depending on\n * `shouldWarnAnonymous`.\n */\nexport function captioned<T extends AnyFunction>(\n\tfn: T,\n\toptions: CaptionedOptions<T> = {}\n): Captioned<T> {\n\tconst settings: ResolvedCaptionedOptions<T> = {\n\t\tcallbackIndex: options.callbackIndex ?? 0,\n\t\tname: options.name ?? (fn.name || 'callback'),\n\t\trename: options.rename ?? ((caption, callback) => renameCallback(caption, callback)),\n\t\t// biome-ignore lint/suspicious/noConsole: This is the whole point here\n\t\twarn: options.warn ?? ((message) => console.warn(message)),\n\t\tshouldWarnAnonymous: options.shouldWarnAnonymous,\n\t}\n\t;(fn as T & { [captionedOptionsSymbol]?: CaptionedOptions<T> })[captionedOptionsSymbol] = settings\n\n\treturn new Proxy(fn, {\n\t\tget(target, prop, receiver) {\n\t\t\tif (prop === captionedOptionsSymbol) return settings\n\t\t\treturn Reflect.get(target, prop, receiver)\n\t\t},\n\t\tapply(target, thisArg, args) {\n\t\t\tif (isTemplateStringsArray(args[0])) {\n\t\t\t\tconst caption = renderTemplate(args[0], args.slice(1))\n\t\t\t\treturn function captionedCall(this: unknown, ...callArgs: Parameters<T>) {\n\t\t\t\t\tconst callback = callArgs[settings.callbackIndex]\n\t\t\t\t\tif (typeof callback !== 'function')\n\t\t\t\t\t\tthrow new TypeError(\n\t\t\t\t\t\t\t`${settings.name} template calls require a callback at argument index ${settings.callbackIndex}`\n\t\t\t\t\t\t)\n\t\t\t\t\tconst nextArgs = [...callArgs] as Parameters<T>\n\t\t\t\t\tnextArgs[settings.callbackIndex] = settings.rename(\n\t\t\t\t\t\tcaption,\n\t\t\t\t\t\tcallback\n\t\t\t\t\t) as Parameters<T>[number]\n\t\t\t\t\treturn Reflect.apply(target, this, nextArgs)\n\t\t\t\t} as T\n\t\t\t}\n\t\t\tconst callback = args[settings.callbackIndex]\n\t\t\tif (typeof callback === 'function' && isAnonymousCallback(callback)) {\n\t\t\t\tconst shouldWarn = settings.shouldWarnAnonymous?.(callback, args as Parameters<T>) ?? true\n\t\t\t\tif (shouldWarn)\n\t\t\t\t\tsettings.warn(\n\t\t\t\t\t\t`${settings.name}: anonymous callback detected. Use template syntax for automatic naming:\\n` +\n\t\t\t\t\t\t\t` Current: ${settings.name}(() => { ... })\\n` +\n\t\t\t\t\t\t\t` Fix: ${settings.name}\\`descriptive-name\\`(() => { ... })\\n` +\n\t\t\t\t\t\t\t`The captioned system uses the template literal as the effect name for better debugging.`\n\t\t\t\t\t)\n\t\t\t}\n\t\t\treturn Reflect.apply(target, thisArg, args)\n\t\t},\n\t}) as Captioned<T>\n}\n\nexport function inheritCaption<T extends AnyFunction>(source: AnyFunction, target: T): T {\n\tconst settings = (source as AnyFunction & { [captionedOptionsSymbol]?: CaptionedOptions<T> })[\n\t\tcaptionedOptionsSymbol\n\t]\n\treturn settings ? (captioned(target, settings) as T) : target\n}\n\n/**\n * Creates a flavored (extensible) version of a function with chainable property modifiers.\n */\nexport function flavored<T extends (...args: any[]) => any, F>(\n\tfn: T,\n\tflavors: F & ThisType<T & F>\n): T & F {\n\t// Store flavors for recursive flavoring\n\t;(fn as any).flavors = flavors\n\n\treturn new Proxy(fn, {\n\t\tget(target, prop, receiver) {\n\t\t\tif (prop in flavors) {\n\t\t\t\treturn Reflect.get(flavors, prop, receiver)\n\t\t\t}\n\t\t\treturn (target as any)[prop]\n\t\t},\n\t}) as T & F\n}\n\n/**\n * Creates a new flavored function that transforms arguments before calling the base.\n *\n * @param fn - The base flavored function\n * @param transform - Function that receives the original arguments and returns transformed arguments\n * @returns A new flavored function with the transformation applied\n *\n * @example\n * ```typescript\n * const loudGreet = createFlavor(greet, (name, opts) => [name, { ...opts, loud: true }])\n * ```\n */\nexport function createFlavor<T extends (...args: any[]) => any>(\n\tfn: T,\n\ttransform: (...args: Parameters<T>) => Parameters<T>,\n\tname?: string\n): T {\n\tconst fct = function flavorWrapper(this: any, ...args: Parameters<T>) {\n\t\treturn fn.apply(this, transform(...args))\n\t}\n\tif (name) named(name, fct)\n\n\treturn flavored(inheritCaption(fn, fct as T), (fn as any).flavors || {})\n}\n\n/**\n * Creates a new flavored function that merges options objects at a specific index.\n * By default, uses the function's arity (length) as the index for options.\n *\n * @param fn - The base flavored function\n * @param defaultOptions - Options to merge\n * @param optionsIndex - Optional explicit index for options (defaults to fn.length)\n * @param name - Optional name for the wrapper\n * @returns A new flavored function\n */\nexport function flavorOptions<T extends (...args: any[]) => any>(\n\tfn: T,\n\tdefaultOptions: Record<string, any>,\n\topts: {\n\t\toptionsIndex?: number\n\t\tname?: string\n\t} = {}\n): T {\n\t// If the function is already flavorOptions-wrapped, it might have an index stored\n\tconst targetIndex = opts.optionsIndex ?? (fn as any).optionsIndex ?? fn.length\n\n\tconst fct = function flavorOptionsWrapper(this: any, ...args: any[]) {\n\t\tconst newArgs = [...args]\n\n\t\t// Ensure we have enough arguments to reach the options index\n\t\twhile (newArgs.length <= targetIndex) {\n\t\t\tnewArgs.push(undefined)\n\t\t}\n\n\t\tconst currentOptions = newArgs[targetIndex]\n\t\tconst isObject =\n\t\t\tcurrentOptions !== null &&\n\t\t\ttypeof currentOptions === 'object' &&\n\t\t\t!Array.isArray(currentOptions)\n\n\t\tnewArgs[targetIndex] = isObject ? { ...defaultOptions, ...currentOptions } : defaultOptions\n\n\t\treturn fn.apply(this, newArgs)\n\t}\n\n\tif (opts.name) named(`${fn.name}.${opts.name}`, fct)\n\n\t// Preserve arity and options track\n\tObject.defineProperty(fct, 'length', { value: fn.length })\n\t;(fct as any).optionsIndex = targetIndex\n\n\treturn flavored(inheritCaption(fn, fct as T), (fn as any).flavors || {})\n}\n","/**\n * Symbol for defining custom getter logic for numeric index access\n */\nexport const getAt = Symbol('getAt')\n/**\n * Symbol for defining custom setter logic for numeric index access\n */\nexport const setAt = Symbol('setAt')\n\ninterface IndexingAt<Items = any> {\n\t[getAt](index: number): Items\n}\n\ninterface Accessor<T, Items> {\n\tget(this: T, index: number): Items\n\tset?(this: T, index: number, value: Items): void\n\tgetLength?(this: T): number\n\tsetLength?(this: T, value: number): void\n}\n\nabstract class AbstractGetAt<Items = any> {\n\tabstract [getAt](index: number): Items\n}\n\n/**\n * Creates an indexable class with a base class and accessor object\n * @param base - The base class to extend\n * @param accessor - Object containing get/set methods for numeric index access\n * @returns A class that supports numeric index access\n */\nexport function Indexable<Items, Base extends abstract new (...args: any[]) => any>(\n\tbase: Base,\n\taccessor: Accessor<InstanceType<Base>, Items>\n): new (\n\t...args: ConstructorParameters<Base>\n) => InstanceType<Base> & { [x: number]: Items }\n\n/**\n * Creates an indexable class with only an accessor object (no base class)\n * @param accessor - Object containing get/set methods for numeric index access\n * @returns A class that supports numeric index access\n */\nexport function Indexable<Items>(accessor: Accessor<any, Items>): new () => { [x: number]: Items }\n\n/**\n * Creates an indexable class with a base class that has [getAt] method\n * @param base - The base class that implements [getAt] method\n * @returns A class that supports numeric index access using the base class's [getAt] method\n */\nexport function Indexable<Base extends new (...args: any[]) => IndexingAt>(\n\tbase: Base\n): new (\n\t...args: ConstructorParameters<Base>\n) => InstanceType<Base> & { [x: number]: AtReturnType<InstanceType<Base>> }\n\n/**\n * Creates an abstract indexable base class\n * @returns An abstract class that supports numeric index access\n */\nexport function Indexable<Items>(): abstract new (\n\t...args: any[]\n) => AbstractGetAt & { [x: number]: Items }\n\nexport function Indexable<Items, Base extends abstract new (...args: any[]) => any>(\n\tbase?: Base | Accessor<Base, Items>,\n\taccessor?: Accessor<Base, Items>\n) {\n\tif (base && typeof base !== 'function') {\n\t\taccessor = base as Accessor<Base, Items>\n\t\tbase = undefined\n\t}\n\tif (!base) {\n\t\t//@ts-expect-error\n\t\tbase = class {} as Base\n\t}\n\tif (!accessor) {\n\t\taccessor = {\n\t\t\tget(this: any, index: number) {\n\t\t\t\tif (typeof this[getAt] !== 'function') {\n\t\t\t\t\tthrow new Error('Indexable class must have an [getAt] method')\n\t\t\t\t}\n\t\t\t\treturn this[getAt](index)\n\t\t\t},\n\t\t\tset(this: any, index: number, value: Items) {\n\t\t\t\tif (typeof this[setAt] !== 'function') {\n\t\t\t\t\tthrow new Error('Indexable class has read-only numeric index access')\n\t\t\t\t}\n\t\t\t\tthis[setAt](index, value)\n\t\t\t},\n\t\t}\n\t}\n\n\tabstract class Indexable extends (base as Base) {\n\t\t[x: number]: Items\n\t}\n\n\tObject.setPrototypeOf(\n\t\tIndexable.prototype,\n\t\tnew Proxy((base as Base).prototype, {\n\t\t\t//@ts-expect-error\n\t\t\t[Symbol.toStringTag]: 'MutTs Indexable',\n\t\t\tget(target, prop, receiver) {\n\t\t\t\tif (prop in target) {\n\t\t\t\t\tconst getter = Object.getOwnPropertyDescriptor(target, prop)?.get\n\t\t\t\t\treturn getter ? getter.call(receiver) : target[prop]\n\t\t\t\t}\n\t\t\t\tif (typeof prop === 'string') {\n\t\t\t\t\tif (prop === 'length' && accessor.getLength) return accessor.getLength.call(receiver)\n\t\t\t\t\tconst numProp = Number(prop)\n\t\t\t\t\tif (!Number.isNaN(numProp)) {\n\t\t\t\t\t\treturn accessor.get!.call(receiver, numProp) as Items\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn undefined\n\t\t\t},\n\t\t\tset(target, prop, value, receiver) {\n\t\t\t\tif (prop in target) {\n\t\t\t\t\tconst setter = Object.getOwnPropertyDescriptor(target, prop)?.set\n\t\t\t\t\tif (setter) setter.call(receiver, value)\n\t\t\t\t\telse target[prop] = value\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t\tif (typeof prop === 'string') {\n\t\t\t\t\tif (prop === 'length' && accessor.setLength) {\n\t\t\t\t\t\taccessor.setLength.call(receiver, value)\n\t\t\t\t\t\treturn true\n\t\t\t\t\t}\n\t\t\t\t\tconst numProp = Number(prop)\n\t\t\t\t\tif (!Number.isNaN(numProp)) {\n\t\t\t\t\t\tif (!accessor.set) throw new Error('Indexable class has read-only numeric index access')\n\t\t\t\t\t\taccessor.set!.call(receiver, numProp, value)\n\t\t\t\t\t\treturn true\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tObject.defineProperty(receiver, prop, {\n\t\t\t\t\tvalue,\n\t\t\t\t\twritable: true,\n\t\t\t\t\tenumerable: true,\n\t\t\t\t\tconfigurable: true,\n\t\t\t\t})\n\t\t\t\treturn true\n\t\t\t},\n\t\t\thas(target, prop) {\n\t\t\t\tif (prop in target) return true\n\t\t\t\tif (typeof prop === 'string') {\n\t\t\t\t\tif (prop === 'length' && accessor.getLength) return true\n\t\t\t\t\tconst numProp = Number(prop)\n\t\t\t\t\tif (!Number.isNaN(numProp)) return true\n\t\t\t\t}\n\t\t\t\treturn false\n\t\t\t},\n\t\t\townKeys(target) {\n\t\t\t\tconst keys = Reflect.ownKeys(target)\n\t\t\t\tif (accessor.getLength) {\n\t\t\t\t\tkeys.push('length')\n\t\t\t\t\tconst len = accessor.getLength.call(this as any)\n\t\t\t\t\tfor (let i = 0; i < len; i++) keys.push(String(i))\n\t\t\t\t}\n\t\t\t\treturn keys\n\t\t\t},\n\t\t\tgetOwnPropertyDescriptor(target, prop) {\n\t\t\t\tif (prop in target) return Object.getOwnPropertyDescriptor(target, prop)\n\t\t\t\tif (typeof prop === 'string') {\n\t\t\t\t\tif (prop === 'length' && accessor.getLength) {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tenumerable: false,\n\t\t\t\t\t\t\tconfigurable: true,\n\t\t\t\t\t\t\tget: () => accessor.getLength!.call(this as any),\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tconst numProp = Number(prop)\n\t\t\t\t\tif (!Number.isNaN(numProp)) {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tenumerable: true,\n\t\t\t\t\t\t\tconfigurable: true,\n\t\t\t\t\t\t\tget: () => accessor.get!.call(this as any, numProp),\n\t\t\t\t\t\t\tset: accessor.set\n\t\t\t\t\t\t\t\t? (v: any) => accessor.set!.call(this as any, numProp, v)\n\t\t\t\t\t\t\t\t: undefined,\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn undefined\n\t\t\t},\n\t\t})\n\t)\n\treturn Indexable\n}\n\ntype AtReturnType<T> = T extends { [getAt](index: number): infer R } ? R : never\n\n/**\n * Symbol for accessing the forwarded array in ArrayReadForward\n */\nexport const forwardArray = Symbol('forwardArray')\n\n/**\n * A read-only array forwarder that implements all reading/iterating methods of Array\n * but does not implement modification methods.\n *\n * The constructor takes a callback that returns an array, and all methods forward\n * their behavior to the result of that callback.\n */\nexport class ArrayReadForward<T> {\n\tprotected get [forwardArray](): readonly T[] {\n\t\tthrow new Error('ArrayReadForward is not implemented')\n\t}\n\n\t/**\n\t * Get the length of the array\n\t */\n\tget length(): number {\n\t\treturn this[forwardArray].length\n\t}\n\n\t/**\n\t * Get an element at a specific index\n\t */\n\t[index: number]: T | undefined\n\n\t/**\n\t * Iterator protocol support\n\t */\n\t[Symbol.iterator](): Iterator<T> {\n\t\treturn this[forwardArray][Symbol.iterator]()\n\t}\n\n\t// Reading/Iterating methods\n\n\t/**\n\t * Creates a new array with the results of calling a provided function on every element\n\t */\n\tmap<U>(callbackfn: (value: T, index: number, array: readonly T[]) => U, thisArg?: any): U[] {\n\t\treturn this[forwardArray].map(callbackfn, thisArg)\n\t}\n\n\t/**\n\t * Creates a new array with all elements that pass the test implemented by the provided function\n\t */\n\tfilter<S extends T>(\n\t\tpredicate: (value: T, index: number, array: readonly T[]) => value is S,\n\t\tthisArg?: any\n\t): S[]\n\tfilter(predicate: (value: T, index: number, array: readonly T[]) => unknown, thisArg?: any): T[]\n\tfilter(predicate: (value: T, index: number, array: readonly T[]) => unknown, thisArg?: any): T[] {\n\t\treturn this[forwardArray].filter(predicate, thisArg)\n\t}\n\n\t/**\n\t * Executes a reducer function on each element of the array, resulting in a single output value\n\t */\n\treduce(\n\t\tcallbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: readonly T[]) => T\n\t): T\n\treduce(\n\t\tcallbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: readonly T[]) => T,\n\t\tinitialValue: T\n\t): T\n\treduce<U>(\n\t\tcallbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: readonly T[]) => U,\n\t\tinitialValue: U\n\t): U\n\treduce(\n\t\tcallbackfn: (\n\t\t\tpreviousValue: any,\n\t\t\tcurrentValue: T,\n\t\t\tcurrentIndex: number,\n\t\t\tarray: readonly T[]\n\t\t) => any,\n\t\tinitialValue?: any\n\t): any {\n\t\treturn initialValue !== undefined\n\t\t\t? this[forwardArray].reduce(callbackfn, initialValue)\n\t\t\t: this[forwardArray].reduce(callbackfn)\n\t}\n\n\t/**\n\t * Executes a reducer function on each element of the array (right-to-left), resulting in a single output value\n\t */\n\treduceRight(\n\t\tcallbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: readonly T[]) => T\n\t): T\n\treduceRight(\n\t\tcallbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: readonly T[]) => T,\n\t\tinitialValue: T\n\t): T\n\treduceRight<U>(\n\t\tcallbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: readonly T[]) => U,\n\t\tinitialValue: U\n\t): U\n\treduceRight(\n\t\tcallbackfn: (\n\t\t\tpreviousValue: any,\n\t\t\tcurrentValue: T,\n\t\t\tcurrentIndex: number,\n\t\t\tarray: readonly T[]\n\t\t) => any,\n\t\tinitialValue?: any\n\t): any {\n\t\treturn initialValue !== undefined\n\t\t\t? this[forwardArray].reduceRight(callbackfn, initialValue)\n\t\t\t: this[forwardArray].reduceRight(callbackfn)\n\t}\n\n\t/**\n\t * Executes a provided function once for each array element\n\t */\n\tforEach(callbackfn: (value: T, index: number, array: readonly T[]) => void, thisArg?: any): void {\n\t\tthis[forwardArray].forEach(callbackfn, thisArg)\n\t}\n\n\t/**\n\t * Returns the value of the first element in the array that satisfies the provided testing function\n\t */\n\tfind<S extends T>(\n\t\tpredicate: (value: T, index: number, array: readonly T[]) => value is S,\n\t\tthisArg?: any\n\t): S | undefined\n\tfind(\n\t\tpredicate: (value: T, index: number, array: readonly T[]) => unknown,\n\t\tthisArg?: any\n\t): T | undefined\n\tfind(\n\t\tpredicate: (value: T, index: number, array: readonly T[]) => unknown,\n\t\tthisArg?: any\n\t): T | undefined {\n\t\treturn this[forwardArray].find(predicate, thisArg)\n\t}\n\n\t/**\n\t * Returns the index of the first element in the array that satisfies the provided testing function\n\t */\n\tfindIndex(\n\t\tpredicate: (value: T, index: number, array: readonly T[]) => unknown,\n\t\tthisArg?: any\n\t): number {\n\t\treturn this[forwardArray].findIndex(predicate, thisArg)\n\t}\n\n\t/**\n\t * Returns the value of the last element in the array that satisfies the provided testing function\n\t */\n\tfindLast<S extends T>(\n\t\tpredicate: (value: T, index: number, array: readonly T[]) => value is S,\n\t\tthisArg?: any\n\t): S | undefined\n\tfindLast(\n\t\tpredicate: (value: T, index: number, array: readonly T[]) => unknown,\n\t\tthisArg?: any\n\t): T | undefined\n\tfindLast(\n\t\tpredicate: (value: T, index: number, array: readonly T[]) => unknown,\n\t\tthisArg?: any\n\t): T | undefined {\n\t\treturn this[forwardArray].findLast(predicate, thisArg)\n\t}\n\n\t/**\n\t * Returns the index of the last element in the array that satisfies the provided testing function\n\t */\n\tfindLastIndex(\n\t\tpredicate: (value: T, index: number, array: readonly T[]) => unknown,\n\t\tthisArg?: any\n\t): number {\n\t\treturn this[forwardArray].findLastIndex(predicate, thisArg)\n\t}\n\n\t/**\n\t * Determines whether an array includes a certain value among its entries\n\t */\n\tincludes(searchElement: T, fromIndex?: number): boolean {\n\t\treturn this[forwardArray].includes(searchElement, fromIndex)\n\t}\n\n\t/**\n\t * Returns the first index at which a given element can be found in the array\n\t */\n\tindexOf(searchElement: T, fromIndex?: number): number {\n\t\treturn this[forwardArray].indexOf(searchElement, fromIndex)\n\t}\n\n\t/**\n\t * Returns the last index at which a given element can be found in the array\n\t */\n\tlastIndexOf(searchElement: T, fromIndex?: number): number {\n\t\treturn this[forwardArray].lastIndexOf(searchElement, fromIndex)\n\t}\n\n\t/**\n\t * Returns a shallow copy of a portion of an array into a new array object\n\t */\n\tslice(start?: number, end?: number): T[] {\n\t\treturn this[forwardArray].slice(start, end)\n\t}\n\n\t/**\n\t * Returns a new array comprised of this array joined with other array(s) and/or value(s)\n\t */\n\tconcat(...items: ConcatArray<T>[]): T[]\n\tconcat(...items: (T | ConcatArray<T>)[]): T[]\n\tconcat(...items: (T | ConcatArray<T>)[]): T[] {\n\t\treturn this[forwardArray].concat(...items)\n\t}\n\n\t/**\n\t * Tests whether all elements in the array pass the test implemented by the provided function\n\t */\n\tevery(\n\t\tpredicate: (value: T, index: number, array: readonly T[]) => unknown,\n\t\tthisArg?: any\n\t): boolean {\n\t\treturn this[forwardArray].every(predicate, thisArg)\n\t}\n\n\t/**\n\t * Tests whether at least one element in the array passes the test implemented by the provided function\n\t */\n\tsome(\n\t\tpredicate: (value: T, index: number, array: readonly T[]) => unknown,\n\t\tthisArg?: any\n\t): boolean {\n\t\treturn this[forwardArray].some(predicate, thisArg)\n\t}\n\n\t/**\n\t * Joins all elements of an array into a string\n\t */\n\tjoin(separator?: string): string {\n\t\treturn this[forwardArray].join(separator)\n\t}\n\n\t/**\n\t * Returns a new array iterator that contains the keys for each index in the array\n\t */\n\tkeys(): IterableIterator<number> {\n\t\treturn this[forwardArray].keys()\n\t}\n\n\t/**\n\t * Returns a new array iterator that contains the values for each index in the array\n\t */\n\tvalues(): IterableIterator<T> {\n\t\treturn this[forwardArray].values()\n\t}\n\n\t/**\n\t * Returns a new array iterator that contains the key/value pairs for each index in the array\n\t */\n\tentries(): IterableIterator<[number, T]> {\n\t\treturn this[forwardArray].entries()\n\t}\n\n\t/**\n\t * Returns a string representation of the array\n\t */\n\ttoString(): string {\n\t\treturn this[forwardArray].toString()\n\t}\n\n\t/**\n\t * Returns a localized string representing the array\n\t */\n\ttoLocaleString(\n\t\tlocales?: string | string[],\n\t\toptions?: Intl.NumberFormatOptions | Intl.DateTimeFormatOptions\n\t): string {\n\t\treturn this[forwardArray].toLocaleString(locales as string | string[], options)\n\t}\n\n\t/**\n\t * Returns the element at the specified index, or undefined if the index is out of bounds\n\t */\n\tat(index: number): T | undefined {\n\t\treturn this[forwardArray].at(index)\n\t}\n\n\t/**\n\t * Returns a new array with all sub-array elements concatenated into it recursively up to the specified depth\n\t */\n\tflat(depth?: number): T[] {\n\t\treturn this[forwardArray].flat(depth) as T[]\n\t}\n\n\t/**\n\t * Returns a new array formed by applying a given callback function to each element of the array,\n\t * and then flattening the result by one level\n\t */\n\tflatMap<U, This = undefined>(\n\t\tcallback: (this: This, value: T, index: number, array: readonly T[]) => U | ReadonlyArray<U>,\n\t\tthisArg?: This\n\t): U[] {\n\t\treturn this[forwardArray].flatMap(callback as any, thisArg)\n\t}\n\n\t/**\n\t * Returns a new array with elements in reversed order (ES2023)\n\t */\n\ttoReversed(): T[] {\n\t\treturn this[forwardArray].toReversed?.() ?? [...this[forwardArray]].reverse()\n\t}\n\n\t/**\n\t * Returns a new array with elements sorted (ES2023)\n\t */\n\ttoSorted(compareFn?: ((a: T, b: T) => number) | undefined): T[] {\n\t\treturn this[forwardArray].toSorted?.(compareFn) ?? [...this[forwardArray]].sort(compareFn)\n\t}\n\n\t/**\n\t * Returns a new array with some elements removed and/or replaced at a given index (ES2023)\n\t */\n\ttoSpliced(start: number, deleteCount?: number, ...items: T[]): T[] {\n\t\tif (deleteCount === undefined) return this[forwardArray].toSpliced(start)\n\t\treturn this[forwardArray].toSpliced(start, deleteCount, ...items)\n\t}\n\n\t/**\n\t * Returns a new array with the element at the given index replaced with the given value (ES2023)\n\t */\n\twith(index: number, value: T): T[] {\n\t\treturn this[forwardArray].with(index, value)\n\t}\n\tget [Symbol.unscopables]() {\n\t\treturn this[forwardArray][Symbol.unscopables]\n\t}\n}\n","/// <reference lib=\"esnext.collection\" />\n\n/**\n * Uses weak references but still may iterate through them\n * Note: The behavior is highly dependant on the garbage collector - some entries are perhaps deemed to be collected: don't resuscitate them\n */\nexport class IterableWeakMap<K extends WeakKey, V> implements Map<K, V> {\n\tprivate uuids = new WeakMap<K, string>()\n\tprivate refs: Record<string, [WeakRef<K>, any]> = {}\n\tprivate readonly registry: FinalizationRegistry<string>\n\n\tconstructor(entries?: Iterable<[K, V]>) {\n\t\t// Create a FinalizationRegistry to clean up refs when keys are garbage collected\n\t\tthis.registry = new FinalizationRegistry((uuid: string) => {\n\t\t\tdelete this.refs[uuid]\n\t\t})\n\t\tif (entries) for (const [k, v] of entries) this.set(k, v)\n\t}\n\tprivate createIterator<I>(cb: (key: K, value: V) => I): MapIterator<I> {\n\t\tconst { refs } = this\n\t\treturn (function* () {\n\t\t\tfor (const uuid of Object.keys(refs)) {\n\t\t\t\tconst [keyRef, value] = refs[uuid]\n\t\t\t\tconst key = keyRef.deref()\n\t\t\t\tif (key) yield cb(key, value)\n\t\t\t\telse delete refs[uuid]\n\t\t\t}\n\t\t\treturn undefined\n\t\t})()\n\t}\n\tclear(): void {\n\t\t// Unregister all keys from the FinalizationRegistry\n\t\tfor (const uuid of Object.keys(this.refs)) {\n\t\t\tconst key = this.refs[uuid][0].deref()\n\t\t\tif (key) this.registry.unregister(key)\n\t\t}\n\t\tthis.uuids = new WeakMap<K, string>()\n\t\tthis.refs = {}\n\t}\n\tdelete(key: K): boolean {\n\t\tconst uuid = this.uuids.get(key)\n\t\tif (!uuid) return false\n\t\tdelete this.refs[uuid]\n\t\tthis.uuids.delete(key)\n\t\tthis.registry.unregister(key)\n\t\treturn true\n\t}\n\tforEach(callbackfn: (value: V, key: K, map: Map<K, V>) => void, thisArg?: any): void {\n\t\tfor (const [k, v] of this) callbackfn.call(thisArg ?? this, v, k, thisArg ?? this)\n\t}\n\tget(key: K): V | undefined {\n\t\tconst uuid = this.uuids.get(key)\n\t\tif (!uuid) return undefined\n\t\treturn this.refs[uuid][1]\n\t}\n\thas(key: K): boolean {\n\t\treturn this.uuids.has(key)\n\t}\n\tset(key: K, value: V): this {\n\t\tlet uuid = this.uuids.get(key)\n\t\tif (uuid) {\n\t\t\tthis.refs[uuid][1] = value\n\t\t} else {\n\t\t\tuuid = crypto.randomUUID()\n\t\t\tthis.uuids.set(key, uuid)\n\t\t\tthis.refs[uuid] = [new WeakRef(key), value]\n\t\t\t// Register key for cleanup when garbage collected\n\t\t\tthis.registry.register(key, uuid, key)\n\t\t}\n\t\treturn this\n\t}\n\tget size(): number {\n\t\treturn [...this].length\n\t}\n\tentries(): MapIterator<[K, V]> {\n\t\treturn this.createIterator((key, value) => [key, value] as [K, V])\n\t}\n\tkeys(): MapIterator<K> {\n\t\treturn this.createIterator((key, _value) => key)\n\t}\n\tvalues(): MapIterator<V> {\n\t\treturn this.createIterator((_key, value) => value)\n\t}\n\t[Symbol.iterator](): MapIterator<[K, V]> {\n\t\treturn this.entries()\n\t}\n\treadonly [Symbol.toStringTag]: string = 'IterableWeakMap'\n}\n\n/**\n * Uses weak references but still may iterate through them\n * Note: The behavior is highly dependant on the garbage collector - some entries are perhaps deemed to be collected: don't resuscitate them\n */\nexport class IterableWeakSet<K extends WeakKey> implements Set<K> {\n\tprivate uuids = new WeakMap<K, string>()\n\tprivate refs: Record<string, WeakRef<K>> = {}\n\tprivate readonly registry: FinalizationRegistry<string>\n\n\tconstructor(entries?: Iterable<K>) {\n\t\t// Create a FinalizationRegistry to clean up refs when values are garbage collected\n\t\tthis.registry = new FinalizationRegistry((uuid: string) => {\n\t\t\tdelete this.refs[uuid]\n\t\t})\n\t\tif (entries) for (const k of entries) this.add(k)\n\t}\n\tprivate createIterator<I>(cb: (key: K) => I): MapIterator<I> {\n\t\tconst { refs } = this\n\t\treturn (function* () {\n\t\t\tfor (const uuid of Object.keys(refs)) {\n\t\t\t\tconst key = refs[uuid].deref()\n\t\t\t\tif (key) yield cb(key)\n\t\t\t\telse delete refs[uuid]\n\t\t\t}\n\t\t\treturn undefined\n\t\t})()\n\t}\n\n\tclear(): void {\n\t\t// Unregister all values from the FinalizationRegistry\n\t\tfor (const uuid of Object.keys(this.refs)) {\n\t\t\tconst value = this.refs[uuid].deref()\n\t\t\tif (value) this.registry.unregister(value)\n\t\t}\n\t\tthis.uuids = new WeakMap<K, string>()\n\t\tthis.refs = {}\n\t}\n\n\tadd(value: K): this {\n\t\tlet uuid = this.uuids.get(value)\n\t\tif (!uuid) {\n\t\t\tuuid = crypto.randomUUID()\n\t\t\tthis.uuids.set(value, uuid)\n\t\t\tthis.refs[uuid] = new WeakRef(value)\n\t\t\t// Register value for cleanup when garbage collected\n\t\t\tthis.registry.register(value, uuid, value)\n\t\t}\n\t\treturn this\n\t}\n\tdelete(value: K): boolean {\n\t\tconst uuid = this.uuids.get(value)\n\t\tif (!uuid) return false\n\t\tdelete this.refs[uuid]\n\t\tthis.uuids.delete(value)\n\t\tthis.registry.unregister(value)\n\t\treturn true\n\t}\n\n\tforEach(callbackfn: (value: K, value2: K, set: Set<K>) => void, thisArg?: any): void {\n\t\tfor (const value of this) callbackfn.call(thisArg ?? this, value, value, thisArg ?? this)\n\t}\n\n\thas(value: K): boolean {\n\t\treturn this.uuids.has(value)\n\t}\n\tget size(): number {\n\t\treturn [...this].length\n\t}\n\tentries(): SetIterator<[K, K]> {\n\t\treturn this.createIterator((key) => [key, key] as [K, K])\n\t}\n\tkeys(): SetIterator<K> {\n\t\treturn this.createIterator((key) => key)\n\t}\n\tvalues(): SetIterator<K> {\n\t\treturn this.createIterator((key) => key)\n\t}\n\t[Symbol.iterator](): SetIterator<K> {\n\t\treturn this.keys()\n\t}\n\treadonly [Symbol.toStringTag]: string = 'IterableWeakSet'\n\n\tunion<U>(other: ReadonlySetLike<U>): Set<K | U> {\n\t\tconst others = {\n\t\t\t[Symbol.iterator]() {\n\t\t\t\treturn other.keys()\n\t\t\t},\n\t\t}\n\t\tconst that = this\n\t\treturn new Set(\n\t\t\t(function* () {\n\t\t\t\tyield* that\n\t\t\t\tfor (const value of others) if (!that.has(<K>(<unknown>value))) yield value\n\t\t\t})()\n\t\t)\n\t}\n\tintersection<U /**/>(other: ReadonlySetLike<U>): Set<K & U> {\n\t\tconst that = this\n\t\treturn new Set(\n\t\t\t(function* () {\n\t\t\t\tfor (const value of that) if (other.has(<U>(<unknown>value))) yield <K & U>value\n\t\t\t})()\n\t\t)\n\t}\n\tdifference<U>(other: ReadonlySetLike<U>): Set<K> {\n\t\tconst that = this\n\t\treturn new Set(\n\t\t\t(function* () {\n\t\t\t\tfor (const value of that) if (!other.has(<U>(<unknown>value))) yield <K>value\n\t\t\t})()\n\t\t)\n\t}\n\tsymmetricDifference<U>(other: ReadonlySetLike<U>): Set<K | U> {\n\t\tconst others = {\n\t\t\t[Symbol.iterator]() {\n\t\t\t\treturn other.keys()\n\t\t\t},\n\t\t}\n\t\tconst that = this\n\t\treturn new Set(\n\t\t\t(function* () {\n\t\t\t\tfor (const value of that) if (!other.has(<U>(<unknown>value))) yield <K | U>value\n\t\t\t\tfor (const value of others) if (!that.has(<K>(<unknown>value))) yield <K | U>value\n\t\t\t})()\n\t\t)\n\t}\n\tisSubsetOf(other: ReadonlySetLike<unknown>): boolean {\n\t\tfor (const value of this) if (!other.has(value)) return false\n\t\treturn true\n\t}\n\tisSupersetOf(other: ReadonlySetLike<unknown>): boolean {\n\t\tconst others = {\n\t\t\t[Symbol.iterator]() {\n\t\t\t\treturn other.keys()\n\t\t\t},\n\t\t}\n\t\tfor (const value of others) if (!this.has(<K>value)) return false\n\t\treturn true\n\t}\n\tisDisjointFrom(other: ReadonlySetLike<unknown>): boolean {\n\t\tfor (const value of this) if (other.has(value)) return false\n\t\treturn true\n\t}\n}\n","import { FoolProof, isConstructor } from './utils'\n\n/**\n * A mixin function that takes a base class and returns a new class with mixed-in functionality\n * @template Mixed - The functionality to be mixed in\n */\nexport type MixinFunction<Mixed> = <Base>(\n\tbase: new (...args: any[]) => Base\n) => new (\n\t...args: any[]\n) => Base & Mixed\n\n/**\n * A mixin class that can be used both as a base class and as a mixin function\n * @template Mixed - The functionality to be mixed in\n */\nexport type MixinClass<Mixed> = new (...args: any[]) => Mixed\n\n/**\n * Creates a mixin that can be used both as a class (extends) and as a function (mixin)\n *\n * This function supports:\n * - Using mixins as base classes: `class MyClass extends MyMixin`\n * - Using mixins as functions: `class MyClass extends MyMixin(SomeBase)`\n * - Composing mixins: `const Composed = MixinA(MixinB)`\n * - Type-safe property inference for all patterns\n *\n * @param mixinFunction - The function that creates the mixin\n * @param unwrapFunction - Optional function to unwrap reactive objects for method calls\n * @returns A mixin that can be used both as a class and as a function\n */\nexport function mixin<MixinFn extends (base: any) => new (...args: any[]) => any>(\n\tmixinFunction: MixinFn,\n\tunwrapFunction?: (obj: any) => any\n): (new (\n\t...args: any[]\n) => InstanceType<ReturnType<MixinFn>>) &\n\t(<Base>(\n\t\tbase: abstract new (...args: any[]) => Base\n\t) => new (\n\t\t...args: any[]\n\t) => InstanceType<ReturnType<MixinFn>> & Base) {\n\t/**\n\t * Cache for mixin results to ensure the same base class always returns the same mixed class\n\t */\n\tconst mixinCache = new WeakMap<new (...args: any[]) => any, new (...args: any[]) => any>()\n\n\t// Apply the mixin to Object as the base class\n\tconst MixedBase = mixinFunction(Object)\n\tmixinCache.set(Object, MixedBase)\n\n\t// Create the proxy that handles both constructor and function calls\n\treturn new Proxy(MixedBase, {\n\t\t// Handle `MixinClass(SomeBase)` - use as mixin function\n\t\tapply(_target, _thisArg, args) {\n\t\t\tif (args.length === 0) {\n\t\t\t\tthrow new Error('Mixin requires a base class')\n\t\t\t}\n\n\t\t\tconst baseClass = args[0]\n\t\t\tif (typeof baseClass !== 'function') {\n\t\t\t\tthrow new Error('Mixin requires a constructor function')\n\t\t\t}\n\n\t\t\t// Check if it's a valid constructor or a mixin\n\t\t\tif (\n\t\t\t\t!isConstructor(baseClass) &&\n\t\t\t\t!(baseClass && typeof baseClass === 'function' && baseClass.prototype)\n\t\t\t) {\n\t\t\t\tthrow new Error('Mixin requires a valid constructor')\n\t\t\t}\n\n\t\t\t// Check cache first\n\t\t\tconst cached = mixinCache.get(baseClass)\n\t\t\tif (cached) {\n\t\t\t\treturn cached\n\t\t\t}\n\n\t\t\tlet usedBase = baseClass\n\t\t\tif (unwrapFunction) {\n\t\t\t\t// Create a proxied base class that handles method unwrapping\n\t\t\t\tconst ProxiedBaseClass = class extends baseClass {}\n\n\t\t\t\t// Proxy the prototype methods to handle unwrapping\n\t\t\t\tconst originalPrototype = baseClass.prototype\n\t\t\t\tconst proxiedPrototype = new Proxy(originalPrototype, {\n\t\t\t\t\tget(target, prop, receiver) {\n\t\t\t\t\t\tconst value = FoolProof.get(target, prop, receiver)\n\n\t\t\t\t\t\t// Only wrap methods that are likely to access private fields\n\t\t\t\t\t\t// Skip symbols and special properties that the reactive system needs\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\ttypeof value === 'function' &&\n\t\t\t\t\t\t\ttypeof prop === 'string' &&\n\t\t\t\t\t\t\t!['constructor', 'toString', 'valueOf'].includes(prop)\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t// Return a wrapped version that uses unwrapped context\n\t\t\t\t\t\t\treturn function (this: any, ...args: any[]) {\n\t\t\t\t\t\t\t\t// Use the unwrapping function if provided, otherwise use this\n\t\t\t\t\t\t\t\tconst context = unwrapFunction(this as any)\n\t\t\t\t\t\t\t\treturn value.apply(context, args)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\treturn value\n\t\t\t\t\t},\n\t\t\t\t})\n\n\t\t\t\t// Set the proxied prototype\n\t\t\t\tObject.setPrototypeOf(ProxiedBaseClass.prototype, proxiedPrototype)\n\t\t\t\tusedBase = ProxiedBaseClass\n\t\t\t}\n\n\t\t\t// Create the mixed class using the proxied base class\n\t\t\tconst mixedClass = mixinFunction(usedBase)\n\n\t\t\t// Cache the result\n\t\t\tmixinCache.set(baseClass, mixedClass)\n\n\t\t\treturn mixedClass\n\t\t},\n\t}) as MixinFn & (new (...args: any[]) => InstanceType<ReturnType<MixinFn>>)\n}\n","type Resolved<T> =\n\tT extends Promise<infer U>\n\t\t? Resolved<U>\n\t\t: T extends (...args: infer Args) => infer R\n\t\t\t? (...args: Args) => Resolved<R>\n\t\t\t: T extends object\n\t\t\t\t? {\n\t\t\t\t\t\t[k in keyof T]: k extends 'then' | 'catch' | 'finally' ? T[k] : Resolved<T[k]>\n\t\t\t\t\t}\n\t\t\t\t: T\ntype PromiseAnd<T> = Resolved<T> & Promise<Resolved<T>>\n/**\n * Type that transforms promises into chainable objects\n * Allows calling methods directly on promise results without awaiting them first\n */\nexport type PromiseChain<T> = T extends (...args: infer Args) => infer R\n\t? PromiseAnd<(...args: Args) => PromiseChain<Resolved<R>>>\n\t: T extends object\n\t\t? PromiseAnd<{\n\t\t\t\t[k in keyof T]: k extends 'then' | 'catch' | 'finally' ? T[k] : PromiseChain<Resolved<T[k]>>\n\t\t\t}>\n\t\t: Promise<Resolved<T>>\n\nconst forward =\n\t(name: string, target: any) =>\n\t(...args: any[]) => {\n\t\treturn target[name](...args)\n\t}\n\nconst alreadyChained = new WeakMap<any, PromiseChain<any>>()\nconst originals = new WeakMap<Promise<any>, any>()\n\nfunction cache(target: any, rv: PromiseChain<any>) {\n\toriginals.set(rv, target)\n\talreadyChained.set(target, rv)\n}\n\ntype ChainedFunction<T> = ((...args: any[]) => PromiseChain<T>) & {\n\tthen: Promise<T>['then']\n\tcatch: Promise<T>['catch']\n\tfinally: Promise<T>['finally']\n}\n\nconst promiseProxyHandler: ProxyHandler<ChainedFunction<any>> = {\n\t//@ts-expect-error\n\t[Symbol.toStringTag]: 'MutTs PromiseChain function',\n\tget(target, prop) {\n\t\tif (prop === Symbol.toStringTag) return 'PromiseProxy'\n\t\tif (typeof prop === 'string' && ['then', 'catch', 'finally'].includes(prop))\n\t\t\treturn target[prop as keyof typeof target]\n\t\treturn chainPromise(target.then((r) => r[prop as keyof typeof r]))\n\t},\n}\nconst promiseForward = (target: any) => ({\n\t// biome-ignore lint/suspicious/noThenProperty: This one is the whole point\n\tthen: forward('then', target),\n\tcatch: forward('catch', target),\n\tfinally: forward('finally', target),\n})\nconst objectProxyHandler: ProxyHandler<any> = {\n\t//@ts-expect-error\n\t[Symbol.toStringTag]: 'MutTs PromiseChain object',\n\tget(target, prop, receiver) {\n\t\tconst getter = Object.getOwnPropertyDescriptor(target, prop)?.get\n\t\tconst rv = getter ? getter.call(receiver) : target[prop]\n\t\t// Allows fct.call or fct.apply to bypass the chain system\n\t\tif (typeof target === 'function') return rv\n\t\treturn chainPromise(rv)\n\t},\n\tapply(target, thisArg, args) {\n\t\treturn chainPromise(target.apply(thisArg, args))\n\t},\n}\nfunction chainObject<T extends object | Function>(given: T): PromiseChain<T> {\n\tconst rv = new Proxy(given, objectProxyHandler) as PromiseChain<T>\n\tcache(given, rv)\n\treturn rv\n}\n\nfunction chainable(x: any): x is object | Function {\n\treturn x && ['function', 'object'].includes(typeof x)\n}\n/**\n * Transforms a promise or value into a chainable object\n * Allows calling methods directly on promise results without awaiting them first\n * @param given - The promise or value to make chainable\n * @returns A chainable version of the input\n */\nexport function chainPromise<T>(given: Promise<T> | T): PromiseChain<T> {\n\tif (!chainable(given)) return given as PromiseChain<T>\n\tif (alreadyChained.has(given)) return alreadyChained.get(given) as PromiseChain<T>\n\tif (!(given instanceof Promise)) return chainObject(given)\n\t// @ts-expect-error It's ok as we check if it's an object above\n\tgiven = given.then((r) => (chainable(r) ? chainObject(r) : r))\n\tconst target = Object.assign(function (this: any, ...args: any[]) {\n\t\treturn chainPromise(\n\t\t\tgiven.then((r) => {\n\t\t\t\treturn this?.then\n\t\t\t\t\t? this.then((t: any) => (r as any).apply(t, args))\n\t\t\t\t\t: (r as any).apply(this, args)\n\t\t\t})\n\t\t)\n\t}, promiseForward(given)) as ChainedFunction<T>\n\tconst chained = new Proxy(\n\t\ttarget,\n\t\tpromiseProxyHandler as ProxyHandler<ChainedFunction<T>>\n\t) as PromiseChain<T>\n\tcache(given, chained as PromiseChain<any>)\n\treturn chained\n}\n","import type { EffectTrigger, Evolution } from './types'\n\nexport interface DebugHooks {\n\tisDevtoolsEnabled: () => boolean\n\tregisterEffect: (effect: EffectTrigger) => void\n\tgetTriggerChain: (effect: EffectTrigger) => string[]\n\tcaptureStack: (error?: unknown) => unknown\n\tcaptureLineage: (effect?: EffectTrigger, stack?: unknown) => unknown\n\tformatStack: (stack: unknown) => unknown[]\n\trecordTriggerLink: (\n\t\tsource: EffectTrigger | undefined,\n\t\ttarget: EffectTrigger,\n\t\tobj: object,\n\t\tprop: any,\n\t\tevolution: Evolution\n\t) => void\n\tdecorateError: (error: unknown, trigger: EffectTrigger) => void\n}\n\nexport const debugHooks: DebugHooks = {\n\tisDevtoolsEnabled: () => false,\n\tregisterEffect: () => {},\n\tgetTriggerChain: () => [],\n\tcaptureStack: () => [],\n\tcaptureLineage: () => new Error().stack,\n\tformatStack: (stack: unknown) => [stack],\n\trecordTriggerLink: () => {},\n\tdecorateError: () => {},\n}\n\nexport function setDebugHooks(hooks: Partial<DebugHooks>) {\n\tObject.assign(debugHooks, hooks)\n}\n","import { asyncHooks } from './async'\nimport { named, tag } from './utils'\n\ninterface InternalZoneUse<T> {\n\tenter(value?: T): unknown\n\tleave(entered: unknown): void\n}\nfunction isu<T>(z: AZone<T> | InternalZoneUse<T>): InternalZoneUse<T> {\n\treturn z as InternalZoneUse<T>\n}\nexport abstract class AZone<T> {\n\tabstract active?: T\n\tprotected enter(value?: T): unknown {\n\t\tconst prev = this.active\n\t\tthis.active = value\n\t\treturn prev\n\t}\n\tprotected leave(entered: unknown): void {\n\t\tthis.active = entered as T | undefined\n\t}\n\twith<R>(value: T | undefined, fn: () => R): R {\n\t\tconst entered = this.enter(value)\n\t\tlet res: R\n\t\ttry {\n\t\t\tres = fn()\n\t\t} finally {\n\t\t\tthis.leave(entered)\n\t\t}\n\t\t// [HACK]: Sanitization\n\t\t// See BROWSER_ASYNC_POLYFILL.md\n\t\treturn asyncHooks.sanitizePromise(res) as R\n\t}\n\troot<R>(fn: () => R): R {\n\t\tconst prev = this.enter()\n\t\ttry {\n\t\t\treturn fn()\n\t\t} finally {\n\t\t\tthis.leave(prev)\n\t\t}\n\t}\n\tget zoned(): GetterWrapper {\n\t\tconst active = this.active\n\t\treturn named(`${this}@${active}`, (fn) => this.with(active, fn))\n\t}\n}\n\nexport type GetterWrapper = <R>(fn: () => R) => R\n\nexport class Zone<T> extends AZone<T> {\n\tactive: T | undefined\n}\n\nexport type HistoryValue<T> = { present: T | undefined; history: Set<T> }\nexport class ZoneHistory<T> extends AZone<HistoryValue<T>> {\n\tprivate history = new Set<T>()\n\tpublic readonly present: AZone<T>\n\tpublic has(value: T): boolean {\n\t\treturn this.history.has(value)\n\t}\n\tpublic some(predicate: (value: T) => boolean): boolean {\n\t\tfor (const value of this.history) if (predicate(value)) return true\n\t\treturn false\n\t}\n\tconstructor(private controlled: AZone<T> = new Zone<T>()) {\n\t\tsuper()\n\t\tconst self = this\n\t\tthis.present = Object.create(\n\t\t\tcontrolled,\n\t\t\tObject.getOwnPropertyDescriptors({\n\t\t\t\tget active() {\n\t\t\t\t\treturn controlled.active\n\t\t\t\t},\n\t\t\t\tset active(value: T | undefined) {\n\t\t\t\t\tcontrolled.active = value\n\t\t\t\t},\n\t\t\t\tenter(value?: T) {\n\t\t\t\t\tif (value && self.history.has(value))\n\t\t\t\t\t\tthrow new Error('ZoneHistory: re-entering historical zone')\n\t\t\t\t\tif (value !== undefined) self.history.add(value)\n\t\t\t\t\treturn { added: value, entered: isu(controlled).enter(value) }\n\t\t\t\t},\n\t\t\t\tleave(entered: { added: T | undefined; entered: unknown }) {\n\t\t\t\t\tif (entered.added !== undefined) self.history.delete(entered.added)\n\t\t\t\t\treturn isu(controlled).leave(entered.entered)\n\t\t\t\t},\n\t\t\t})\n\t\t)\n\t}\n\tget active() {\n\t\treturn { present: this.controlled.active, history: new Set(this.history) }\n\t}\n\tset active(value: HistoryValue<T> | undefined) {\n\t\tthis.history = value?.history ? new Set(value.history) : new Set()\n\t\tthis.controlled.active = value?.present\n\t}\n}\n\nexport class ZoneAggregator extends AZone<Map<AZone<unknown>, unknown>> {\n\t#zones = new Set<AZone<unknown>>()\n\tconstructor(...zones: AZone<unknown>[]) {\n\t\tsuper()\n\t\tfor (const z of zones) this.#zones.add(z)\n\t}\n\tget active(): Map<AZone<unknown>, unknown> | undefined {\n\t\tconst rv = new Map<AZone<unknown>, unknown>()\n\t\tfor (const z of this.#zones) if (z.active !== undefined) rv.set(z, z.active)\n\t\treturn rv\n\t}\n\tset active(value: Map<AZone<unknown>, unknown> | undefined) {\n\t\tfor (const z of this.#zones) z.active = value?.get(z)\n\t}\n\tenter(value?: Map<AZone<unknown>, unknown> | undefined) {\n\t\tconst entered = new Map<AZone<unknown>, unknown>()\n\t\tfor (const z of this.#zones) {\n\t\t\tconst v = value?.get(z)\n\t\t\tentered.set(z, isu(z).enter(v))\n\t\t}\n\t\treturn entered\n\t}\n\tleave(entered: Map<AZone<unknown>, unknown>): void {\n\t\tfor (const z of this.#zones) isu(z).leave(entered.get(z))\n\t}\n\tadd(z: AZone<unknown>) {\n\t\tthis.#zones.add(z)\n\t}\n\tdelete(z: AZone<unknown>) {\n\t\tthis.#zones.delete(z)\n\t}\n\tclear() {\n\t\tthis.#zones.clear()\n\t}\n}\n\n/**\n * Aggregator of zones that should be preserved across async boundaries.\n * If you add a zone here, it will be preserved across async boundaries.\n *\n * @example\n * ```ts\n * import { Zone, asyncZone } from 'mutts'\n * const userZone = new Zone<User>()\n * asyncZone.add(userZone)\n * ```\n */\nexport const asyncZone = tag('async', new ZoneAggregator())\nasyncHooks.addHook(() => {\n\t// capture state before async boundary\n\tconst zone = asyncZone.active\n\treturn () => {\n\t\t// restore state after async boundary, temporarily\n\t\tconst prev = asyncZone.active\n\t\tasyncZone.active = zone\n\t\treturn () => {\n\t\t\t// restore previous state from before our restore\n\t\t\tasyncZone.active = prev\n\t\t}\n\t}\n})\n","import type { EffectNode, EffectTrigger } from './types'\n\n// Symbol for storing root function on the function itself\nexport const rootFunctionSymbol = Symbol('root-function')\n\nexport type RootMarkedFunction = Function & {\n\t[rootFunctionSymbol]?: Function\n}\n\n// Track which effects are watching which reactive objects for cleanup\nexport let effectToReactiveObjects = new WeakMap<EffectTrigger, Set<object>>()\n\n// Track effects per reactive object and property\nexport let watchers = new WeakMap<object, Map<any, Set<EffectTrigger>>>()\n\n// Track effect metadata and relationships\nexport let effectNodes = new WeakMap<EffectTrigger, EffectNode>()\n\nexport function getEffectNode(effect: EffectTrigger): EffectNode {\n\tlet node = effectNodes.get(effect)\n\tif (!node) {\n\t\tnode = {}\n\t\teffectNodes.set(effect, node)\n\t}\n\treturn node\n}\n\n// Track reverse mapping to ensure unicity: One Root -> One Function\nlet reverseRoots = new WeakMap<any, WeakRef<Function>>()\n\nexport function resetRegistry() {\n\teffectToReactiveObjects = new WeakMap()\n\twatchers = new WeakMap()\n\teffectNodes = new WeakMap()\n\treverseRoots = new WeakMap()\n}\n\n/**\n * Marks a function with its root function for effect tracking\n * Enforces strict unicity: A root function can only identify ONE function.\n * @param fn - The function to mark\n * @param root - The root function\n * @returns The marked function\n */\nexport function markWithRoot<T extends Function>(fn: T, root: any): T {\n\tconst marked = fn as T & RootMarkedFunction\n\t// Check for collision\n\tconst existingRef = reverseRoots.get(root)\n\tconst existing = existingRef?.deref()\n\n\tif (existing && existing !== fn) {\n\t\tconst rootName = root.name || 'anonymous'\n\t\tconst existingName = existing.name || 'anonymous'\n\t\tconst fnName = fn.name || 'anonymous'\n\t\tthrow new Error(\n\t\t\t`[reactive] Abusive Shared Root detected: Root '${rootName}' is already identifying function '${existingName}'. ` +\n\t\t\t\t`Cannot reuse it for '${fnName}'. Shared roots cause lost updates and broken identity logic.`\n\t\t)\n\t}\n\n\t// Always update the map so subsequent checks find this one\n\t// (Last writer wins for the check)\n\treverseRoots.set(root, new WeakRef(fn))\n\n\t// Store root mapping as symbol property on the function\n\tmarked[rootFunctionSymbol] = getRoot(root)\n\treturn marked\n}\n\n/**\n * Gets the root function of a function for effect tracking\n * @param fn - The function to get the root of\n * @returns The root function\n */\nexport function getRoot<T extends Function | undefined>(fn: T): T {\n\twhile (fn) {\n\t\tconst r = (fn as RootMarkedFunction)[rootFunctionSymbol]\n\t\tif (!r) break\n\t\tfn = r as T\n\t}\n\treturn fn\n}\n","import { tag } from '../utils'\nimport { asyncZone, Zone, ZoneAggregator, ZoneHistory } from '../zone'\nimport { getRoot } from './registry'\nimport type { CleanupReason, EffectTrigger, ScopedCallback } from './types'\n\nexport const effectHistory = tag('effectHistory', new ZoneHistory<EffectTrigger>())\ntag('effectHistory.present', effectHistory.present)\nasyncZone.add(effectHistory)\nexport const externalReason = tag('externalReason', new Zone<CleanupReason>())\nasyncZone.add(externalReason)\n\n/**\n * Aggregator for zones that need to be tracked along effects.\n * ie. in each effect, the active zone of the given zoning will be the one active at effect's definition\n */\nexport const effectAggregator = tag('effectAggregator', new ZoneAggregator(effectHistory.present))\neffectAggregator.add(externalReason)\n\nexport function chainExternalReason(reason?: CleanupReason): CleanupReason | undefined {\n\tconst external = externalReason.active\n\tif (!external) return reason\n\tif (!reason) return external\n\tlet current: CleanupReason | undefined = reason\n\twhile (current) {\n\t\tif (\n\t\t\tcurrent.type === 'external' &&\n\t\t\texternal.type === 'external' &&\n\t\t\tcurrent.detail === external.detail\n\t\t)\n\t\t\treturn reason\n\t\tcurrent = current.chain\n\t}\n\treturn { ...reason, chain: chainExternalReason(reason.chain) }\n}\n\nexport function isRunning(effect: EffectTrigger): boolean {\n\tconst root = getRoot(effect)\n\treturn effectHistory.some((e) => getRoot(e) === root)\n}\n\nexport function getActiveEffect() {\n\treturn effectHistory.present.active\n}\n\n/**\n * Opaque token representing a captured effect context.\n * Obtained via `effectContext()`, consumed by `withEffectContext()`.\n */\nexport type EffectContext = { readonly __brand: unique symbol }\n\n/**\n * Captures the current effect context so that deferred code can later\n * create child effects parented to this point in the effect tree.\n *\n * @returns An opaque token to pass to `withEffectContext()`\n *\n * @example\n * ```ts\n * const ctx = effectContext() // inside an effect or root()\n * // later, in a deferred callback:\n * withEffectContext(ctx, () => {\n * effect(() => { /* child of the captured context */ })\n * })\n * ```\n */\nexport function effectContext(): EffectContext | undefined {\n\treturn effectHistory.active as unknown as EffectContext | undefined\n}\n\n/**\n * Runs `fn` within a previously captured effect context.\n * Any effects created inside `fn` become children of the captured parent.\n *\n * @param ctx - The context token from `effectContext()`, or `undefined` for root context\n * @param fn - The function to execute within the restored context\n * @returns The return value of `fn`\n */\nexport function withEffectContext<R>(ctx: EffectContext | undefined, fn: () => R): R {\n\treturn effectHistory.with(ctx as any, fn)\n}\n\nconst cleanups = new WeakMap<object, Set<ScopedCallback | object>>()\n\n/**\n * Attach cleanup dependencies to an object. When `unlink(obj)` is called,\n * each dependency is disposed: functions are invoked with the cleanup reason,\n * objects are recursively `unlink`ed. This forms a cleanup tree.\n *\n * @param obj - The owner object\n * @param cleanupFns - Cleanup callbacks and/or child objects to unlink recursively\n * @returns The owner object (for chaining)\n *\n * @example\n * ```ts\n * // Functions are called with CleanupReason\n * link(parent, () => console.log('disposed'))\n *\n * // Objects are recursively unlinked\n * link(parent, childA, childB)\n *\n * // Mixed\n * link(parent, childObj, () => timer.clear())\n *\n * unlink(parent) // disposes childA, childB, calls the function\n * ```\n */\nexport function link<T extends object>(\n\tobj: T,\n\t...cleanupFns: (ScopedCallback | object | undefined)[]\n): T {\n\tconst set = cleanups.get(obj)\n\tif (!set)\n\t\tcleanups.set(\n\t\t\tobj,\n\t\t\tnew Set(cleanupFns.filter((fn): fn is ScopedCallback | object => fn !== undefined))\n\t\t)\n\telse for (const fn of cleanupFns) if (fn) set.add(fn)\n\treturn obj\n}\n\n/**\n * Dispose an object's cleanup dependencies. Functions are called with the\n * reason; linked objects are recursively unlinked. The cleanup set is removed\n * so calling `unlink` twice is safe (second call is a no-op).\n *\n * @param obj - The object to dispose\n * @param reason - Optional cleanup reason propagated to callbacks\n */\nexport function unlink(obj: object, reason?: CleanupReason): void {\n\tconst set = cleanups.get(obj)\n\tif (set) {\n\t\tcleanups.delete(obj)\n\t\tfor (const fn of set)\n\t\t\tif (typeof fn === 'function') fn(reason)\n\t\t\telse unlink(fn, reason)\n\t}\n}\n","import type { GetterWrapper } from '../zone'\nimport { debugHooks } from './debug-hooks'\n\nexport type EffectAccessEvents = {\n\ttriggered(event: string, ...args: any[]): void\n}\n\n/**\n * Effect access passed to user callbacks within effects/watch\n * Provides functions to track dependencies and information about the effect execution\n */\nexport interface EffectAccess {\n\t/**\n\t * Tracks dependencies in the current effect context\n\t * Use this for normal dependency tracking within the effect\n\t * @example\n\t * ```typescript\n\t * effect(({ tracked }) => {\n\t * // In async context, use tracked to restore dependency tracking\n\t * await someAsyncOperation()\n\t * const value = tracked(() => state.count) // Tracks state.count in this effect\n\t * })\n\t * ```\n\t */\n\ttracked: GetterWrapper\n\t/**\n\t * Tracks dependencies in the parent effect context\n\t * Use this when child effects should track dependencies in the parent,\n\t * allowing parent cleanup to manage child effects while dependencies trigger the parent\n\t * @example\n\t * ```typescript\n\t * effect(({ ascend }) => {\n\t * const length = inputs.length\n\t * if (length > 0) {\n\t * ascend(() => {\n\t * // Dependencies here are tracked in the parent effect\n\t * inputs.forEach(item => console.log(item))\n\t * })\n\t * }\n\t * })\n\t * ```\n\t */\n\tascend: GetterWrapper\n\t/**\n\t * `false` on the first execution, `true` or `CleanupReason` on subsequent runs.\n\t * `true` means this is a re-run but detailed reason gathering is disabled or unavailable.\n\t * A `CleanupReason` describes *why* the previous run was torn down.\n\t * @example\n\t * ```typescript\n\t * effect(({ reaction }) => {\n\t * if (!reaction) {\n\t * // First run — setup\n\t * } else if (reaction !== true && reaction.type === 'propChange') {\n\t * // Re-run due to dependency change (with details)\n\t * for (const { evolution } of reaction.triggers)\n\t * console.log(`${'prop' in evolution ? evolution.prop : evolution.method}: ${evolution.type}`)\n\t * }\n\t * })\n\t * ```\n\t */\n\treaction: boolean | CleanupReason\n\t/**\n\t * AbortSignal that is aborted when the effect is cleaned up or re-runs.\n\t * Use this to cancel async operations (like fetch) when the effect is no longer valid.\n\t */\n\tsignal: AbortSignal\n}\n// Zone-based async context preservation is implemented in zone.ts\n// It automatically preserves effect context across Promise boundaries (.then, .catch, .finally)\n\n/**\n * Base type for effect callbacks - simple function without additional properties\n */\nexport type ScopedCallback = (reason?: CleanupReason) => void\n\nexport const effectMarker = {\n\tenter: 'effect:enter',\n\tleave: 'effect:leave',\n}\n\nexport type PropTrigger = {\n\tobj: object\n\tevolution: Evolution\n\tdependency?: unknown // Stack from when dependency was created\n\ttouch?: unknown // Stack from when touch occurred\n}\n\n/**\n * Reason for an effect cleanup/reaction\n */\nexport type CleanupReason =\n\t| { type: 'propChange'; triggers: PropTrigger[]; chain?: CleanupReason }\n\t| { type: 'invalidate'; cause: CleanupReason; chain?: CleanupReason }\n\t| { type: 'external'; detail: string; chain?: CleanupReason }\n\t| { type: 'stopped'; detail?: string; chain?: CleanupReason } // explicit stop() call\n\t| { type: 'gc'; chain?: CleanupReason } // FinalizationRegistry collected the holder\n\t| { type: 'lineage'; parent: CleanupReason; chain?: CleanupReason } // parent effect cleaned up (recursive)\n\t| { type: 'error'; error: unknown; chain?: CleanupReason } // error handler chain (reactionCleanup called with error)\n\t| { type: 'multiple'; reasons: CleanupReason[]; chain?: CleanupReason }\n\nfunction formatTrigger({ obj, evolution, dependency, touch }: PropTrigger): unknown[] {\n\tconst detail = evolution.type === 'bunch' ? evolution.method : String(evolution.prop)\n\tconst parts: unknown[] = [`${evolution.type} ${detail} on`, obj]\n\n\tif (dependency) {\n\t\tparts.push('\\n Dependency created at:')\n\t\tparts.push(...debugHooks.formatStack(dependency))\n\t}\n\n\tif (touch) {\n\t\tparts.push('\\n Touched from:')\n\t\tparts.push(...debugHooks.formatStack(touch))\n\t}\n\n\treturn parts\n}\n\n/**\n * Console-friendly description of a `CleanupReason`.\n * Returns an array of arguments to spread into `console.log` / `console.warn`,\n * mixing strings and raw object references so the console can render them as inspectable values.\n *\n * @example\n * ```typescript\n * effect(({ reaction }) => {\n * if (reaction !== true) console.log(...formatCleanupReason(reaction))\n * })\n * ```\n */\nexport function formatCleanupReason(reason: CleanupReason, depth = 0): unknown[] {\n\tconst indent = depth ? ' '.repeat(depth) : ''\n\tswitch (reason.type) {\n\t\tcase 'propChange': {\n\t\t\tconst parts: unknown[] = [`${indent}propChange:`]\n\t\t\tfor (let i = 0; i < reason.triggers.length; i++) {\n\t\t\t\tif (i > 0) parts.push(',')\n\t\t\t\tparts.push(...formatTrigger(reason.triggers[i]))\n\t\t\t}\n\t\t\tif (reason.chain) {\n\t\t\t\tparts.push('\\n', ...formatCleanupReason(reason.chain, depth))\n\t\t\t}\n\t\t\treturn parts\n\t\t}\n\t\tcase 'stopped': {\n\t\t\tconst parts: unknown[] = [`${indent}stopped`]\n\t\t\tif (reason.detail) parts.push(`(${reason.detail})`)\n\t\t\tif (reason.chain) {\n\t\t\t\tparts.push('\\n', ...formatCleanupReason(reason.chain, depth))\n\t\t\t}\n\t\t\treturn parts\n\t\t}\n\t\tcase 'external': {\n\t\t\tconst parts: unknown[] = [`${indent}external:`, reason.detail]\n\t\t\tif (reason.chain) {\n\t\t\t\tparts.push('\\n', ...formatCleanupReason(reason.chain, depth))\n\t\t\t}\n\t\t\treturn parts\n\t\t}\n\t\tcase 'gc': {\n\t\t\tconst parts: unknown[] = [`${indent}gc`]\n\t\t\tif (reason.chain) {\n\t\t\t\tparts.push('\\n', ...formatCleanupReason(reason.chain, depth))\n\t\t\t}\n\t\t\treturn parts\n\t\t}\n\t\tcase 'error': {\n\t\t\tconst parts: unknown[] = [`${indent}error:`, reason.error]\n\t\t\tif (reason.chain) {\n\t\t\t\tparts.push('\\n', ...formatCleanupReason(reason.chain, depth))\n\t\t\t}\n\t\t\treturn parts\n\t\t}\n\t\tcase 'lineage': {\n\t\t\tconst parts: unknown[] = [\n\t\t\t\t`${indent}lineage ←\\n`,\n\t\t\t\t...formatCleanupReason(reason.parent, depth + 1),\n\t\t\t]\n\t\t\tif (reason.chain) {\n\t\t\t\tparts.push('\\n', ...formatCleanupReason(reason.chain, depth))\n\t\t\t}\n\t\t\treturn parts\n\t\t}\n\t\tcase 'invalidate': {\n\t\t\tconst parts: unknown[] = [\n\t\t\t\t`${indent}invalidate ←\\n`,\n\t\t\t\t...formatCleanupReason(reason.cause, depth + 1),\n\t\t\t]\n\t\t\tif (reason.chain) {\n\t\t\t\tparts.push('\\n', ...formatCleanupReason(reason.chain, depth))\n\t\t\t}\n\t\t\treturn parts\n\t\t}\n\t\tcase 'multiple': {\n\t\t\tconst parts: unknown[] = []\n\t\t\tfor (let i = 0; i < reason.reasons.length; i++) {\n\t\t\t\tif (i > 0) parts.push('\\n')\n\t\t\t\tparts.push(...formatCleanupReason(reason.reasons[i], depth))\n\t\t\t}\n\t\t\tif (reason.chain) {\n\t\t\t\tparts.push('\\n', ...formatCleanupReason(reason.chain, depth))\n\t\t\t}\n\t\t\treturn parts\n\t\t}\n\t}\n}\n\n/**\n * Type for effect cleanup functions.\n */\nexport type EffectCleanup = ScopedCallback\n\n/**\n * Centralized node for all effect metadata and relationships\n */\nexport interface EffectNode {\n\t// Graph relationships\n\tparent?: EffectTrigger\n\tchildren?: Set<EffectCleanup>\n\n\t// Lifecycle\n\tcleanup?: ScopedCallback\n\tstopped?: boolean\n\t/** The reason why the effect is (re-)executing */\n\tnextReason?: CleanupReason\n\t/** The reason for the current execution (only available during effect run) */\n\tcurrentReason?: CleanupReason\n\n\t// Error handling\n\tforwardThrow?: CatchFunction\n\tcatchers?: CatchFunction[]\n\n\t// Debug / Metadata\n\tcreationStack?: unknown\n\tdependencyHook?: (obj: any, prop: any) => void\n\n\t// Configuration\n\tisOpaque?: boolean\n\n\t// Pending triggers to be batched into CleanupReason\n\tpendingTriggers?: PropTrigger[]\n}\n\n/**\n * Type for the `runEffect` function of an effect - argument-less function to call to trigger the effect\n */\nexport type EffectTrigger = ScopedCallback\n\n/**\n * Async execution mode for effects\n * - `cancel`: Cancel previous async execution when dependencies change (default)\n * - `queue`: Queue next execution to run after current completes\n * - `ignore`: Ignore new executions while async work is running\n */\nexport type AsyncExecutionMode = 'cancel' | 'queue' | 'ignore'\n\n/**\n * Options for effect creation\n */\nexport interface EffectOptions {\n\t/**\n\t * How to handle async effect executions when dependencies change\n\t * @default 'cancel'\n\t */\n\tasyncMode?: AsyncExecutionMode\n\t/**\n\t * If true, this effect is \"opaque\" to deep optimizations: it sees the object reference itself\n\t * and must be notified when it changes, regardless of deep content similarity.\n\t * Use this for effects that depend on object identity (like memoize).\n\t */\n\topaque?: boolean\n\t/**\n\t * Used for debugging purpose. Provides a callback to be called every time a dependency is created.\n\t */\n\tdependencyHook?: (obj: any, prop: any) => void\n\t/**\n\t * Used for debugging purpose. Provides a name for the effect.\n\t */\n\tname?: string\n}\n\n/**\n * Type for property evolution events\n */\nexport type PropEvolution = {\n\ttype: 'set' | 'del' | 'add' | 'invalidate'\n\tprop: any\n}\n\n/**\n * Type for collection operation evolution events\n */\nexport type BunchEvolution = {\n\ttype: 'bunch'\n\tmethod: string\n}\nexport type Evolution = PropEvolution | BunchEvolution\n\nexport type State =\n\t| {\n\t\t\tevolution: Evolution\n\t\t\tnext: State\n\t }\n\t| {}\n\n// Track native reactivity\n\n/**\n * Symbol to mark class properties as non-reactive\n */\nexport const unreactiveProperties = Symbol('unreactive-properties')\n\n/**\n * Symbol representing all properties in reactive tracking\n */\nexport const allProps = Symbol('all-props')\n\n/**\n * Symbol for structure-only tracking (triggered on key add/delete, not value changes).\n * Used by ownKeys proxy trap — Object.keys(), for..in, Map.keys() depend on this.\n */\nexport const keysOf = Symbol('keys-of')\n\n/**\n * Symbol for accessing projection information on reactive objects\n */\nexport const projectionInfo = Symbol('projection-info')\n\nexport const forwardThrow = Symbol('throw')\n\nexport type EffectCloser = (reason?: CleanupReason) => void\nexport type CatchFunction = (error: unknown) => EffectCloser | undefined | void\n\n/**\n * Context for a running projection item effect\n */\nexport interface ProjectionContext {\n\tsource: any\n\tkey?: any\n\ttarget: any\n\tdepth: number\n\tparent?: ProjectionContext\n}\n\n/**\n * Structured error codes for machine-readable diagnosis\n */\nexport enum ReactiveErrorCode {\n\tCycleDetected = 'Cycle detected',\n\tMaxDepthExceeded = 'Max depth exceeded',\n\tMaxReactionExceeded = 'Max reaction exceeded',\n\tWriteInComputed = 'Write in computed',\n\tTrackingError = 'Tracking error',\n\tBrokenEffects = 'Broken effects',\n}\n\nexport type CycleDebugInfo = {\n\tcode: ReactiveErrorCode.CycleDetected\n\tcycle: string[]\n\tdetails?: string\n\tcausalChain?: string[]\n\tlineage?: unknown\n}\n\nexport type MaxDepthDebugInfo = {\n\tcode: ReactiveErrorCode.MaxDepthExceeded\n\teffectuatedRoots: any[]\n\tcycle: any[] | null\n\ttrace: string\n\tmaxEffectChain: number\n\tqueued: string[]\n\tqueuedCount: number\n\tcausalChain?: string[]\n\tlineage?: unknown\n}\n\nexport type MaxReactionDebugInfo = {\n\tcode: ReactiveErrorCode.MaxReactionExceeded\n\tcount: number\n\teffect: string\n\tcausalChain?: string[]\n\tlineage?: unknown\n}\n\nexport type GenericDebugInfo = {\n\tcode: ReactiveErrorCode\n\tcausalChain?: string[]\n\tlineage?: unknown\n\t[key: string]: any\n}\n\nexport type ReactiveDebugInfo =\n\t| CycleDebugInfo\n\t| MaxDepthDebugInfo\n\t| MaxReactionDebugInfo\n\t| GenericDebugInfo\n\n/**\n * Error class for reactive system errors\n */\nexport class ReactiveError extends Error {\n\tconstructor(\n\t\tmessage: string,\n\t\tpublic debugInfo?: ReactiveDebugInfo\n\t) {\n\t\tsuper(message)\n\t\tthis.name = 'ReactiveError'\n\t}\n\n\tget code(): ReactiveErrorCode | undefined {\n\t\treturn this.debugInfo?.code\n\t}\n\n\tget cause(): any {\n\t\treturn (this.debugInfo as any)?.cause\n\t}\n}\n\n// biome-ignore-start lint/correctness/noUnusedFunctionParameters: Interface declaration with empty defaults\n/**\n * Global options for the reactive system\n */\nexport const options = {\n\t/**\n\t * Debug purpose: called when an effect is entered\n\t * @param effect - The effect that is entered\n\t */\n\tenter: (_effect: Function) => {},\n\t/**\n\t * Debug purpose: called when an effect is left\n\t * @param effect - The effect that is left\n\t */\n\tleave: (_effect: Function) => {},\n\t/**\n\t * Debug purpose: called when an effect is chained\n\t * @param target - The effect that is being triggered\n\t * @param caller - The effect that is calling the target\n\t */\n\tchain: (_targets: Function[], _caller?: Function) => {},\n\t/**\n\t * Debug purpose: called when an effect chain is started\n\t * @param target - The effect that is being triggered\n\t */\n\tbeginChain: (_targets: Function[]) => {},\n\t/**\n\t * Debug purpose: called when an effect chain is ended\n\t */\n\tendChain: () => {},\n\tgarbageCollected: (_fn: Function) => {},\n\t/**\n\t * Debug purpose: called when an object is touched\n\t * @param obj - The object that is touched\n\t * @param evolution - The type of change\n\t * @param props - The properties that changed\n\t * @param deps - The dependencies that changed\n\t */\n\ttouched: (_obj: any, _evolution: Evolution, _props?: any[], _deps?: EffectTrigger[]) => {},\n\t/**\n\t * Debug purpose: called when an effect is skipped because it's already running\n\t * @param effect - The effect that is already running\n\t * @param runningChain - The array of effects from the detected one to the currently running one\n\t */\n\tskipRunningEffect: (_effect: EffectTrigger) => {},\n\t/**\n\t * Debug purpose: called when an effect starts executing.\n\t * @param effect - The effect being executed (root function)\n\t * @param reaction - false for initial creation, true/CleanupReason for subsequent runs\n\t */\n\teffectRun: (_effect: Function, _reaction: boolean | CleanupReason) => {},\n\t/**\n\t * Debug purpose: maximum effect chain (like call stack max depth)\n\t * Used to prevent infinite loops\n\t * @default 100\n\t */\n\tmaxEffectChain: 100,\n\t/**\n\t * Maximum number of times an effect can be triggered by the same cause in a single batch\n\t * Used to detect aggressive re-computation or infinite loops\n\t * @default 10\n\t */\n\tmaxTriggerPerBatch: 10,\n\t/**\n\t * Debug purpose: maximum effect reaction (like call stack max depth)\n\t * Used to prevent infinite loops\n\t * @default 'throw'\n\t */\n\tmaxEffectReaction: 'throw' as 'throw' | 'debug' | 'warn',\n\t/**\n\t * Callback called when a memoization discrepancy is detected (debug only)\n\t * When defined, memoized functions will run a second time (untracked) to verify consistency.\n\t * If the untracked run returns a different value than the cached one, this callback is triggered.\n\t *\n\t * This is the primary tool for detecting missing reactive dependencies in computed values.\n\t *\n\t * @param cached - The value currently in the memoization cache\n\t * @param fresh - The value obtained by re-running the function untracked\n\t * @param fn - The memoized function itself\n\t * @param args - Arguments passed to the function\n\t *\n\t * @example\n\t * ```typescript\n\t * reactiveOptions.onMemoizationDiscrepancy = (cached, fresh, fn, args) => {\n\t * throw new Error(`Memoization discrepancy in ${fn.name}!`);\n\t * };\n\t * ```\n\t */\n\tonMemoizationDiscrepancy: undefined as\n\t\t| ((\n\t\t\t\tcached: any,\n\t\t\t\tfresh: any,\n\t\t\t\tfn: Function,\n\t\t\t\targs: any[],\n\t\t\t\tcause: 'calculation' | 'comparison'\n\t\t ) => void)\n\t\t| undefined,\n\t/**\n\t * How to handle cycles detected in effect batches.\n\t *\n\t * - `'production'` (Default): High-performance mode. Disables dependency graph maintenance and\n\t * Topological Sorting in favor of a simple FIFO queue. Use this for trustworthy, acyclic UI code.\n\t * Cycle detection is heuristic (uses maxEffectChain execution counts).\n\t *\n\t * - `'development'`: Maintains direct dependency graph for early cycle detection during edge creation.\n\t * Catches cycles before effects execute via DFS check when adding edges. Throws immediately with\n\t * basic path information. Good balance of debugging help with moderate overhead.\n\t *\n\t * - `'debug'`: Full diagnostic mode with transitive closures and topological sorting.\n\t * Provides detailed cycle path reporting. Highest overhead but most informative for bug hunting.\n\t *\n\t * @default 'production'\n\t */\n\tcycleHandling: 'development' as 'production' | 'development' | 'debug',\n\t/**\n\t * Internal flag used by memoization discrepancy detector to avoid counting calls in tests\n\t * @warning Do not modify this flag manually, this flag is given by the engine\n\t */\n\tisVerificationRun: false,\n\t/**\n\t * Maximum depth for deep watching traversal\n\t * Used to prevent infinite recursion in circular references\n\t * @default 100\n\t */\n\tmaxDeepWatchDepth: 100,\n\t/**\n\t * Only react on instance members modification (not inherited properties)\n\t * For instance, do not track class methods\n\t * @default true\n\t */\n\tinstanceMembers: true,\n\t/**\n\t * Ignore accessors (getters and setters) and only track direct properties\n\t * @default true\n\t */\n\tignoreAccessors: true,\n\t/**\n\t * Enable recursive touching when objects with the same prototype are replaced\n\t * When enabled, replacing an object with another of the same prototype triggers\n\t * recursive diffing instead of notifying parent effects\n\t * @default true\n\t */\n\trecursiveTouching: true,\n\t/**\n\t * Default async execution mode for effects that return Promises\n\t * - 'cancel': Cancel previous async execution when dependencies change (default, enables async zone)\n\t * - 'queue': Queue next execution to run after current completes (enables async zone)\n\t * - 'ignore': Ignore new executions while async work is running (enables async zone)\n\t * - false: Disable async zone and async mode handling (effects run concurrently)\n\t *\n\t * **When truthy:** Enables async zone (Promise.prototype wrapping) for automatic context\n\t * preservation in Promise callbacks. Warning: This modifies Promise.prototype globally.\n\t * Only enable if no other library modifies Promise.prototype.\n\t *\n\t * **When false:** Async zone is disabled. Use `tracked()` manually in Promise callbacks.\n\t *\n\t * Can be overridden per-effect via EffectOptions\n\t * @default 'cancel'\n\t */\n\tasyncMode: 'cancel' as AsyncExecutionMode | false,\n\t// biome-ignore lint/suspicious/noConsole: This is the whole point here\n\twarn: (...args: any[]) => console.warn(...args),\n\t// biome-ignore lint/suspicious/noConsole: This is the whole point here\n\terror: (...args: any[]) => console.error(...args),\n\n\t/**\n\t * Introspection and debug aids. Set to `null` to disable all debug overhead in production.\n\t *\n\t * - `gatherReasons`: collect `PropTrigger[]` for `CleanupReason` on effect re-runs (default `true`)\n\t * - `lineages`: what lineages to capture in PropTrigger (default `'touch'`)\n\t * - `logErrors`: log errors with detailed context (default `true`)\n\t * - `enableHistory`: keep a history of mutations (default `true`)\n\t * - `historySize`: number of mutations to keep in history (default `50`)\n\t *\n\t * `enableDevTools()` sets `logErrors` to `true` automatically.\n\t *\n\t * @example\n\t * ```typescript\n\t * // Production: disable all introspection\n\t * reactiveOptions.introspection = null\n\t * ```\n\t */\n\tintrospection: {\n\t\tgatherReasons: { lineages: 'touch' },\n\t\tlogErrors: true,\n\t\tenableHistory: true,\n\t\thistorySize: 50,\n\t} as {\n\t\tgatherReasons: { lineages: 'none' | 'touch' | 'dependency' | 'both' }\n\t\tlogErrors: boolean\n\t\tenableHistory: boolean\n\t\thistorySize: number\n\t} | null,\n}\n// biome-ignore-end lint/correctness/noUnusedFunctionParameters: Interface declaration with empty defaults\n\ntype CallableOption = {\n\t[K in keyof typeof options]: (typeof options)[K] extends ((...args: any[]) => any) | undefined\n\t\t? K\n\t\t: never\n}[keyof typeof options]\n\nexport function optionCall<K extends CallableOption>(\n\tname: K,\n\t...args: NonNullable<(typeof options)[K]> extends (...a: infer A) => unknown ? A : never\n): void {\n\tconst fn = options[name]\n\tif (typeof fn !== 'function') return\n\ttry {\n\t\t;(fn as Function)(...args)\n\t} catch (error) {\n\t\toptions.warn(`options.${name} threw`, error)\n\t}\n}\n\n/** Production preset: no introspection, heuristic cycle detection, minimal overhead */\nexport const prodPreset: Partial<typeof options> = {\n\tmaxEffectReaction: 'throw',\n\tcycleHandling: 'production',\n\tintrospection: null,\n\tonMemoizationDiscrepancy: undefined,\n}\n\n/** Development preset (default): introspection on, early cycle detection, warnings */\nexport const devPreset: Partial<typeof options> = {\n\tmaxEffectReaction: 'warn',\n\tcycleHandling: 'development',\n\tintrospection: {\n\t\tgatherReasons: { lineages: 'touch' },\n\t\tlogErrors: true,\n\t\tenableHistory: true,\n\t\thistorySize: 50,\n\t},\n\tonMemoizationDiscrepancy: undefined,\n}\n\n/** Debug preset: full diagnostics, throws on violations, rich lineage capture */\nexport const debugPreset: Partial<typeof options> = {\n\tmaxEffectReaction: 'debug',\n\tcycleHandling: 'debug',\n\tintrospection: {\n\t\tgatherReasons: { lineages: 'both' },\n\t\tlogErrors: true,\n\t\tenableHistory: true,\n\t\thistorySize: 200,\n\t},\n}\n\n// --- Proxy State (Merged from proxy-state.ts) ---\n\nexport const objectToProxy = new WeakMap<object, object>()\nexport const proxyToObject = new WeakMap<object, object>()\n\nexport function storeProxyRelationship(target: object, proxy: object) {\n\tobjectToProxy.set(target, proxy)\n\tproxyToObject.set(proxy, target)\n}\n\nexport function getExistingProxy<T extends object>(target: T): T | undefined {\n\treturn objectToProxy.get(target) as T | undefined\n}\n\nexport function trackProxyObject(proxy: object, target: object) {\n\tproxyToObject.set(proxy, target)\n}\n\nexport function unwrap<T>(obj: T): T {\n\tif (!obj || typeof obj !== 'object') return obj\n\treturn (proxyToObject.get(obj as object) as T) || obj\n}\n\nexport function isReactive(obj: any): boolean {\n\treturn proxyToObject.has(obj)\n}\n","import { debugHooks } from './debug-hooks'\nimport { getActiveEffect } from './effect-context'\nimport { effectToReactiveObjects, getEffectNode, watchers } from './registry'\nimport { allProps, type EffectTrigger, keysOf, options, unwrap } from './types'\n\n// Track dependency stacks per (obj, prop, effect)\nlet dependencyStacks = new WeakMap<object, Map<any, Map<EffectTrigger, unknown>>>()\nlet assertUntrackedFlag = false\n\nexport function resetTracking() {\n\tdependencyStacks = new WeakMap()\n}\n\n/**\n * Executes a function and throws if any reactive dependencies are tracked during execution.\n * Used to assert that code runs in an untracked context.\n */\nexport function assertUntracked<T>(fn: () => T): T {\n\tif (assertUntrackedFlag) {\n\t\tthrow new Error('assertUntracked: nested calls are not supported')\n\t}\n\tassertUntrackedFlag = true\n\ttry {\n\t\treturn fn()\n\t} finally {\n\t\tassertUntrackedFlag = false\n\t}\n}\n\nfunction getDependencyStack(effect: EffectTrigger, obj: object, prop: any): unknown | undefined {\n\tconst objStacks = dependencyStacks.get(obj)\n\tif (!objStacks) return undefined\n\treturn objStacks.get(prop)?.get(effect) ?? objStacks.get(allProps)?.get(effect)\n}\n\nexport { getDependencyStack }\n\n/**\n * Marks a property as a dependency of the current effect\n * @param obj - The object containing the property\n * @param prop - The property name (defaults to allProps)\n */\nexport function dependant(obj: any, prop: any = allProps) {\n\tif (assertUntrackedFlag) {\n\t\tthrow new Error(\n\t\t\t`Reactive dependency tracking detected in assertUntracked context: ${String(prop)} on ${obj}`\n\t\t)\n\t}\n\tobj = unwrap(obj)\n\tconst currentActiveEffect = getActiveEffect()\n\n\t// Early return if no active effect, tracking disabled, or invalid prop\n\tif (!currentActiveEffect || (typeof prop === 'symbol' && prop !== allProps && prop !== keysOf))\n\t\treturn\n\n\tconst node = getEffectNode(currentActiveEffect)\n\tif ('dependencyHook' in node) {\n\t\tnode.dependencyHook?.(obj, prop)\n\t}\n\tlet objectWatchers = watchers.get(obj)\n\tif (!objectWatchers) {\n\t\tobjectWatchers = new Map<PropertyKey, Set<EffectTrigger>>()\n\t\twatchers.set(obj, objectWatchers)\n\t}\n\tlet deps = objectWatchers.get(prop)\n\tif (!deps) {\n\t\tdeps = new Set<EffectTrigger>()\n\t\tobjectWatchers.set(prop, deps)\n\t}\n\tdeps.add(currentActiveEffect)\n\n\t// Track which reactive objects this effect is watching\n\tconst effectObjects = effectToReactiveObjects.get(currentActiveEffect)\n\tif (effectObjects) {\n\t\teffectObjects.add(obj)\n\t} else {\n\t\teffectToReactiveObjects.set(currentActiveEffect, new Set([obj]))\n\t}\n\n\t// Store dependency stack if introspection is enabled\n\tconst gatherReasons = options.introspection?.gatherReasons\n\tif (gatherReasons) {\n\t\tconst lineageConfig = gatherReasons.lineages\n\t\tif (lineageConfig === 'dependency' || lineageConfig === 'both') {\n\t\t\tlet objStacks = dependencyStacks.get(obj)\n\t\t\tif (!objStacks) {\n\t\t\t\tobjStacks = new Map()\n\t\t\t\tdependencyStacks.set(obj, objStacks)\n\t\t\t}\n\t\t\tlet propStacks = objStacks.get(prop)\n\t\t\tif (!propStacks) {\n\t\t\t\tpropStacks = new Map()\n\t\t\t\tobjStacks.set(prop, propStacks)\n\t\t\t}\n\t\t\tpropStacks.set(currentActiveEffect, debugHooks.captureLineage())\n\t\t}\n\t}\n}\n","import { decorator } from '../decorator'\nimport { type Captioned, captioned, flavored, flavorOptions } from '../flavored'\nimport { IterableWeakSet } from '../iterableWeak'\nimport { named } from '../utils'\nimport type { HistoryValue } from '../zone'\nimport { debugHooks } from './debug-hooks'\nimport {\n\tchainExternalReason,\n\teffectAggregator,\n\teffectHistory,\n\texternalReason,\n\tgetActiveEffect,\n} from './effect-context'\nimport {\n\teffectToReactiveObjects,\n\tgetEffectNode,\n\tgetRoot,\n\tmarkWithRoot,\n\tresetRegistry,\n\twatchers,\n} from './registry'\nimport { resetTracking } from './tracking'\nimport {\n\ttype CatchFunction,\n\ttype CleanupReason,\n\ttype EffectAccess,\n\ttype EffectCleanup,\n\ttype EffectCloser,\n\ttype EffectOptions,\n\ttype EffectTrigger,\n\ttype Evolution,\n\teffectMarker,\n\toptionCall,\n\toptions,\n\t// type AsyncExecutionMode,\n\ttype PropTrigger,\n\tReactiveError,\n\tReactiveErrorCode,\n\ttype ScopedCallback,\n\tunwrap,\n} from './types'\n\n/**\n * Finds a cycle in a sequence of functions by looking for the first repetition\n */\nfunction findCycleInChain(roots: Function[]): Function[] | null {\n\tconst seen = new Map<Function, number>()\n\tfor (let i = 0; i < roots.length; i++) {\n\t\tconst root = roots[i]\n\t\tif (seen.has(root)) {\n\t\t\treturn roots.slice(seen.get(root)!)\n\t\t}\n\t\tseen.set(root, i)\n\t}\n\treturn null\n}\n\n/**\n * Formats a list of function roots into a readable trace\n */\nfunction formatRoots(roots: Function[], limit = 20): string {\n\tconst names = roots.map((r) => r.name || '<anonymous>')\n\tif (names.length <= limit) return names.join(' → ')\n\tconst start = names.slice(0, 5)\n\tconst end = names.slice(-10)\n\treturn `${start.join(' → ')} ... (${names.length - 15} more) ... ${end.join(' → ')}`\n}\n\nfunction externalReasonFrom(fn: Function): CleanupReason | undefined {\n\treturn fn.name ? { type: 'external', detail: fn.name } : undefined\n}\n\nexport interface ActivationRecord {\n\teffect: EffectTrigger\n\tobj: any\n\tevolution: Evolution\n\tprop: any\n\tbatchId: number\n}\n\n// Nested map structure for efficient counting and batch cleanup\n// batchId -> effect root -> obj -> prop -> count\nlet activationRegistry: Map<Function, Map<any, Map<any, number>>> | undefined\n\nexport const activationLog: Omit<ActivationRecord, 'batchId'>[] = new Array(100)\n\n/**\n * Returns the activation log containing recent effect activations for debugging.\n * The log is a circular buffer of the last 100 activations.\n *\n * @returns Array of activation records\n */\nexport function getActivationLog() {\n\treturn activationLog\n}\n\nexport function recordActivation(effect: EffectTrigger, obj: any, evolution: Evolution, prop: any) {\n\tconst root = getRoot(effect)\n\n\tif (!activationRegistry) return\n\tlet effectData = activationRegistry.get(root)\n\tif (!effectData) {\n\t\teffectData = new Map()\n\t\tactivationRegistry.set(root, effectData)\n\t}\n\tlet objData = effectData.get(obj)\n\tif (!objData) {\n\t\tobjData = new Map()\n\t\teffectData.set(obj, objData)\n\t}\n\tconst count = (objData.get(prop) ?? 0) + 1\n\tobjData.set(prop, count)\n\n\t// Keep a limited history for diagnostics\n\tactivationLog.unshift({\n\t\teffect,\n\t\tobj,\n\t\tevolution,\n\t\tprop,\n\t})\n\tactivationLog.pop()\n\n\tif (count >= options.maxTriggerPerBatch) {\n\t\tconst effectName = root.name\n\t\tconst message = `Aggressive trigger detected: effect \"${effectName}\" triggered ${count} times in the batch by the same cause.`\n\t\tif (options.maxEffectReaction === 'throw') {\n\t\t\tthrow new ReactiveError(message, {\n\t\t\t\tcode: ReactiveErrorCode.MaxReactionExceeded,\n\t\t\t\tcount,\n\t\t\t\teffect: root,\n\t\t\t})\n\t\t}\n\t\toptions.warn(`[reactive] ${message}`)\n\t}\n}\n\nexport function caught(onThrow: CatchFunction, effect?: EffectTrigger) {\n\teffect ??= getActiveEffect()\n\tif (!effect) throw new Error('Tracking an effect throw while not in an effect')\n\tconst node = getEffectNode(effect)\n\tif (!node.catchers) node.catchers = [onThrow]\n\telse node.catchers.push(onThrow)\n}\n/** @deprecated Use `caught` instead */\nexport const onEffectThrow = caught\n\n// Dependency graph: tracks which effects trigger which other effects\n// Uses roots (Function) as keys for consistency\nlet effectTriggers = new WeakMap<Function, IterableWeakSet<Function>>()\nlet effectTriggeredBy = new WeakMap<Function, IterableWeakSet<Function>>()\n\n// Transitive closures: track all indirect relationships\n// causesClosure: for each effect, all effects that trigger it (directly or indirectly)\n// consequencesClosure: for each effect, all effects that it triggers (directly or indirectly)\nlet causesClosure = new WeakMap<Function, IterableWeakSet<Function>>()\nlet consequencesClosure = new WeakMap<Function, IterableWeakSet<Function>>()\n\n// Batch re-entrance depth and broken state\nlet broken = false\n\n// Debug: Capture where an effect was created\nexport const effectCreationStacks = new WeakMap<Function, unknown[]>()\n\n/**\n * Gets or creates an IterableWeakSet for a closure map\n */\nfunction getOrCreateClosure(\n\tclosure: WeakMap<Function, IterableWeakSet<Function>>,\n\troot: Function\n): IterableWeakSet<Function> {\n\tlet set = closure.get(root)\n\tif (!set) {\n\t\tset = new IterableWeakSet()\n\t\tclosure.set(root, set)\n\t}\n\treturn set\n}\n\n/**\n * Adds an edge to the dependency graph: callerRoot → targetRoot\n * Also maintains transitive closures\n * @param callerRoot - Root function of the effect that triggers\n * @param targetRoot - Root function of the effect being triggered\n */\nfunction addGraphEdge(callerRoot: Function, targetRoot: Function) {\n\tif (options.cycleHandling === 'production') return\n\t// Add to forward graph: callerRoot → targetRoot\n\tconst triggers = effectTriggers.get(callerRoot)\n\n\tif (!triggers) {\n\t\tconst newTriggers = new IterableWeakSet<Function>()\n\t\tnewTriggers.add(targetRoot)\n\t\teffectTriggers.set(callerRoot, newTriggers)\n\t} else {\n\t\ttriggers.add(targetRoot)\n\t}\n\n\t// Add to reverse graph: targetRoot ← callerRoot\n\tlet triggeredBy = effectTriggeredBy.get(targetRoot)\n\tif (!triggeredBy) {\n\t\ttriggeredBy = new IterableWeakSet()\n\t\teffectTriggeredBy.set(targetRoot, triggeredBy)\n\t}\n\ttriggeredBy.add(callerRoot)\n\n\t// Update transitive closures\n\t// When U→V is added, we need to propagate the relationship:\n\t// 1. Add U to causesClosure(V) and V to consequencesClosure(U) (direct relationship)\n\t// 2. For each X in causesClosure(U): add V to consequencesClosure(X) and X to causesClosure(V)\n\t// 3. For each Y in consequencesClosure(V): add U to causesClosure(Y) and Y to consequencesClosure(U)\n\t// Note: Self-loops (U→U) are not added to closures - if an effect appears in its own closure,\n\t// it means there's an indirect cycle that should be detected\n\n\t// Self-loops are explicitly ignored - an effect reading and writing the same property\n\t// (e.g., obj.prop++) should not create a dependency relationship or appear in closures\n\tif (callerRoot === targetRoot) {\n\t\treturn\n\t}\n\n\tconst uConsequences = getOrCreateClosure(consequencesClosure, callerRoot)\n\tconst vCauses = getOrCreateClosure(causesClosure, targetRoot)\n\n\t// 1. Add direct relationship\n\tuConsequences.add(targetRoot)\n\tvCauses.add(callerRoot)\n\n\t// 2. For each X in causesClosure(U): X→U→V means X→V\n\tconst uCausesSet = causesClosure.get(callerRoot)\n\tif (uCausesSet) {\n\t\tfor (const x of uCausesSet) {\n\t\t\t// Skip if this would create a self-loop\n\t\t\tif (x === targetRoot) continue\n\t\t\tconst xConsequences = getOrCreateClosure(consequencesClosure, x)\n\t\t\txConsequences.add(targetRoot)\n\t\t\tvCauses.add(x)\n\t\t}\n\t}\n\n\t// 3. For each Y in consequencesClosure(V): U→V→Y means U→Y\n\tconst vConsequencesSet = consequencesClosure.get(targetRoot)\n\tif (vConsequencesSet) {\n\t\tfor (const y of vConsequencesSet) {\n\t\t\t// Skip if this would create a self-loop\n\t\t\tif (y === callerRoot) continue\n\t\t\tconst yCauses = getOrCreateClosure(causesClosure, y)\n\t\t\tyCauses.add(callerRoot)\n\t\t\tuConsequences.add(y)\n\t\t}\n\t}\n\n\t// 4. Cross-product: for each X in causesClosure(U) and Y in consequencesClosure(V): X→Y\n\tif (uCausesSet?.size && vConsequencesSet?.size) {\n\t\tfor (const x of uCausesSet) {\n\t\t\tconst xConsequences = getOrCreateClosure(consequencesClosure, x)\n\t\t\tfor (const y of vConsequencesSet) {\n\t\t\t\t// Skip if this would create a self-loop\n\t\t\t\tif (x === y) continue\n\t\t\t\txConsequences.add(y)\n\t\t\t\tconst yCauses = getOrCreateClosure(causesClosure, y)\n\t\t\t\tyCauses.add(x)\n\t\t\t}\n\t\t}\n\t}\n}\n\n/**\n * Checks if there's a path from start to end in the dependency graph, excluding a specific node\n * Uses BFS to find any path that doesn't go through the excluded node\n * @param start - Starting node\n * @param end - Target node\n * @param exclude - Node to exclude from the path\n * @returns true if a path exists without going through the excluded node\n */\nfunction hasPathExcluding(start: Function, end: Function, exclude: Function): boolean {\n\tif (start === end) return true\n\tif (start === exclude) return false\n\n\tconst visited = new Set<Function>()\n\tconst queue: Function[] = [start]\n\tvisited.add(start)\n\tvisited.add(exclude) // Pre-mark excluded node as visited to skip it\n\n\twhile (queue.length > 0) {\n\t\tconst current = queue.shift()!\n\t\tconst triggers = effectTriggers.get(current)\n\t\tif (!triggers) continue\n\n\t\tfor (const next of triggers) {\n\t\t\tif (next === end) return true\n\t\t\tif (!visited.has(next)) {\n\t\t\t\tvisited.add(next)\n\t\t\t\tqueue.push(next)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn false\n}\n\n/**\n * Removes all edges involving the given effect from the dependency graph\n * Also cleans up transitive closures by propagating cleanup to all affected effects\n * Called when an effect is stopped/cleaned up\n * @param effect - The effect being cleaned up\n */\nfunction cleanupEffectFromGraph(effect: EffectTrigger) {\n\tif (options.cycleHandling === 'production') return\n\tconst root = getRoot(effect)\n\n\t// Get closures before removing direct edges (needed for propagation)\n\tconst rootCauses = causesClosure.get(root)\n\tconst rootConsequences = consequencesClosure.get(root)\n\n\t// Remove from effectTriggers (outgoing edges)\n\tconst triggers = effectTriggers.get(root)\n\tif (triggers) {\n\t\t// Remove this root from all targets' effectTriggeredBy sets\n\t\tfor (const targetRoot of triggers) {\n\t\t\tconst triggeredBy = effectTriggeredBy.get(targetRoot)\n\t\t\ttriggeredBy?.delete(root)\n\t\t}\n\t\teffectTriggers.delete(root)\n\t}\n\n\t// Remove from effectTriggeredBy (incoming edges)\n\tconst triggeredBy = effectTriggeredBy.get(root)\n\tif (triggeredBy) {\n\t\t// Remove this root from all sources' effectTriggers sets\n\t\tfor (const sourceRoot of triggeredBy) {\n\t\t\tconst triggers = effectTriggers.get(sourceRoot)\n\t\t\ttriggers?.delete(root)\n\t\t}\n\t\teffectTriggeredBy.delete(root)\n\t}\n\n\t// Propagate closure cleanup to all affected effects\n\t// When removing B from A → B → C:\n\t// - Remove B from causesClosure(C) and consequencesClosure(A)\n\t// - For each X in causesClosure(B): remove C from consequencesClosure(X) if B was the only path\n\t// - For each Y in consequencesClosure(B): remove A from causesClosure(Y) if B was the only path\n\t// - Remove transitive relationships that depended on B\n\n\tif (rootCauses) {\n\t\t// For each X that triggers root: remove root from X's consequences\n\t\t// Only remove root's consequences if no alternate path exists\n\t\tfor (const causeRoot of rootCauses) {\n\t\t\tconst causeConsequences = consequencesClosure.get(causeRoot)\n\t\t\tif (causeConsequences) {\n\t\t\t\t// Remove root itself (it's being cleaned up)\n\t\t\t\tcauseConsequences.delete(root)\n\t\t\t\t// Only remove consequences of root if there's no alternate path from causeRoot to them\n\t\t\t\tif (rootConsequences) {\n\t\t\t\t\tfor (const consequence of rootConsequences) {\n\t\t\t\t\t\t// Check if causeRoot can still reach consequence without going through root\n\t\t\t\t\t\tif (!hasPathExcluding(causeRoot, consequence, root)) {\n\t\t\t\t\t\t\tcauseConsequences.delete(consequence)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif (rootConsequences) {\n\t\t// For each Y that root triggers: remove root from Y's causes\n\t\t// Only remove root's causes if no alternate path exists\n\t\tfor (const consequenceRoot of rootConsequences) {\n\t\t\tconst consequenceCauses = causesClosure.get(consequenceRoot)\n\t\t\tif (consequenceCauses) {\n\t\t\t\t// Remove root itself (it's being cleaned up)\n\t\t\t\tconsequenceCauses.delete(root)\n\t\t\t\t// Only remove causes of root if there's no alternate path from them to consequenceRoot\n\t\t\t\tif (rootCauses) {\n\t\t\t\t\tfor (const cause of rootCauses) {\n\t\t\t\t\t\t// Check if cause can still reach consequenceRoot without going through root\n\t\t\t\t\t\tif (!hasPathExcluding(cause, consequenceRoot, root)) {\n\t\t\t\t\t\t\tconsequenceCauses.delete(cause)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Cross-product cleanup: for each X in causesClosure(B) and Y in consequencesClosure(B),\n\t// remove X→Y if B was the only path connecting them\n\tif (rootCauses && rootConsequences) {\n\t\tfor (const x of rootCauses) {\n\t\t\tconst xConsequences = consequencesClosure.get(x)\n\t\t\tif (xConsequences) {\n\t\t\t\tfor (const y of rootConsequences) {\n\t\t\t\t\t// Check if there's still a path from X to Y without going through root\n\t\t\t\t\t// Use BFS to find any path that doesn't include root\n\t\t\t\t\tif (!hasPathExcluding(x, y, root)) {\n\t\t\t\t\t\txConsequences.delete(y)\n\t\t\t\t\t\tconst yCauses = causesClosure.get(y)\n\t\t\t\t\t\tyCauses?.delete(x)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Finally, delete the closures for this effect\n\tcausesClosure.delete(root)\n\tconsequencesClosure.delete(root)\n}\n\n// Batch queue structure - optimized with cached in-degrees\ninterface BatchQueue {\n\t// All effects in the current batch that still need to be executed (todos)\n\tall: Map<Function, EffectTrigger> // root → effect\n\t// Cached in-degrees for each effect in the batch (number of causes in batch)\n\tinDegrees: Map<Function, number> // root → in-degree count\n\t// Deferred callbacks to run after this batch completes (populated by defer())\n\tdeferreds: Set<ScopedCallback>\n}\n\n// Track currently executing effects to prevent re-execution\n// These are all the effects triggered under `activeEffect`\n// Batch stack - handles nested batches by giving each its own queue\nconst batchStack: BatchQueue[] = []\nexport function hasBatched(effect: EffectTrigger) {\n\tconst root = getRoot(effect)\n\treturn batchStack.some((bs) => bs.all.has(root))\n}\n// DEV: stack of currently-executing effects (push on enter, pop on leave)\nconst executingStack: EffectTrigger[] = []\nexport function getExecutingStack(): readonly EffectTrigger[] {\n\treturn executingStack\n}\n\n/**\n * Computes and caches in-degrees for all effects in the batch\n * Called once when batch starts or when new effects are added\n */\nfunction computeAllInDegrees(batch: BatchQueue): void {\n\tif (options.cycleHandling === 'production') return\n\tconst activeEffect = getActiveEffect()\n\tconst activeRoot = activeEffect ? getRoot(activeEffect) : null\n\n\t// Reset all in-degrees\n\tbatch.inDegrees.clear()\n\n\tfor (const [root] of batch.all) {\n\t\tlet inDegree = 0\n\t\tconst causes = causesClosure.get(root)\n\t\tif (causes) {\n\t\t\tfor (const causeRoot of causes) {\n\t\t\t\t// Only count if it's in the batch and not the active/self effect\n\t\t\t\tif (batch.all.has(causeRoot) && causeRoot !== activeRoot && causeRoot !== root) {\n\t\t\t\t\tinDegree++\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tbatch.inDegrees.set(root, inDegree)\n\t}\n}\n\n/**\n * Decrements in-degrees of all effects that depend on the executed effect\n * Called after an effect is executed to update the cached in-degrees\n */\nfunction decrementInDegreesForExecuted(batch: BatchQueue, executedRoot: Function): void {\n\t// Get all effects that this executed effect triggers\n\tconst consequences = consequencesClosure.get(executedRoot)\n\tif (!consequences) return\n\n\tfor (const consequenceRoot of consequences) {\n\t\t// Only update if it's still in the batch\n\t\tif (batch.all.has(consequenceRoot)) {\n\t\t\tconst currentDegree = batch.inDegrees.get(consequenceRoot) ?? 0\n\t\t\tif (currentDegree > 0) {\n\t\t\t\tbatch.inDegrees.set(consequenceRoot, currentDegree - 1)\n\t\t\t}\n\t\t}\n\t}\n}\n\n/**\n * Finds a path from startRoot to endRoot in the dependency graph\n * Uses DFS to find the path through direct edges\n * @param startRoot - Starting effect root\n * @param endRoot - Target effect root\n * @param visited - Set of visited nodes (for recursion)\n * @param path - Current path being explored\n * @returns Path from startRoot to endRoot, or empty array if no path exists\n */\nfunction findPath(\n\tstartRoot: Function,\n\tendRoot: Function,\n\tvisited: Set<Function> = new Set(),\n\tpath: Function[] = []\n): Function[] {\n\tif (startRoot === endRoot) {\n\t\treturn [...path, endRoot]\n\t}\n\n\tif (visited.has(startRoot)) {\n\t\treturn []\n\t}\n\n\tvisited.add(startRoot)\n\tconst newPath = [...path, startRoot]\n\n\tconst triggers = effectTriggers.get(startRoot)\n\tif (triggers) {\n\t\tfor (const targetRoot of triggers) {\n\t\t\tconst result = findPath(targetRoot, endRoot, visited, newPath)\n\t\t\tif (result.length > 0) {\n\t\t\t\treturn result\n\t\t\t}\n\t\t}\n\t}\n\n\treturn []\n}\n\n/**\n * Gets the cycle path when adding an edge would create a cycle\n * @param callerRoot - Root of the effect that triggers\n * @param targetRoot - Root of the effect being triggered\n * @returns Array of effect roots forming the cycle, or empty array if no cycle\n */\nfunction getCyclePathForEdge(callerRoot: Function, targetRoot: Function): Function[] {\n\t// Find path from targetRoot back to callerRoot (this is the existing path)\n\t// Then adding callerRoot -> targetRoot completes the cycle\n\tconst path = findPath(targetRoot, callerRoot)\n\tif (path.length > 0) {\n\t\t// The cycle is: callerRoot -> targetRoot -> ... -> callerRoot\n\t\treturn [callerRoot, ...path]\n\t}\n\treturn []\n}\n\n/**\n * Checks if adding an edge would create a cycle\n * Uses causesClosure to check if callerRoot is already a cause of targetRoot\n * Self-loops (callerRoot === targetRoot) are explicitly ignored and return false\n *\n * **Note**: This is the primary optimization benefit of the transitive closure system.\n * It allows detecting cycles in O(1) time before they are executed.\n *\n * @param callerRoot - Root of the effect that triggers\n * @param targetRoot - Root of the effect being triggered\n * @returns true if adding this edge would create a cycle\n */\nfunction wouldCreateCycle(callerRoot: Function, targetRoot: Function): boolean {\n\t// Self-loops are explicitly ignored - an effect reading and writing the same property\n\t// (e.g., obj.prop++) should not create a dependency relationship\n\tif (callerRoot === targetRoot) {\n\t\treturn false\n\t}\n\n\t// Check if targetRoot already triggers callerRoot (directly or indirectly)\n\t// This would create a cycle: callerRoot -> targetRoot -> ... -> callerRoot\n\t// Using consequencesClosure: if targetRoot triggers callerRoot, then callerRoot is in consequencesClosure(targetRoot)\n\tconst targetConsequences = consequencesClosure.get(targetRoot)\n\tif (targetConsequences?.has(callerRoot)) {\n\t\treturn true // Cycle detected: targetRoot -> ... -> callerRoot, and we're adding callerRoot -> targetRoot\n\t}\n\n\treturn false\n}\n\n/**\n * Adds an effect to the batch queue\n * @param effect - The effect to add\n * @param caller - The active effect that triggered this one (optional)\n * @param immediate - If true, don't create edges in the dependency graph\n */\nfunction addToBatch(\n\teffect: EffectTrigger,\n\tcaller?: EffectTrigger,\n\timmediate?: boolean,\n\treason?: CleanupReason\n) {\n\tconst node = getEffectNode(effect)\n\tconst currentBatch = batchStack[batchStack.length - 1]\n\n\tif (!currentBatch) {\n\t\treturn\n\t}\n\n\tconst root = getRoot(effect)\n\n\t// Build reason from pending triggers if not provided\n\tif (!reason && node.pendingTriggers) {\n\t\treason = { type: 'propChange', triggers: node.pendingTriggers }\n\t\t// Add chain: if this is being triggered from another effect, get its reason\n\t\tif (caller) {\n\t\t\tconst callerNode = getEffectNode(caller)\n\t\t\tif (callerNode.currentReason) {\n\t\t\t\treason.chain = callerNode.currentReason\n\t\t\t}\n\t\t}\n\t\treason = chainExternalReason(reason)\n\t}\n\tnode.pendingTriggers = undefined\n\n\tif (reason) {\n\t\tconst existing = node.nextReason\n\t\tif (!existing) {\n\t\t\tnode.nextReason = reason\n\t\t} else {\n\t\t\tconst mergePropChange = (\n\t\t\t\tinto: CleanupReason,\n\t\t\t\tfrom: { type: 'propChange'; triggers: PropTrigger[] }\n\t\t\t): boolean => {\n\t\t\t\tif (into.type === 'propChange') {\n\t\t\t\t\tinto.triggers.push(...from.triggers)\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t\tif (into.type === 'multiple') {\n\t\t\t\t\tconst target = into.reasons.find((r) => r.type === 'propChange') as\n\t\t\t\t\t\t| { type: 'propChange'; triggers: PropTrigger[] }\n\t\t\t\t\t\t| undefined\n\t\t\t\t\tif (target) {\n\t\t\t\t\t\ttarget.triggers.push(...from.triggers)\n\t\t\t\t\t\treturn true\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\tif (reason.type === 'propChange') {\n\t\t\t\tif (!mergePropChange(existing, reason)) {\n\t\t\t\t\tif (existing.type === 'multiple') {\n\t\t\t\t\t\texisting.reasons.push(reason)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tnode.nextReason = { type: 'multiple', reasons: [existing, reason] }\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else if (existing.type === 'multiple') {\n\t\t\t\texisting.reasons.push(reason)\n\t\t\t} else {\n\t\t\t\tnode.nextReason = { type: 'multiple', reasons: [existing, reason] }\n\t\t\t}\n\t\t}\n\t}\n\n\t// 1. Add to batch first (needed for cycle detection)\n\t// TODO: Check if it's the correct way to do (these different behavior in function of dev/production)\n\tif (options.cycleHandling === 'production') {\n\t\t// Production mode: FIFO (delete and re-add to move to end)\n\t\tif (currentBatch.all.has(root)) {\n\t\t\tcurrentBatch.all.delete(root)\n\t\t}\n\t} else {\n\t\t// Dev mode: skip if already queued — the existing entry will re-run\n\t\tif (currentBatch.all.has(root)) {\n\t\t\treturn\n\t\t}\n\t}\n\n\t// If the effect was stopped during cleanup (e.g. lazy memoization), don't add it to the batch\n\tif (node.stopped) return\n\n\tcurrentBatch.all.set(root, effect)\n\n\tif (caller && !immediate && options.cycleHandling !== 'production') {\n\t\tconst callerRoot = getRoot(caller)\n\t\t// const root = getRoot(effect) // Already have root\n\n\t\t// Check for cycle BEFORE adding edge\n\t\tif (wouldCreateCycle(callerRoot, root)) {\n\t\t\tconst cyclePath = getCyclePathForEdge(callerRoot, root)\n\t\t\tconst cycleMessage =\n\t\t\t\tcyclePath.length > 0\n\t\t\t\t\t? `Cycle detected: ${cyclePath.map((r) => r.name || r.toString()).join(' → ')}`\n\t\t\t\t\t: `Cycle detected: ${callerRoot.name || callerRoot.toString()} → ${root.name || root.toString()} (and back)`\n\n\t\t\tcurrentBatch.all.delete(root)\n\t\t\tconst causalChain = debugHooks.getTriggerChain(effect)\n\t\t\tconst lineage = getEffectNode(effect).creationStack\n\n\t\t\tthrow new ReactiveError(`[reactive] ${cycleMessage}`, {\n\t\t\t\tcode: ReactiveErrorCode.CycleDetected,\n\t\t\t\tcycle: cyclePath.map((r) => r.name || r.toString()),\n\t\t\t\tdetails: cycleMessage,\n\t\t\t\tcausalChain,\n\t\t\t\tlineage,\n\t\t\t})\n\t\t}\n\n\t\taddGraphEdge(callerRoot, root)\n\t}\n}\n\n/**\n * Adds a cleanup function to be called when the current batch of effects completes\n * @param cleanup - The cleanup function to add\n */\nexport function addBatchCleanup(cleanup: EffectCleanup) {\n\tconst currentBatch = batchStack[batchStack.length - 1]\n\tif (!currentBatch) cleanup()\n\telse currentBatch.deferreds.add(cleanup)\n}\n\n/**\n * Semantic alias for `addBatchCleanup` - defers work to the end of the current reactive batch.\n *\n * Use this when an effect needs to perform an action that would modify state the effect depends on,\n * which would create a reactive cycle. The deferred callback runs after all effects complete.\n *\n * @param callback - The callback to defer until after the current batch completes\n *\n * @example\n * ```typescript\n * effect(() => {\n * processData()\n *\n * // Defer to avoid cycle (createMovement modifies state this effect reads)\n * defer(() => {\n * createMovement(data)\n * })\n * })\n * ```\n */\nexport const defer = addBatchCleanup\n\n/**\n * Gets a cycle path for debugging\n * Uses DFS to find cycles in the batch\n * @param batch - The batch queue\n * @returns Array of effect roots forming a cycle\n */\nfunction getCyclePath(batch: BatchQueue): Function[] {\n\t// If all effects have in-degree > 0, there must be a cycle\n\t// Use DFS to find it\n\tconst visited = new Set<Function>()\n\tconst recursionStack = new Set<Function>()\n\tconst path: Function[] = []\n\n\tfor (const [root] of batch.all) {\n\t\tif (visited.has(root)) continue\n\t\tconst cycle = findCycle(root, visited, recursionStack, path, batch)\n\t\tif (cycle.length > 0) {\n\t\t\treturn cycle\n\t\t}\n\t}\n\n\treturn []\n}\n\nfunction findCycle(\n\troot: Function,\n\tvisited: Set<Function>,\n\trecursionStack: Set<Function>,\n\tpath: Function[],\n\tbatch: BatchQueue\n): Function[] {\n\tif (recursionStack.has(root)) {\n\t\t// Found a cycle! Return the path from the cycle start to root\n\t\tconst cycleStart = path.indexOf(root)\n\t\treturn path.slice(cycleStart).concat([root])\n\t}\n\n\tif (visited.has(root)) {\n\t\treturn []\n\t}\n\n\tvisited.add(root)\n\trecursionStack.add(root)\n\tpath.push(root)\n\n\t// Follow edges to effects in the batch\n\t// Use direct edges (effectTriggers) for cycle detection\n\tconst triggers = effectTriggers.get(root)\n\tif (triggers) {\n\t\tfor (const targetRoot of triggers) {\n\t\t\tif (batch.all.has(targetRoot)) {\n\t\t\t\tconst cycle = findCycle(targetRoot, visited, recursionStack, path, batch)\n\t\t\t\tif (cycle.length > 0) {\n\t\t\t\t\treturn cycle\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tpath.pop()\n\trecursionStack.delete(root)\n\treturn []\n}\n\n/**\n * Executes the next effect in dependency order (using cached in-degrees)\n * Finds an effect with in-degree 0 and executes it\n * @returns The return value of the executed effect, or null if batch is complete\n */\nfunction executeNext(effectuatedRoots: Function[]): any {\n\tconst currentBatch = batchStack[batchStack.length - 1]\n\tif (!currentBatch) return null\n\n\t// Find an effect with in-degree 0 using cached values\n\tlet nextEffect: EffectTrigger | null = null\n\tlet nextRoot: Function | null = null\n\n\tif (options.cycleHandling === 'production') {\n\t\t// In flat mode, we just take the first effect in the queue (FIFO)\n\t\tconst first = currentBatch.all.entries().next().value\n\t\tif (first) {\n\t\t\t;[nextRoot, nextEffect] = first\n\t\t}\n\t} else {\n\t\t// Find an effect with in-degree 0 (no dependencies in batch that still need execution)\n\t\t// Using cached in-degrees for O(n) lookup instead of O(n²)\n\t\tfor (const [root, effect] of currentBatch.all) {\n\t\t\tconst inDegree = currentBatch.inDegrees.get(root) ?? 0\n\t\t\tif (inDegree === 0) {\n\t\t\t\tnextEffect = effect\n\t\t\t\tnextRoot = root\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tif (!nextEffect) {\n\t\t// No effect with in-degree 0 - there must be a cycle\n\t\t// If all effects have dependencies, it means there's a circular dependency\n\t\tif (currentBatch.all.size > 0) {\n\t\t\tlet cycle = getCyclePath(currentBatch)\n\t\t\t// If we couldn't find a cycle path using direct edges, try using closures\n\t\t\t// (transitive relationships) - if all effects have in-degree > 0, there must be a cycle\n\t\t\tif (cycle.length === 0) {\n\t\t\t\t// Try to find a cycle using consequencesClosure (transitive relationships)\n\t\t\t\t// Note: Self-loops are ignored - we only look for cycles between different effects\n\t\t\t\tfor (const [root] of currentBatch.all) {\n\t\t\t\t\tconst consequences = consequencesClosure.get(root)\n\t\t\t\t\tif (consequences) {\n\t\t\t\t\t\t// Check if any consequence in the batch also has root as a consequence\n\t\t\t\t\t\tfor (const consequence of consequences) {\n\t\t\t\t\t\t\t// Skip self-loops - they are ignored\n\t\t\t\t\t\t\tif (consequence === root) continue\n\t\t\t\t\t\t\tif (currentBatch.all.has(consequence)) {\n\t\t\t\t\t\t\t\tconst consequenceConsequences = consequencesClosure.get(consequence)\n\t\t\t\t\t\t\t\tif (consequenceConsequences?.has(root)) {\n\t\t\t\t\t\t\t\t\t// Found cycle: root -> consequence -> root\n\t\t\t\t\t\t\t\t\tcycle = [root, consequence, root]\n\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (cycle.length > 0) break\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst cycleMessage =\n\t\t\t\tcycle.length > 0\n\t\t\t\t\t? `Cycle detected: ${cycle.map((r) => r.name || '<anonymous>').join(' → ')}`\n\t\t\t\t\t: 'Cycle detected in effect batch - all effects have dependencies that prevent execution'\n\n\t\t\tthrow new ReactiveError(`[reactive] ${cycleMessage}`, {\n\t\t\t\tcode: ReactiveErrorCode.CycleDetected,\n\t\t\t\tcycle: cycle.map((r) => r.name || r.toString()),\n\t\t\t\tdetails: cycleMessage,\n\t\t\t})\n\t\t}\n\t\treturn null // Batch complete\n\t}\n\n\teffectuatedRoots.push(getRoot(nextEffect))\n\t// Execute the effect\n\texecutingStack.push(nextEffect)\n\tlet result: any\n\ttry {\n\t\tconst node = getEffectNode(nextEffect)\n\t\tconst reason = node.nextReason\n\t\tif (node.cleanup) {\n\t\t\tconst cleanup = node.cleanup\n\t\t\tnode.cleanup = undefined\n\t\t\tcleanup(reason)\n\t\t}\n\t\tresult = nextEffect()\n\t} finally {\n\t\texecutingStack.pop()\n\t}\n\n\t// Remove from ALL batches in the stack and update in-degrees of dependents\n\tfor (let i = batchStack.length - 1; i >= 0; i--) {\n\t\tconst batch = batchStack[i]\n\t\tif (batch.all.has(nextRoot!)) {\n\t\t\tbatch.all.delete(nextRoot!)\n\t\t\tbatch.inDegrees.delete(nextRoot!)\n\t\t\tdecrementInDegreesForExecuted(batch, nextRoot!)\n\t\t}\n\t}\n\n\treturn result\n}\n\n// Track which sub-effects have been executed to prevent infinite loops\n// These are all the effects triggered under `activeEffect` and all their sub-effects\nexport function batch(\n\teffect: EffectTrigger | EffectTrigger[],\n\timmediate?: 'immediate',\n\tcaller?: EffectTrigger\n) {\n\tif (broken) {\n\t\tthrow new ReactiveError(\n\t\t\t'[reactive] Reactive system is broken after an unrecoverable error. Call reset() to recover.',\n\t\t\t{ code: ReactiveErrorCode.BrokenEffects }\n\t\t)\n\t}\n\tif (!Array.isArray(effect)) effect = [effect]\n\tconst roots = effect.map(getRoot)\n\n\tconst isNewBatch = batchStack.length === 0\n\tif (isNewBatch) {\n\t\tif (!activationRegistry) activationRegistry = new Map()\n\t\telse throw new Error('Activation registry already exists')\n\t\toptionCall('beginChain', roots)\n\t}\n\n\t// TODO: Consider this has been produced but was useless - it might be more correct ?const caller = executingStack.length > 0 ? getActiveEffect() : undefined\n\tconst activeCaller = getActiveEffect()\n\tconst callerToUse = caller || activeCaller\n\n\t// Optimization: If nested and NOT immediate, just join the existing batch\n\tif (!isNewBatch && !immediate) {\n\t\tfor (let i = 0; i < effect.length; i++) {\n\t\t\taddToBatch(effect[i], callerToUse, false)\n\t\t}\n\t\treturn\n\t}\n\n\tconst currentBatch: BatchQueue = {\n\t\tall: new Map(),\n\t\tinDegrees: new Map(),\n\t\tdeferreds: new Set(),\n\t}\n\tbatchStack.push(currentBatch)\n\n\tlet success = false\n\ttry {\n\t\tconst effectuatedRoots: Function[] = []\n\t\tconst firstReturn: { value?: any } = {}\n\n\t\tif (immediate) {\n\t\t\t// Execute initial effects in providing order\n\t\t\tfor (let i = 0; i < effect.length; i++) {\n\t\t\t\texecutingStack.push(effect[i])\n\t\t\t\ttry {\n\t\t\t\t\tconst node = getEffectNode(effect[i])\n\t\t\t\t\tconst reason = node.nextReason\n\t\t\t\t\tif (node.cleanup) {\n\t\t\t\t\t\tconst cleanup = node.cleanup\n\t\t\t\t\t\tnode.cleanup = undefined\n\t\t\t\t\t\tcleanup(reason)\n\t\t\t\t\t}\n\t\t\t\t\tconst rv = effect[i]()\n\t\t\t\t\tif (rv !== undefined && !('value' in firstReturn)) firstReturn.value = rv\n\t\t\t\t} finally {\n\t\t\t\t\texecutingStack.pop()\n\t\t\t\t\tcurrentBatch.all.delete(getRoot(effect[i]))\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\t// Add initial effects to batch and compute dependencies\n\t\t\tfor (let i = 0; i < effect.length; i++) {\n\t\t\t\taddToBatch(effect[i], callerToUse, false)\n\t\t\t}\n\t\t\tcomputeAllInDegrees(currentBatch)\n\t\t}\n\n\t\t// Process the current batch queue\n\t\twhile (currentBatch.all.size > 0 || currentBatch.deferreds.size > 0) {\n\t\t\tif (currentBatch.all.size > 0) {\n\t\t\t\tif (effectuatedRoots.length > options.maxEffectChain) {\n\t\t\t\t\tconst cycle = findCycleInChain(effectuatedRoots as any)\n\t\t\t\t\tconst trace = formatRoots(effectuatedRoots as any)\n\t\t\t\t\tconst message = cycle\n\t\t\t\t\t\t? `Max effect chain reached (cycle detected: ${formatRoots(cycle)})`\n\t\t\t\t\t\t: `Max effect chain reached (trace: ${trace})`\n\n\t\t\t\t\tconst queuedRoots = Array.from(currentBatch.all.keys())\n\t\t\t\t\tconst queued = queuedRoots.map((r) => r.name || '<anonymous>')\n\t\t\t\t\tconst debugInfo = {\n\t\t\t\t\t\tcode: ReactiveErrorCode.MaxDepthExceeded,\n\t\t\t\t\t\teffectuatedRoots,\n\t\t\t\t\t\tcycle,\n\t\t\t\t\t\ttrace,\n\t\t\t\t\t\tmaxEffectChain: options.maxEffectChain,\n\t\t\t\t\t\tqueued: queued.slice(0, 50),\n\t\t\t\t\t\tqueuedCount: queued.length,\n\t\t\t\t\t\tcausalChain:\n\t\t\t\t\t\t\teffectuatedRoots.length > 0\n\t\t\t\t\t\t\t\t? debugHooks.getTriggerChain(\n\t\t\t\t\t\t\t\t\t\tcurrentBatch.all.get(effectuatedRoots[effectuatedRoots.length - 1])!\n\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t: [],\n\t\t\t\t\t}\n\t\t\t\t\tswitch (options.maxEffectReaction) {\n\t\t\t\t\t\tcase 'throw':\n\t\t\t\t\t\t\tthrow new ReactiveError(`[reactive] ${message}`, debugInfo)\n\t\t\t\t\t\tcase 'debug':\n\t\t\t\t\t\t\t// biome-ignore lint/suspicious/noDebugger: This is the whole point here\n\t\t\t\t\t\t\tdebugger\n\t\t\t\t\t\t\tthrow new ReactiveError(`[reactive] ${message}`, debugInfo)\n\t\t\t\t\t\tcase 'warn':\n\t\t\t\t\t\t\toptions.warn(\n\t\t\t\t\t\t\t\t`[reactive] ${message} (queued: ${queued.slice(0, 10).join(', ')}${queued.length > 10 ? ', …' : ''})`\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tconst rv = executeNext(effectuatedRoots)\n\t\t\t\tif (rv !== undefined && !('value' in firstReturn)) firstReturn.value = rv\n\t\t\t} else {\n\t\t\t\t// Process deferreds for this batch.\n\t\t\t\tconst deferreds = Array.from(currentBatch.deferreds)\n\t\t\t\tcurrentBatch.deferreds.clear()\n\t\t\t\tfor (const deferred of deferreds) deferred()\n\t\t\t}\n\t\t}\n\t\tsuccess = true\n\t\treturn firstReturn.value\n\t} catch (error) {\n\t\tif (batchStack.length === 1)\n\t\t\toptionCall('error', '[reactive] Root batch failure before broken state:', error)\n\t\tthrow error\n\t} finally {\n\t\tif (!success && batchStack.length === 1) {\n\t\t\tbroken = true\n\t\t}\n\t\tbatchStack.pop()\n\t\tif (batchStack.length === 0) {\n\t\t\tactivationRegistry = undefined\n\t\t\toptionCall('endChain')\n\t\t}\n\t}\n}\n\n/**\n * Resets the reactive system to a consistent state.\n * Call this after an unrecoverable error has set the system to \"broken\".\n * This clears all batch state, effect dependency graphs, and watcher registrations.\n * All existing effects become orphaned and must be recreated.\n */\nexport function reset() {\n\tbroken = false\n\tactivationRegistry = undefined\n\tbatchStack.length = 0\n\teffectTriggers = new WeakMap()\n\teffectTriggeredBy = new WeakMap()\n\tcausesClosure = new WeakMap()\n\tconsequencesClosure = new WeakMap()\n\tresetRegistry()\n\tresetTracking()\n\teffectHistory.present.active = undefined\n}\n\nexport { reset as resetBatchQueueForTest }\n\n// Inject batch function to allow atomic game loops in requestAnimationFrame/setTimeout/...\n// Note: Automatic batching of async callbacks (setTimeout, Promise.then, etc.) is NOT implemented.\n// Rationale: (1) asyncHooks.addHook API doesn't support knowing when callbacks complete (needed for batching),\n// (2) hooking all callback-creating functions adds overhead without guaranteed benefit,\n// (3) incomplete coverage in Node (async_hooks misses user-land patterns).\n// Solution: Use explicit @atomic decorator or manual batch() calls where optimization is needed.\n\n/**\n * Decorator that makes methods atomic - batches all effects triggered within the method\n */\nexport const atomic = decorator({\n\tmethod(original) {\n\t\treturn function (this: any, ...args: any[]) {\n\t\t\tconst atomicEffect = () => original.apply(this, args)\n\t\t\t// Debug: helpful to have a name\n\t\t\tObject.defineProperty(atomicEffect, 'name', { value: `atomic(${original.name})` })\n\t\t\treturn batch(atomicEffect as EffectTrigger, 'immediate')\n\t\t}\n\t},\n\tdefault<Args extends any[], Return>(\n\t\toriginal: (...args: Args) => Return\n\t): (...args: Args) => Return {\n\t\treturn function (this: any, ...args: Args) {\n\t\t\tconst atomicEffect = () => original.apply(this, args)\n\t\t\t// Debug: helpful to have a name\n\t\t\tObject.defineProperty(atomicEffect, 'name', { value: `atomic(${original.name})` })\n\t\t\treturn batch(atomicEffect as EffectTrigger, 'immediate')\n\t\t}\n\t},\n})\n\n/**\n * Wraps `fn` so it runs within `effect`'s zone context when invoked later.\n *\n * Useful for deferred callbacks (event listeners, `DOMContentLoaded`, etc.)\n * that need sub-effects parented to the original effect.\n *\n * @param prev - The effect whose context should be restored, or `undefined` for root context\n * @param fn - The function to wrap\n * @returns A function with the same signature that restores the effect context before calling `fn`\n */\nexport function captured<Args extends any[], Return>(\n\tprev: HistoryValue<EffectTrigger> | undefined,\n\tfn: (...args: Args) => Return\n): (...args: Args) => Return {\n\tprev ??= effectHistory.active\n\treturn named(effectMarker.leave, (...args: Args) => {\n\t\treturn effectHistory.with(prev, () => fn(...args))\n\t})\n}\n\n/**\n * Runs `fn` atomically and **always immediately**, batching all reactive effects\n * triggered inside it so they fire only once after `fn` completes.\n *\n * Unlike `atomic(fn)` which **wraps** a function for later invocation,\n * `atom(fn)` **executes** the function right away.\n *\n * @example\n * ```ts\n * const state = reactive({ a: 0, b: 0 })\n * effect(() => console.log(state.a, state.b)) // logs once after atom completes\n *\n * atom(() => {\n * state.a = 1\n * state.b = 2\n * })\n * ```\n */\nexport function atom<T>(fn: () => T) {\n\treturn batch(fn, 'immediate')\n}\n\nconst fr = new FinalizationRegistry<() => void>((f) => f())\n\n/**\n * @param fn - The effect function to run - provides the cleaner\n * @returns The cleanup function\n */\n/**\n * Reactive effect function with chainable flavor modifiers.\n */\ntype EffectCallback = (access: EffectAccess) => EffectCloser | undefined | void | Promise<any>\ntype EffectApplication = (fn: EffectCallback, effectOptions?: EffectOptions) => EffectCleanup\n\nexport interface Effect extends Captioned<EffectApplication> {\n\t(fn: EffectCallback, effectOptions?: EffectOptions): EffectCleanup\n\t/** Opaque flavor: bypasses deep-touch optimizations */\n\treadonly opaque: Effect\n\t/** @deprecated Use `effect\\`name\\`(fn)` instead. */\n\tnamed(name: string): Effect\n}\n\n/**\n * Creates a reactive effect that automatically re-runs when dependencies change\n * @param fn - The effect function that provides dependencies and may return a cleanup function or Promise\n * @param options - Options for effect execution\n * @returns A cleanup function to stop the effect\n */\nexport const effect: Effect = captioned(\n\tnamed(\n\t\teffectMarker.leave,\n\t\tflavored(\n\t\t\tfunction effect(fn: EffectCallback, effectOptions: EffectOptions = {}): EffectCleanup {\n\t\t\t\tif (effectOptions?.name) Object.defineProperty(fn, 'name', { value: effectOptions.name })\n\t\t\t\t// Use per-effect asyncMode or fall back to global option\n\t\t\t\tconst asyncMode = effectOptions?.asyncMode ?? options.asyncMode ?? 'cancel'\n\n\t\t\t\t// Create the effect function - naming it for debug\n\t\t\t\tconst runEffect: EffectTrigger = () => {\n\t\t\t\t\tconst node = getEffectNode(runEffect)\n\t\t\t\t\t// Clear previous dependencies\n\t\t\t\t\tif (node.cleanup) {\n\t\t\t\t\t\tconst prevCleanup = node.cleanup\n\t\t\t\t\t\tnode.cleanup = undefined\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tuntracked`effect:cleanup`(() =>\n\t\t\t\t\t\t\t\tprevCleanup(\n\t\t\t\t\t\t\t\t\tchainExternalReason(\n\t\t\t\t\t\t\t\t\t\tnode.nextReason || {\n\t\t\t\t\t\t\t\t\t\t\ttype: 'stopped',\n\t\t\t\t\t\t\t\t\t\t\tchain: node.currentReason,\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\t// If we want to report them, we could use options.warn or similar\n\t\t\t\t\t\t\toptions.warn('Error during effect cleanup', error)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t// Handle async modes when effect is retriggered\n\t\t\t\t\tif (runningPromise) {\n\t\t\t\t\t\tif (asyncMode === 'cancel' && cancelPrevious) {\n\t\t\t\t\t\t\t// Cancel previous execution\n\t\t\t\t\t\t\tabort()\n\t\t\t\t\t\t\tcancelPrevious()\n\t\t\t\t\t\t\tcancelPrevious = null\n\t\t\t\t\t\t\trunningPromise = null\n\t\t\t\t\t\t} else if (asyncMode === 'ignore') {\n\t\t\t\t\t\t\t// Ignore new execution while async work is running\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Note: 'queue' mode not yet implemented\n\t\t\t\t\t}\n\n\t\t\t\t\t// The effect has been stopped after having been planned\n\t\t\t\t\tif (effectStopped) return\n\n\t\t\t\t\tlet reactionCleanup: EffectCloser | undefined\n\t\t\t\t\tfunction cleanupReaction(reason?: CleanupReason) {\n\t\t\t\t\t\tconst toCleanup = reactionCleanup\n\t\t\t\t\t\treactionCleanup = undefined\n\t\t\t\t\t\ttoCleanup?.(reason)\n\t\t\t\t\t}\n\t\t\t\t\t// Set reaction reason for the upcoming run\n\t\t\t\t\taccess.reaction = node.nextReason || access.reaction\n\t\t\t\t\tnode.currentReason =\n\t\t\t\t\t\tnode.nextReason ||\n\t\t\t\t\t\t(access.reaction && access.reaction !== true ? access.reaction : undefined)\n\t\t\t\t\tnode.nextReason = undefined\n\n\t\t\t\t\toptionCall('enter', getRoot(fn))\n\t\t\t\t\toptionCall('effectRun', getRoot(fn), access.reaction)\n\t\t\t\t\tlet result: any\n\t\t\t\t\tlet caught = 0\n\n\t\t\t\t\t// Define bubbling thrower\n\t\t\t\t\tconst thrower: CatchFunction = (error: any) => {\n\t\t\t\t\t\tconst catches = node.catchers\n\t\t\t\t\t\tconst reason: CleanupReason = { type: 'error', error }\n\t\t\t\t\t\tif (catches)\n\t\t\t\t\t\t\twhile (caught < catches.length) {\n\t\t\t\t\t\t\t\tcleanupReaction(reason)\n\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\treactionCleanup = catches[caught](error) as EffectCloser\n\t\t\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t\t\t} catch (_e) {\n\t\t\t\t\t\t\t\t\tcaught++\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\tif (parent) {\n\t\t\t\t\t\t\tconst parentNode = getEffectNode(parent)\n\t\t\t\t\t\t\tif (parentNode.forwardThrow) parentNode.forwardThrow(error)\n\t\t\t\t\t\t\telse throw error\n\t\t\t\t\t\t} else throw error\n\t\t\t\t\t}\n\t\t\t\t\tnode.forwardThrow = thrower\n\n\t\t\t\t\tlet errorToThrow: Error | undefined\n\t\t\t\t\ttry {\n\t\t\t\t\t\tresult = tracked(named(effectMarker.enter, () => fn.call(null, access)))\n\t\t\t\t\t\taccess.reaction = true\n\t\t\t\t\t\toptionCall('leave', fn)\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\tresult &&\n\t\t\t\t\t\t\ttypeof result !== 'function' &&\n\t\t\t\t\t\t\t(typeof result !== 'object' || !('then' in result))\n\t\t\t\t\t\t)\n\t\t\t\t\t\t\tthrow new ReactiveError(`[reactive] Effect returned a non-function value: ${result}`)\n\t\t\t\t\t\t// Check if result is a Promise (async effect)\n\t\t\t\t\t\tif (result && typeof result === 'object' && typeof result.then === 'function') {\n\t\t\t\t\t\t\tconst originalPromise = result as Promise<any>\n\n\t\t\t\t\t\t\t// Create a cancellation promise that we can reject\n\t\t\t\t\t\t\tlet cancelReject: ((reason: any) => void) | null = null\n\t\t\t\t\t\t\tconst cancelPromise = new Promise<never>((_, reject) => {\n\t\t\t\t\t\t\t\tcancelReject = reject\n\t\t\t\t\t\t\t})\n\n\t\t\t\t\t\t\tconst cancelError = new ReactiveError(\n\t\t\t\t\t\t\t\t'[reactive] Effect canceled due to dependency change'\n\t\t\t\t\t\t\t)\n\n\t\t\t\t\t\t\t// Race between the actual promise and cancellation\n\t\t\t\t\t\t\t// If canceled, the race rejects, which will propagate through any promise chain\n\t\t\t\t\t\t\trunningPromise = Promise.race([originalPromise, cancelPromise])\n\n\t\t\t\t\t\t\t// Store the cancellation function\n\t\t\t\t\t\t\tcancelPrevious = () => {\n\t\t\t\t\t\t\t\tif (cancelReject) {\n\t\t\t\t\t\t\t\t\tcancelReject(cancelError)\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// Wrap the original promise chain so cancellation propagates\n\t\t\t\t\t\t\t// This ensures that when we cancel, the original promise's .catch() handlers are triggered\n\t\t\t\t\t\t\t// We do this by rejecting the race promise, which makes the original promise chain see the rejection\n\t\t\t\t\t\t\t// through the zone-wrapped .then()/.catch() handlers\n\t\t\t\t\t\t\trunningPromise = runningPromise\n\t\t\t\t\t\t\t\t.catch((error) => {\n\t\t\t\t\t\t\t\t\t// Propagate async errors to the effect's error handler\n\t\t\t\t\t\t\t\t\t// This ensures onEffectThrow handlers are triggered for async errors\n\t\t\t\t\t\t\t\t\tif (error !== cancelError) {\n\t\t\t\t\t\t\t\t\t\tthrower(error)\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t// If thrower didn't throw (handled), we absorb the error.\n\t\t\t\t\t\t\t\t\t// If thrower threw (unhandled), it propagates as a new unhandled rejection, which is correct.\n\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t.finally(() => {\n\t\t\t\t\t\t\t\t\t// Clear currentReason when async effect completes\n\t\t\t\t\t\t\t\t\tnode.currentReason = undefined\n\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t// Synchronous result - treat as cleanup function\n\t\t\t\t\t\t\treactionCleanup = result as undefined | EffectCloser\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tdebugHooks.decorateError(error, runEffect)\n\t\t\t\t\t\t// catcher:self`\n\t\t\t\t\t\terrorToThrow = error instanceof Error ? error : new Error(String(error))\n\t\t\t\t\t} finally {\n\t\t\t\t\t\t// Clear currentReason for synchronous effects\n\t\t\t\t\t\tif (!runningPromise) {\n\t\t\t\t\t\t\tnode.currentReason = undefined\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t// Create cleanup function for next run\n\t\t\t\t\tnode.cleanup = (reason?: CleanupReason) => {\n\t\t\t\t\t\tnode.cleanup = undefined\n\t\t\t\t\t\tabort()\n\t\t\t\t\t\tcleanupReaction(reason)\n\t\t\t\t\t\tdelete node.catchers\n\t\t\t\t\t\t// Remove this effect from all reactive objects it's watching\n\t\t\t\t\t\tconst effectObjects = effectToReactiveObjects.get(runEffect)\n\t\t\t\t\t\tif (effectObjects) {\n\t\t\t\t\t\t\tfor (const reactiveObj of effectObjects) {\n\t\t\t\t\t\t\t\tconst objectWatchers = watchers.get(reactiveObj)\n\t\t\t\t\t\t\t\tif (objectWatchers) {\n\t\t\t\t\t\t\t\t\tfor (const [prop, deps] of objectWatchers.entries()) {\n\t\t\t\t\t\t\t\t\t\tdeps.delete(runEffect)\n\t\t\t\t\t\t\t\t\t\tif (deps.size === 0) objectWatchers.delete(prop)\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tif (objectWatchers.size === 0) watchers.delete(reactiveObj)\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\teffectToReactiveObjects.delete(runEffect)\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Invoke all child stops (recursive via subEffectCleanup calling its own mainCleanup)\n\t\t\t\t\t\tconst children = node.children\n\t\t\t\t\t\tif (children) {\n\t\t\t\t\t\t\tconst childReason: CleanupReason = reason\n\t\t\t\t\t\t\t\t? reason.type === 'lineage'\n\t\t\t\t\t\t\t\t\t? reason\n\t\t\t\t\t\t\t\t\t: { type: 'lineage', parent: reason, chain: node.currentReason }\n\t\t\t\t\t\t\t\t: (chainExternalReason({ type: 'stopped', chain: node.currentReason }) ?? {\n\t\t\t\t\t\t\t\t\t\ttype: 'stopped',\n\t\t\t\t\t\t\t\t\t\tchain: node.currentReason,\n\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\tfor (const childCleanup of children) childCleanup(childReason)\n\t\t\t\t\t\t\tdelete node.children\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (errorToThrow) thrower(errorToThrow)\n\t\t\t\t}\n\n\t\t\t\t// Initialize metadata node\n\t\t\t\tconst node = getEffectNode(runEffect)\n\n\t\t\t\tif (debugHooks.isDevtoolsEnabled()) {\n\t\t\t\t\tconst stack = debugHooks.captureStack() // Robustly skips internal mutts frames\n\t\t\t\t\tif (stack) {\n\t\t\t\t\t\tnode.creationStack = stack\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tconst tracked = effectHistory.present.with(runEffect, () =>\n\t\t\t\t\tnamed(effectMarker.leave, effectAggregator.zoned)\n\t\t\t\t)\n\t\t\t\tconst ascended = named(effectMarker.leave, effectHistory.zoned)\n\t\t\t\tconst parent = effectHistory.present.active\n\t\t\t\t// Set parent relationship in node\n\t\t\t\tnode.parent = parent\n\n\t\t\t\t// let thrower: CatchFunction | undefined // Moved inside runEffect\n\t\t\t\tlet effectStopped = false\n\t\t\t\tlet abortController: AbortController | undefined\n\n\t\t\t\tconst access: EffectAccess = {\n\t\t\t\t\ttracked,\n\t\t\t\t\tascend: named(effectMarker.leave, (fn) =>\n\t\t\t\t\t\tascended(named(effectMarker.enter, () => fn.call(null)))\n\t\t\t\t\t),\n\t\t\t\t\t//named(effectMarker.enter, (fn) => ascended(fn)),\n\t\t\t\t\treaction: false,\n\t\t\t\t\tget signal() {\n\t\t\t\t\t\tif (!abortController) {\n\t\t\t\t\t\t\tabortController = new AbortController()\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn abortController.signal\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t\tlet runningPromise: Promise<any> | null = null\n\t\t\t\tlet cancelPrevious: (() => void) | null = null\n\t\t\t\tif (effectOptions?.dependencyHook) node.dependencyHook = effectOptions.dependencyHook\n\t\t\t\t// Mark the runEffect callback with the original function as its root\n\t\t\t\tmarkWithRoot(runEffect, fn)\n\n\t\t\t\t// Register strict mode if enabled\n\t\t\t\tif (effectOptions?.opaque) {\n\t\t\t\t\tnode.isOpaque = true\n\t\t\t\t}\n\n\t\t\t\tif (debugHooks.isDevtoolsEnabled()) {\n\t\t\t\t\tdebugHooks.registerEffect(runEffect)\n\t\t\t\t}\n\n\t\t\t\t// Store parent relationship for hierarchy traversal - ALREADY DONE ABOVE via getEffectNode\n\n\t\t\t\tconst abort = () => {\n\t\t\t\t\tif (abortController) {\n\t\t\t\t\t\tabortController.abort(\n\t\t\t\t\t\t\tnew ReactiveError('[reactive] Effect aborted due to dependency change or stop')\n\t\t\t\t\t\t)\n\t\t\t\t\t\tabortController = undefined\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tbatch(runEffect, 'immediate')\n\t\t\t\t// Only ROOT effects are registered for GC cleanup and zone tracking\n\t\t\t\tconst isRootEffect = !parent\n\n\t\t\t\tconst stopEffect = (reason?: CleanupReason): void => {\n\t\t\t\t\tif (effectStopped) return\n\t\t\t\t\teffectStopped = true\n\t\t\t\t\tnode.stopped = true\n\t\t\t\t\t// Cancel any running async work\n\t\t\t\t\tabort()\n\t\t\t\t\tif (cancelPrevious) {\n\t\t\t\t\t\tcancelPrevious()\n\t\t\t\t\t\tcancelPrevious = null\n\t\t\t\t\t\trunningPromise = null\n\t\t\t\t\t}\n\t\t\t\t\ttry {\n\t\t\t\t\t\tnode.cleanup?.(\n\t\t\t\t\t\t\tchainExternalReason(reason || { type: 'stopped', chain: node.currentReason })\n\t\t\t\t\t\t)\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t// Cleanup errors should basically be ignored or at least not stop the world\n\t\t\t\t\t\t// If we want to report them, we could use options.warn or similar\n\t\t\t\t\t\toptions.warn('Error during effect cleanup', error)\n\t\t\t\t\t}\n\t\t\t\t\t// Clean up dependency graph edges\n\t\t\t\t\tcleanupEffectFromGraph(runEffect)\n\t\t\t\t\tfr.unregister(stopEffect)\n\t\t\t\t}\n\t\t\t\tif (isRootEffect) {\n\t\t\t\t\tconst callIfCollected = (reason?: CleanupReason) => stopEffect(reason)\n\t\t\t\t\tfr.register(\n\t\t\t\t\t\tcallIfCollected,\n\t\t\t\t\t\t() => {\n\t\t\t\t\t\t\tstopEffect({ type: 'gc' })\n\t\t\t\t\t\t\toptionCall('garbageCollected', fn)\n\t\t\t\t\t\t},\n\t\t\t\t\t\tstopEffect\n\t\t\t\t\t)\n\t\t\t\t\treturn callIfCollected\n\t\t\t\t}\n\t\t\t\t// Register this effect to be stopped when the parent effect is cleaned up\n\t\t\t\tif (parent) {\n\t\t\t\t\tconst parentNode = getEffectNode(parent)\n\t\t\t\t\tif (!parentNode.children) {\n\t\t\t\t\t\tparentNode.children = new Set()\n\t\t\t\t\t}\n\t\t\t\t\tconst children = parentNode.children\n\n\t\t\t\t\tconst subEffectCleanup = (reason?: CleanupReason) => {\n\t\t\t\t\t\tchildren.delete(subEffectCleanup)\n\t\t\t\t\t\t// Execute this child effect cleanup (which triggers its own mainCleanup)\n\t\t\t\t\t\tstopEffect(reason)\n\t\t\t\t\t}\n\t\t\t\t\tchildren.add(subEffectCleanup)\n\t\t\t\t\treturn subEffectCleanup\n\t\t\t\t}\n\t\t\t\t// Should not be reachable given isRootEffect check, but for type safety\n\t\t\t\treturn (reason) => stopEffect(reason)\n\t\t\t},\n\t\t\t{\n\t\t\t\tget opaque() {\n\t\t\t\t\treturn flavorOptions(this, { opaque: true }, { name: 'opaque' }) as Effect\n\t\t\t\t},\n\t\t\t\tnamed(name: string) {\n\t\t\t\t\treturn flavorOptions(this, { name }, { name: 'named' }) as Effect\n\t\t\t\t},\n\t\t\t}\n\t\t)\n\t),\n\t{\n\t\tname: 'effect',\n\t\twarn: (message) => options.warn(`[reactive] ${message}`),\n\t\tshouldWarnAnonymous: (_callback, args) =>\n\t\t\t!(args[1] && typeof args[1] === 'object' && 'name' in args[1]),\n\t}\n) as Effect\n\n/**\n * Executes a function without tracking dependencies but maintains parent cleanup relationship\n * Effects created inside will still be cleaned up when the parent effect is destroyed\n * @param fn - The function to execute\n */\ntype RootRunner = <T>(fn: () => T) => T\n\nexport const untracked: Captioned<RootRunner> = captioned(function untracked<T>(fn: () => T): T {\n\tconst external = externalReasonFrom(fn)\n\treturn external\n\t\t? externalReason.with(external, () => effectHistory.present.root(fn))\n\t\t: effectHistory.present.root(fn)\n})\n\n/**\n * Executes a function from a virgin/root context - no parent effect, no tracking\n * Creates completely independent effects that won't be cleaned up by any parent\n * @param fn - The function to execute\n */\nexport const root: Captioned<RootRunner> = captioned(function root<T>(fn: () => T): T {\n\tconst external = externalReasonFrom(fn)\n\treturn external\n\t\t? externalReason.with(external, () => effectHistory.root(fn))\n\t\t: effectHistory.root(fn)\n})\n\n/**\n * Creates a bidirectional binding between a reactive value and a non-reactive external value\n * Prevents infinite loops by automatically suppressing circular notifications\n *\n * @param received - Function called when the reactive value changes (external setter)\n * @param get - Getter for the reactive value OR an object with `{ get, set }` properties\n * @param set - Setter for the reactive value (required if `get` is a function)\n * @returns A function to manually provide updates from the external side\n *\n * @example\n * ```typescript\n * const model = reactive({ value: '' })\n * const input = { value: '' }\n *\n * // Bidirectional binding\n * const provide = biDi(\n * (v) => input.value = v, // external setter\n * () => model.value, // reactive getter\n * (v) => model.value = v // reactive setter\n * )\n *\n * // External notification (e.g., from input event)\n * provide('new value') // Updates model.value, doesn't trigger circular loop\n * ```\n *\n * @example Using object syntax\n * ```typescript\n * const provide = biDi(\n * (v) => setHTMLValue(v),\n * { get: () => reactiveObj.value, set: (v) => reactiveObj.value = v }\n * )\n * ```\n */\nexport function biDi<T>(\n\treceived: (value: T) => void,\n\tvalue: { get: () => T; set: (value: T) => void }\n): (value: T) => void\nexport function biDi<T>(\n\treceived: (value: T) => void,\n\tget: () => T,\n\tset: (value: T) => void\n): (value: T) => void\nexport function biDi<T>(\n\treceived: (value: T) => void,\n\tget: (() => T) | { get: () => T; set: (value: T) => void },\n\tset?: (value: T) => void\n): (value: T) => void {\n\tif (typeof get !== 'function') {\n\t\tset = get.set\n\t\tget = get.get\n\t}\n\tlet programmaticallySetValue: any = Symbol()\n\teffect`biDi`(\n\t\tmarkWithRoot(() => {\n\t\t\tconst newValue = get()\n\t\t\tconst pValue = programmaticallySetValue\n\t\t\tprogrammaticallySetValue = Symbol()\n\t\t\tif (unwrap(newValue) !== pValue) received(newValue)\n\t\t}, received)\n\t)\n\treturn set\n\t\t? atomic((value: T) => {\n\t\t\t\tprogrammaticallySetValue = unwrap(value)\n\t\t\t\tset(value)\n\t\t\t})\n\t\t: () => {}\n}\n","import { debugHooks } from './debug-hooks'\nimport { batch } from './effects'\nimport { getEffectNode } from './registry'\nimport { getDependencyStack } from './tracking'\nimport { allProps, type EffectTrigger, type Evolution, options } from './types'\n\n// Track which objects contain which other objects (back-references)\nexport const objectParents = new WeakMap<object, Set<{ parent: object; prop: PropertyKey }>>()\n\n// Track which objects have deep watchers\nexport const objectsWithDeepWatchers = new WeakSet<object>()\nlet deepWatcherCount = 0\nexport function registerDeepWatcher() {\n\tdeepWatcherCount++\n}\n\n// Track deep watchers per object\nexport const deepWatchers = new WeakMap<object, Set<EffectTrigger>>()\n\n// Track which effects are doing deep watching\nexport const effectToDeepWatchedObjects = new WeakMap<EffectTrigger, Set<object>>()\n\n/**\n * Add a back-reference from child to parent\n */\nexport function addBackReference(child: object, parent: object, prop: any) {\n\tlet parents = objectParents.get(child)\n\tif (!parents) {\n\t\tparents = new Set()\n\t\tobjectParents.set(child, parents)\n\t}\n\tparents.add({ parent, prop })\n}\n\n/**\n * Remove a back-reference from child to parent\n */\nexport function removeBackReference(child: object, parent: object, prop: any) {\n\tconst parents = objectParents.get(child)\n\tif (parents) {\n\t\tfor (const entry of parents) {\n\t\t\tif (entry.parent === parent && entry.prop === prop) {\n\t\t\t\tparents.delete(entry)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif (parents.size === 0) {\n\t\t\tobjectParents.delete(child)\n\t\t}\n\t}\n}\n\n/**\n * Check if an object needs back-references (has deep watchers or parents with deep watchers)\n */\nexport function needsBackReferences(obj: object): boolean {\n\t// Fast path: if no deep watchers exist anywhere, skip entirely\n\tif (!deepWatcherCount) return false // fast path: no deep watchers anywhere\n\t// Check if object itself has deep watchers\n\tif (objectsWithDeepWatchers.has(obj)) return true\n\t// Slow path: check if any parent has deep watchers (recursive)\n\treturn hasParentWithDeepWatchers(obj)\n}\n\n/**\n * Bubble up changes through the back-reference chain\n */\nexport function bubbleUpChange(changedObject: object, evolution: Evolution) {\n\tconst parents = objectParents.get(changedObject)\n\tif (!parents) return\n\n\tfor (const { parent } of parents) {\n\t\t// Trigger deep watchers on parent\n\t\tconst parentDeepWatchers = deepWatchers.get(parent)\n\t\tif (parentDeepWatchers) {\n\t\t\tif (options.introspection?.gatherReasons) {\n\t\t\t\tconst gatherReasons = options.introspection.gatherReasons\n\t\t\t\tconst lineageConfig = gatherReasons.lineages\n\n\t\t\t\tlet touchLineage: unknown | undefined\n\t\t\t\tif (lineageConfig === 'touch' || lineageConfig === 'both') {\n\t\t\t\t\ttouchLineage = debugHooks.captureLineage()\n\t\t\t\t}\n\n\t\t\t\tfor (const watcher of parentDeepWatchers) {\n\t\t\t\t\tconst dependencyStack =\n\t\t\t\t\t\tlineageConfig === 'dependency' || lineageConfig === 'both'\n\t\t\t\t\t\t\t? getDependencyStack(watcher, parent, allProps)\n\t\t\t\t\t\t\t: undefined\n\n\t\t\t\t\tconst node = getEffectNode(watcher)\n\t\t\t\t\tif (!node.pendingTriggers) node.pendingTriggers = []\n\t\t\t\t\tnode.pendingTriggers.push({\n\t\t\t\t\t\tobj: parent,\n\t\t\t\t\t\tevolution,\n\t\t\t\t\t\tdependency: dependencyStack,\n\t\t\t\t\t\ttouch: touchLineage,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (const watcher of parentDeepWatchers) batch(watcher)\n\t\t}\n\n\t\t// Continue bubbling up\n\t\tbubbleUpChange(parent, evolution)\n\t}\n}\n\nfunction hasParentWithDeepWatchers(obj: object): boolean {\n\tconst parents = objectParents.get(obj)\n\tif (!parents) return false\n\n\tfor (const { parent } of parents) {\n\t\tif (objectsWithDeepWatchers.has(parent)) return true\n\t\tif (hasParentWithDeepWatchers(parent)) return true\n\t}\n\treturn false\n}\n","import { debugHooks } from './debug-hooks'\nimport { bubbleUpChange, objectsWithDeepWatchers } from './deep-watch-state'\nimport { getActiveEffect, isRunning } from './effect-context'\nimport { batch, hasBatched, recordActivation } from './effects'\nimport { getEffectNode, watchers } from './registry'\nimport { getDependencyStack } from './tracking'\nimport {\n\tallProps,\n\ttype EffectTrigger,\n\ttype Evolution,\n\tkeysOf,\n\toptionCall,\n\toptions,\n\ttype State,\n\tunwrap,\n} from './types'\n\nconst states = new WeakMap<object, State>()\n\nexport function addState(obj: any, evolution: Evolution) {\n\tobj = unwrap(obj)\n\tconst next = {}\n\tconst state = getState(obj)\n\tif (state) Object.assign(state, { evolution, next })\n\tstates.set(obj, next)\n}\n\n/**\n * Gets the current state of a reactive object for evolution tracking\n * @param obj - The reactive object\n * @returns The current state object\n */\nexport function getState(obj: any) {\n\tobj = unwrap(obj)\n\tlet state = states.get(obj)\n\tif (!state) {\n\t\tstate = {}\n\t\tstates.set(obj, state)\n\t}\n\treturn state\n}\n\nexport function collectEffects(\n\tobj: any,\n\tevolution: Evolution,\n\teffects: Map<EffectTrigger, unknown>,\n\tobjectWatchers: Map<any, Set<EffectTrigger>>,\n\t...keyChains: Iterable<any>[]\n) {\n\tconst sourceEffect = getActiveEffect()\n\tfor (const keys of keyChains)\n\t\tfor (const key of keys) {\n\t\t\tconst deps = objectWatchers.get(key)\n\t\t\tif (deps) {\n\t\t\t\t// Make sure `some.prop++` does not keep a dependency to `some.props`\n\t\t\t\tif (sourceEffect) deps.delete(sourceEffect)\n\t\t\t\tfor (const effect of deps) {\n\t\t\t\t\tconst runningChain = isRunning(effect)\n\t\t\t\t\tif (runningChain) {\n\t\t\t\t\t\toptionCall('skipRunningEffect', effect)\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tif (!effects.has(effect)) {\n\t\t\t\t\t\teffects.set(effect, getDependencyStack(effect, obj, key))\n\t\t\t\t\t\tif (!hasBatched(effect)) recordActivation(effect, obj, evolution, key)\n\t\t\t\t\t}\n\t\t\t\t\tdebugHooks.recordTriggerLink(sourceEffect, effect, obj, key, evolution)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n}\n\n/**\n * Triggers effects for a single property change\n * @param obj - The object that changed\n * @param evolution - The type of change\n * @param prop - The property that changed\n */\nexport function touched1(obj: any, evolution: Evolution, prop: any) {\n\ttouched(obj, evolution, [prop])\n}\n\n/**\n * Triggers effects for property changes\n * @param obj - The object that changed\n * @param evolution - The type of change\n * @param props - The properties that changed\n */\nexport function touched(obj: any, evolution: Evolution, props?: Iterable<any>) {\n\tobj = unwrap(obj)\n\taddState(obj, evolution)\n\tconst objectWatchers = watchers.get(obj)\n\tif (objectWatchers) {\n\t\t// Note: we have to collect effects to remove duplicates in the specific case when no batch is running\n\t\tconst effects = new Map<EffectTrigger, unknown>()\n\t\tconst structural = !['set', 'invalidate'].includes(evolution.type)\n\t\tconst broad = structural ? [allProps, keysOf] : [allProps]\n\t\tif (props) collectEffects(obj, evolution, effects, objectWatchers, broad, props)\n\t\telse collectEffects(obj, evolution, effects, objectWatchers, objectWatchers.keys())\n\t\tconst triggers = Array.from(effects.keys())\n\t\tconst sourceEffect = getActiveEffect()\n\t\toptionCall('touched', obj, evolution, props as any[] | undefined, triggers)\n\t\t// Store pending triggers for CleanupReason before batching\n\t\tif (options.introspection?.gatherReasons) {\n\t\t\tconst gatherReasons = options.introspection.gatherReasons\n\t\t\tconst lineageConfig = gatherReasons.lineages\n\n\t\t\tlet touchLineage: unknown | undefined\n\t\t\tif (lineageConfig === 'touch' || lineageConfig === 'both') {\n\t\t\t\ttouchLineage = debugHooks.captureLineage()\n\t\t\t}\n\n\t\t\tfor (const [effect, dependencyStack] of effects) {\n\t\t\t\tconst node = getEffectNode(effect)\n\t\t\t\tif (!node.pendingTriggers) node.pendingTriggers = []\n\t\t\t\tnode.pendingTriggers.push({\n\t\t\t\t\tobj,\n\t\t\t\t\tevolution,\n\t\t\t\t\tdependency: dependencyStack,\n\t\t\t\t\ttouch: touchLineage,\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t\tbatch(triggers, undefined, sourceEffect)\n\t}\n\n\t// Bubble up changes if this object has deep watchers\n\tif (objectsWithDeepWatchers.has(obj)) {\n\t\tbubbleUpChange(obj, evolution)\n\t}\n}\n\n/**\n * Triggers only opaque effects for property changes\n * Used by deep-touch to ensure opaque listeners are notified even when deep optimization is active\n */\nexport function touchedOpaque(obj: any, evolution: Evolution, prop: any) {\n\tobj = unwrap(obj)\n\tconst objectWatchers = watchers.get(obj)\n\tif (!objectWatchers) return\n\n\tconst deps = objectWatchers.get(prop)\n\tif (!deps) return\n\n\tconst effects = new Set<EffectTrigger>()\n\tconst sourceEffect = getActiveEffect()\n\n\tconst gather = options.introspection?.gatherReasons\n\n\tif (gather) {\n\t\tconst lineageConfig = gather.lineages\n\n\t\tfor (const effect of deps) {\n\t\t\tconst node = getEffectNode(effect)\n\t\t\tif (!node.isOpaque) continue\n\n\t\t\tconst runningChain = isRunning(effect)\n\t\t\tif (runningChain) {\n\t\t\t\toptionCall('skipRunningEffect', effect)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\teffects.add(effect)\n\t\t\tif (gather) {\n\t\t\t\tlet touchLineage: unknown | undefined\n\t\t\t\tlet dependencyStack: unknown | undefined\n\n\t\t\t\tif (lineageConfig === 'touch' || lineageConfig === 'both') {\n\t\t\t\t\ttouchLineage = debugHooks.captureLineage()\n\t\t\t\t}\n\t\t\t\tif (lineageConfig === 'dependency' || lineageConfig === 'both') {\n\t\t\t\t\tdependencyStack = getDependencyStack(effect, obj, prop)\n\t\t\t\t}\n\n\t\t\t\tif (!node.pendingTriggers) node.pendingTriggers = []\n\t\t\t\tnode.pendingTriggers.push({\n\t\t\t\t\tobj,\n\t\t\t\t\tevolution,\n\t\t\t\t\tdependency: dependencyStack,\n\t\t\t\t\ttouch: touchLineage,\n\t\t\t\t})\n\t\t\t}\n\t\t\trecordActivation(effect, obj, evolution, prop)\n\t\t\tdebugHooks.recordTriggerLink(sourceEffect, effect, obj, prop, evolution)\n\t\t}\n\t} else {\n\t\t// When not gathering reasons, process effects normally\n\t\tfor (const effect of deps) {\n\t\t\tconst node = getEffectNode(effect)\n\t\t\tif (!node.isOpaque) continue\n\n\t\t\tconst runningChain = isRunning(effect)\n\t\t\tif (runningChain) {\n\t\t\t\toptionCall('skipRunningEffect', effect)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\teffects.add(effect)\n\t\t\trecordActivation(effect, obj, evolution, prop)\n\t\t\tdebugHooks.recordTriggerLink(sourceEffect, effect, obj, prop, evolution)\n\t\t}\n\t}\n\n\tif (effects.size > 0) {\n\t\toptionCall('touched', obj, evolution, [prop], Array.from(effects))\n\t\tbatch(Array.from(effects), undefined, sourceEffect)\n\t}\n}\n","import { unreactiveProperties } from './types'\nexport const absent = Symbol('absent')\n\ntype UnreactiveMarker = true | Set<PropertyKey>\ntype UnreactiveHost = {\n\t[unreactiveProperties]?: UnreactiveMarker\n}\n\n/**\n * Add unreactive properties to a prototype.\n * If no set is provided, marks the entire object/prototype as non-reactive (sets [unreactiveProperties] = true).\n * If a set is provided, merges with existing unreactive properties (never overrides true).\n */\nexport function addUnreactiveProps<T extends object>(proto: T, set?: Iterable<PropertyKey>): T {\n\tif (unreactiveProperties in proto) {\n\t\tconst existing = (proto as UnreactiveHost)[unreactiveProperties]\n\t\t// If already fully unreactive, don't change\n\t\tif (existing === true) return proto\n\t\t// If no set provided, upgrade to fully unreactive\n\t\tif (!set) {\n\t\t\t;(proto as UnreactiveHost)[unreactiveProperties] = true\n\t\t\treturn proto\n\t\t}\n\t\t// Merge sets\n\t\tconst merged = new Set<PropertyKey>(existing)\n\t\t;(proto as UnreactiveHost)[unreactiveProperties] = merged\n\t\tfor (const p of set) merged.add(p)\n\t}\n\t// If no set, mark as fully unreactive, otherwise create set\n\telse (proto as UnreactiveHost)[unreactiveProperties] = set ? new Set<PropertyKey>(set) : true\n\treturn proto\n}\n\n/** Check if a property is marked unreactive on obj or any of its prototypes (trap-free) */\nexport function isUnreactiveProp(obj: object, prop: PropertyKey): boolean {\n\tif (typeof prop === 'symbol' || prop === 'constructor') return true\n\tconst marker = (obj as UnreactiveHost)[unreactiveProperties]\n\treturn (\n\t\tmarker === true || // Fully unreactive\n\t\tmarker?.has?.(prop) || // Property is unreactive\n\t\tfalse\n\t)\n}\n\nexport function nonReactive<T extends object[]>(...obj: T): T[0] {\n\tfor (const o of obj) {\n\t\t;(o as UnreactiveHost)[unreactiveProperties] = true\n\t}\n\treturn obj[0]\n}\n\nexport function nonReactiveClass<T extends (new (...args: any[]) => any)[]>(...cls: T): T[0] {\n\tfor (const c of cls) if (c) (c.prototype as UnreactiveHost)[unreactiveProperties] = true\n\treturn cls[0]\n}\n\nexport function isNonReactive(obj: any): boolean {\n\treturn !obj || (obj as UnreactiveHost)[unreactiveProperties] === true\n}\n\nnonReactiveClass(Date, RegExp, Error, Promise, Function)\nif (typeof window !== 'undefined') {\n\tnonReactive(window, document)\n\tnonReactiveClass(Node, Element, HTMLElement, EventTarget, HTMLCollection, NodeList)\n}\n","import { addState, collectEffects, touched1, touchedOpaque } from './change'\nimport { debugHooks } from './debug-hooks'\nimport { bubbleUpChange, objectsWithDeepWatchers } from './deep-watch-state'\nimport { batch, untracked } from './effects'\nimport { isNonReactive } from './non-reactive'\nimport { effectToReactiveObjects, getEffectNode, watchers } from './registry'\nimport { getDependencyStack } from './tracking'\nimport {\n\tallProps,\n\ttype EffectCleanup,\n\ttype EffectTrigger,\n\ttype Evolution,\n\tkeysOf,\n\toptionCall,\n\toptions,\n\tunwrap,\n} from './types'\n\nfunction getPrototypeToken(value: any): object | null | undefined {\n\tif (Array.isArray(value)) return Array.prototype\n\tif (typeof value !== 'object') return undefined\n\ttry {\n\t\treturn value.constructor\n\t} catch {\n\t\treturn undefined\n\t}\n}\n\nexport function shouldRecurseTouch(oldValue: any, newValue: any): boolean {\n\tif (oldValue === newValue) return false\n\tif (\n\t\t(typeof oldValue !== 'object' && !Array.isArray(oldValue)) ||\n\t\t(typeof newValue !== 'object' && !Array.isArray(newValue))\n\t)\n\t\treturn false\n\tif (isNonReactive(oldValue) /*|| isNonReactive(newValue)*/) return false\n\treturn getPrototypeToken(oldValue) === getPrototypeToken(newValue)\n}\n\n/**\n * Migrate all watcher registrations from oldRef to newRef.\n * Called when deep touch replaces an object identity without any child value differences,\n * to prevent watcher orphaning (effects still pointing at the discarded old object).\n */\nfunction migrateWatchers(oldRef: object, newRef: object) {\n\tconst oldMap = watchers.get(oldRef)\n\tif (!oldMap) return\n\t// Move the entire watcher map\n\twatchers.set(newRef, oldMap)\n\twatchers.delete(oldRef)\n\t// Update the reverse map (effect → objects it watches)\n\tfor (const deps of oldMap.values()) {\n\t\tfor (const effect of deps) {\n\t\t\tconst objects = effectToReactiveObjects.get(effect)\n\t\t\tif (objects) {\n\t\t\t\tobjects.delete(oldRef)\n\t\t\t\tobjects.add(newRef)\n\t\t\t}\n\t\t}\n\t}\n}\n\n/**\n * Centralized function to handle property change notifications with optional recursive touch\n * @param targetObj - The object whose property changed\n * @param prop - The property that changed\n * @param oldValue - The old value (before change)\n * @param newValue - The new value (after change)\n * @param hadProperty - Whether the property existed before (for add vs set)\n */\nexport function notifyPropertyChange(\n\ttargetObj: any,\n\tprop: any,\n\toldValue: any,\n\tnewValue: any,\n\thadProperty: boolean\n) {\n\tconst evolution: Evolution = { type: hadProperty ? 'set' : 'add', prop }\n\n\tif (\n\t\toptions.recursiveTouching &&\n\t\toldValue !== undefined &&\n\t\tshouldRecurseTouch(oldValue, newValue)\n\t) {\n\t\tconst unwrappedObj = unwrap(targetObj)\n\t\tconst origin = { obj: unwrappedObj, prop }\n\t\t// Deep touch: only notify nested property changes with origin filtering\n\t\t// Don't notify direct property change - the whole point is to avoid parent effects re-running\n\n\t\tconst changes = untracked`deepTouch:recursive`(() =>\n\t\t\trecursiveTouch(oldValue, newValue, new WeakMap(), [], origin)\n\t\t)\n\n\t\t// When deep touch found no child differences, the object identity still changed.\n\t\t// Migrate watchers from old → new so the dependency chain is preserved.\n\t\tif (changes.length === 0) {\n\t\t\tmigrateWatchers(unwrap(oldValue), unwrap(newValue))\n\t\t} else {\n\t\t\tdispatchNotifications(changes)\n\t\t}\n\n\t\t// Notify opaque listeners (like memoize) that always want to know about identity changes\n\t\ttouchedOpaque(targetObj, evolution, prop)\n\t} else {\n\t\ttouched1(targetObj, evolution, prop)\n\t}\n}\n\ntype VisitedPairs = WeakMap<object, WeakSet<object>>\ntype PendingNotification = {\n\ttarget: any\n\tevolution: Evolution\n\tprop: any\n\torigin?: { obj: object; prop: PropertyKey } // The property access that triggered this deep touch\n}\n\nfunction hasVisitedPair(visited: VisitedPairs, oldObj: object, newObj: object): boolean {\n\tlet mapped = visited.get(oldObj)\n\tif (!mapped) {\n\t\tmapped = new WeakSet<object>()\n\t\tvisited.set(oldObj, mapped)\n\t}\n\tif (mapped.has(newObj)) return true\n\tmapped.add(newObj)\n\treturn false\n}\n\nfunction collectObjectKeys(obj: any): Set<PropertyKey> {\n\tconst keys = new Set<PropertyKey>(Reflect.ownKeys(obj))\n\tlet proto = Object.getPrototypeOf(obj)\n\t// Continue walking while prototype exists and doesn't have its own constructor\n\t// This stops at Object.prototype (has own constructor) and class prototypes (have own constructor)\n\t// but continues for data prototypes (Object.create({}), Object.create(instance), etc.)\n\twhile (proto && !Object.hasOwn(proto, 'constructor')) {\n\t\tfor (const key of Reflect.ownKeys(proto)) keys.add(key)\n\t\tproto = Object.getPrototypeOf(proto)\n\t}\n\treturn keys\n}\n\nexport function recursiveTouch(\n\toldValue: any,\n\tnewValue: any,\n\tvisited: VisitedPairs = new WeakMap(),\n\tnotifications: PendingNotification[] = [],\n\torigin?: { obj: object; prop: PropertyKey }\n): PendingNotification[] {\n\tif (!shouldRecurseTouch(oldValue, newValue)) return notifications\n\tif (\n\t\t(typeof oldValue !== 'object' && !Array.isArray(oldValue)) ||\n\t\t(typeof newValue !== 'object' && !Array.isArray(newValue))\n\t)\n\t\treturn notifications\n\tif (hasVisitedPair(visited, oldValue, newValue)) return notifications\n\n\tif (Array.isArray(oldValue) && Array.isArray(newValue)) {\n\t\tdiffArrayElements(oldValue, newValue, visited, notifications, origin)\n\t\treturn notifications\n\t}\n\n\tdiffObjectProperties(oldValue, newValue, visited, notifications, origin)\n\treturn notifications\n}\n\nfunction diffArrayElements(\n\toldArray: any[] | readonly any[],\n\tnewArray: any[] | readonly any[],\n\t_visited: VisitedPairs,\n\tnotifications: PendingNotification[],\n\torigin?: { obj: object; prop: PropertyKey }\n) {\n\tconst local: PendingNotification[] = []\n\tconst oldLength = oldArray.length\n\tconst newLength = newArray.length\n\tconst max = Math.max(oldLength, newLength)\n\n\tfor (let index = 0; index < max; index++) {\n\t\tconst hasOld = index < oldLength\n\t\tconst hasNew = index < newLength\n\t\tif (hasOld && !hasNew) {\n\t\t\tlocal.push({ target: oldArray, evolution: { type: 'del', prop: index }, prop: index, origin })\n\t\t\tcontinue\n\t\t}\n\t\tif (!hasOld && hasNew) {\n\t\t\tlocal.push({ target: oldArray, evolution: { type: 'add', prop: index }, prop: index, origin })\n\t\t\tcontinue\n\t\t}\n\t\tif (!hasOld || !hasNew) continue\n\t\tconst oldEntry = unwrap(oldArray[index])\n\t\tconst newEntry = unwrap(newArray[index])\n\t\tif (!Object.is(oldEntry, newEntry)) {\n\t\t\tlocal.push({ target: oldArray, evolution: { type: 'set', prop: index }, prop: index, origin })\n\t\t}\n\t}\n\n\tif (oldLength !== newLength)\n\t\tlocal.push({\n\t\t\ttarget: oldArray,\n\t\t\tevolution: { type: 'set', prop: 'length' },\n\t\t\tprop: 'length',\n\t\t\torigin,\n\t\t})\n\n\tnotifications.push(...local)\n}\n\nfunction diffObjectProperties(\n\toldObj: any,\n\tnewObj: any,\n\tvisited: VisitedPairs,\n\tnotifications: PendingNotification[],\n\torigin?: { obj: object; prop: PropertyKey }\n) {\n\tconst oldKeys = collectObjectKeys(oldObj)\n\tconst newKeys = collectObjectKeys(newObj)\n\tconst local: PendingNotification[] = []\n\n\tfor (const key of oldKeys)\n\t\tif (!newKeys.has(key))\n\t\t\tlocal.push({ target: oldObj, evolution: { type: 'del', prop: key }, prop: key, origin })\n\n\tfor (const key of newKeys) {\n\t\tif (!oldKeys.has(key)) {\n\t\t\tlocal.push({ target: oldObj, evolution: { type: 'add', prop: key }, prop: key, origin })\n\t\t\tcontinue\n\t\t}\n\t\tconst oldEntry = unwrap((oldObj as any)[key])\n\t\tconst newEntry = unwrap((newObj as any)[key])\n\t\tif (shouldRecurseTouch(oldEntry, newEntry)) {\n\t\t\trecursiveTouch(oldEntry, newEntry, visited, notifications, origin)\n\t\t} else if (!Object.is(oldEntry, newEntry)) {\n\t\t\tlocal.push({ target: oldObj, evolution: { type: 'set', prop: key }, prop: key, origin })\n\t\t}\n\t}\n\n\tnotifications.push(...local)\n}\n\n/**\n * Checks if an effect or any of its ancestors is in the allowed set\n */\nfunction hasAncestorInSet(\n\teffect: EffectTrigger | EffectCleanup,\n\tallowedSet: Set<EffectTrigger | EffectCleanup>\n): boolean {\n\tlet current: EffectTrigger | EffectCleanup | undefined = effect\n\tconst visited = new WeakSet<EffectTrigger | EffectCleanup>()\n\twhile (current && !visited.has(current)) {\n\t\tvisited.add(current)\n\t\tif (allowedSet.has(current)) return true\n\t\tconst node = getEffectNode(current as EffectTrigger)\n\t\tcurrent = node.parent\n\t}\n\treturn false\n}\n\nexport function dispatchNotifications(notifications: PendingNotification[]) {\n\tif (!notifications.length) return\n\tconst combinedEffects = new Set<EffectTrigger>()\n\tconst effectCauses = new Map<EffectTrigger, PendingNotification[]>()\n\n\t// Extract origin from first notification (all should have the same origin from a single deep touch)\n\tconst origin = notifications[0]?.origin\n\tlet allowedEffects: Set<EffectTrigger> | undefined\n\n\t// If origin exists, compute allowed effects (those that depend on origin.obj[origin.prop])\n\tif (origin) {\n\t\tallowedEffects = new Set<EffectTrigger>()\n\t\tconst originWatchers = watchers.get(origin.obj)\n\t\tif (originWatchers) {\n\t\t\tconst originEffects = new Map<EffectTrigger, unknown>()\n\t\t\tcollectEffects(\n\t\t\t\torigin.obj,\n\t\t\t\t{ type: 'set', prop: origin.prop },\n\t\t\t\toriginEffects,\n\t\t\t\toriginWatchers,\n\t\t\t\t[allProps],\n\t\t\t\t[origin.prop]\n\t\t\t)\n\t\t\tallowedEffects = new Set(originEffects.keys())\n\t\t}\n\t\t// If no allowed effects, skip all notifications (no one should be notified)\n\t\tif (!allowedEffects?.size) return\n\t}\n\n\tfor (const notification of notifications) {\n\t\tconst { target, evolution, prop } = notification\n\t\tif (typeof target !== 'object' && !Array.isArray(target)) continue\n\t\tconst obj = unwrap(target)\n\t\taddState(obj, evolution)\n\t\tconst objectWatchers = watchers.get(obj)\n\t\tlet currentEffects: Map<EffectTrigger, unknown> | undefined\n\t\tconst propsArray = [prop]\n\t\tif (objectWatchers) {\n\t\t\tcurrentEffects = new Map<EffectTrigger, unknown>()\n\t\t\tconst broad = evolution.type !== 'set' ? [allProps, keysOf] : [allProps]\n\t\t\tcollectEffects(obj, evolution, currentEffects, objectWatchers, broad, propsArray)\n\n\t\t\t// Filter effects by ancestor chain if origin exists\n\t\t\t// Include effects that either directly depend on origin or have an ancestor that does\n\t\t\tif (origin && allowedEffects) {\n\t\t\t\tconst filteredEffects = new Map<EffectTrigger, unknown>()\n\t\t\t\tfor (const [effect, associated] of currentEffects) {\n\t\t\t\t\t// Check if effect itself is allowed OR has an ancestor that is allowed\n\t\t\t\t\tif (allowedEffects.has(effect) || hasAncestorInSet(effect, allowedEffects)) {\n\t\t\t\t\t\tfilteredEffects.set(effect, associated)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcurrentEffects = filteredEffects\n\t\t\t}\n\n\t\t\tfor (const effect of currentEffects.keys()) {\n\t\t\t\tcombinedEffects.add(effect)\n\t\t\t\tlet causes = effectCauses.get(effect)\n\t\t\t\tif (!causes) {\n\t\t\t\t\tcauses = []\n\t\t\t\t\teffectCauses.set(effect, causes)\n\t\t\t\t}\n\t\t\t\tcauses.push(notification)\n\t\t\t}\n\t\t}\n\t\tif (currentEffects) {\n\t\t\toptionCall('touched', obj, evolution, propsArray, Array.from(currentEffects.keys()))\n\t\t}\n\t\tif (objectsWithDeepWatchers.has(obj)) bubbleUpChange(obj, evolution)\n\t}\n\tif (combinedEffects.size) {\n\t\tif (options.introspection?.gatherReasons) {\n\t\t\tconst gatherReasons = options.introspection.gatherReasons\n\t\t\tconst lineageConfig = gatherReasons.lineages\n\n\t\t\tlet touchLineage: unknown | undefined\n\t\t\tif (lineageConfig === 'touch' || lineageConfig === 'both') {\n\t\t\t\ttouchLineage = debugHooks.captureLineage()\n\t\t\t}\n\n\t\t\tfor (const effect of combinedEffects) {\n\t\t\t\tconst node = getEffectNode(effect)\n\t\t\t\tif (!node.pendingTriggers) node.pendingTriggers = []\n\t\t\t\tfor (const { target, evolution, prop } of effectCauses.get(effect)!) {\n\t\t\t\t\tconst dependencyStack =\n\t\t\t\t\t\tlineageConfig === 'dependency' || lineageConfig === 'both'\n\t\t\t\t\t\t\t? getDependencyStack(effect, unwrap(target), prop ?? allProps)\n\t\t\t\t\t\t\t: undefined\n\t\t\t\t\tnode.pendingTriggers.push({\n\t\t\t\t\t\tobj: unwrap(target),\n\t\t\t\t\t\tevolution,\n\t\t\t\t\t\tdependency: dependencyStack,\n\t\t\t\t\t\ttouch: touchLineage,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tbatch([...combinedEffects])\n\t}\n}\n","import { decorator } from '../decorator'\nimport { mixin } from '../mixins'\nimport { FoolProof, isOwnAccessor } from '../utils'\nimport { touched1 } from './change'\nimport { notifyPropertyChange } from './deep-touch'\nimport {\n\taddBackReference,\n\tbubbleUpChange,\n\tneedsBackReferences,\n\tobjectsWithDeepWatchers,\n\tremoveBackReference,\n} from './deep-watch-state'\nimport { getActiveEffect } from './effect-context'\nimport { absent, isNonReactive, isUnreactiveProp } from './non-reactive'\nimport { dependant } from './tracking'\nimport {\n\tgetExistingProxy,\n\tisReactive,\n\tkeysOf,\n\toptions,\n\tproxyToObject,\n\tReactiveError,\n\tReactiveErrorCode,\n\tstoreProxyRelationship,\n\tunwrap,\n} from './types'\nexport const metaProtos = new WeakMap()\nexport const wrapProtos = new WeakMap()\nconst arrayLengths = new WeakMap<unknown[], number>()\nconst hasReentry = new Set<PropertyKey>()\nexport type SubProxy = {\n\tget?(obj: any, prop: PropertyKey, receiver: any): any\n\thas?(obj: any, prop: PropertyKey): boolean\n\townKeys?(obj: any): ArrayLike<string | symbol>\n\tgetOwnPropertyDescriptor?(obj: any, prop: PropertyKey): PropertyDescriptor | undefined\n}\n// Sub-proxy registration for custom reactive behaviors\nconst subsRegister = new WeakMap<any, SubProxy>()\n// Internal untracked flag for setter/getter operations - only used when testing oldValue while setting a value\n// TODO: `touched` trigger also compares to old value and should use the internalUntracked flag\nlet internalUntracked = false\n\nfunction wrapReactiveValue(obj: any, prop: PropertyKey, value: any) {\n\tif (!isReactive(value) && typeof value === 'object' && value !== null) {\n\t\tconst reactiveValue = reactiveObject(value)\n\n\t\t// Only create back-references if this object needs them\n\t\tif (needsBackReferences(obj)) {\n\t\t\taddBackReference(reactiveValue, obj, prop)\n\t\t}\n\n\t\treturn reactiveValue\n\t}\n\treturn value\n}\n\nconst reactiveHandlers: ProxyHandler<any> & Record<symbol, unknown> = {\n\t[Symbol.toStringTag]: 'MutTs Reactive',\n\tget(obj, prop, receiver) {\n\t\tif (internalUntracked) return FoolProof.get(obj, prop, receiver)\n\t\tif (obj && typeof obj === 'object' && prop !== Symbol.toStringTag) {\n\t\t\tconst metaProto = metaProtos.get(obj.constructor)\n\t\t\tif (metaProto && Object.hasOwn(metaProto, prop)) {\n\t\t\t\tconst desc = Object.getOwnPropertyDescriptor(metaProto, prop)!\n\t\t\t\tif (desc.get) {\n\t\t\t\t\tif (!Object.hasOwn(obj, prop)) return desc.get.call(obj)\n\t\t\t\t\t// For own properties (e.g., array length): only override if writable/configurable\n\t\t\t\t\tconst ownDesc = Object.getOwnPropertyDescriptor(obj, prop)!\n\t\t\t\t\tif (ownDesc.configurable || ownDesc.writable || ownDesc.get) return desc.get.call(obj)\n\t\t\t\t} else if (!Object.hasOwn(obj, prop)) return (...args: any[]) => desc.value.apply(obj, args)\n\t\t\t}\n\t\t\tconst wrapProto = wrapProtos.get(obj.constructor)\n\t\t\tif (wrapProto && Object.hasOwn(wrapProto, prop)) return wrapProto[prop]\n\t\t}\n\t\t// Symbols: fast-path — no reactivity tracking\n\t\tif (typeof prop === 'symbol' || prop === 'constructor' || isUnreactiveProp(obj, prop))\n\t\t\treturn FoolProof.get(obj, prop, receiver)\n\n\t\tif (!getActiveEffect()) {\n\t\t\tconst value = (subsRegister.get(obj)?.get || FoolProof.get)(obj, prop, receiver)\n\t\t\treturn wrapReactiveValue(obj, prop, value)\n\t\t}\n\n\t\t// Check if property exists using a trap-free walk to avoid triggering\n\t\t// the has-trap cascade on prototype chains of reactive proxies.\n\t\tconst isOwnProp = Object.hasOwn(obj, prop)\n\n\t\t// For accessor properties, check the unwrapped object to see if it's an accessor\n\t\t// This ensures ignoreAccessors works correctly even after operations like Object.setPrototypeOf\n\t\t// Skip for null-proto objects (pounce scopes) — they never have accessors\n\t\tconst shouldIgnoreAccessor =\n\t\t\toptions.ignoreAccessors &&\n\t\t\tisOwnProp &&\n\t\t\tObject.getPrototypeOf(obj) !== null &&\n\t\t\t(isOwnAccessor(receiver, prop) || isOwnAccessor(obj, prop))\n\n\t\t// Check if property exists using a trap-free walk to avoid triggering\n\t\t// the has-trap cascade on prototype chains of reactive proxies.\n\t\tlet hasProp = isOwnProp\n\t\tlet owner: any = isOwnProp ? obj : undefined\n\t\tif (!isOwnProp) {\n\t\t\tlet raw = Object.getPrototypeOf(obj)\n\t\t\twhile (raw && raw !== Object.prototype) {\n\t\t\t\tif (Object.hasOwn(raw, prop)) {\n\t\t\t\t\thasProp = true\n\t\t\t\t\towner = raw\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\traw = Object.getPrototypeOf(raw)\n\t\t\t}\n\t\t}\n\t\tconst isInheritedAccess = hasProp && !isOwnProp\n\n\t\t// Depend if...\n\t\tif (\n\t\t\t!hasProp ||\n\t\t\t(!(options.instanceMembers && isInheritedAccess && obj instanceof Object) &&\n\t\t\t\t!shouldIgnoreAccessor)\n\t\t)\n\t\t\tdependant(obj, prop)\n\n\t\t// Two-Point Tracking: for inherited access on null-proto chains, also track\n\t\t// the owning ancestor so that writing directly to it triggers dependent effects.\n\t\tif (isInheritedAccess && owner && (!options.instanceMembers || !(obj instanceof Object))) {\n\t\t\tdependant(owner, prop)\n\t\t}\n\t\t// For arrays, use FoolProof.get (Indexer path) for numeric index reactivity.\n\t\t// For all other objects, inline Reflect.get directly (skips 3 function calls).\n\t\tconst value = (subsRegister.get(obj)?.get || FoolProof.get)(obj, prop, receiver)\n\t\treturn wrapReactiveValue(obj, prop, value)\n\t},\n\tset(obj, prop, value, receiver) {\n\t\tconst unwrapped = unwrap(receiver)\n\t\tif (obj !== unwrapped)\n\t\t\treturn Object.defineProperty(unwrapped, prop, {\n\t\t\t\tvalue,\n\t\t\t\tconfigurable: true,\n\t\t\t\twritable: true,\n\t\t\t\tenumerable: true,\n\t\t\t})\n\t\tif (internalUntracked)\n\t\t\tthrow new Error('Internal untracked: setting a value in an getter in a set operation')\n\t\t//return FoolProof.set(obj, prop, value, receiver)\n\n\t\t// Check if this property is marked as unreactive\n\t\tif (isUnreactiveProp(obj, prop)) return FoolProof.set(obj, prop, value, receiver)\n\t\tconst newValue = unwrap(value)\n\t\t// metaProto setter dispatch (e.g., reactive array length)\n\t\tif (obj && typeof obj === 'object' && prop !== Symbol.toStringTag) {\n\t\t\tconst metaProto = obj.constructor && metaProtos.get(obj.constructor)\n\t\t\tif (metaProto && Object.hasOwn(metaProto, prop)) {\n\t\t\t\tconst desc = Object.getOwnPropertyDescriptor(metaProto, prop)!\n\t\t\t\tif (desc.set) {\n\t\t\t\t\tdesc.set.call(obj, newValue)\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// Read old value, using withEffect(undefined, ...) for getter-only accessors to avoid\n\t\t// breaking memoization dependency tracking during SET operations\n\t\tlet oldVal = absent\n\t\tconst isArrayLength = prop === 'length' && Array.isArray(obj)\n\t\tinternalUntracked = true\n\t\ttry {\n\t\t\tif (Reflect.has(obj, prop)) {\n\t\t\t\toldVal = isArrayLength\n\t\t\t\t\t? arrayLengths.get(obj) === newValue\n\t\t\t\t\t\t? newValue\n\t\t\t\t\t\t: absent\n\t\t\t\t\t: Reflect.get(obj, prop, receiver)\n\t\t\t}\n\t\t} finally {\n\t\t\tinternalUntracked = false\n\t\t}\n\t\tif (objectsWithDeepWatchers.has(obj)) {\n\t\t\tif (typeof oldVal === 'object' && oldVal !== null) {\n\t\t\t\tremoveBackReference(oldVal, obj, prop)\n\t\t\t}\n\t\t\tif (typeof newValue === 'object' && newValue !== null) {\n\t\t\t\tconst reactiveValue = reactiveObject(newValue)\n\t\t\t\taddBackReference(reactiveValue, obj, prop)\n\t\t\t}\n\t\t}\n\t\tif (oldVal !== newValue) {\n\t\t\t// For getter-only accessors, Reflect.set() may fail, but we still return true\n\t\t\t// to avoid throwing errors. Only proceed with change notifications if set succeeded.\n\t\t\tif (FoolProof.set(obj, prop, newValue, receiver)) {\n\t\t\t\tif (isArrayLength) arrayLengths.set(obj, newValue)\n\t\t\t\tnotifyPropertyChange(obj, prop, oldVal, newValue, oldVal !== absent)\n\t\t\t}\n\t\t}\n\t\treturn true\n\t},\n\thas(obj, prop) {\n\t\tif (hasReentry.has(obj))\n\t\t\tthrow new ReactiveError(\n\t\t\t\t`[reactive] Circular dependency detected in 'has' check for property '${String(prop)}'`,\n\t\t\t\t{\n\t\t\t\t\tcode: ReactiveErrorCode.CycleDetected,\n\t\t\t\t\tcycle: [], // We don't have the full cycle here, but we know it involves obj\n\t\t\t\t}\n\t\t\t)\n\t\thasReentry.add(obj)\n\t\tif (!internalUntracked && !isUnreactiveProp(obj, prop)) dependant(obj, prop)\n\t\tconst rv = (subsRegister.get(obj)?.has || Reflect.has)(obj, prop)\n\t\thasReentry.delete(obj)\n\t\treturn rv\n\t},\n\tdeleteProperty(obj, prop) {\n\t\tif (!Object.hasOwn(obj, prop)) return false\n\n\t\tconst oldVal = (obj as any)[prop]\n\n\t\t// Remove back-references if this object has deep watchers\n\t\tif (objectsWithDeepWatchers.has(obj) && typeof oldVal === 'object' && oldVal !== null) {\n\t\t\tremoveBackReference(oldVal, obj, prop)\n\t\t}\n\n\t\tdelete (obj as any)[prop]\n\t\ttouched1(obj, { type: 'del', prop }, prop)\n\n\t\t// Bubble up changes if this object has deep watchers\n\t\tif (objectsWithDeepWatchers.has(obj)) {\n\t\t\tbubbleUpChange(obj, { type: 'del', prop })\n\t\t}\n\n\t\treturn true\n\t},\n\townKeys(obj) {\n\t\tdependant(obj, keysOf)\n\t\treturn subsRegister.get(obj)?.ownKeys?.(obj) || Reflect.ownKeys(obj)\n\t},\n\tgetOwnPropertyDescriptor(obj, prop) {\n\t\treturn (\n\t\t\tsubsRegister.get(obj)?.getOwnPropertyDescriptor?.(obj, prop) ||\n\t\t\tReflect.getOwnPropertyDescriptor(obj, prop)\n\t\t)\n\t},\n}\n\nconst reactiveClasses = new WeakSet<Function>()\n\n// Create the ReactiveBase mixin\n/**\n * Base mixin for reactive classes that provides proper constructor reactivity\n * Solves constructor reactivity issues in complex inheritance trees\n */\nexport const ReactiveBase = mixin((base) => {\n\tclass ReactiveMixin extends base {\n\t\tconstructor(...args: any[]) {\n\t\t\tsuper(...args)\n\t\t\t// Only apply reactive transformation if the class is marked with @reactive\n\t\t\t// This allows the mixin to work properly with method inheritance\n\t\t\t// biome-ignore lint/correctness/noConstructorReturn: This is the whole point here\n\t\t\treturn reactiveClasses.has(new.target) ? reactive(this) : this\n\t\t}\n\t}\n\treturn ReactiveMixin\n})\nfunction reactiveObject<T>(anyTarget: T, subProxy?: SubProxy): T {\n\tif (!anyTarget || typeof anyTarget !== 'object') return anyTarget\n\tconst target = anyTarget as any\n\t// If target is already a proxy, return it\n\tif (isNonReactive(target)) return target as T\n\tconst isProxy = proxyToObject.has(target)\n\tif (isProxy) return target as T\n\n\t// If we already have a proxy for this object, return it (optimized: get returns undefined if not found)\n\tconst existing = getExistingProxy(target)\n\tif (existing !== undefined) return existing as T\n\n\tif (subProxy) subsRegister.set(target, subProxy)\n\tconst proxy = new Proxy(target, reactiveHandlers)\n\tif (Array.isArray(target)) arrayLengths.set(target, target.length)\n\t// Store the relationships\n\tstoreProxyRelationship(target, proxy)\n\treturn proxy as T\n}\n\n/**\n * Main decorator for making classes reactive\n * Automatically makes class instances reactive when created\n */\nexport const reactive = decorator({\n\tclass(original) {\n\t\tif (original.prototype instanceof ReactiveBase) {\n\t\t\treactiveClasses.add(original)\n\t\t\treturn original\n\t\t}\n\n\t\tclass Reactive extends original {\n\t\t\tconstructor(...args: any[]) {\n\t\t\t\tsuper(...args)\n\t\t\t\tif (new.target !== Reactive && !reactiveClasses.has(new.target))\n\t\t\t\t\toptions.warn(\n\t\t\t\t\t\t`${(original as any).name} has been inherited by ${this.constructor.name} that is not reactive.\n@reactive decorator must be applied to the leaf class OR classes have to extend ReactiveBase.`\n\t\t\t\t\t)\n\t\t\t\t// biome-ignore lint/correctness/noConstructorReturn: This is the whole point here\n\t\t\t\treturn reactive(this)\n\t\t\t}\n\t\t}\n\t\tObject.defineProperty(Reactive, 'name', {\n\t\t\tvalue: `Reactive<${original.name}>`,\n\t\t})\n\t\treturn Reactive as any\n\t},\n\tget(original: any) {\n\t\treturn reactiveObject(original)\n\t},\n\tdefault: reactiveObject,\n})\n","import { arrayDiff } from '../diff'\nimport { type Captioned, captioned, flavored } from '../flavored'\nimport { tag } from '../utils'\nimport type { GetterWrapper } from '../zone'\nimport { getState, touched, touched1 } from './change'\nimport { chainExternalReason, getActiveEffect, link } from './effect-context'\nimport { effect } from './effects'\nimport { reactive } from './proxy'\nimport { getEffectNode, markWithRoot } from './registry'\nimport { dependant } from './tracking'\nimport {\n\ttype CleanupReason,\n\ttype EffectAccess,\n\ttype EffectCloser,\n\tisReactive,\n\tkeysOf,\n\toptions,\n\ttype ScopedCallback,\n\ttype State,\n} from './types'\n\n/**\n * Reactively attends to each entry of a collection or each key yielded by an\n * enumeration callback. For each key, an inner effect runs the callback. When a\n * key disappears, its inner effect is disposed. The callback may return a cleanup\n * (like a regular effect closer).\n *\n * Accepts arrays, records, Maps, Sets, or a raw `() => Iterable<Key>` callback.\n *\n * @example\n * ```typescript\n * // Record shorthand\n * attend(record, (key) => { console.log(key, record[key]) })\n *\n * // Array shorthand\n * attend(array, (index) => { console.log(index, array[index]) })\n *\n * // Raw enumeration callback\n * attend(() => Object.keys(record), (key) => { ... })\n * ```\n */\nexport interface Attend\n\textends Captioned<\n\t\t(\n\t\t\tsource: any,\n\t\t\tcallback: (key: any, access: EffectAccess) => EffectCloser | void\n\t\t) => ScopedCallback\n\t> {\n\t<T>(\n\t\tsource: readonly T[],\n\t\tcallback: (index: number, access: EffectAccess) => EffectCloser | void\n\t): ScopedCallback\n\t<K, V>(\n\t\tsource: Map<K, V>,\n\t\tcallback: (key: K, access: EffectAccess) => EffectCloser | void\n\t): ScopedCallback\n\t<T>(\n\t\tsource: Set<T>,\n\t\tcallback: (value: T, access: EffectAccess) => EffectCloser | void\n\t): ScopedCallback\n\t<S extends object>(\n\t\tsource: S,\n\t\tcallback: (key: keyof S & string, access: EffectAccess) => EffectCloser | void\n\t): ScopedCallback\n\t<Key>(\n\t\tenumerate: () => Iterable<Key>,\n\t\tcallback: (key: Key, access: EffectAccess) => EffectCloser | void\n\t): ScopedCallback\n}\n\nexport const attend: Attend = captioned(\n\tfunction attend(\n\t\tsource: any,\n\t\tcallback: (key: any, access: EffectAccess) => EffectCloser | void\n\t): ScopedCallback {\n\t\tconst enumerate: () => Iterable<any> =\n\t\t\ttypeof source === 'function'\n\t\t\t\t? source\n\t\t\t\t: Array.isArray(source)\n\t\t\t\t\t? () => Array.from({ length: source.length }, (_, i) => i)\n\t\t\t\t\t: source instanceof Map\n\t\t\t\t\t\t? () => source.keys()\n\t\t\t\t\t\t: source instanceof Set\n\t\t\t\t\t\t\t? () => source.values()\n\t\t\t\t\t\t\t: () => Object.keys(source)\n\n\t\tconst keyEffects = new Map<any, ScopedCallback>()\n\t\tconst callbackLabel = callback.name ? callback.name : ''\n\n\t\tconst outer = effect`attend`(({ ascend }) => {\n\t\t\tconst keys = new Set<any>()\n\t\t\tfor (const key of enumerate()) keys.add(key)\n\n\t\t\tfor (const key of keys) {\n\t\t\t\tif (keyEffects.has(key)) continue\n\t\t\t\tconst indexRef = { value: key }\n\t\t\t\tkeyEffects.set(\n\t\t\t\t\tkey,\n\t\t\t\t\tascend(() =>\n\t\t\t\t\t\teffect`attend${callbackLabel ? `:${callbackLabel}` : ''}:${key}`(\n\t\t\t\t\t\t\t(access) => callback(indexRef.value, access)\n\t\t\t\t\t\t)\n\t\t\t\t\t)\n\t\t\t\t)\n\t\t\t}\n\n\t\t\tfor (const key of Array.from(keyEffects.keys())) {\n\t\t\t\tif (!keys.has(key)) {\n\t\t\t\t\tkeyEffects.get(key)!()\n\t\t\t\t\tkeyEffects.delete(key)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\n\t\treturn (reason?: CleanupReason) => {\n\t\t\touter(reason)\n\t\t\tfor (const stop of keyEffects.values()) stop(reason)\n\t\t\tkeyEffects.clear()\n\t\t}\n\t},\n\t{\n\t\tname: 'attend',\n\t\tcallbackIndex: 1,\n\t\twarn: (message) => options.warn(`[reactive] ${message}`),\n\t}\n) as Attend\n\n/**\n * Lifts a callback that returns an array into a reactive array that automatically\n * synchronizes with the source array returned by the callback.\n *\n * The returned reactive array will update whenever the callback's dependencies change,\n * efficiently syncing only the elements that differ from the previous result.\n *\n * @example\n * ```typescript\n * const items = reactive([1, 2, 3])\n * const doubled = lift(() => items.map(x => x * 2))\n *\n * console.log([...doubled]) // [2, 4, 6]\n *\n * items.push(4)\n * console.log([...doubled]) // [2, 4, 6, 8]\n * ```\n *\n * @param cb Callback function that returns an array\n * @returns A reactive array synchronized with the callback's result, with a [cleanup] property to stop tracking\n */\nexport interface Lift {\n\t<Output extends any[]>(cb: (access: EffectAccess) => Output): Output\n\t<Output extends object>(cb: (access: EffectAccess) => Output): Output\n\t(strings: TemplateStringsArray, ...values: readonly unknown[]): Lift\n}\n\n/**\n * Lifts a callback that returns an object into a reactive object that automatically\n * synchronizes with the source object returned by the callback.\n *\n * The returned reactive object will update whenever the callback's dependencies change,\n * efficiently syncing only the properties that differ from the previous result using\n * Object.assign(). Properties that no longer exist in the source are automatically removed.\n *\n * @example\n * ```typescript\n * const user = reactive({ name: 'John', age: 30 })\n * const profile = lift(() => ({\n * displayName: user.name.toUpperCase(),\n * isAdult: user.age >= 18,\n * description: `${user.name} is ${user.age} years old`\n * }))\n *\n * console.log(profile.displayName) // JOHN\n * console.log(profile.isAdult) // true\n *\n * user.name = 'Jane'\n * console.log(profile.displayName) // JANE\n * console.log(profile.description) // Jane is 30 years old\n * ```\n *\n * @param cb Callback function that returns an object\n * @returns A reactive object synchronized with the callback's result, with a [cleanup] property to stop tracking\n */\nexport const lift: Lift = captioned(\n\tfunction lift<Output extends any[] | object>(cb: (access: EffectAccess) => Output): Output {\n\t\tlet result!: Output\n\t\tlet rawResult!: Output\n\t\tconst resultName = `lift:${cb.name || 'anonymous'}`\n\t\tconst liftCleanup = effect`lift:${cb.name}`(\n\t\t\tmarkWithRoot((access) => {\n\t\t\t\tconst source = cb(access)\n\t\t\t\tif (!source || typeof source !== 'object')\n\t\t\t\t\tthrow new Error('lift callback must return an array or object')\n\t\t\t\tconst sourceProto = Object.getPrototypeOf(source)\n\t\t\t\tif (!result) {\n\t\t\t\t\trawResult = tag(resultName, Array.isArray(source) ? [] : Object.create(sourceProto))\n\t\t\t\t\tresult = reactive(rawResult)\n\t\t\t\t}\n\t\t\t\tif (sourceProto !== Object.getPrototypeOf(result))\n\t\t\t\t\tthrow new Error('lift callback must return the same type as the previous result')\n\n\t\t\t\tif (Array.isArray(source)) {\n\t\t\t\t\tconst res = result as unknown[]\n\t\t\t\t\tfor (const { indexA, sliceA, sliceB } of arrayDiff(res, source).sort(\n\t\t\t\t\t\t(a, b) => a.indexA - b.indexA\n\t\t\t\t\t))\n\t\t\t\t\t\tres.splice(indexA, sliceA.length, ...sliceB)\n\t\t\t\t} else {\n\t\t\t\t\tconst recordResult = rawResult as Record<string, unknown>\n\t\t\t\t\tfor (const key of Object.keys(source)) {\n\t\t\t\t\t\tconst had = key in rawResult\n\t\t\t\t\t\tconst newDesc = Object.getOwnPropertyDescriptor(source, key)!\n\t\t\t\t\t\tif (had) {\n\t\t\t\t\t\t\tconst oldDesc = Object.getOwnPropertyDescriptor(rawResult, key)\n\t\t\t\t\t\t\tconst sameAccessor = oldDesc && newDesc.get && oldDesc.get === newDesc.get\n\t\t\t\t\t\t\tObject.defineProperty(rawResult, key, newDesc)\n\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t!sameAccessor &&\n\t\t\t\t\t\t\t\trecordResult[key] !==\n\t\t\t\t\t\t\t\t\t(oldDesc ? (oldDesc.get ? oldDesc.get() : oldDesc.value) : undefined)\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\ttouched1(rawResult, { type: 'set', prop: key }, key)\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tObject.defineProperty(rawResult, key, newDesc)\n\t\t\t\t\t\t\ttouched1(rawResult, { type: 'add', prop: key }, key)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tfor (const key of Object.keys(rawResult))\n\t\t\t\t\t\tif (!(key in source)) {\n\t\t\t\t\t\t\tdelete recordResult[key]\n\t\t\t\t\t\t\ttouched1(rawResult, { type: 'del', prop: key }, key)\n\t\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}, cb)\n\t\t)\n\t\treturn link(result, liftCleanup)\n\t},\n\t{\n\t\tname: 'lift',\n\t\twarn: (message) => options.warn(`[reactive] ${message}`),\n\t}\n) as Lift\n\n/**\n * Options for `morph` and its variants.\n *\n * @property pure - When `true`, the mapping function is assumed pure (no reactive reads inside `fn`).\n * Per-item effects are skipped and items are computed eagerly. When a predicate `(i) => boolean`,\n * purity is evaluated per item — pure items skip the effect wrapper, non-pure items get their own.\n */\nexport type MorphOptions<I> = { pure?: boolean | ((i: I) => boolean) }\n\n/**\n * Reactively maps an array source through `fn`, producing a lazy reactive output array.\n *\n * Each source item gets its own isolated effect (via `root()`) so that changes to one item\n * only recompute that item's projection. Structural changes (push, splice, reorder) are detected\n * via `arrayDiff` and surgically applied to the output cache.\n *\n * The source can be a reactive array or a function returning an array. When a function is provided,\n * the function is re-evaluated inside an effect whenever its dependencies change.\n *\n * Output elements are computed lazily — accessing `result[i]` triggers computation if not yet cached.\n *\n * @param source - A reactive array or a function returning an array\n * @param fn - Mapping function applied to each element\n * @param options - Optional purity hints to skip per-item effects\n * @returns A readonly reactive array with a `[cleanup]` method to dispose all effects\n */\nexport function morphArray<I, O>(\n\tsource: readonly I[] | (() => readonly I[]),\n\tfn: (arg: I, access?: EffectAccess) => O,\n\toptions?: MorphOptions<I>\n): readonly O[] {\n\tif (typeof source !== 'function' && !isReactive(source) && options?.pure === true) {\n\t\treturn source.map((i) => fn(i)) as any\n\t}\n\n\tlet track!: GetterWrapper\n\tconst itemEffects = new Map<any, { stop: ScopedCallback; index: { value: number } }>()\n\tconst cache = tag(`morph:${fn.name || 'anonymous'}`, [] as O[])\n\tlet input: readonly I[] = []\n\n\tfunction stopItem(key: any) {\n\t\tconst entry = itemEffects.get(key)\n\t\tif (entry) {\n\t\t\tconst activeEffect = getActiveEffect()\n\t\t\tlet chain: CleanupReason | undefined\n\t\t\tif (activeEffect) {\n\t\t\t\tconst node = getEffectNode(activeEffect)\n\t\t\t\tchain = node.currentReason\n\t\t\t}\n\t\t\tentry.stop(chainExternalReason({ type: 'stopped', chain }))\n\t\t\titemEffects.delete(key)\n\t\t}\n\t}\n\n\tfunction computeItem(key: number, input: I) {\n\t\tconst isPure =\n\t\t\toptions?.pure === true || (typeof options?.pure === 'function' && options.pure(input))\n\t\tif (isPure) {\n\t\t\ttrack(() => {\n\t\t\t\tcache[key] = fn(input)\n\t\t\t})\n\t\t} else {\n\t\t\tconst indexRef = { value: key }\n\t\t\tconst stop = track(() =>\n\t\t\t\teffect.opaque`morph:${fn.name}:${key}`((access) => {\n\t\t\t\t\tcache[indexRef.value] = fn(input, access)\n\t\t\t\t\treturn (reason) => {\n\t\t\t\t\t\tdelete cache[indexRef.value]\n\t\t\t\t\t\ttouched1(cache, { type: 'invalidate', prop: 'morph' }, String(key))\n\t\t\t\t\t\tconst activeEffect = getActiveEffect()\n\t\t\t\t\t\tlet chain: CleanupReason | undefined\n\t\t\t\t\t\tif (activeEffect) {\n\t\t\t\t\t\t\tconst node = getEffectNode(activeEffect)\n\t\t\t\t\t\t\tchain = node.currentReason\n\t\t\t\t\t\t}\n\t\t\t\t\t\tstop?.({\n\t\t\t\t\t\t\ttype: 'invalidate',\n\t\t\t\t\t\t\tcause: chainExternalReason(reason ?? { type: 'stopped', chain })!,\n\t\t\t\t\t\t\tchain: chainExternalReason(chain),\n\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t)\n\t\t\titemEffects.set(key, { stop, index: indexRef })\n\t\t}\n\t}\n\n\tconst proxy = reactive(cache, {\n\t\tget(cache, prop) {\n\t\t\tconst n = typeof prop === 'string' ? Number(prop) : NaN\n\t\t\tif (Number.isNaN(n)) return cache[prop]\n\t\t\tif (!(n in cache)) computeItem(n, input[n])\n\t\t\treturn cache[n]\n\t\t},\n\t\thas(_cache, prop) {\n\t\t\treturn Reflect.has(input, prop)\n\t\t},\n\t})\n\n\tconst stopMain = effect`morph:${fn.name}`(({ ascend }) => {\n\t\ttrack = ascend\n\t\tconst newInput = [...(typeof source === 'function' ? source() : source)]\n\t\tconst diffs = arrayDiff(input, newInput).toSorted((a, b) => b.indexA - a.indexA)\n\n\t\tif (diffs.length > 0) {\n\t\t\tfor (const diff of diffs) {\n\t\t\t\t// Stop items in removed range\n\t\t\t\tfor (let i = diff.indexA; i < diff.indexA + diff.sliceA.length; i++) stopItem(i)\n\n\t\t\t\t// Shift existing itemEffects in the Map to match the new indices\n\t\t\t\tconst shift = diff.sliceB.length - diff.sliceA.length\n\t\t\t\tif (shift !== 0) {\n\t\t\t\t\t// We need to move entries in the Map.\n\t\t\t\t\tconst entries = Array.from(itemEffects.entries()).sort((a, b) => a[0] - b[0])\n\t\t\t\t\t// Remove entries that will be shifted\n\t\t\t\t\tfor (const [idx, _entry] of entries) {\n\t\t\t\t\t\tif (idx >= diff.indexA + diff.sliceA.length) {\n\t\t\t\t\t\t\titemEffects.delete(idx)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t// Re-add them with shifted indices\n\t\t\t\t\tfor (const [idx, entry] of entries) {\n\t\t\t\t\t\tif (idx >= diff.indexA + diff.sliceA.length) {\n\t\t\t\t\t\t\tconst newIdx = idx + shift\n\t\t\t\t\t\t\tentry.index.value = newIdx\n\t\t\t\t\t\t\titemEffects.set(newIdx, entry)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Splice the cache\n\t\t\t\tcache.splice(\n\t\t\t\t\tdiff.indexA,\n\t\t\t\t\tdiff.sliceA.length,\n\t\t\t\t\t...new Array(diff.sliceB.length).fill(undefined)\n\t\t\t\t)\n\n\t\t\t\t// Make holes for lazy computation\n\t\t\t\tfor (let i = diff.indexA; i < diff.indexA + diff.sliceB.length; i++) delete cache[i]\n\t\t\t}\n\n\t\t\tconst invalidates = new Set<PropertyKey>([keysOf])\n\t\t\tif (input.length !== newInput.length) invalidates.add('length')\n\t\t\tfor (const diff of diffs) {\n\t\t\t\tconst max = Math.max(diff.sliceA.length, diff.sliceB.length)\n\t\t\t\tfor (let i = 0; i < max; i++) invalidates.add(String(diff.indexA + i))\n\t\t\t}\n\t\t\ttouched(cache, { type: 'bunch', method: 'morph-input' }, invalidates)\n\t\t}\n\n\t\tinput = newInput\n\t})\n\n\treturn link(proxy, (reason) => {\n\t\tstopMain(reason)\n\t\tfor (const entry of itemEffects.values()) entry.stop(reason)\n\t\titemEffects.clear()\n\t})\n}\n\n/**\n * Reactively maps a `Map` source through `fn`, producing a reactive output Map.\n *\n * Each key gets its own isolated effect so that value changes for one key only recompute\n * that key's projection. Key additions and removals are tracked via `keysOf` dependency.\n *\n * @param source - A reactive Map\n * @param fn - Mapping function applied to each value\n * @param options - Optional purity hints to skip per-key effects\n * @returns A reactive Map with a `[cleanup]` method to dispose all effects\n */\nexport function morphMap<K, V, O>(\n\tsource: Map<K, V>,\n\tfn: (arg: V, key: K, access?: EffectAccess) => O,\n\toptions?: MorphOptions<V>\n): Map<K, O> {\n\tif (!isReactive(source) && options?.pure === true) {\n\t\tconst res = new Map<K, O>()\n\t\tfor (const [k, v] of source) res.set(k, fn(v, k))\n\t\treturn res as any\n\t}\n\n\tlet track!: GetterWrapper\n\tconst itemEffects = new Map<any, ScopedCallback>()\n\tconst cache = tag(`morph:${fn.name || 'anonymous'}`, new Map<K, O>())\n\tObject.defineProperty(cache, 'constructor', { value: Object, enumerable: false })\n\n\tfunction stopItem(key: any) {\n\t\tconst stop = itemEffects.get(key)\n\t\tif (stop) {\n\t\t\tconst activeEffect = getActiveEffect()\n\t\t\tlet chain: CleanupReason | undefined\n\t\t\tif (activeEffect) {\n\t\t\t\tconst node = getEffectNode(activeEffect)\n\t\t\t\tchain = node.currentReason\n\t\t\t}\n\t\t\tstop({ type: 'stopped', chain })\n\t\t\titemEffects.delete(key)\n\t\t}\n\t}\n\n\tfunction computeItem(key: any, val: any) {\n\t\tconst isPure =\n\t\t\toptions?.pure === true || (typeof options?.pure === 'function' && options.pure(val))\n\t\tif (isPure) {\n\t\t\tcache.set(\n\t\t\t\tkey,\n\t\t\t\ttrack(() => fn(val, key))\n\t\t\t)\n\t\t} else {\n\t\t\tconst stop = track(() =>\n\t\t\t\teffect.opaque`morph:${fn.name}:${key}`((access) => {\n\t\t\t\t\tconst next = source.get(key)\n\t\t\t\t\tif (next === undefined && !source.has(key)) return\n\t\t\t\t\tcache.set(key, fn(next as V, key, access))\n\t\t\t\t\treturn (reason) => {\n\t\t\t\t\t\tcache.delete(key)\n\t\t\t\t\t\ttouched1(cache, { type: 'invalidate', prop: 'morph' }, String(key))\n\t\t\t\t\t\tconst activeEffect = getActiveEffect()\n\t\t\t\t\t\tlet chain: CleanupReason | undefined\n\t\t\t\t\t\tif (activeEffect) {\n\t\t\t\t\t\t\tconst node = getEffectNode(activeEffect)\n\t\t\t\t\t\t\tchain = node.currentReason\n\t\t\t\t\t\t}\n\t\t\t\t\t\tstop?.({\n\t\t\t\t\t\t\ttype: 'invalidate',\n\t\t\t\t\t\t\tcause: chainExternalReason(reason ?? { type: 'stopped', chain })!,\n\t\t\t\t\t\t\tchain: chainExternalReason(chain),\n\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t)\n\t\t\titemEffects.set(key, stop)\n\t\t}\n\t}\n\n\tconst proxy = reactive(cache, {\n\t\tget(cache, prop) {\n\t\t\tif (prop === 'get')\n\t\t\t\treturn (key: any) => {\n\t\t\t\t\tif (!cache.has(key) && source.has(key)) computeItem(key, source.get(key))\n\t\t\t\t\treturn cache.get(key)\n\t\t\t\t}\n\t\t\tif (prop === 'has')\n\t\t\t\treturn (key: any) => {\n\t\t\t\t\treturn source.has(key)\n\t\t\t\t}\n\t\t\tif (prop === 'keys')\n\t\t\t\treturn () => {\n\t\t\t\t\treturn source.keys()\n\t\t\t\t}\n\t\t\tif (prop === 'values')\n\t\t\t\treturn function* () {\n\t\t\t\t\tfor (const key of source.keys()) {\n\t\t\t\t\t\tyield proxy.get(key)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tif (prop === 'entries')\n\t\t\t\treturn function* () {\n\t\t\t\t\tfor (const key of source.keys()) {\n\t\t\t\t\t\tyield [key, proxy.get(key)]\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tif (prop === Symbol.iterator)\n\t\t\t\treturn function* () {\n\t\t\t\t\tfor (const key of source.keys()) {\n\t\t\t\t\t\tyield [key, proxy.get(key)]\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\treturn (cache as any)[prop]\n\t\t},\n\t}) as any\n\n\tlet stateSnapshot: State = getState(source)\n\tconst stopMain = effect`morph:${fn.name}`(({ ascend }) => {\n\t\ttrack = ascend\n\t\tdependant(source, keysOf)\n\t\twhile ('evolution' in stateSnapshot) {\n\t\t\tconst { evolution } = stateSnapshot\n\t\t\tstateSnapshot = stateSnapshot.next\n\t\t\tif (evolution.type === 'add') {\n\t\t\t\ttouched1(cache, evolution, evolution.prop)\n\t\t\t} else if (evolution.type === 'del') {\n\t\t\t\tstopItem(evolution.prop)\n\t\t\t\tcache.delete(evolution.prop)\n\t\t\t\ttouched1(cache, evolution, evolution.prop)\n\t\t\t}\n\t\t}\n\t})\n\n\treturn link(proxy, (reason) => {\n\t\tstopMain(reason)\n\t\tfor (const stop of itemEffects.values()) stop(reason)\n\t\titemEffects.clear()\n\t})\n}\n\n/**\n * Reactively maps a record/object source through `fn`, producing a reactive output record.\n *\n * Each key gets its own isolated effect so that value changes for one key only recompute\n * that key's projection. Key additions and removals are tracked automatically.\n *\n * @param source - A reactive record\n * @param fn - Mapping function applied to each value\n * @param options - Optional purity hints to skip per-key effects\n * @returns A reactive record with a `[cleanup]` method to dispose all effects\n */\nexport function morphRecord<S extends Record<PropertyKey, any>, O>(\n\tsource: S,\n\tfn: (arg: S[keyof S], key: keyof S, access?: EffectAccess) => O,\n\toptions?: MorphOptions<S[keyof S]>\n): { [K in keyof S]: O } {\n\tif (!isReactive(source) && options?.pure === true) {\n\t\tconst res = {} as any\n\t\tfor (const k of Object.keys(source)) res[k] = fn(source[k], k)\n\t\treturn res\n\t}\n\n\tlet track!: GetterWrapper\n\tconst itemEffects = new Map<any, ScopedCallback>()\n\tconst cache = {} as any\n\n\tfunction stopItem(key: any) {\n\t\tconst stop = itemEffects.get(key)\n\t\tif (stop) {\n\t\t\tconst activeEffect = getActiveEffect()\n\t\t\tlet chain: CleanupReason | undefined\n\t\t\tif (activeEffect) {\n\t\t\t\tconst node = getEffectNode(activeEffect)\n\t\t\t\tchain = node.currentReason\n\t\t\t}\n\t\t\tstop({ type: 'stopped', chain })\n\t\t\titemEffects.delete(key)\n\t\t}\n\t}\n\n\tfunction computeItem(key: any, val: any) {\n\t\tconst isPure =\n\t\t\toptions?.pure === true || (typeof options?.pure === 'function' && options.pure(val))\n\t\tif (isPure) {\n\t\t\tcache[key] = track(() => fn(val, key))\n\t\t} else {\n\t\t\tconst stop = track(() =>\n\t\t\t\teffect.opaque`morph:${fn.name}:${key}`((access) => {\n\t\t\t\t\tcache[key] = fn(source[key], key, access)\n\t\t\t\t\treturn (reason) => {\n\t\t\t\t\t\tdelete cache[key]\n\t\t\t\t\t\ttouched1(cache, { type: 'invalidate', prop: 'morph' }, String(key))\n\t\t\t\t\t\tconst activeEffect = getActiveEffect()\n\t\t\t\t\t\tlet chain: CleanupReason | undefined\n\t\t\t\t\t\tif (activeEffect) {\n\t\t\t\t\t\t\tconst node = getEffectNode(activeEffect)\n\t\t\t\t\t\t\tchain = node.currentReason\n\t\t\t\t\t\t}\n\t\t\t\t\t\tstop?.({\n\t\t\t\t\t\t\ttype: 'invalidate',\n\t\t\t\t\t\t\tcause: chainExternalReason(reason ?? { type: 'stopped', chain })!,\n\t\t\t\t\t\t\tchain: chainExternalReason(chain),\n\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t)\n\t\t\titemEffects.set(key, stop)\n\t\t}\n\t}\n\tfunction get(prop: PropertyKey) {\n\t\tif (!(prop in cache) && prop in source) computeItem(prop, source[prop])\n\t\treturn cache[prop]\n\t}\n\tconst proxy = reactive(cache, {\n\t\tget(_, prop) {\n\t\t\treturn get(prop)\n\t\t},\n\t\thas(_, prop) {\n\t\t\treturn prop in source\n\t\t},\n\t\townKeys() {\n\t\t\treturn Reflect.ownKeys(source)\n\t\t},\n\t\tgetOwnPropertyDescriptor(_cache, prop) {\n\t\t\tif (prop in source) return { configurable: true, enumerable: true, get: () => get(prop) }\n\t\t},\n\t})\n\n\tlet stateSnapshot: State = getState(source)\n\tconst stopMain = effect`morph:${fn.name}`(({ ascend }) => {\n\t\ttrack = ascend\n\t\t// Track only structural changes on source\n\t\tdependant(source, keysOf)\n\t\twhile ('evolution' in stateSnapshot) {\n\t\t\tconst { evolution } = stateSnapshot\n\t\t\tstateSnapshot = stateSnapshot.next\n\t\t\tif (evolution.type === 'add') {\n\t\t\t\ttouched1(cache, evolution, evolution.prop)\n\t\t\t} else if (evolution.type === 'del') {\n\t\t\t\tstopItem(evolution.prop)\n\t\t\t\tdelete cache[evolution.prop]\n\t\t\t\ttouched1(cache, evolution, evolution.prop)\n\t\t\t}\n\t\t}\n\t})\n\n\treturn link(proxy, (reason) => {\n\t\tstopMain(reason)\n\t\tfor (const stop of itemEffects.values()) stop(reason)\n\t\titemEffects.clear()\n\t})\n}\n\n/**\n * Unified reactive collection mapper. Dispatches to `morphArray`, `morphMap`, or `morphRecord`\n * based on the source type. Access `morph.pure(source, fn)` for the `{ pure: true }` shorthand.\n *\n * @see morphArray\n * @see morphMap\n * @see morphRecord\n */\nexport type Morph = {\n\t<I, O>(\n\t\tsource: readonly I[] | (() => readonly I[]),\n\t\tfn: (arg: I, access?: EffectAccess) => O,\n\t\toptions?: MorphOptions<I>\n\t): readonly O[]\n\n\t<K, V, O>(\n\t\tsource: Map<K, V>,\n\t\tfn: (arg: V, key: K, access?: EffectAccess) => O,\n\t\toptions?: MorphOptions<V>\n\t): Map<K, O>\n\n\t<S extends Record<PropertyKey, any>, O>(\n\t\tsource: S,\n\t\tfn: (arg: S[keyof S], key: keyof S, access?: EffectAccess) => O,\n\t\toptions?: MorphOptions<S[keyof S]>\n\t): { [K in keyof S]: O }\n\n\t(strings: TemplateStringsArray, ...values: readonly unknown[]): Morph\n\tpure: Morph\n}\n\n/**\n * Reactively maps a collection (array, Map, or record) through a per-entry function.\n *\n * Each entry in the source gets its own reactive context — when only one entry's dependencies\n * change, only that entry's projection recomputes. Structural changes (additions, removals,\n * reorders) are detected via diffing and applied surgically.\n *\n * Use `morph.pure(source, fn)` when `fn` has no reactive reads (skips per-item effects).\n *\n * @example\n * ```ts\n * const users = reactive([{ name: 'John' }, { name: 'Jane' }])\n * const names = morph(users, u => u.name.toUpperCase())\n * // names[0] = 'JOHN', names[1] = 'JANE'\n * // Changing users[0].name only recomputes names[0]\n * ```\n */\nexport const morph = captioned(\n\tflavored(\n\t\tfunction morph(source: any, fn: any, options?: any): any {\n\t\t\tif (Array.isArray(source) || typeof source === 'function')\n\t\t\t\treturn morphArray(source, fn, options)\n\t\t\tif (source instanceof Map) return morphMap(source, fn, options)\n\t\t\treturn morphRecord(source, fn, options)\n\t\t},\n\t\t{\n\t\t\tget pure() {\n\t\t\t\treturn (source: any, fn: any, _opt: unknown) => this(source, fn, { pure: true })\n\t\t\t},\n\t\t}\n\t),\n\t{\n\t\tname: 'morph',\n\t\tcallbackIndex: 1,\n\t\twarn: (message) => options.warn(`[reactive] ${message}`),\n\t}\n) as Morph\n","import {\n\tdeepWatchers,\n\teffectToDeepWatchedObjects,\n\tobjectsWithDeepWatchers,\n\tregisterDeepWatcher,\n} from './deep-watch-state'\nimport { effect, untracked } from './effects'\nimport { isNonReactive } from './non-reactive'\nimport { reactive } from './proxy'\nimport { markWithRoot } from './registry'\nimport { dependant } from './tracking'\nimport { type EffectCleanup, type EffectTrigger, options, unwrap } from './types'\n\n/**\n * Deep watch an object and all its nested properties\n * @param target - The object to watch deeply\n * @param callback - The callback to call when any nested property changes\n * @param options - Options for the deep watch\n * @returns A cleanup function to stop watching\n */\n/**\n * Sets up deep watching for an object, tracking all nested property changes\n * @param target - The object to watch\n * @param callback - The callback to call when changes occur\n * @param options - Options for deep watching\n * @returns A cleanup function to stop deep watching\n */\nexport function deepWatch<T extends object>(\n\ttarget: T,\n\tcallback: (value: T) => void,\n\t{ immediate = false } = {}\n): EffectCleanup | undefined {\n\tif (target === null || target === undefined) return undefined\n\tif (typeof target !== 'object') throw new Error('Target of deep watching must be an object')\n\t// Create a wrapper callback that matches EffectTrigger signature\n\tconst wrappedCallback: EffectTrigger = markWithRoot(\n\t\t(() => callback(target)) as EffectTrigger,\n\t\tcallback\n\t)\n\n\tregisterDeepWatcher()\n\n\t// Use the existing effect system to register dependencies\n\treturn effect`deepWatch`(() => {\n\t\t// Mark the target object as having deep watchers\n\t\tobjectsWithDeepWatchers.add(target)\n\n\t\t// Track which objects this effect is watching for cleanup\n\t\tlet effectObjects = effectToDeepWatchedObjects.get(wrappedCallback)\n\t\tif (!effectObjects) {\n\t\t\teffectObjects = new Set()\n\t\t\teffectToDeepWatchedObjects.set(wrappedCallback, effectObjects)\n\t\t}\n\t\teffectObjects!.add(target)\n\n\t\t// Traverse the object graph and register dependencies\n\t\t// This will re-run every time the effect runs, ensuring we catch all changes\n\t\tconst visited = new WeakSet()\n\t\tfunction traverseAndTrack(obj: any, depth = 0) {\n\t\t\t// Prevent infinite recursion and excessive depth\n\t\t\tif (!obj || visited.has(obj) || typeof obj !== 'object' || depth > options.maxDeepWatchDepth)\n\t\t\t\treturn\n\t\t\t// Do not traverse into unreactive objects\n\t\t\tif (isNonReactive(obj)) return\n\t\t\tvisited.add(obj)\n\n\t\t\t// Mark this object as having deep watchers\n\t\t\tobjectsWithDeepWatchers.add(obj)\n\t\t\teffectObjects!.add(obj)\n\n\t\t\t// Traverse all properties to register dependencies\n\t\t\t// unwrap to avoid kicking dependency\n\t\t\tfor (const key in unwrap(obj)) {\n\t\t\t\tif (Object.hasOwn(obj, key)) {\n\t\t\t\t\t// Access the property to register dependency\n\t\t\t\t\tconst value = (obj as any)[key]\n\t\t\t\t\t// Make the value reactive if it's an object\n\t\t\t\t\tconst reactiveValue =\n\t\t\t\t\t\ttypeof value === 'object' && value !== null ? reactive(value) : value\n\t\t\t\t\ttraverseAndTrack(reactiveValue, depth + 1)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Also handle array indices and length\n\t\t\t// Handle arrays and collections using iterators to ensure proxy tracking is triggered\n\t\t\tif (typeof obj[Symbol.iterator] === 'function') {\n\t\t\t\t// Access the iterator to track additions/removals/collection changes\n\t\t\t\tfor (const value of obj) {\n\t\t\t\t\t// Make the value reactive if it's an object\n\t\t\t\t\tconst reactiveValue =\n\t\t\t\t\t\ttypeof value === 'object' && value !== null ? reactive(value) : value\n\t\t\t\t\ttraverseAndTrack(reactiveValue, depth + 1)\n\t\t\t\t}\n\n\t\t\t\t// Explicitly depend on length so array mutations changing count trigger re-evaluation\n\t\t\t\tif ('length' in obj) {\n\t\t\t\t\tdependant(obj, 'length')\n\t\t\t\t}\n\n\t\t\t\t// For Maps, also ensure we track values explicitly if the iterator yields entries\n\t\t\t\tif (obj instanceof Map) {\n\t\t\t\t\tfor (const value of obj.values()) {\n\t\t\t\t\t\tconst reactiveValue =\n\t\t\t\t\t\t\ttypeof value === 'object' && value !== null ? reactive(value) : value\n\t\t\t\t\t\ttraverseAndTrack(reactiveValue, depth + 1)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Note: WeakSet and WeakMap cannot be iterated, so we can't deep watch their contents\n\t\t\t// They will only trigger when the collection itself is replaced\n\t\t}\n\n\t\t// Traverse the target object to register all dependencies\n\t\t// This will register dependencies on all current properties and array elements\n\t\ttraverseAndTrack(target)\n\n\t\t// Only call the callback if immediate is true or if it's not the first run\n\t\tif (immediate) {\n\t\t\tuntracked`deepWatch:callback`(() => callback(target))\n\t\t}\n\t\timmediate = true\n\n\t\t// Return a cleanup function that properly removes deep watcher tracking\n\t\treturn () => {\n\t\t\t// Get the objects this effect was watching\n\t\t\tconst effectObjects = effectToDeepWatchedObjects.get(wrappedCallback)\n\t\t\tif (effectObjects) {\n\t\t\t\t// Remove deep watcher tracking from all objects this effect was watching\n\t\t\t\tfor (const obj of effectObjects) {\n\t\t\t\t\t// Check if this object still has other deep watchers\n\t\t\t\t\tconst watchers = deepWatchers.get(obj)\n\t\t\t\t\tif (watchers) {\n\t\t\t\t\t\t// Remove this effect's callback from the watchers\n\t\t\t\t\t\twatchers.delete(wrappedCallback)\n\n\t\t\t\t\t\t// If no more watchers, remove the object from deep watchers tracking\n\t\t\t\t\t\tif (watchers.size === 0) {\n\t\t\t\t\t\t\tdeepWatchers.delete(obj)\n\t\t\t\t\t\t\tobjectsWithDeepWatchers.delete(obj)\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// No watchers found, remove from deep watchers tracking\n\t\t\t\t\t\tobjectsWithDeepWatchers.delete(obj)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Clean up the tracking data\n\t\t\t\teffectToDeepWatchedObjects.delete(wrappedCallback)\n\t\t\t}\n\t\t}\n\t})\n}\n","import { decorator } from '../decorator'\nimport { flavored } from '../flavored'\nimport { deepCompare, named } from '../utils'\nimport { touched1 } from './change'\nimport { chainExternalReason, getActiveEffect } from './effect-context'\nimport { effect, root, untracked } from './effects'\nimport {\n\tgetEffectNode,\n\tgetRoot,\n\tmarkWithRoot,\n\ttype RootMarkedFunction,\n\trootFunctionSymbol,\n} from './registry'\nimport { dependant } from './tracking'\nimport { type CleanupReason, optionCall, options, proxyToObject } from './types'\n\nexport type MemoizableArgument = object | any[] | ((...args: any[]) => any)\nexport type Memoizable = ((...args: MemoizableArgument[]) => unknown) | Record<string, any>\n\ntype MemoCacheTree<Result> = {\n\tresult?: Result\n\tcleanup?: (reason?: CleanupReason) => void\n\tbranches?: WeakMap<MemoizableArgument, MemoCacheTree<Result>>\n}\n\nconst memoizedRegistry = new WeakMap<any, Memoizable>()\nconst wrapperRegistry = new WeakMap<Function, (that: object) => unknown>()\n\nfunction getBranch<Result>(\n\ttree: MemoCacheTree<Result>,\n\tkey: MemoizableArgument\n): MemoCacheTree<Result> {\n\ttree.branches ??= new WeakMap()\n\tlet branch = tree.branches.get(key)\n\tif (!branch) {\n\t\tbranch = {}\n\t\ttree.branches.set(key, branch)\n\t}\n\treturn branch\n}\n\nfunction memoizeFunction<Result, Args extends MemoizableArgument[]>(\n\tfn: (...args: Args) => Result,\n\topts?: {\n\t\tlenient?: boolean\n\t}\n): (...args: Args) => Result {\n\tconst fnRoot = getRoot(fn)\n\tconst existing = memoizedRegistry.get(fnRoot)\n\tif (existing) return existing as (...args: Args) => Result\n\n\tconst cacheRoot: MemoCacheTree<Result> = {}\n\tconst memoized = markWithRoot(function memoized(this: unknown, ...args: Args): Result {\n\t\tif (args.some((arg) => !(arg && ['object', 'symbol', 'function'].includes(typeof arg)))) {\n\t\t\tif (opts?.lenient) return fn.apply(this, args)\n\t\t\tthrow new Error('memoize expects non-null object arguments')\n\t\t}\n\n\t\tlet node: MemoCacheTree<Result> = cacheRoot\n\t\t// Note: decorators add `this` as first argument\n\t\tfor (const arg of args) {\n\t\t\tnode = getBranch(node, arg)\n\t\t}\n\n\t\tdependant(node, 'memoize')\n\t\tif ('result' in node) {\n\t\t\tif (options.onMemoizationDiscrepancy) {\n\t\t\t\tconst wasVerification = options.isVerificationRun\n\t\t\t\toptions.isVerificationRun = true\n\t\t\t\ttry {\n\t\t\t\t\tconst fresh = untracked`memoize:verify-calculation`(() => fn.apply(this, args))\n\t\t\t\t\tif (!deepCompare(node.result, fresh)) {\n\t\t\t\t\t\toptionCall('onMemoizationDiscrepancy', node.result, fresh, fn, args, 'calculation')\n\t\t\t\t\t}\n\t\t\t\t} finally {\n\t\t\t\t\toptions.isVerificationRun = wasVerification\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn node.result!\n\t\t}\n\n\t\t// Create memoize internal effect to track dependencies and invalidate cache\n\t\t// Use untracked to prevent the effect creation from being affected by parent effects\n\t\tnode.cleanup = root`memoize:root`(() =>\n\t\t\teffect`memoize`(\n\t\t\t\t() => {\n\t\t\t\t\t// Execute the function and track its dependencies\n\t\t\t\t\t// The function execution will automatically track dependencies on reactive objects\n\t\t\t\t\tnode.result = fn.apply(this, args)\n\t\t\t\t\treturn (reason) => {\n\t\t\t\t\t\t// When dependencies change, clear the cache and notify consumers\n\t\t\t\t\t\tdelete node.result\n\t\t\t\t\t\ttouched1(node, { type: 'invalidate', prop: args }, 'memoize')\n\t\t\t\t\t\t// Lazy memoization: stop the effect so it doesn't re-run immediately.\n\t\t\t\t\t\t// It will be re-created on next access.\n\t\t\t\t\t\tif (node.cleanup) {\n\t\t\t\t\t\t\tconst activeEffect = getActiveEffect()\n\t\t\t\t\t\t\tlet chain: CleanupReason | undefined\n\t\t\t\t\t\t\tif (activeEffect) {\n\t\t\t\t\t\t\t\tconst effectNode = getEffectNode(activeEffect)\n\t\t\t\t\t\t\t\tchain = effectNode.currentReason\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tnode.cleanup({\n\t\t\t\t\t\t\t\ttype: 'invalidate',\n\t\t\t\t\t\t\t\tcause: chainExternalReason(reason ?? { type: 'stopped', chain })!,\n\t\t\t\t\t\t\t\tchain: chainExternalReason(chain),\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\tnode.cleanup = undefined\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t{ opaque: true }\n\t\t\t)\n\t\t)\n\n\t\tif (options.onMemoizationDiscrepancy) {\n\t\t\tconst wasVerification = options.isVerificationRun\n\t\t\toptions.isVerificationRun = true\n\t\t\ttry {\n\t\t\t\tconst fresh = untracked`memoize:verify-comparison`(() => fn.apply(this, args))\n\t\t\t\tif (!deepCompare(node.result, fresh)) {\n\t\t\t\t\toptionCall('onMemoizationDiscrepancy', node.result, fresh, fn, args, 'comparison')\n\t\t\t\t}\n\t\t\t} finally {\n\t\t\t\toptions.isVerificationRun = wasVerification\n\t\t\t}\n\t\t}\n\n\t\treturn node.result!\n\t}, fn)\n\n\tmemoizedRegistry.set(fnRoot, memoized)\n\tmemoizedRegistry.set(memoized, memoized)\n\treturn memoized as (...args: Args) => Result\n}\n\nfunction memoizeObject<T extends Record<string, any>>(target: T, opts?: { lenient?: boolean }): T {\n\tconst existing = memoizedRegistry.get(target)\n\tif (existing) return existing as T\n\n\tconst proxy = new Proxy(target, {\n\t\tget(source, prop, receiver) {\n\t\t\t// 1. Walk prototype chain to find descriptor\n\t\t\tlet current = source\n\t\t\tlet desc: PropertyDescriptor | undefined\n\t\t\twhile (current) {\n\t\t\t\tdesc = Object.getOwnPropertyDescriptor(current, prop)\n\t\t\t\tif (desc) break\n\t\t\t\tcurrent = Object.getPrototypeOf(current)\n\t\t\t}\n\t\t\tif (!desc) return Reflect.get(source, prop, receiver)\n\t\t\t// 2. If getter, memoize\n\t\t\tif (desc.get) {\n\t\t\t\tconst originalGetter = desc.get\n\t\t\t\tlet wrapper = wrapperRegistry.get(originalGetter)\n\t\t\t\tif (!wrapper) {\n\t\t\t\t\twrapper = markWithRoot(\n\t\t\t\t\t\tnamed(\n\t\t\t\t\t\t\t`${String(source?.constructor?.name ?? 'Object')}.${String(prop)}`,\n\t\t\t\t\t\t\t(that: any) => {\n\t\t\t\t\t\t\t\treturn originalGetter.call(that)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t),\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tpropertyKey: prop,\n\t\t\t\t\t\t}\n\t\t\t\t\t)\n\t\t\t\t\tconst origRoot = (originalGetter as RootMarkedFunction)[rootFunctionSymbol]\n\t\t\t\t\tif (origRoot) (wrapper as RootMarkedFunction)[rootFunctionSymbol] = origRoot\n\t\t\t\t\twrapperRegistry.set(originalGetter, wrapper)\n\t\t\t\t}\n\t\t\t\tconst memoized = memoizeFunction(wrapper, opts)\n\t\t\t\treturn memoized(receiver)\n\t\t\t}\n\n\t\t\t// 3. Otherwise forward\n\t\t\treturn Reflect.get(source, prop, receiver)\n\t\t},\n\t\t// Forward set to the target (source) to ensure it acts as the receiver for reactivity notifications\n\t\tset(source, prop, value, _receiver) {\n\t\t\t// By strictly passing `source` as receiver, we ensure that if `source` is a reactive proxy,\n\t\t\t// it recognizes itself and triggers change notifications.\n\t\t\treturn Reflect.set(source, prop, value, source)\n\t\t},\n\t})\n\n\tproxyToObject.set(proxy, target)\n\tmemoizedRegistry.set(target, proxy)\n\treturn proxy\n}\n\n/**\n * Decorator and function wrapper for memoizing computed values based on reactive dependencies.\n *\n * When used as a decorator on getters or methods, it caches the result and automatically\n * invalidates the cache when reactive dependencies change.\n *\n * When used as a function wrapper, it memoizes based on object arguments (WeakMap-based cache).\n *\n * @example\n * ```typescript\n * class User {\n * @memoize\n * get fullName() {\n * return `${this.firstName} ${this.lastName}`\n * }\n * }\n *\n * // Or as a function wrapper\n * const expensive = memoize((obj: SomeObject) => {\n * return heavyComputation(obj)\n * })\n * ```\n */\nfunction makeMemoizeDecorator(memoizeOpts?: { lenient?: boolean }) {\n\treturn decorator({\n\t\tgetter(original, target, propertyKey) {\n\t\t\treturn function (this: any) {\n\t\t\t\tlet wrapper = wrapperRegistry.get(original)\n\t\t\t\tif (!wrapper) {\n\t\t\t\t\twrapper = markWithRoot(\n\t\t\t\t\t\tnamed(\n\t\t\t\t\t\t\t`${String(target?.constructor?.name ?? target?.name ?? 'Object')}.${String(propertyKey)}`,\n\t\t\t\t\t\t\t(that: object) => {\n\t\t\t\t\t\t\t\treturn original.call(that)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t),\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tmethod: original,\n\t\t\t\t\t\t\tpropertyKey,\n\t\t\t\t\t\t}\n\t\t\t\t\t)\n\t\t\t\t\tconst origRoot = (original as RootMarkedFunction)[rootFunctionSymbol]\n\t\t\t\t\tif (origRoot) (wrapper as RootMarkedFunction)[rootFunctionSymbol] = origRoot\n\t\t\t\t\twrapperRegistry.set(original, wrapper)\n\t\t\t\t}\n\t\t\t\tconst memoized = memoizeFunction(wrapper as any, memoizeOpts)\n\t\t\t\treturn memoized(this)\n\t\t\t}\n\t\t},\n\t\tmethod(original, target, name) {\n\t\t\treturn function (this: any, ...args: object[]) {\n\t\t\t\tlet wrapper = wrapperRegistry.get(original)\n\t\t\t\tif (!wrapper) {\n\t\t\t\t\twrapper = markWithRoot(\n\t\t\t\t\t\tnamed(\n\t\t\t\t\t\t\t`${String(target?.constructor?.name ?? target?.name ?? 'Object')}.${String(name)}`,\n\t\t\t\t\t\t\t(that: object, ...args: object[]) => {\n\t\t\t\t\t\t\t\treturn original.call(that, ...args)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t),\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tmethod: original,\n\t\t\t\t\t\t\tpropertyKey: name,\n\t\t\t\t\t\t}\n\t\t\t\t\t)\n\t\t\t\t\tconst origRoot = (original as RootMarkedFunction)[rootFunctionSymbol]\n\t\t\t\t\tif (origRoot) (wrapper as RootMarkedFunction)[rootFunctionSymbol] = origRoot\n\t\t\t\t\twrapperRegistry.set(original, wrapper)\n\t\t\t\t}\n\t\t\t\tconst memoized = memoizeFunction(wrapper as any, memoizeOpts) as (\n\t\t\t\t\t...args: object[]\n\t\t\t\t) => unknown\n\t\t\t\treturn memoized(this, ...args)\n\t\t\t}\n\t\t},\n\t\tdefault: <T extends Memoizable>(target: T): T =>\n\t\t\ttypeof target === 'object'\n\t\t\t\t? (memoizeObject(target, memoizeOpts) as T)\n\t\t\t\t: (memoizeFunction(target, memoizeOpts) as T),\n\t})\n}\n\nexport const memoize: ReturnType<typeof makeMemoizeDecorator> & {\n\treadonly lenient: ReturnType<typeof makeMemoizeDecorator>\n} = flavored(makeMemoizeDecorator(), {\n\tget lenient() {\n\t\treturn makeMemoizeDecorator({ lenient: true })\n\t},\n})\n","import { decorator, type GenericClassDecorator } from '../decorator'\nimport { captioned, flavored, flavorOptions } from '../flavored'\nimport { deepWatch } from './deep-watch'\nimport { effectHistory, link } from './effect-context'\nimport { captured, effect, untracked } from './effects'\nimport { addUnreactiveProps, isNonReactive } from './non-reactive'\nimport { reactive } from './proxy'\nimport { markWithRoot } from './registry'\nimport { dependant } from './tracking'\nimport {\n\ttype EffectAccess,\n\ttype EffectCleanup,\n\toptions,\n\ttype ScopedCallback,\n\tunreactiveProperties,\n\tunwrap,\n} from './types'\n\n//#region watch\n\nconst unsetYet = Symbol('unset-yet')\n/**\n * Options for the watch function\n */\nexport interface WatchOptions {\n\t/** Whether to call the callback immediately */\n\timmediate?: boolean\n\t/** Whether to watch nested properties */\n\tdeep?: boolean\n}\n\n/**\n * Watches a reactive value and calls a callback when it changes\n */\nexport interface Watch {\n\t<T>(\n\t\tvalue: (dep: EffectAccess) => T,\n\t\tchanged: (value: T, oldValue?: T) => void,\n\t\toptions?: Omit<WatchOptions, 'deep'> & { deep?: false }\n\t): EffectCleanup\n\t/**\n\t * Watches a reactive value with deep watching enabled\n\t */\n\t<T extends object | any[]>(\n\t\tvalue: (dep: EffectAccess) => T,\n\t\tchanged: (value: T, oldValue?: T) => void,\n\t\toptions?: Omit<WatchOptions, 'deep'> & { deep: true }\n\t): EffectCleanup\n\t/**\n\t * Watches a reactive object directly\n\t */\n\t<T extends object | any[]>(\n\t\tvalue: T,\n\t\tchanged: (value: T) => void,\n\t\toptions?: WatchOptions\n\t): EffectCleanup\n\t(strings: TemplateStringsArray, ...values: readonly unknown[]): Watch\n\n\t/** Deep watch flavor */\n\tget deep(): Watch\n\t/** Immediate watch flavor */\n\tget immediate(): Watch\n}\n\nexport const watch = captioned(\n\tflavored(\n\t\tfunction watch(\n\t\t\tvalue: any, //object | ((dep: DependencyAccess) => object),\n\t\t\tchanged: (value?: object, oldValue?: object) => void,\n\t\t\toptions: any = {}\n\t\t) {\n\t\t\treturn typeof value === 'function'\n\t\t\t\t? watchCallBack(value, changed, options)\n\t\t\t\t: typeof value === 'object' && value !== null\n\t\t\t\t\t? watchObject(value, changed, options)\n\t\t\t\t\t: (() => {\n\t\t\t\t\t\t\tthrow new Error('watch: value must be a function or an object')\n\t\t\t\t\t\t})()\n\t\t},\n\t\t{\n\t\t\tget deep() {\n\t\t\t\treturn flavorOptions(this, { deep: true })\n\t\t\t},\n\t\t\tget immediate() {\n\t\t\t\treturn flavorOptions(this, { immediate: true })\n\t\t\t},\n\t\t}\n\t),\n\t{\n\t\tname: 'watch',\n\t\twarn: (message) => options.warn(`[reactive] ${message}`),\n\t}\n) as Watch\n\nfunction watchObject(\n\tvalue: object,\n\tchanged: (value: object) => void,\n\t{ immediate = false, deep = false } = {}\n): EffectCleanup {\n\tif (deep) return deepWatch(value, changed, { immediate })!\n\treturn effect`watch:object`(() => {\n\t\tdependant(value)\n\t\tif (immediate) changed(value)\n\t\timmediate = true\n\t})\n}\n\nfunction watchCallBack<T>(\n\tvalue: (dep: EffectAccess) => T,\n\tchanged: (value: T, oldValue?: T) => void,\n\t{ immediate = false, deep = false } = {}\n): EffectCleanup {\n\tlet oldValue: T | typeof unsetYet = unsetYet\n\tlet deepCleanup: EffectCleanup | undefined\n\tconst cbCleanup = effect`watch:callback`(\n\t\tmarkWithRoot((access) => {\n\t\t\tconst newValue = value(access)\n\t\t\tif (oldValue !== newValue) {\n\t\t\t\tconst old = oldValue\n\t\t\t\tif (old === unsetYet) {\n\t\t\t\t\tif (immediate) untracked`watch:changed`(() => changed(newValue))\n\t\t\t\t} else untracked`watch:changed`(() => changed(newValue, old as T))\n\t\t\t}\n\t\t\toldValue = newValue\n\t\t\tif (deep) {\n\t\t\t\tif (deepCleanup) deepCleanup()\n\t\t\t\tdeepCleanup = deepWatch(newValue as object, (value) => changed(value as T, value as T))\n\t\t\t}\n\t\t}, value)\n\t)\n\treturn (() => {\n\t\tcbCleanup()\n\t\tif (deepCleanup) deepCleanup()\n\t}) as EffectCleanup\n}\n\n//#endregion\n\n//#region when\n\n/**\n * Returns a promise that resolves when the predicate returns a truthy value.\n * The predicate is evaluated reactively — it re-runs whenever its dependencies change.\n * @param predicate - Reactive function that returns a value; resolves when truthy\n * @param timeout - Optional timeout in milliseconds — rejects if condition is not met within this duration\n * @returns Promise that resolves with the first truthy return value\n */\nexport function when<T>(predicate: (dep: EffectAccess) => T, timeout?: number): Promise<T> {\n\treturn new Promise<T>((resolve, reject) => {\n\t\tlet timer: ReturnType<typeof setTimeout> | undefined\n\t\tconst stop = effect`watch:when`((access) => {\n\t\t\ttry {\n\t\t\t\tconst value = predicate(access)\n\t\t\t\tif (value) {\n\t\t\t\t\tif (timer !== undefined) clearTimeout(timer)\n\t\t\t\t\ttimer = undefined\n\t\t\t\t\tqueueMicrotask(() => stop())\n\t\t\t\t\tresolve(value)\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tif (timer !== undefined) clearTimeout(timer)\n\t\t\t\ttimer = undefined\n\t\t\t\treject(error)\n\t\t\t}\n\t\t})\n\t\tif (timeout !== undefined) {\n\t\t\ttimer = setTimeout(() => {\n\t\t\t\tstop()\n\t\t\t\ttimer = undefined\n\t\t\t\treject(new Error(`when: timed out after ${timeout}ms`))\n\t\t\t}, timeout)\n\t\t}\n\t})\n}\n\n//#endregion\n\n//#region nonReactive\n\n/**\n * Mark an object as non-reactive. This object and all its properties will never be made reactive.\n * @param obj - The object to mark as non-reactive\n */\nfunction shallowNonReactive<T>(obj: T): T {\n\tobj = unwrap(obj)\n\tif (isNonReactive(obj)) return obj\n\t;(obj as any)[unreactiveProperties] = true\n\treturn obj\n}\nfunction unreactiveApplication<T extends object>(...args: (keyof T)[]): GenericClassDecorator<T>\nfunction unreactiveApplication<T extends object>(obj: T): T\nfunction unreactiveApplication<T extends object>(\n\targ1: T | keyof T,\n\t...args: (keyof T)[]\n): GenericClassDecorator<T> | T {\n\treturn typeof arg1 === 'object'\n\t\t? shallowNonReactive(arg1)\n\t\t: (((original) => {\n\t\t\t\t// Copy the parent's unreactive properties if they exist\n\t\t\t\tconst parentMarker = (original.prototype as any)[unreactiveProperties]\n\t\t\t\t// If parent is fully unreactive, child is too\n\t\t\t\tif (parentMarker === true) {\n\t\t\t\t\t;(original.prototype as any)[unreactiveProperties] = true\n\t\t\t\t} else {\n\t\t\t\t\tconst set = new Set<PropertyKey>(parentMarker || [])\n\t\t\t\t\t// Add all arguments (including the first one)\n\t\t\t\t\tset.add(arg1)\n\t\t\t\t\tfor (const arg of args) set.add(arg)\n\t\t\t\t\taddUnreactiveProps(original.prototype, set)\n\t\t\t\t}\n\t\t\t\treturn original // Return the class\n\t\t\t}) as GenericClassDecorator<T>)\n}\n/**\n * Decorator that marks classes or properties as non-reactive\n * Prevents objects from being made reactive\n */\nexport const unreactive = decorator({\n\tclass(original) {\n\t\t// Called without arguments, mark entire class as non-reactive\n\t\t;(original.prototype as any)[unreactiveProperties] = true\n\t},\n\tdefault: unreactiveApplication,\n})\n\n//#endregion\n\n//#region resource\n\nexport function lazyInit<T extends object>(resource: T, load: ScopedCallback) {\n\tconst creation = effectHistory.active\n\tlet fresh = true\n\tconst target = resource as T & Record<PropertyKey, unknown>\n\treturn new Proxy(resource, {\n\t\t[Symbol.toStringTag]: 'LazyInit',\n\t\tget(target, prop) {\n\t\t\tif (fresh) {\n\t\t\t\tcaptured(creation, load)()\n\t\t\t\tfresh = false\n\t\t\t}\n\t\t\treturn (target as typeof target & Record<PropertyKey, unknown>)[prop]\n\t\t},\n\t} as ProxyHandler<T>)\n}\n\nexport interface Resource<T> {\n\tvalue: T | undefined\n\tloading: boolean\n\terror: any\n\tlatest: T | undefined\n\treload(): void\n\tpromise: Promise<void>\n}\n\n/**\n * Creates a reactive resource that automatically tracks async state.\n * @param fetcher - Async function that returns the value. Reactive dependencies are tracked.\n * @param options - Resource options (initialValue)\n * @returns Reactive Resource object with value, loading, error, latest properties\n */\nexport function resource<T>(\n\tfetcher: (access: EffectAccess) => Promise<T> | T,\n\toptions: { initialValue?: T } = {}\n): Resource<T> {\n\tconst resource: Partial<Resource<T>> = reactive({\n\t\tvalue: options.initialValue,\n\t\tloading: true,\n\t\terror: undefined as any,\n\t\tlatest: options.initialValue,\n\t\treload() {\n\t\t\treloadSignal.value++\n\t\t},\n\t})\n\n\tconst reloadSignal = reactive({ value: 0 })\n\t// Solve race conditions: make sure a new fast request is not overloaded by a slow old one\n\tlet counter = 0\n\n\treturn lazyInit(resource as Resource<T>, () => {\n\t\tlink(\n\t\t\tresource,\n\t\t\teffect`watch:resource`((access) => {\n\t\t\t\t// Track reload signal to enable manual reloading\n\t\t\t\tvoid reloadSignal.value\n\n\t\t\t\tconst id = ++counter\n\t\t\t\tresource.loading = true\n\t\t\t\tresource.error = undefined\n\n\t\t\t\ttry {\n\t\t\t\t\tconst result = fetcher(access)\n\n\t\t\t\t\tif (result instanceof Promise) {\n\t\t\t\t\t\tresource.promise = result\n\t\t\t\t\t\t\t.then((val) => {\n\t\t\t\t\t\t\t\tif (id === counter) {\n\t\t\t\t\t\t\t\t\tresource.value = val\n\t\t\t\t\t\t\t\t\tresource.latest = val\n\t\t\t\t\t\t\t\t\tresource.loading = false\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t.catch((err) => {\n\t\t\t\t\t\t\t\tif (id === counter) {\n\t\t\t\t\t\t\t\t\tresource.error = err\n\t\t\t\t\t\t\t\t\tresource.loading = false\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t})\n\t\t\t\t\t} else {\n\t\t\t\t\t\tresource.promise = Promise.resolve()\n\t\t\t\t\t\tresource.value = result\n\t\t\t\t\t\tresource.latest = result\n\t\t\t\t\t\tresource.loading = false\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tresource.promise = Promise.reject(err)\n\t\t\t\t\tresource.error = err\n\t\t\t\t\tresource.loading = false\n\t\t\t\t}\n\t\t\t})\n\t\t) as Resource<T>\n\t})\n}\n\n//#endregion\n","import { reactive } from './proxy'\n\n/**\n * Converts an iterator to a generator that yields reactive values\n */\nexport function* makeReactiveIterator<T>(iterator: Iterator<T>): Generator<T> {\n\tlet result = iterator.next()\n\twhile (!result.done) {\n\t\tyield reactive(result.value)\n\t\tresult = iterator.next()\n\t}\n}\n\n/**\n * Converts an iterator of key-value pairs to a generator that yields reactive key-value pairs\n */\nexport function* makeReactiveEntriesIterator<K, V>(iterator: Iterator<[K, V]>): Generator<[K, V]> {\n\tlet result = iterator.next()\n\twhile (!result.done) {\n\t\tconst [key, value] = result.value\n\t\tyield [reactive(key), reactive(value)]\n\t\tresult = iterator.next()\n\t}\n}\n","import { FoolProof } from '../utils'\nimport { touched } from './change'\nimport { atomic } from './effects'\nimport { makeReactiveEntriesIterator, makeReactiveIterator } from './iterator-helpers'\nimport { reactive } from './proxy'\nimport { dependant } from './tracking'\nimport { keysOf, unwrap } from './types'\n\nfunction* index(i: number, { length = true } = {}): IterableIterator<number | 'length'> {\n\tif (length) yield 'length'\n\tyield i\n}\nexport abstract class Indexer extends Array {\n\tget(i: number): any {\n\t\tdependant(this, i)\n\t\treturn reactive(this[i])\n\t}\n\t// Returns undefined intentionally: signals the proxy handler that notifications\n\t// were already dispatched via touched(), preventing double notification\n\tset(i: number, value: any) {\n\t\tconst added = i >= this.length\n\t\tthis[i] = value\n\t\ttouched(this, { type: 'set', prop: i }, index(i, { length: added }))\n\t}\n}\nconst indexLess = { get: FoolProof.get, set: FoolProof.set }\n// Fast numeric-string check: first char is a digit (0-9)\nfunction asIndex(prop: string): number {\n\tconst c = prop.charCodeAt(0)\n\tif (c < 48 || c > 57) return -1 // not 0-9\n\tconst n = +prop // coerce — faster than parseInt, handles \"0\", \"12\", etc.\n\treturn n === (n | 0) && n >= 0 ? n : -1\n}\nObject.assign(FoolProof, {\n\tget(obj: any, prop: any, receiver: any) {\n\t\tif (Array.isArray(obj) && typeof prop === 'string') {\n\t\t\tconst i = asIndex(prop)\n\t\t\tif (i >= 0) return Indexer.prototype.get.call(obj, i)\n\t\t}\n\t\treturn indexLess.get(obj, prop, receiver)\n\t},\n\tset(obj: any, prop: any, value: any, receiver: any) {\n\t\tif (Array.isArray(obj) && typeof prop === 'string') {\n\t\t\tconst i = asIndex(prop)\n\t\t\tif (i >= 0) return Indexer.prototype.set.call(obj, i, value)\n\t\t}\n\t\treturn indexLess.set(obj, prop, value, receiver)\n\t},\n})\n\nexport abstract class ReactiveArray extends Array {\n\ttoJSON() {\n\t\treturn this\n\t}\n}\n/**\n * This is a wrapper class for Array that adds reactive behavior.\n * It extends Array and overrides methods to add reactive behavior, while making sure that the internal representation is not reactive.\n */\nexport abstract class ReactiveArrayWrapper extends Array {\n\tat(index: number): any {\n\t\treturn reactive(super.at(index))\n\t}\n\n\tconcat(...items: any[]): any[] {\n\t\treturn reactive(super.concat(...items.map(unwrap)))\n\t}\n\n\tentries(): any {\n\t\tdependant(this, keysOf)\n\t\treturn makeReactiveEntriesIterator(super.entries())\n\t}\n\n\tevery<S>(\n\t\tpredicate: (value: any, index: number, array: any[]) => value is S,\n\t\tthisArg?: any\n\t): this is S[]\n\tevery(predicate: (value: any, index: number, array: any[]) => unknown, thisArg?: any): boolean\n\tevery(predicate: (value: any, index: number, array: any[]) => any, thisArg?: any): any {\n\t\treturn super.every((v, i, a) => predicate.call(thisArg, reactive(v), i, a), thisArg)\n\t}\n\n\t@atomic\n\tfill(value: any, start?: number, end?: number): this {\n\t\treturn super.fill(unwrap(value), start, end) as this\n\t}\n\n\t@atomic\n\tcopyWithin(target: number, start: number, end?: number): this {\n\t\treturn super.copyWithin(target, start, end) as this\n\t}\n\n\tfilter<S>(predicate: (value: any, index: number, array: any[]) => value is S, thisArg?: any): S[]\n\tfilter(predicate: (value: any, index: number, array: any[]) => unknown, thisArg?: any): any[]\n\tfilter(predicate: (value: any, index: number, array: any[]) => unknown, thisArg?: any): any {\n\t\treturn reactive(super.filter((v, i, a) => predicate.call(thisArg, reactive(v), i, a), thisArg))\n\t}\n\n\tfind<S>(\n\t\tpredicate: (value: any, index: number, array: any[]) => value is S,\n\t\tthisArg?: any\n\t): S | undefined\n\tfind(\n\t\tpredicate: (value: any, index: number, array: any[]) => unknown,\n\t\tthisArg?: any\n\t): any | undefined\n\tfind(predicate: (value: any, index: number, array: any[]) => unknown, thisArg?: any): any {\n\t\treturn reactive(super.find((v, i, a) => predicate.call(thisArg, reactive(v), i, a), thisArg))\n\t}\n\n\tfindIndex(\n\t\tpredicate: (value: any, index: number, array: any[]) => unknown,\n\t\tthisArg?: any\n\t): number {\n\t\treturn super.findIndex((v, i, a) => predicate.call(thisArg, reactive(v), i, a), thisArg)\n\t}\n\n\tfindLast<S>(\n\t\tpredicate: (value: any, index: number, array: any[]) => value is S,\n\t\tthisArg?: any\n\t): S | undefined\n\tfindLast(\n\t\tpredicate: (value: any, index: number, array: any[]) => unknown,\n\t\tthisArg?: any\n\t): any | undefined\n\tfindLast(predicate: (value: any, index: number, array: any[]) => unknown, thisArg?: any): any {\n\t\treturn reactive(\n\t\t\tsuper.findLast((v, i, a) => predicate.call(thisArg, reactive(v), i, a), thisArg)\n\t\t)\n\t}\n\n\tfindLastIndex(\n\t\tpredicate: (value: any, index: number, array: any[]) => unknown,\n\t\tthisArg?: any\n\t): number {\n\t\treturn super.findLastIndex((v, i, a) => predicate.call(thisArg, reactive(v), i, a), thisArg)\n\t}\n\n\tflat(depth?: number): any[] {\n\t\tdependant(this, keysOf)\n\t\treturn reactive(super.flat(depth))\n\t}\n\n\tflatMap(callbackfn: (value: any, index: number, array: any[]) => any, thisArg?: any): any[] {\n\t\treturn reactive(\n\t\t\tsuper.flatMap((v, i, a) => unwrap(callbackfn.call(thisArg, reactive(v), i, a)), thisArg)\n\t\t)\n\t}\n\n\tforEach(callbackfn: (value: any, index: number, array: any[]) => void, thisArg?: any): void {\n\t\tsuper.forEach((v, i, a) => {\n\t\t\tcallbackfn.call(thisArg, reactive(v), i, a)\n\t\t}, thisArg)\n\t}\n\n\tincludes(searchElement: any, fromIndex?: number): boolean {\n\t\treturn arguments.length > 1\n\t\t\t? super.includes(unwrap(searchElement), fromIndex)\n\t\t\t: super.includes(unwrap(searchElement))\n\t}\n\n\tindexOf(searchElement: any, fromIndex?: number): number {\n\t\treturn arguments.length > 1\n\t\t\t? super.indexOf(unwrap(searchElement), fromIndex)\n\t\t\t: super.indexOf(unwrap(searchElement))\n\t}\n\n\tjoin(separator?: string): string {\n\t\treturn super.join(separator)\n\t}\n\n\tkeys(): any {\n\t\tdependant(this, 'length')\n\t\treturn super.keys()\n\t}\n\n\tlastIndexOf(searchElement: any, fromIndex?: number): number {\n\t\treturn arguments.length > 1\n\t\t\t? super.lastIndexOf(unwrap(searchElement), fromIndex)\n\t\t\t: super.lastIndexOf(unwrap(searchElement))\n\t}\n\n\tmap<U>(callbackfn: (value: any, index: number, array: any[]) => U, thisArg?: any): U[] {\n\t\treturn reactive(\n\t\t\tsuper.map((v, i, a) => unwrap(callbackfn.call(thisArg, reactive(v), i, a)), thisArg)\n\t\t)\n\t}\n\n\t@atomic\n\tpop(): any {\n\t\treturn reactive(super.pop())\n\t}\n\n\t@atomic\n\tpush(...items: any[]): number {\n\t\treturn super.push(...items.map(unwrap))\n\t}\n\n\treduce(\n\t\tcallbackfn: (acc: any, value: any, index: number, array: any[]) => any,\n\t\tinitialValue?: any\n\t): any {\n\t\treturn reactive(\n\t\t\targuments.length > 1\n\t\t\t\t? super.reduce((acc, v, i, a) => unwrap(callbackfn(acc, reactive(v), i, a)), initialValue)\n\t\t\t\t: super.reduce((acc, v, i, a) => unwrap(callbackfn(acc, reactive(v), i, a)))\n\t\t)\n\t}\n\n\treduceRight(\n\t\tcallbackfn: (acc: any, value: any, index: number, array: any[]) => any,\n\t\tinitialValue?: any\n\t): any {\n\t\treturn reactive(\n\t\t\targuments.length > 1\n\t\t\t\t? super.reduceRight(\n\t\t\t\t\t\t(acc, v, i, a) => unwrap(callbackfn(acc, reactive(v), i, a)),\n\t\t\t\t\t\tinitialValue\n\t\t\t\t\t)\n\t\t\t\t: super.reduceRight((acc, v, i, a) => unwrap(callbackfn(acc, reactive(v), i, a)))\n\t\t)\n\t}\n\n\t@atomic\n\treverse(): any[] {\n\t\treturn reactive(super.reverse())\n\t}\n\n\t@atomic\n\tshift(): any {\n\t\treturn reactive(super.shift())\n\t}\n\n\tslice(start?: number, end?: number): any[] {\n\t\treturn reactive(super.slice(start, end))\n\t}\n\n\tsome<S>(\n\t\tpredicate: (value: any, index: number, array: any[]) => value is S,\n\t\tthisArg?: any\n\t): this is S[]\n\tsome(predicate: (value: any, index: number, array: any[]) => unknown, thisArg?: any): boolean\n\tsome(predicate: (value: any, index: number, array: any[]) => any, thisArg?: any): any {\n\t\treturn super.some((v, i, a) => predicate.call(thisArg, reactive(v), i, a), thisArg)\n\t}\n\n\t@atomic\n\tsort(compareFn?: (a: any, b: any) => number): this {\n\t\tconst wrappedCompare = compareFn\n\t\t\t? (a: any, b: any) => compareFn(reactive(a), reactive(b))\n\t\t\t: undefined\n\t\treturn super.sort(wrappedCompare) as this\n\t}\n\n\t@atomic\n\tsplice(start: number, deleteCount?: number, ...items: any[]): any {\n\t\tif (arguments.length > 2)\n\t\t\treturn reactive(super.splice(start, deleteCount!, ...items.map(unwrap)))\n\t\tif (arguments.length === 2) return reactive(super.splice(start, deleteCount!))\n\t\tif (arguments.length === 1) return reactive(super.splice(start))\n\t\treturn reactive([])\n\t}\n\n\t@atomic\n\tunshift(...items: any[]): number {\n\t\treturn super.unshift(...items.map(unwrap))\n\t}\n\n\tvalues(): any {\n\t\tdependant(this, keysOf)\n\t\treturn makeReactiveIterator(super.values())\n\t}\n\n\t[Symbol.iterator](): any {\n\t\tdependant(this, keysOf)\n\t\treturn makeReactiveIterator(super[Symbol.iterator]())\n\t}\n\n\ttoReversed(): any[] {\n\t\treturn reactive(super.toReversed())\n\t}\n\n\ttoSorted(compareFn?: (a: any, b: any) => number): any[] {\n\t\tconst wrappedCompare = compareFn\n\t\t\t? (a: any, b: any) => compareFn(reactive(a), reactive(b))\n\t\t\t: undefined\n\t\treturn reactive(super.toSorted(wrappedCompare))\n\t}\n\n\ttoSpliced(start: number, deleteCount?: number, ...items: any[]): any {\n\t\tif (arguments.length > 2)\n\t\t\treturn reactive(super.toSpliced(start, deleteCount!, ...items.map(unwrap)))\n\t\tif (arguments.length === 2) return reactive(super.toSpliced(start, deleteCount!))\n\t\tif (arguments.length === 1) return reactive(super.toSpliced(start))\n\t\treturn reactive([...this])\n\t}\n\n\twith(index: number, value: any): any[] {\n\t\treturn reactive(super.with(index, unwrap(value)))\n\t}\n}\n","import { contentRef } from '../utils'\nimport { touched, touched1 } from './change'\nimport { notifyPropertyChange } from './deep-touch'\nimport { batch } from './effects'\nimport { makeReactiveEntriesIterator, makeReactiveIterator } from './iterator-helpers'\nimport { reactive } from './proxy'\nimport { dependant } from './tracking'\nimport { keysOf } from './types'\n\n/**\n * Reactive wrapper around JavaScript's WeakMap class\n * Only tracks individual key operations, no size tracking (WeakMap limitation)\n */\nexport abstract class ReactiveWeakMap<K extends object, V> extends WeakMap<K, V> {\n\t// Implement WeakMap interface methods with reactivity\n\tdelete(key: K): boolean {\n\t\tconst hadKey = this.has(key)\n\t\tconst result = super.delete(key)\n\n\t\tif (hadKey) touched1(contentRef(this), { type: 'del', prop: key }, key)\n\n\t\treturn result\n\t}\n\n\tget(key: K): V | undefined {\n\t\tdependant(contentRef(this), key)\n\t\treturn reactive(super.get(key))\n\t}\n\n\thas(key: K): boolean {\n\t\tdependant(contentRef(this), key)\n\t\treturn super.has(key)\n\t}\n\n\tset(key: K, value: V): this {\n\t\tconst hadKey = this.has(key)\n\t\tconst oldValue = this.get(key)\n\t\tconst reactiveValue = reactive(value)\n\t\tthis.set(key, reactiveValue)\n\n\t\tif (!hadKey || oldValue !== reactiveValue) {\n\t\t\tnotifyPropertyChange(contentRef(this), key, oldValue, reactiveValue, hadKey)\n\t\t}\n\n\t\treturn this\n\t}\n}\n\n/**\n * Reactive wrapper around JavaScript's Map class\n * Tracks size changes, individual key operations, and collection-wide operations\n */\nexport abstract class ReactiveMap<K, V> extends Map<K, V> {\n\t// Implement Map interface methods with reactivity\n\tget size(): number {\n\t\tdependant(this, 'size') // The ReactiveMap instance still goes through proxy\n\t\treturn super.size\n\t}\n\n\tclear(): void {\n\t\tconst hadEntries = this.size > 0\n\t\tsuper.clear()\n\n\t\tif (hadEntries) {\n\t\t\tconst evolution = { type: 'bunch', method: 'clear' } as const\n\t\t\t// Clear triggers all effects since all keys are affected\n\t\t\tbatch(() => {\n\t\t\t\ttouched1(this, evolution, 'size')\n\t\t\t\ttouched(contentRef(this), evolution)\n\t\t\t})\n\t\t}\n\t}\n\n\tentries(): Generator<[K, V]> {\n\t\tdependant(contentRef(this))\n\t\treturn makeReactiveEntriesIterator(this.entries())\n\t}\n\n\tforEach(callbackfn: (value: V, key: K, map: Map<K, V>) => void, thisArg?: any): void {\n\t\tdependant(contentRef(this))\n\t\tthis.forEach(callbackfn, thisArg)\n\t}\n\n\tkeys(): MapIterator<K> {\n\t\tdependant(contentRef(this), keysOf)\n\t\treturn this.keys()\n\t}\n\n\tvalues(): Generator<V> {\n\t\tdependant(contentRef(this))\n\t\treturn makeReactiveIterator(this.values())\n\t}\n\n\t[Symbol.iterator](): MapIterator<[K, V]> {\n\t\tdependant(contentRef(this))\n\t\tconst it: MapIterator<[K, V]> = Map.prototype[Symbol.iterator].call(this)\n\t\tconst nativeNext = it.next.bind(it)\n\t\tit.next = () => {\n\t\t\tconst result = nativeNext()\n\t\t\tif (result.done) return result\n\t\t\tconst [key, value] = result.value\n\t\t\treturn { value: [reactive(key), reactive(value)], done: false }\n\t\t}\n\t\treturn it\n\t}\n\n\t// Implement Map methods with reactivity\n\tdelete(key: K): boolean {\n\t\tconst hadKey = this.has(key)\n\t\tconst result = super.delete(key)\n\n\t\tif (hadKey) {\n\t\t\tconst evolution = { type: 'del', prop: key } as const\n\t\t\tbatch(() => {\n\t\t\t\ttouched1(contentRef(this), evolution, key)\n\t\t\t\ttouched1(this, evolution, 'size')\n\t\t\t})\n\t\t}\n\n\t\treturn result\n\t}\n\n\tget(key: K): V | undefined {\n\t\tdependant(contentRef(this), key)\n\t\treturn reactive(super.get(key))\n\t}\n\n\thas(key: K): boolean {\n\t\tdependant(contentRef(this), key)\n\t\treturn super.has(key)\n\t}\n\n\tset(key: K, value: V): this {\n\t\tconst hadKey = this.has(key)\n\t\tconst oldValue = this.get(key)\n\t\tconst reactiveValue = reactive(value)\n\t\tsuper.set(key, reactiveValue)\n\n\t\tif (!hadKey || oldValue !== reactiveValue) {\n\t\t\tbatch(() => {\n\t\t\t\tnotifyPropertyChange(contentRef(this), key, oldValue, reactiveValue, hadKey)\n\t\t\t\t// Also notify size change for Map (WeakMap doesn't track size)\n\t\t\t\tconst evolution = { type: hadKey ? 'set' : 'add', prop: key } as const\n\t\t\t\ttouched1(this, evolution, 'size')\n\t\t\t})\n\t\t}\n\n\t\treturn this\n\t}\n}\n","import { contentRef } from '../utils'\nimport { touched, touched1 } from './change'\nimport { batch } from './effects'\nimport { makeReactiveEntriesIterator, makeReactiveIterator } from './iterator-helpers'\nimport { reactive } from './proxy'\nimport { dependant } from './tracking'\n\n/**\n * Reactive wrapper around JavaScript's WeakSet class\n * Only tracks individual value operations, no size tracking (WeakSet limitation)\n */\nexport abstract class ReactiveWeakSet<T extends object> extends WeakSet<T> {\n\tadd(value: T): this {\n\t\tconst had = this.has(value)\n\t\tsuper.add(value)\n\t\tif (!had) {\n\t\t\t// touch the specific value and the collection view\n\t\t\ttouched1(contentRef(this), { type: 'add', prop: value }, value)\n\t\t\t// no size/allProps for WeakSet\n\t\t}\n\t\treturn this\n\t}\n\n\tdelete(value: T): boolean {\n\t\tconst had = this.has(value)\n\t\tconst res = super.delete(value)\n\t\tif (had) touched1(contentRef(this), { type: 'del', prop: value }, value)\n\t\treturn res\n\t}\n\n\thas(value: T): boolean {\n\t\tdependant(contentRef(this), value)\n\t\treturn super.has(value)\n\t}\n}\n\n/**\n * Reactive wrapper around JavaScript's Set class\n * Tracks size changes, individual value operations, and collection-wide operations\n */\nexport abstract class ReactiveSet<T> extends Set<T> {\n\tget size(): number {\n\t\t// size depends on the wrapper instance, like Map counterpart\n\t\tdependant(this, 'size')\n\t\treturn this.size\n\t}\n\n\tadd(value: T): this {\n\t\tconst had = this.has(value)\n\t\tconst reactiveValue = reactive(value)\n\t\tsuper.add(reactiveValue)\n\t\tif (!had) {\n\t\t\tconst evolution = { type: 'add', prop: reactiveValue } as const\n\t\t\t// touch for value-specific and aggregate dependencies\n\t\t\tbatch(() => {\n\t\t\t\ttouched1(contentRef(this), evolution, reactiveValue)\n\t\t\t\ttouched1(this, evolution, 'size')\n\t\t\t})\n\t\t}\n\t\treturn this\n\t}\n\n\tclear(): void {\n\t\tconst hadEntries = this.size > 0\n\t\tsuper.clear()\n\t\tif (hadEntries) {\n\t\t\tconst evolution = { type: 'bunch', method: 'clear' } as const\n\t\t\tbatch(() => {\n\t\t\t\ttouched1(this, evolution, 'size')\n\t\t\t\ttouched(contentRef(this), evolution)\n\t\t\t})\n\t\t}\n\t}\n\n\tdelete(value: T): boolean {\n\t\tconst had = this.has(value)\n\t\tconst res = super.delete(value)\n\t\tif (had) {\n\t\t\tconst evolution = { type: 'del', prop: value } as const\n\t\t\tbatch(() => {\n\t\t\t\ttouched1(contentRef(this), evolution, value)\n\t\t\t\ttouched1(this, evolution, 'size')\n\t\t\t})\n\t\t}\n\t\treturn res\n\t}\n\n\thas(value: T): boolean {\n\t\tdependant(contentRef(this), value)\n\t\treturn this.has(value)\n\t}\n\n\tentries(): Generator<[T, T]> {\n\t\tdependant(contentRef(this))\n\t\treturn makeReactiveEntriesIterator(this.entries())\n\t}\n\n\tforEach(callbackfn: (value: T, value2: T, set: Set<T>) => void, thisArg?: any): void {\n\t\tdependant(contentRef(this))\n\t\tthis.forEach(callbackfn, thisArg)\n\t}\n\n\tkeys(): Generator<T> {\n\t\tdependant(contentRef(this))\n\t\treturn makeReactiveIterator(this.keys())\n\t}\n\n\tvalues(): Generator<T> {\n\t\tdependant(contentRef(this))\n\t\treturn makeReactiveIterator(this.values())\n\t}\n\n\t[Symbol.iterator](): SetIterator<T> {\n\t\tdependant(contentRef(this))\n\t\tconst it: SetIterator<T> = Set.prototype[Symbol.iterator].call(this)\n\t\tconst nativeNext = it.next.bind(it)\n\t\tit.next = () => {\n\t\t\tconst result = nativeNext()\n\t\t\tif (result.done) return result\n\t\t\treturn { value: reactive(result.value), done: false }\n\t\t}\n\t\treturn it\n\t}\n}\n","export { attend, lift, morph } from './buffer'\nexport { getState, touched, touched1 } from './change'\nexport { deepWatch } from './deep-watch'\nexport {\n\ttype EffectContext,\n\teffectAggregator,\n\teffectContext,\n\tgetActiveEffect,\n\tlink,\n\tunlink,\n\twithEffectContext,\n} from './effect-context'\nexport {\n\taddBatchCleanup,\n\tatom,\n\tatomic,\n\t//batch, - NEVER export batch, it deals with EffectTriggers who are internal types - mutts consumers use `atomic` or `atom`\n\tbiDi,\n\tcaptured,\n\tcaught,\n\tdefer,\n\teffect,\n\tgetActivationLog,\n\tonEffectThrow,\n\treset,\n\troot,\n\tuntracked,\n} from './effects'\nexport { type Memoizable, type MemoizableArgument, memoize } from './memoize'\nexport { addUnreactiveProps, isNonReactive } from './non-reactive'\nexport { ReactiveBase, reactive } from './proxy'\nexport { organize, organized } from './record'\nexport { type Resource, resource, unreactive, watch, when } from './satellite'\nexport { assertUntracked } from './tracking'\nexport {\n\ttype CleanupReason,\n\tdebugPreset,\n\tdevPreset,\n\ttype EffectAccess,\n\ttype EffectCleanup,\n\ttype EffectCloser,\n\ttype EffectOptions,\n\ttype EffectTrigger,\n\ttype Evolution,\n\tformatCleanupReason,\n\tisReactive,\n\tobjectToProxy,\n\toptions as reactiveOptions,\n\ttype PropTrigger,\n\tprodPreset,\n\tproxyToObject,\n\tReactiveError,\n\tReactiveErrorCode,\n\ttype ScopedCallback,\n\tunwrap,\n} from './types'\n\nimport { ReactiveArray, ReactiveArrayWrapper } from './array'\nimport {\n\tdeepWatchers,\n\teffectToDeepWatchedObjects,\n\tobjectParents,\n\tobjectsWithDeepWatchers,\n} from './deep-watch-state'\nimport { ReactiveMap, ReactiveWeakMap } from './map'\nimport { metaProtos, wrapProtos } from './proxy'\nimport { effectToReactiveObjects, watchers } from './registry'\nimport { ReactiveSet, ReactiveWeakSet } from './set'\nimport { objectToProxy, proxyToObject } from './types'\n\n// Register native collection types to use specialized reactive wrappers\nmetaProtos.set(Array, ReactiveArray.prototype)\nmetaProtos.set(Set, ReactiveSet.prototype)\nmetaProtos.set(WeakSet, ReactiveWeakSet.prototype)\nmetaProtos.set(Map, ReactiveMap.prototype)\nmetaProtos.set(WeakMap, ReactiveWeakMap.prototype)\nwrapProtos.set(Array, ReactiveArrayWrapper.prototype)\n\n/**\n * Object containing internal reactive system state for debugging and profiling\n */\nexport const profileInfo: any = {\n\tobjectToProxy,\n\tproxyToObject,\n\teffectToReactiveObjects,\n\twatchers,\n\tobjectParents,\n\tobjectsWithDeepWatchers,\n\tdeepWatchers,\n\teffectToDeepWatchedObjects,\n}\n","import { decorator, type GenericClassDecorator } from './decorator'\nimport { options } from './reactive/types'\n\n// In order to avoid async re-entrance, we could use zone.js or something like that.\nconst syncCalculating: { object: object; prop: PropertyKey }[] = []\n/**\n * Decorator that caches the result of a getter method and only recomputes when dependencies change\n * Prevents circular dependencies and provides automatic cache invalidation\n */\nexport const cached = decorator({\n\tgetter(original, _target, propertyKey) {\n\t\treturn function (this: any) {\n\t\t\tconst alreadyCalculating = syncCalculating.findIndex(\n\t\t\t\t(c) => c.object === this && c.prop === propertyKey\n\t\t\t)\n\t\t\tif (alreadyCalculating > -1)\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Circular dependency detected: ${syncCalculating\n\t\t\t\t\t\t.slice(alreadyCalculating)\n\t\t\t\t\t\t.map((c) => `${c.object.constructor.name}.${String(c.prop)}`)\n\t\t\t\t\t\t.join(' -> ')} -> again`\n\t\t\t\t)\n\t\t\tsyncCalculating.push({ object: this, prop: propertyKey })\n\t\t\ttry {\n\t\t\t\tconst rv = original.call(this)\n\t\t\t\tcache(this, propertyKey, rv)\n\t\t\t\treturn rv\n\t\t\t} finally {\n\t\t\t\tsyncCalculating.pop()\n\t\t\t}\n\t\t}\n\t},\n})\n\n/**\n * Checks if a property is cached (has a cached value)\n * @param object - The object to check\n * @param propertyKey - The property key to check\n * @returns True if the property has a cached value\n */\nexport function isCached(object: Object, propertyKey: PropertyKey) {\n\treturn !!Object.getOwnPropertyDescriptor(object, propertyKey)\n}\n\n/**\n * Caches a value for a property on an object\n * @param object - The object to cache the value on\n * @param propertyKey - The property key to cache\n * @param value - The value to cache\n */\nexport function cache(object: Object, propertyKey: PropertyKey, value: any) {\n\tObject.defineProperty(object, propertyKey, { value })\n}\n\ntype DescriptorShape = {\n\tenumerable?: boolean\n\tconfigurable?: boolean\n\twritable?: boolean\n}\n\ntype DescriptorDecorator = <T>(...properties: (keyof T)[]) => GenericClassDecorator<T>\n\ntype DescriptorBuilder = ((descriptor: DescriptorShape) => DescriptorDecorator) & {\n\treadonly enumerable: DescriptorDecorator\n\treadonly hidden: DescriptorDecorator\n\treadonly configurable: DescriptorDecorator\n\treadonly frozen: DescriptorDecorator\n\treadonly writable: DescriptorDecorator\n\treadonly readonly: DescriptorDecorator\n}\n\nfunction descriptorBase(descriptor: DescriptorShape): DescriptorDecorator {\n\treturn function descriptorDecorator<T>(...properties: (keyof T)[]): GenericClassDecorator<T> {\n\t\treturn (Base) => {\n\t\t\treturn class extends Base {\n\t\t\t\tconstructor(...args: any[]) {\n\t\t\t\t\tsuper(...args)\n\t\t\t\t\tfor (const key of properties) {\n\t\t\t\t\t\tconst existing = Object.getOwnPropertyDescriptor(this, key)\n\t\t\t\t\t\tObject.defineProperty(this, key, Object.assign(existing || {}, descriptor))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\n/**\n * Creates a decorator that modifies property descriptors for specified properties\n * @param descriptor - The descriptor properties to apply\n * @returns A class decorator that applies the descriptor to specified properties\n */\nexport const descriptor: DescriptorBuilder = Object.assign(descriptorBase, {\n\t/**\n\t * enumerable: true\n\t */\n\tget enumerable(): DescriptorDecorator {\n\t\treturn descriptorBase({ enumerable: true })\n\t},\n\t/**\n\t * enumerable: false\n\t */\n\tget hidden(): DescriptorDecorator {\n\t\treturn descriptorBase({ enumerable: false })\n\t},\n\t/**\n\t * configurable: true\n\t */\n\tget configurable(): DescriptorDecorator {\n\t\treturn descriptorBase({ configurable: true })\n\t},\n\t/**\n\t * configurable: false\n\t */\n\tget frozen(): DescriptorDecorator {\n\t\treturn descriptorBase({ configurable: false })\n\t},\n\t/**\n\t * writable: true\n\t */\n\tget writable(): DescriptorDecorator {\n\t\treturn descriptorBase({ writable: true })\n\t},\n\t/**\n\t * writable: false\n\t */\n\tget readonly(): DescriptorDecorator {\n\t\treturn descriptorBase({ writable: false })\n\t},\n})\n\n/**\n * Decorator that marks methods, properties, or classes as deprecated\n * Provides warning messages when deprecated items are used\n */\nexport const deprecated = Object.assign(\n\tdecorator({\n\t\tmethod(original, _target, propertyKey) {\n\t\t\treturn function (this: any, ...args: any[]) {\n\t\t\t\tdeprecated.warn(this, propertyKey)\n\t\t\t\treturn original.apply(this, args)\n\t\t\t}\n\t\t},\n\t\tgetter(original, _target, propertyKey) {\n\t\t\treturn function (this: any) {\n\t\t\t\tdeprecated.warn(this, propertyKey)\n\t\t\t\treturn original.call(this)\n\t\t\t}\n\t\t},\n\t\tsetter(original, _target, propertyKey) {\n\t\t\treturn function (this: any, value: any) {\n\t\t\t\tdeprecated.warn(this, propertyKey)\n\t\t\t\treturn original.call(this, value)\n\t\t\t}\n\t\t},\n\t\tclass(original) {\n\t\t\treturn class extends original {\n\t\t\t\tconstructor(...args: any[]) {\n\t\t\t\t\tsuper(...args)\n\t\t\t\t\tdeprecated.warn(this, 'constructor')\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\tdefault(message: string) {\n\t\t\treturn decorator({\n\t\t\t\tmethod(original, _target, propertyKey) {\n\t\t\t\t\treturn function (this: any, ...args: any[]) {\n\t\t\t\t\t\tdeprecated.warn(this, propertyKey, message)\n\t\t\t\t\t\treturn original.apply(this, args)\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\tgetter(original, _target, propertyKey) {\n\t\t\t\t\treturn function (this: any) {\n\t\t\t\t\t\tdeprecated.warn(this, propertyKey, message)\n\t\t\t\t\t\treturn original.call(this)\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\tsetter(original, _target, propertyKey) {\n\t\t\t\t\treturn function (this: any, value: any) {\n\t\t\t\t\t\tdeprecated.warn(this, propertyKey, message)\n\t\t\t\t\t\treturn original.call(this, value)\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\tclass(original) {\n\t\t\t\t\treturn class extends original {\n\t\t\t\t\t\tconstructor(...args: any[]) {\n\t\t\t\t\t\t\tsuper(...args)\n\t\t\t\t\t\t\tdeprecated.warn(this, 'constructor', message)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t})\n\t\t},\n\t}),\n\t{\n\t\twarn: (target: any, propertyKey: PropertyKey, message?: string) => {\n\t\t\toptions.warn(\n\t\t\t\t`${target.constructor.name}.${String(propertyKey)} is deprecated${message ? `: ${message}` : ''}`\n\t\t\t)\n\t\t},\n\t}\n)\n\n/**\n * Creates a debounced method decorator that delays execution until after the delay period has passed\n * @param delay - The delay in milliseconds\n * @returns A method decorator that debounces method calls\n */\nexport function debounce(delay: number) {\n\treturn decorator({\n\t\tmethod(original, _target, _propertyKey) {\n\t\t\tlet timeoutId: ReturnType<typeof setTimeout> | null = null\n\n\t\t\treturn function (this: any, ...args: any[]) {\n\t\t\t\t// Clear existing timeout\n\t\t\t\tif (timeoutId) {\n\t\t\t\t\tclearTimeout(timeoutId)\n\t\t\t\t}\n\n\t\t\t\t// Set new timeout\n\t\t\t\ttimeoutId = setTimeout(() => {\n\t\t\t\t\toriginal.apply(this, args)\n\t\t\t\t\ttimeoutId = null\n\t\t\t\t}, delay)\n\t\t\t}\n\t\t},\n\t})\n}\n\n/**\n * Creates a throttled method decorator that limits execution to once per delay period\n * @param delay - The delay in milliseconds\n * @returns A method decorator that throttles method calls\n */\nexport function throttle(delay: number) {\n\treturn decorator({\n\t\tmethod(original, _target, _propertyKey) {\n\t\t\tlet lastCallTime = 0\n\t\t\tlet timeoutId: ReturnType<typeof setTimeout> | null = null\n\n\t\t\treturn function (this: any, ...args: any[]) {\n\t\t\t\tconst now = Date.now()\n\n\t\t\t\t// If enough time has passed since last call, execute immediately\n\t\t\t\tif (now - lastCallTime >= delay) {\n\t\t\t\t\t// Clear any pending timeout since we're executing now\n\t\t\t\t\tif (timeoutId) {\n\t\t\t\t\t\tclearTimeout(timeoutId)\n\t\t\t\t\t\ttimeoutId = null\n\t\t\t\t\t}\n\t\t\t\t\tlastCallTime = now\n\t\t\t\t\treturn original.apply(this, args)\n\t\t\t\t}\n\n\t\t\t\t// Otherwise, schedule execution for when the delay period ends\n\t\t\t\tif (!timeoutId) {\n\t\t\t\t\tconst remainingTime = delay - (now - lastCallTime)\n\t\t\t\t\tconst scheduledArgs = [...args] // Capture args at scheduling time\n\t\t\t\t\ttimeoutId = setTimeout(() => {\n\t\t\t\t\t\tlastCallTime = Date.now()\n\t\t\t\t\t\toriginal.apply(this, scheduledArgs)\n\t\t\t\t\t\ttimeoutId = null\n\t\t\t\t\t}, remainingTime)\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t})\n}\n","export * from './async'\nexport * from './decorator'\nexport * from './destroyable'\nexport * from './diff'\nexport * from './eventful'\nexport * from './flavored'\nexport * from './indexable'\nexport * from './iterableWeak'\nexport * from './mixins'\nexport * from './promiseChain'\nexport * from './reactive'\nexport * from './std-decorators'\nexport {\n\tarrayEquals,\n\tCompareSymbol,\n\tdeepCompare,\n\tisConstructor,\n\tisDev,\n\tisObject,\n\tisProd,\n\tisTest,\n\tnamed,\n\ttag,\n\tzip,\n} from './utils'\nexport * from './zone'\n\n// Important: let it here!\nimport pkg from '../package.json'\n\nconst { version } = pkg\n\nconst GLOBAL_MUTTS_KEY = '__MUTTS_INSTANCE__'\nconst runtimeGlobals = globalThis as typeof globalThis & {\n\twindow?: typeof window\n\tglobal?: typeof globalThis\n\t__filename?: string\n\t[GLOBAL_MUTTS_KEY]?: unknown\n}\nconst globalScope = (\n\ttypeof globalThis !== 'undefined'\n\t\t? globalThis\n\t\t: runtimeGlobals.window\n\t\t\t? runtimeGlobals.window\n\t\t\t: runtimeGlobals.global\n\t\t\t\t? runtimeGlobals.global\n\t\t\t\t: false\n) as any\nif (globalScope) {\n\tlet source = 'mutts/index'\n\ttry {\n\t\tif (runtimeGlobals.__filename) source = runtimeGlobals.__filename\n\t\telse if (typeof import.meta !== 'undefined' && import.meta.url) {\n\t\t\tsource = import.meta.url\n\t\t}\n\t} catch (_e) {}\n\n\tconst currentSourceInfo = { version, source, timestamp: Date.now() }\n\n\tif (globalScope[GLOBAL_MUTTS_KEY]) {\n\t\tconst existing = globalScope[GLOBAL_MUTTS_KEY]\n\t\tthrow new Error(\n\t\t\t`[Mutts] Multiple instances detected!\\n` +\n\t\t\t\t`Existing instance: ${JSON.stringify(existing, null, 2)}\\n` +\n\t\t\t\t`New instance: ${JSON.stringify(currentSourceInfo, null, 2)}\\n` +\n\t\t\t\t`This usually happens when 'mutts' is both installed as a dependency and bundled, ` +\n\t\t\t\t`or when different versions are loaded. ` +\n\t\t\t\t`Please check your build configuration (aliases, externals) to ensure a single source of truth.`\n\t\t)\n\t}\n\tglobalScope[GLOBAL_MUTTS_KEY] = currentSourceInfo\n}\n","import { FoolProof } from '../utils'\nimport { attend } from './buffer'\nimport { touched1 } from './change'\nimport { link } from './effect-context'\nimport { reactive } from './proxy'\nimport type { CleanupReason, EffectCloser } from './types'\n\n/**\n * Provides type-safe access to a source object's property within the organized callback.\n * @template Source - The type of the source object\n * @template Key - The type of the property key in the source object\n */\nexport type OrganizedAccess<Source extends Record<PropertyKey, any>, Key extends keyof Source> = {\n\t/** The property key being accessed */\n\treadonly key: Key\n\n\t/**\n\t * Gets the current value of the property from the source object\n\t * @returns The current value of the property\n\t */\n\tget(): Source[Key]\n\n\t/**\n\t * Updates the property value in the source object\n\t * @param value - The new value to set\n\t * @returns {boolean} True if the update was successful\n\t */\n\tset(value: Source[Key]): boolean\n\n\t/**\n\t * The current value of the property (equivalent to using get()/set() directly)\n\t */\n\tvalue: Source[Key]\n}\n\n/**\n * Callback function type for the organized function that processes each source property.\n * @template Source - The type of the source object\n * @template Target - The type of the target object\n */\nexport type OrganizedCallback<Source extends Record<PropertyKey, any>, Target extends object> = <\n\tKey extends keyof Source,\n>(\n\t/**\n\t * Accessor object for the current source property\n\t */\n\taccess: OrganizedAccess<Source, Key>,\n\n\t/**\n\t * The target object where organized data will be stored\n\t */\n\ttarget: Target\n) => EffectCloser | undefined\n\n/**\n * The result type of the organized function, combining the target object with cleanup capability.\n * @template Target - The type of the target object\n */\nexport type OrganizedResult<Target extends object> = Target\n\n/**\n * Organizes a source object's properties into a target object using a callback function.\n * This creates a reactive mapping between source properties and a target object,\n * automatically handling property additions, updates, and removals.\n *\n * @template Source - The type of the source object\n * @template Target - The type of the target object (defaults to Record<PropertyKey, any>)\n *\n * @param {Source} source - The source object to organize\n * @param {OrganizedCallback<Source, Target>} apply - Callback function that defines how each source property is mapped to the target\n * @param {Target} [baseTarget={}] - Optional base target object to use (will be made reactive if not already)\n *\n * @returns {OrganizedResult<Target>} The target object with cleanup capability\n *\n * @example\n * // Organize user permissions into role-based access\n * const user = reactive({ isAdmin: true, canEdit: false });\n * const permissions = organized(\n * user,\n * (access, target) => {\n * if (access.key === 'isAdmin') {\n * target.hasFullAccess = access.value;\n * }\n * target[`can${access.key.charAt(0).toUpperCase() + access.key.slice(1)}`] = access.value;\n * }\n * );\n *\n * @example\n * // Transform object structure with cleanup\n * const source = reactive({ firstName: 'John', lastName: 'Doe' });\n * const formatted = organized(\n * source,\n * (access, target) => {\n * if (access.key === 'firstName' || access.key === 'lastName') {\n * target.fullName = `${source.firstName} ${source.lastName}`.trim();\n * }\n * }\n * );\n *\n * @example\n * // Using with cleanup in a component\n * effect(() => {\n * const data = fetchData();\n * const organizedData = organized(data, (access, target) => {\n * // Transform data\n * });\n *\n * // The cleanup will be called automatically when the effect is disposed\n * return () => organizedData[cleanup]();\n * });\n */\nexport function organized<\n\tSource extends Record<PropertyKey, any>,\n\tTarget extends object = Record<PropertyKey, any>,\n>(\n\tsource: Source,\n\tapply: OrganizedCallback<Source, Target>,\n\tbaseTarget: Target = {} as Target\n): OrganizedResult<Target> {\n\tconst observedSource = reactive(source) as Source\n\tconst target = reactive(baseTarget) as Target\n\n\tconst stop = attend`organized:entries`(\n\t\tfunction enumerateObservedSourceKeys() {\n\t\t\tconst keys: PropertyKey[] = []\n\t\t\tfor (const key in observedSource) keys.push(key)\n\t\t\treturn keys\n\t\t},\n\t\tfunction applyObservedSourceKey(key) {\n\t\t\tconst sourceKey = key as keyof Source\n\t\t\tconst accessBase = {\n\t\t\t\tkey: sourceKey,\n\t\t\t\tget: () => FoolProof.get(observedSource, sourceKey, observedSource),\n\t\t\t\tset: (value: Source[typeof sourceKey]) =>\n\t\t\t\t\tFoolProof.set(observedSource, sourceKey, value, observedSource),\n\t\t\t}\n\t\t\tObject.defineProperty(accessBase, 'value', {\n\t\t\t\tget: accessBase.get,\n\t\t\t\tset: accessBase.set,\n\t\t\t\tconfigurable: true,\n\t\t\t\tenumerable: true,\n\t\t\t})\n\t\t\treturn apply(accessBase as OrganizedAccess<Source, typeof sourceKey>, target)\n\t\t}\n\t)\n\n\treturn link(target, (reason?: CleanupReason) => stop(reason)) as OrganizedResult<Target>\n}\n\n/**\n * Organizes a property on a target object\n * Shortcut for defineProperty/delete with touched signal\n * @param target - The target object\n * @param property - The property to organize\n * @param access - The access object\n * @returns The property descriptor\n */\nexport function organize<T>(\n\ttarget: object,\n\tproperty: PropertyKey,\n\taccess: { get?(): T; set?(value: T): boolean }\n) {\n\tObject.defineProperty(target, property, {\n\t\tget: access.get,\n\t\tset: access.set,\n\t\tconfigurable: true,\n\t\tenumerable: true,\n\t})\n\ttouched1(target, { type: 'set', prop: property }, property)\n\treturn () => delete (target as any)[property]\n}\n"],"names":["hooks","Set","asyncHooks","addHook","hook","add","delete","sanitizePromise","p","promiseContexts","WeakMap","captureRestorers","restorers","restorer","wrap","fn","capturedRestorers","args","undoers","restore","push","apply","this","res","then","Promise","resolve","reject","setTimeout","GLOBAL_ORIGINALS","Symbol","for","GLOBAL_PROMISE","originals","OriginalPromise","patchedThen","onFulfilled","onRejected","context","get","nextPromise","call","size","set","PatchedPromise","executor","wrappedResolve","wrappedReject","globalThis","prototype","catch","finally","all","allSettled","race","any","setInterval","setImmediate","requestAnimationFrame","queueMicrotask","Object","assign","value","has","reason","values","onFinally","defineProperty","species","configurable","_e","callback","nativeConstructors","Array","Date","Function","Map","WeakSet","Error","TypeError","ReferenceError","SyntaxError","RangeError","URIError","EvalError","Reflect","Proxy","RegExp","String","Number","Boolean","isConstructor","toString","startsWith","hasNode","Node","FoolProof","obj","prop","receiver","isOwnAccessor","opd","getOwnPropertyDescriptor","CompareSymbol","deepCompare","a","b","cache","x","y","getPrototypeOf","compared","isArray","length","i","getTime","val","found","bVal","key","foundMatch","bKey","keysA","keys","keysB","hasOwn","contentRefs","contentRef","container","seal","create","contentOf","writable","tag","name","defineProperties","toStringTag","named","runtimeGlobals","_mode","process","env","NODE_ENV","undefined","isDev","isProd","isTest","DecoratorError","constructor","message","super","legacyDecorator","description","target","propertyKey","descriptor","class","includes","newGetter","getter","newSetter","setter","newMethod","method","default","modernDecorator","kind","rv","decorator","modern","legacy","contextOrKey","mode","_target","detectDecoratorMode","fr","FinalizationRegistry","f","destructor","allocatedValues","DestructionError","msg","destroyedHandler","throw","allocated","original","arrayDiff","A","B","start","endA","endB","lenA","lenB","indexA","indexB","sliceA","sliceB","slice","maxD","Math","min","vOffset","V","Int32Array","history","d","k","buildPatches","offset","finalX","finalY","finalD","finalK","ops","prev","prevK","down","prevXEnd","xStart","yStart","patches","currA","currB","patchA","patchB","flush","op","events","getEventMap","getHookSet","eventBehavior","on","eventOrEvents","cb","eventMap","e","callbacks","off","emit","event","self","perEvent","eventful","fct","use","cached","_a","captionedOptionsSymbol","captioned","options","settings","callbackIndex","rename","caption","renameCallback","warn","shouldWarnAnonymous","thisArg","raw","strings","result","renderTemplate","callArgs","nextArgs","isAnonymousCallback","inheritCaption","source","flavored","flavors","flavorOptions","defaultOptions","opts","targetIndex","optionsIndex","newArgs","currentOptions","isObject","getAt","setAt","forwardArray","ArrayReadForward","iterator","map","callbackfn","filter","predicate","reduce","initialValue","reduceRight","forEach","find","findIndex","findLast","findLastIndex","searchElement","fromIndex","indexOf","lastIndexOf","end","concat","items","every","some","join","separator","entries","toLocaleString","locales","at","index","flat","depth","flatMap","toReversed","reverse","toSorted","compareFn","sort","toSpliced","deleteCount","with","unscopables","IterableWeakMap","uuids","refs","registry","uuid","v","createIterator","keyRef","deref","clear","unregister","crypto","randomUUID","WeakRef","register","_value","_key","IterableWeakSet","_b","union","other","others","that","intersection","difference","symmetricDifference","isSubsetOf","isSupersetOf","isDisjointFrom","mixin","mixinFunction","unwrapFunction","mixinCache","MixedBase","_thisArg","baseClass","usedBase","ProxiedBaseClass","originalPrototype","proxiedPrototype","setPrototypeOf","mixedClass","forward","alreadyChained","promiseProxyHandler","chainPromise","r","promiseForward","objectProxyHandler","chainObject","given","chainable","t","chained","debugHooks","stack","isu","z","AZone","enter","active","leave","entered","root","zoned","Zone","ZoneHistory","controlled","present","getOwnPropertyDescriptors","added","ZoneAggregator","zones","_ZoneAggregator_zones","__classPrivateFieldGet","asyncZone","zone","rootFunctionSymbol","effectToReactiveObjects","watchers","effectNodes","getEffectNode","effect","node","reverseRoots","markWithRoot","marked","existingRef","existing","rootName","existingName","fnName","getRoot","effectHistory","externalReason","effectAggregator","chainExternalReason","external","current","type","detail","chain","isRunning","getActiveEffect","cleanups","link","cleanupFns","effectMarker","formatTrigger","evolution","dependency","touch","parts","unreactiveProperties","allProps","keysOf","ReactiveErrorCode","ReactiveError","debugInfo","code","cause","_effect","_targets","_caller","beginChain","endChain","garbageCollected","_fn","touched","_obj","_evolution","_props","_deps","skipRunningEffect","effectRun","_reaction","maxEffectChain","maxTriggerPerBatch","maxEffectReaction","onMemoizationDiscrepancy","cycleHandling","isVerificationRun","maxDeepWatchDepth","instanceMembers","ignoreAccessors","recursiveTouching","asyncMode","error","introspection","gatherReasons","lineages","logErrors","enableHistory","historySize","optionCall","prodPreset","devPreset","objectToProxy","proxyToObject","unwrap","isReactive","activationRegistry","dependencyStacks","assertUntrackedFlag","getDependencyStack","objStacks","dependant","currentActiveEffect","dependencyHook","objectWatchers","deps","effectObjects","lineageConfig","propStacks","findCycleInChain","roots","seen","formatRoots","limit","names","externalReasonFrom","activationLog","recordActivation","effectData","objData","count","unshift","pop","MaxReactionExceeded","caught","onThrow","catchers","onEffectThrow","effectTriggers","effectTriggeredBy","causesClosure","consequencesClosure","broken","getOrCreateClosure","closure","hasPathExcluding","exclude","visited","queue","shift","triggers","next","batchStack","hasBatched","bs","executingStack","decrementInDegreesForExecuted","batch","executedRoot","consequences","consequenceRoot","currentDegree","inDegrees","findPath","startRoot","endRoot","path","newPath","targetRoot","getCyclePathForEdge","callerRoot","addToBatch","caller","immediate","currentBatch","pendingTriggers","callerNode","currentReason","nextReason","mergePropChange","into","from","reasons","stopped","targetConsequences","wouldCreateCycle","cyclePath","cycleMessage","causalChain","lineage","creationStack","CycleDetected","cycle","details","newTriggers","triggeredBy","uConsequences","vCauses","uCausesSet","vConsequencesSet","xConsequences","addGraphEdge","addBatchCleanup","cleanup","deferreds","defer","findCycle","recursionStack","cycleStart","executeNext","effectuatedRoots","nextEffect","nextRoot","first","getCyclePath","consequence","consequenceConsequences","BrokenEffects","isNewBatch","activeCaller","callerToUse","success","firstReturn","activeEffect","activeRoot","inDegree","causes","causeRoot","computeAllInDegrees","trace","queued","MaxDepthExceeded","queuedCount","deferred","atomic","atomicEffect","captured","effectOptions","runEffect","prevCleanup","untracked","runningPromise","cancelPrevious","abort","effectStopped","reactionCleanup","cleanupReaction","toCleanup","access","reaction","thrower","catches","parent","parentNode","forwardThrow","errorToThrow","tracked","originalPromise","cancelReject","cancelPromise","_","cancelError","reactiveObj","children","childReason","childCleanup","ascended","abortController","ascend","signal","AbortController","opaque","isOpaque","stopEffect","rootCauses","rootConsequences","sourceRoot","causeConsequences","consequenceCauses","yCauses","cleanupEffectFromGraph","callIfCollected","subEffectCleanup","_callback","objectParents","objectsWithDeepWatchers","deepWatcherCount","deepWatchers","effectToDeepWatchedObjects","addBackReference","child","parents","removeBackReference","entry","needsBackReferences","hasParentWithDeepWatchers","bubbleUpChange","changedObject","parentDeepWatchers","touchLineage","watcher","dependencyStack","states","addState","state","getState","collectEffects","effects","keyChains","sourceEffect","touched1","props","structural","absent","addUnreactiveProps","proto","merged","isUnreactiveProp","marker","nonReactiveClass","cls","c","isNonReactive","getPrototypeToken","shouldRecurseTouch","oldValue","newValue","notifyPropertyChange","targetObj","hadProperty","origin","changes","recursiveTouch","oldRef","newRef","oldMap","objects","migrateWatchers","notifications","combinedEffects","effectCauses","allowedEffects","originWatchers","originEffects","notification","currentEffects","propsArray","filteredEffects","associated","hasAncestorInSet","dispatchNotifications","gather","touchedOpaque","collectObjectKeys","ownKeys","oldObj","newObj","mapped","hasVisitedPair","oldArray","newArray","_visited","local","oldLength","newLength","max","hasOld","hasNew","oldEntry","newEntry","is","diffArrayElements","oldKeys","newKeys","diffObjectProperties","allowedSet","window","o","nonReactive","document","Element","HTMLElement","EventTarget","HTMLCollection","NodeList","metaProtos","wrapProtos","arrayLengths","hasReentry","subsRegister","internalUntracked","wrapReactiveValue","reactiveValue","reactiveObject","reactiveHandlers","metaProto","desc","ownDesc","wrapProto","isOwnProp","shouldIgnoreAccessor","hasProp","owner","isInheritedAccess","unwrapped","enumerable","oldVal","isArrayLength","deleteProperty","reactiveClasses","ReactiveBase","base","reactive","anyTarget","subProxy","getExistingProxy","proxy","storeProxyRelationship","Reactive","attend","enumerate","keyEffects","callbackLabel","outer","indexRef","stop","lift","rawResult","resultName","liftCleanup","sourceProto","splice","recordResult","had","newDesc","oldDesc","sameAccessor","morphRecord","pure","track","itemEffects","stopItem","computeItem","_cache","stateSnapshot","stopMain","morph","input","n","NaN","isNaN","newInput","diffs","diff","idx","_entry","newIdx","fill","invalidates","morphArray","morphMap","_opt","deepWatch","wrappedCallback","traverseAndTrack","memoizedRegistry","wrapperRegistry","getBranch","tree","branches","branch","memoizeFunction","fnRoot","cacheRoot","memoized","arg","lenient","wasVerification","fresh","makeMemoizeDecorator","memoizeOpts","wrapper","origRoot","originalGetter","_receiver","memoizeObject","memoize","unsetYet","watch","changed","deep","deepCleanup","cbCleanup","old","watchCallBack","watchObject","unreactive","arg1","parentMarker","makeReactiveIterator","done","makeReactiveEntriesIterator","Indexer","indexLess","asIndex","charCodeAt","ReactiveArrayWrapper","_classSuper","copyWithin","arguments","acc","wrappedCompare","_fill_decorators","_pop_decorators","_push_decorators","_shift_decorators","_sort_decorators","_unshift_decorators","__runInitializers","_instanceExtraInitializers","__esDecorate","static","private","metadata","_metadata","_copyWithin_decorators","_reverse_decorators","_splice_decorators","ReactiveWeakMap","hadKey","ReactiveMap","hadEntries","it","nativeNext","bind","ReactiveWeakSet","ReactiveSet","toJSON","profileInfo","syncCalculating","alreadyCalculating","object","descriptorBase","properties","Base","hidden","frozen","readonly","deprecated","version","pkg","GLOBAL_MUTTS_KEY","globalScope","global","__filename","url","location","require","pathToFileURL","href","_documentCurrentScript","tagName","toUpperCase","src","URL","baseURI","currentSourceInfo","timestamp","now","JSON","stringify","destructorObj","destroy","destructors","getOwnPropertyNames","isDestroyable","myDestructor","destruction","accessor","Indexable","getLength","numProp","setLength","len","received","programmaticallySetValue","pValue","called","transform","delay","_propertyKey","timeoutId","clearTimeout","formatCleanupReason","indent","repeat","property","baseTarget","observedSource","sourceKey","accessBase","fetcher","resource","loading","latest","reload","reloadSignal","counter","load","creation","lazyInit","id","promise","err","lastCallTime","remainingTime","scheduledArgs","unlink","timeout","timer","ctx","maxLength","arr","tuple"],"mappings":"2SAIO,MAAMA,EAAQ,IAAIC,IAEZC,EAAa,CACzBC,QAAQC,IACPJ,EAAMK,IAAID,GACH,IAAMJ,EAAMM,OAAOF,IAO3BG,gBAAgBC,GACRA,GCfHC,EAAkB,IAAIC,QAkB5B,SAASC,IACR,MAAMC,EAAY,IAAIX,IACtB,IAAK,MAAMG,KAAQJ,EAAO,CACzB,MAAMa,EAAWT,IACbS,GAAUD,EAAUP,IAAIQ,EAC7B,CACA,OAAOD,CACR,CAEA,SAASE,EACRC,EACAC,GAEA,GAAkB,mBAAPD,EAAmB,OAAOA,EACrC,MAAMH,EAAYI,GAAqBL,IACvC,OAAO,YAAwBM,GAC9B,MAAMC,EAA0B,GAChC,IAAK,MAAMC,KAAWP,EAAWM,EAAQE,KAAKD,KAC9C,IACC,OAAOJ,EAAGM,MAAMC,KAAML,EACvB,SAkBA,CACD,CACD,CAnDAf,EAAWK,gBAAmBgB,GACzBA,GAAoC,mBAArBA,EAAYC,KACvB,IAAIC,QAAQ,CAACC,EAASC,KAC5BC,WAAW,KACRL,EAAYC,KAAKE,EAASC,IAC1B,KAGEJ,EA6CR,MAAMM,EAAmBC,OAAOC,IAAI,mBAC9BC,EAAiBF,OAAOC,IAAI,yBAElC,IAAIE,EACAC,EAiCJ,SAASC,EAAuBC,EAAkBC,GACjD,MAAMC,EAAU7B,EAAgB8B,IAAIjB,OAASX,IACvC6B,EAAcP,EAAUT,KAAKiB,KAClCnB,KACAR,EAAKsB,EAAaE,GAClBxB,EAAKuB,EAAYC,IAGlB,OADIA,EAAQI,KAAO,GAAGjC,EAAgBkC,IAAIH,EAAaF,GAChDE,CACR,CAgBA,SAASI,EAERC,GAEA,GAAwB,mB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