@estjs/signals 0.0.15 → 0.0.16-beta.2

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/constants.ts","../src/propagation.ts","../src/link.ts","../src/reactive.ts","../src/signal.ts","../src/scheduler.ts","../src/batch.ts","../src/effect.ts","../src/computed.ts","../src/store.ts","../src/ref.ts","../src/watch.ts"],"names":["TriggerOpTypes","ARRAY_KEY","COLLECTION_KEY","WEAK_COLLECTION_KEY","ITERATE_KEY","ARRAY_ITERATE_KEY","enqueueEffect","effect","_a","propagate","link","next","stack","top","sub","watcherBit","flags","isValidLink","subSubs","nextSub","shallowPropagate","currentLinkVersion","activeSub","isUntracking","linkReactiveNode","depNode","subNode","prevDep","nextDep","prevSub","newLink","unlinkReactiveNode","linkNode","toRemove","checkDirty","checkDepth","dirty","currentDirty","dep","depFlags","subs","checkedDep","setActiveSub","prev","startTracking","endTracking","depsTail","untrack","fn","prevUntracking","checkLink","targetMap","triggerVersion","collectTriggeredEffects","effects","version","track","target","key","depsMap","trigger","type","newValue","element","iterationKey","reactiveCaches","toRaw","value","isObject","raw","isSignal","arrayInstrumentations","createArrayInstrumentations","instrumentations","args","arr","res","rawArgs","arg","isShallowMode","isShallow","reactiveImpl","i","l","item","rawIterator","done","v","arrayHandlers","shallow","receiver","hasOwn","isStringNumber","oldValue","result","hasChanged","shallowArrayHandlers","deepArrayHandlers","collectionHandlers","collectionInstrumentations","weakCollectionHandlers","weakInstrumentations","hadKey","rawValue","hadValue","hasKey","hadItems","callback","thisArg","wrappedValue","wrappedKey","isReactive","rawKey","objectHandlers","valueUnwrapped","shallowObjectHandlers","deepObjectHandlers","existingProxy","handler","isArray","isSet","isMap","isWeakMap","isWeakSet","proxy","reactive","shallowReactive","toReactive","SignalImpl","unwrapped","originalValue","changed","updater","nextValue","signal","shallowSignal","queue","activePreFlushCbs","p","isFlushPending","nextTick","queueJob","job","queueFlush","flushJobs","queuePreFlushCb","cb","flushPreFlushCbs","_error","callbacks","createScheduler","flush","batchDepth","batch","startBatch","endBatch","isBatching","getBatchDepth","EffectImpl","options","scheduler","isFunction","nextFlags","wasDirty","wasPending","error","effectInstance","runner","stop","isEffect","memoEffect","initialState","currentState","NO_VALUE","ComputedImpl","getter","setter","onTrack","onTrigger","hasValue","clearMask","computed","getterOrOptions","isComputed","isPlainObject","get","set","createOptionsStore","state","getters","actions","initState","__spreadValues","reactiveState","subscriptions","actionCallbacks","notifySubscribers","defaultActions","payload","store","__spreadProps","action","createClassStore","StoreClass","instance","descriptor","createStore","storeDefinition","_b","RefImpl","isRef","ref","INITIAL_WATCHER_VALUE","cleanupMap","traverse","seen","cloneValue","cloned","k","resolveSource","source","s","watch","immediate","deep","currentEffect","cleanups"],"mappings":"2kBAyEO,IAAMA,CAAAA,CAAiB,CAC5B,GAAA,CAAK,KAAA,CACL,IAAK,KAAA,CACL,MAAA,CAAQ,QAAA,CACR,KAAA,CAAO,OACT,EAoCO,IAAMC,CAAAA,CAA2B,MAAA,CAA+B,EAAE,CAAA,CAG5DC,CAAAA,CAAgC,MAAA,CAAoC,EAAE,CAAA,CAGtEC,CAAAA,CAAqC,MAAA,CAAwC,EAAE,CAAA,CAG/EC,EAAAA,CAA6B,OAAiC,EAAE,CAAA,CAStE,IAAMC,CAAAA,CAAmC,MAAA,CAAuC,EAAE,EClHlF,SAASC,EAAAA,CAAcC,CAAAA,CAAsB,CAlBpD,IAAAC,CAAAA,CAAAA,CAmBEA,CAAAA,CAAAD,CAAAA,EAAA,IAAA,CAAA,MAAA,CAAAA,CAAAA,CAAQ,MAAA,GAAR,IAAA,EAAAC,CAAAA,CAAA,IAAA,CAAAD,GACF,CAyBO,SAASE,CAAAA,CAAUC,CAAAA,CAAkB,CAC1C,IAAIC,EAAyBD,CAAAA,CAAK,WAAA,CAC9BE,CAAAA,CAGJC,CAAAA,CAAK,EAAG,CACN,IAAMC,CAAAA,CAAMJ,CAAAA,C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,CAAAA,CAAS4C,EAAAA,CAAcC,CAAM,CAAA,CAG7B9E,CAAAA,CAAM,IAAM,CAChB,IAAMmF,CAAAA,CAAgB1D,CAAAA,CAAO,MAAA,CAC7B,GAAI,CAAC0D,CAAAA,CAAc,GAAA,CACjB,OAIF,IAAMnK,CAAAA,CAAWmK,CAAAA,CAAc,KAAI,CAQ/BlI,UAAAA,CAAWjC,CAAAA,CAAU+B,CAAQ,CAAA,GAC/Bc,CAAAA,CAAS7C,CAAAA,CAAU+B,CAAAA,GAAauH,EAAAA,CAAwB,MAAA,CAAavH,CAAc,CAAA,CAEnFA,CAAAA,CAAW2H,CAAAA,CAAW1J,CAAQ,CAAA,EAElC,CAAA,CAGMyG,EAAShK,CAAAA,CACb,IAAM,CACJ,IAAM4D,CAAAA,CAAQ4G,CAAAA,GAEd,OAAIiD,CAAAA,EACFV,CAAAA,CAASnJ,CAAK,CAAA,CAETA,CACT,EACA,CAEE,SAAA,CAAW,IAAM0E,CAAAA,CAASC,CAAG,CAC/B,CACF,EAGA,OAAIiF,CAAAA,CACFjF,CAAAA,EAAI,CAGJjD,CAAAA,CAAW2H,EAAWjD,CAAAA,CAAO,MAAA,CAAO,GAAA,EAAK,CAAA,CAIpC,IAAM,CACXA,CAAAA,CAAO,IAAA,EAGG,CAGV,IAAM2D,CAAAA,CAAWb,EAAAA,CAAW,GAAA,CAAI9C,CAAAA,CAAO,MAAM,CAAA,CACzC2D,IACFA,CAAAA,CAAS,OAAA,CAAQlL,CAAAA,EAAMA,CAAAA,EAAI,CAAA,CAC3BqK,GAAW,MAAA,CAAO9C,CAAAA,CAAO,MAAM,CAAA,EAEnC,CACF","file":"signals.esm.js","sourcesContent":["/**\r\n * Reactive node state flags\r\n */\r\nexport const enum ReactiveFlags {\r\n /** No state flags */\r\n NONE = 0,\r\n\r\n /**\r\n * Mutable flag - The node's value can change\r\n *\r\n * Signal and Computed are mutable, triggering propagation when their values change.\r\n * Immutable nodes (like constants) don't set this flag.\r\n */\r\n // eslint-disable-next-line unicorn/prefer-math-trunc\r\n MUTABLE = 1 << 0, // 0b00000001 = 1\r\n\r\n /**\r\n * Watching flag - The node is being watched by an Effect\r\n *\r\n * Set when an Effect depends on this node.\r\n * Used to determine whether to add the Effect to the execution queue.\r\n */\r\n WATCHING = 1 << 1, // 0b00000010 = 2\r\n\r\n /**\r\n * Recursion check flag - Currently checking for circular dependencies\r\n *\r\n * Set during the checkDirty process to detect and handle circular dependencies.\r\n * Prevents infinite recursion.\r\n */\r\n RECURSED_CHECK = 1 << 2, // 0b00000100 = 4\r\n\r\n /**\r\n * Recursed flag - Already in the recursion chain\r\n *\r\n * Marks that the node has already appeared in the current propagation path.\r\n * Used to handle complex dependency graph structures.\r\n */\r\n RECURSED = 1 << 3, // 0b00001000 = 8\r\n\r\n /**\r\n * Dirty flag - The node's value has changed but hasn't propagated yet\r\n *\r\n * Set when a Signal value changes.\r\n * Also set when Computed detects dependency changes.\r\n * Indicates need to recompute or notify subscribers.\r\n */\r\n DIRTY = 1 << 4, // 0b00010000 = 16\r\n\r\n /**\r\n * Pending flag - The node may need updating\r\n *\r\n * Set during propagation, indicating the node's dependencies may have become dirty.\r\n * Need to call checkDirty to confirm if update is actually needed.\r\n */\r\n PENDING = 1 << 5, // 0b00100000 = 32\r\n\r\n /**\r\n * Queued flag - Effect has been added to the execution queue\r\n *\r\n * Prevents the same Effect from being added to the queue multiple times.\r\n * This flag is cleared before queue execution.\r\n */\r\n QUEUED = 1 << 6, // 0b01000000 = 64\r\n}\r\n\r\nexport enum EffectFlags {\r\n ALLOW_RECURSE = 1 << 7, // Allow recursive calls\r\n PAUSED = 1 << 8, // Paused\r\n RUNNING = 1 << 9, // Currently executing\r\n STOP = 1 << 10, // Permanently stopped\r\n}\r\n\r\nexport const TriggerOpTypes = {\r\n SET: 'SET',\r\n ADD: 'ADD',\r\n DELETE: 'DELETE',\r\n CLEAR: 'CLEAR',\r\n} as const;\r\n\r\n/**\r\n * Internal flags used to mark and identify different types of reactive objects.\r\n * These flags are attached as properties to objects to indicate their reactive characteristics.\r\n */\r\nexport enum SignalFlags {\r\n /** Mark an object as reactive */\r\n IS_REACTIVE = '_IS_REACTIVE',\r\n\r\n /** Mark an object as readonly */\r\n IS_READONLY = '_IS_READONLY',\r\n\r\n /** Mark an object as shallow reactive (only top-level properties are reactive) */\r\n IS_SHALLOW = '_IS_SHALLOW',\r\n\r\n /** Used to access the raw (non-reactive) version of an object */\r\n RAW = '_RAW',\r\n\r\n /** Mark an object as a signal */\r\n IS_SIGNAL = '_IS_SIGNAL',\r\n\r\n /** Mark an object as a computed property */\r\n IS_COMPUTED = '_IS_COMPUTED',\r\n\r\n /** Mark an object as a ref */\r\n IS_REF = '_IS_REF',\r\n\r\n /** Mark an object as an effect */\r\n IS_EFFECT = '_IS_EFFECT',\r\n}\r\n\r\n/** Symbol used to track signal value changes */\r\nexport const SIGNAL_KEY: unique symbol = Symbol(__DEV__ ? 'Signal_Key' : '');\r\n\r\n/** Symbol used to track array operation changes */\r\nexport const ARRAY_KEY: unique symbol = Symbol(__DEV__ ? 'Array_Key' : '');\r\n\r\n/** Symbol used to track regular collection (Map/Set) operation changes */\r\nexport const COLLECTION_KEY: unique symbol = Symbol(__DEV__ ? 'Collection_Key' : '');\r\n\r\n/** Symbol used to track weak collection (WeakMap/WeakSet) operation changes */\r\nexport const WEAK_COLLECTION_KEY: unique symbol = Symbol(__DEV__ ? 'WeakCollection_Key' : '');\r\n\r\n/** Symbol used to track iteration operations */\r\nexport const ITERATE_KEY: unique symbol = Symbol(__DEV__ ? 'Iterate_Key' : '');\r\n\r\n/** Symbol used to track Map key iteration operations */\r\nexport const MAP_KEY_ITERATE_KEY: unique symbol = Symbol(__DEV__ ? 'MapKeyIterate_Key' : '');\r\n\r\n/** Symbol used to track computed property dependencies */\r\nexport const COMPUTED_KEY: unique symbol = Symbol(__DEV__ ? 'Computed_Key' : '');\r\n\r\n/** Unique symbol used to track array iteration */\r\nexport const ARRAY_ITERATE_KEY: unique symbol = Symbol(__DEV__ ? 'Array_Iterate_Key' : '');\r\n\r\nexport type TRACKING_KEY =\r\n | typeof SIGNAL_KEY\r\n | typeof ARRAY_KEY\r\n | typeof COLLECTION_KEY\r\n | typeof WEAK_COLLECTION_KEY\r\n | typeof ITERATE_KEY\r\n | typeof MAP_KEY_ITERATE_KEY\r\n | typeof COMPUTED_KEY;\r\n","import { ReactiveFlags } from './constants';\nimport { type Link, type ReactiveNode, isValidLink } from './link';\n\n/**\n * Effect interface used internally for propagation\n */\nexport interface Effect extends ReactiveNode {\n notify(): void;\n _active?: boolean;\n}\n\n/**\n * Enqueue an Effect for execution\n *\n * Calls effect.notify() which decides whether to run synchronously or defer.\n *\n * @param effect - The Effect to enqueue\n */\nexport function enqueueEffect(effect: Effect): void {\n effect?.notify?.();\n}\n\n/**\n * Clear propagation flags (PENDING, RECURSED, RECURSED_CHECK) from a node\n *\n * Used by tests and internal cleanup to reset propagation state.\n *\n * @param node - The reactive node to clear flags on\n */\nexport function clearPropagationFlags(node: ReactiveNode): void {\n node.flag &= ~(ReactiveFlags.PENDING | ReactiveFlags.RECURSED | ReactiveFlags.RECURSED_CHECK);\n}\n\n/**\n * Propagate changes through the reactive graph\n *\n * Traverses subscriber graph marking nodes PENDING/DIRTY.\n * For WATCHING nodes (Effects), calls enqueueEffect.\n * For MUTABLE nodes (Computed), descends into their subscribers.\n *\n * Follows the alien-signals propagate algorithm: a stack is used to track\n * the \"next sibling at the current level\" so backtracking works correctly.\n *\n * @param link - Starting Link of the subscriber chain\n */\nexport function propagate(link: Link): void {\n let next: Link | undefined = link.nextSubLink;\n let stack: { value: Link | undefined; prev: typeof stack } | undefined;\n\n // eslint-disable-next-line no-restricted-syntax\n top: do {\n const sub = link.subNode;\n const watcherBit = sub.flag & ReactiveFlags.WATCHING;\n let flags = sub.flag;\n\n if (\n !(\n flags &\n (ReactiveFlags.DIRTY |\n ReactiveFlags.PENDING |\n ReactiveFlags.RECURSED |\n ReactiveFlags.RECURSED_CHECK)\n )\n ) {\n // Case 1: Clean state → mark PENDING\n sub.flag = flags | ReactiveFlags.PENDING;\n if (watcherBit) {\n enqueueEffect(sub as unknown as Effect);\n }\n } else if (!(flags & (ReactiveFlags.RECURSED | ReactiveFlags.RECURSED_CHECK))) {\n // Case 2: Already processed (DIRTY or PENDING alone) → stop downward\n flags = ReactiveFlags.NONE;\n } else if (!(flags & ReactiveFlags.RECURSED_CHECK)) {\n // Case 3: RECURSED set but not checking → clear RECURSED, mark PENDING\n sub.flag = (flags & ~ReactiveFlags.RECURSED) | ReactiveFlags.PENDING;\n } else if (!(flags & (ReactiveFlags.DIRTY | ReactiveFlags.PENDING)) && isValidLink(link, sub)) {\n // Case 4: RECURSED_CHECK set, clean, valid link → allow propagation through recursion\n sub.flag = flags | (ReactiveFlags.RECURSED | ReactiveFlags.PENDING);\n if (watcherBit) {\n enqueueEffect(sub as unknown as Effect);\n }\n flags &= ReactiveFlags.MUTABLE;\n } else {\n // Case 5: Already DIRTY/PENDING in RECURSED_CHECK → stop\n flags = ReactiveFlags.NONE;\n }\n\n if (flags & ReactiveFlags.MUTABLE) {\n // MUTABLE (Computed): descend into its subscribers\n const subSubs = sub.subLink;\n if (subSubs !== undefined) {\n // alien-signals pattern: save the CURRENT 'next' (sibling at outer level) to stack\n // before diving into this node's own subscriber chain.\n const nextSub = subSubs.nextSubLink;\n if (nextSub !== undefined) {\n // comp has multiple subscribers: save next and start at first\n stack = { value: next, prev: stack };\n next = nextSub;\n }\n link = subSubs;\n continue;\n }\n }\n\n // Advance to next sibling or restore from stack\n if ((link = next!) !== undefined) {\n next = link.nextSubLink;\n continue;\n }\n\n while (stack !== undefined) {\n link = stack.value!;\n stack = stack.prev;\n if (link !== undefined) {\n next = link.nextSubLink;\n continue top;\n }\n }\n\n break;\n // eslint-disable-next-line no-constant-condition\n } while (true);\n}\n\n/**\n * Shallow propagate from a Computed value to its direct subscribers\n *\n * Implements alien-signals' shallowPropagate semantics:\n * Only processes subscribers that are PENDING but NOT yet DIRTY.\n *\n * This guards against double-notification:\n * - propagate() marks effects PENDING and immediately calls enqueueEffect→notify().\n * notify() sets DIRTY on the effect (our EffectImpl.notify does this).\n * - When shallowPropagate is later called from checkDirty (which runs inside the\n * already-enqueued effect's fn()), the effect has DIRTY set → skipped by the guard.\n * No double execution.\n * - If the effect is only PENDING (not yet run, e.g., in a multi-subscriber scenario\n * where shallowPropagate fires before propagate reaches the effect naturally), it\n * upgrades PENDING→DIRTY and calls enqueueEffect.\n * - If the effect is RECURSED_CHECK (currently executing via startTracking), it still\n * gets upgraded to DIRTY but notify() is not called — the next run will recheck.\n *\n * @param link - Starting Link of the subscriber chain\n */\nexport function shallowPropagate(link: Link | undefined): void {\n while (link) {\n const sub = link.subNode;\n const flags = sub.flag;\n\n if ((flags & (ReactiveFlags.PENDING | ReactiveFlags.DIRTY)) === ReactiveFlags.PENDING) {\n // PENDING but not DIRTY: upgrade to DIRTY and notify if not mid-run\n sub.flag = flags | ReactiveFlags.DIRTY;\n\n if (\n (flags & (ReactiveFlags.WATCHING | ReactiveFlags.RECURSED_CHECK)) ===\n ReactiveFlags.WATCHING\n ) {\n enqueueEffect(sub as unknown as Effect);\n }\n }\n // DIRTY already → already handled. Neither PENDING nor DIRTY → clean, skip.\n\n link = link.nextSubLink;\n }\n}\n","import { error, isFunction } from '@estjs/shared';\nimport { ARRAY_ITERATE_KEY, ITERATE_KEY, ReactiveFlags } from './constants';\nimport { type Effect, propagate } from './propagation';\n\n/**\n * Link - Bidirectional connection in the dependency graph\n *\n * A Link connects two ReactiveNodes:\n * - depNode: The dependency node (data source)\n * - subNode: The subscriber node (data consumer)\n *\n * Links form doubly-linked lists in two directions:\n * 1. Subscriber Chain: Connects all subscribers of the same dependency\n * 2. Dependency Chain: Connects all dependencies of the same subscriber\n *\n * @example\n * ```\n * Signal A ←─┐\n * ├─→ Effect X\n * Signal B ←─┘\n *\n * Link1: A → X (A's subscriber chain, X's dependency chain)\n * Link2: B → X (B's subscriber chain, X's dependency chain)\n * ```\n */\nexport interface Link {\n /**\n * Version number\n *\n * Used to detect stale Links.\n * The global version number increments each time dependency tracking starts.\n * Links with old versions will be cleaned up.\n *\n */\n version: number;\n\n /**\n * Dependency node - The data source being depended on\n * Examples: Signal, Computed\n */\n depNode: ReactiveNode;\n\n /**\n * Subscriber node - The consumer of the data\n * Examples: Effect, Computed\n */\n subNode: ReactiveNode;\n\n /**\n * Connects multiple subscribers of the same depNode.\n * Previous subscriber Link\n */\n prevSubLink?: Link;\n\n /** Next subscriber Link */\n nextSubLink?: Link;\n\n /**\n * Connects multiple dependencies of the same subNode.\n * Previous dependency Link\n */\n prevDepLink?: Link;\n\n /** Next dependency Link */\n nextDepLink?: Link;\n}\n\n/**\n * Debugger event types for tracking reactive operations\n */\nexport type DebuggerEventType = 'get' | 'set' | 'add' | 'delete' | 'clear' | 'iterate';\n\n/**\n * Debugger event for tracking reactive operations\n *\n * This event is passed to onTrack and onTrigger callbacks to provide\n * detailed information about reactive operations for debugging purposes.\n *\n * @example\n * ```typescript\n * effect(() => {\n * console.log(signal.value);\n * }, {\n * onTrack(event) {\n * console.log('Tracked:', event.type, event.key);\n * },\n * onTrigger(event) {\n * console.log('Triggered:', event.type, event.key, event.newValue);\n * }\n * });\n * ```\n */\nexport interface DebuggerEvent {\n /** The effect or computed that is tracking/being triggered */\n effect: ReactiveNode;\n /** The reactive object being accessed or modified */\n target: object;\n /** The type of operation */\n type: DebuggerEventType | string;\n /** The property key being accessed or modified (optional) */\n key?: any;\n /** The new value being set (optional, only for trigger events) */\n newValue?: any;\n}\n\n/**\n * ReactiveNode - Reactive node interface\n *\n * All objects participating in the reactive system implement this interface.\n * Includes Signal, Computed, Effect, Reactive objects, etc.\n *\n * Nodes form a dependency graph through Links:\n * - depLink: List of nodes I depend on\n * - subLink: List of nodes that depend on me\n */\nexport interface ReactiveNode {\n /**\n * Dependency chain head - The first node I depend on\n *\n * Traverse all dependencies through nextDepLink.\n */\n depLink?: Link;\n\n /**\n * Subscriber chain head - The first node that depends on me\n *\n * Traverse all subscribers through nextSubLink.\n */\n subLink?: Link;\n\n /**\n * Dependency chain tail - The last node I depend on\n *\n * Used for O(1) time complexity linked list append operations.\n */\n depLinkTail?: Link;\n\n /**\n * Subscriber chain tail - The last node that depends on me\n *\n * Used for O(1) time complexity linked list append operations.\n */\n subLinkTail?: Link;\n\n /**\n * State flags\n * @see ReactiveFlags\n */\n flag: ReactiveFlags;\n\n _triggerVersion?: number; // Used for development debugging to track trigger versions\n onTrack?: (event: DebuggerEvent) => void;\n onTrigger?: (event: DebuggerEvent) => void;\n}\n\n/**\n * Current Link version number\n *\n * Increments each time dependency tracking starts.\n * Used to identify and clean up stale Links.\n */\nlet currentLinkVersion = 0;\n\n/**\n * Currently active subscriber\n *\n * Set to the current node when Effect/Computed executes.\n * When a Signal is accessed, it automatically establishes a Link with activeSub.\n */\nexport let activeSub: ReactiveNode | undefined;\n\n/**\n * Whether tracking is disabled\n *\n * The untrack() function temporarily sets this to true.\n * During this time, accessing Signals won't establish dependencies.\n */\nlet isUntracking = false;\n\n/**\n * Get whether currently in untrack mode\n */\nexport function getIsUntracking(): boolean {\n return isUntracking;\n}\n\n/**\n * Link a dependency node to a subscriber node\n *\n * This function establishes a bidirectional link between a dependency (e.g., Signal)\n * and a subscriber (e.g., Effect or Computed). It's called automatically when a\n * reactive value is accessed during effect/computed execution.\n *\n * @param depNode - The dependency node (data source)\n * @param subNode - The subscriber node (data consumer)\n * @returns The link connecting the two nodes, or undefined if in untrack mode\n */\nexport function linkReactiveNode(depNode: ReactiveNode, subNode: ReactiveNode): Link | undefined {\n // If in untrack mode, don't establish any dependencies\n // This is used by untrack() to access reactive values without creating dependencies\n if (isUntracking) {\n return undefined;\n }\n\n const prevDep = subNode.depLinkTail;\n if (prevDep && prevDep.depNode === depNode) {\n // Same dependency as last time - return existing Link immediately\n // This is the fastest path: single pointer comparison\n return prevDep;\n }\n\n const nextDep = prevDep ? prevDep.nextDepLink : subNode.depLink;\n if (nextDep && nextDep.depNode === depNode) {\n // Found a reusable Link! Update its version to mark it as \"still in use\"\n // Links with old versions will be cleaned up by endTracking()\n nextDep.version = currentLinkVersion;\n // Move the tail pointer forward to this Link\n subNode.depLinkTail = nextDep;\n return nextDep;\n }\n\n const prevSub = depNode.subLinkTail;\n if (prevSub && prevSub.version === currentLinkVersion && prevSub.subNode === subNode) {\n // This Link was just created in the current tracking cycle\n // Update subscriber's tail to point to it\n subNode.depLinkTail = prevSub;\n return prevSub;\n }\n\n // No reusable Link found - need to create a new one\n // This happens on first execution or when dependency order changes\n const newLink: Link = {\n version: currentLinkVersion,\n depNode,\n subNode,\n // Subscriber chain pointers (horizontal)\n prevSubLink: prevSub,\n nextSubLink: undefined,\n // Dependency chain pointers (vertical)\n prevDepLink: prevDep,\n nextDepLink: nextDep,\n };\n\n // Insert the new Link into the subscriber's dependency chain\n // This maintains the doubly-linked list structure\n if (nextDep) {\n // There's a Link after this position - update its back pointer\n nextDep.prevDepLink = newLink;\n }\n if (prevDep) {\n // There's a Link before this position - update its forward pointer\n prevDep.nextDepLink = newLink;\n } else {\n // This is the first dependency - update the head pointer\n subNode.depLink = newLink;\n }\n\n // Insert the new Link into the dependency's subscriber chain\n if (prevSub) {\n // There are existing subscribers - append to the end\n prevSub.nextSubLink = newLink;\n } else {\n // This is the first subscriber - update the head pointer\n depNode.subLink = newLink;\n }\n\n // Tail pointers enable O(1) append operations\n // Without them, we'd need O(n) traversal to find the end of the list\n depNode.subLinkTail = newLink;\n subNode.depLinkTail = newLink;\n\n // In development mode, notify debugging tools about the new dependency\n if (__DEV__) {\n if (subNode.onTrack && isFunction(subNode?.onTrack)) {\n subNode.onTrack({\n effect: subNode,\n target: depNode,\n type: 'get',\n key: undefined,\n });\n }\n }\n\n return newLink;\n}\n\n/**\n * Remove a dependency link\n *\n * This function removes a link from the dependency graph, updating all pointers\n * in both the subscriber's dependency chain and the dependency's subscriber chain.\n *\n * @param linkNode - The link to remove\n * @param subNode - The subscriber node (defaults to linkNode.subNode)\n * @returns The next link in the dependency chain (for iteration)\n */\nexport function unlinkReactiveNode(\n linkNode: Link,\n subNode: ReactiveNode = linkNode.subNode,\n): Link | undefined {\n const depNode = linkNode.depNode;\n const prevSub = linkNode.prevSubLink;\n const nextSub = linkNode.nextSubLink;\n const prevDep = linkNode.prevDepLink;\n const nextDep = linkNode.nextDepLink;\n\n // Update the doubly-linked list pointers in the subscriber's dependency chain\n // This removes the link from the vertical chain (all dependencies of subNode)\n if (nextDep) {\n nextDep.prevDepLink = prevDep;\n } else {\n // This was the tail - update tail pointer\n subNode.depLinkTail = prevDep;\n }\n if (prevDep) {\n prevDep.nextDepLink = nextDep;\n } else {\n // This was the head - update head pointer\n subNode.depLink = nextDep;\n }\n\n // Update the doubly-linked list pointers in the dependency's subscriber chain\n // This removes the link from the horizontal chain (all subscribers of depNode)\n if (nextSub) {\n nextSub.prevSubLink = prevSub;\n } else {\n // This was the tail - update tail pointer\n depNode.subLinkTail = prevSub;\n }\n if (prevSub) {\n prevSub.nextSubLink = nextSub;\n } else {\n // This was the head - update head pointer and check for cascading cleanup\n depNode.subLink = nextSub;\n\n // If depNode has no more subscribers, it doesn't need to track its dependencies\n // This is a critical optimization for memory management\n if (nextSub === undefined) {\n // No more subscribers - clean up all dependencies recursively\n let toRemove = depNode.depLink;\n while (toRemove) {\n toRemove = unlinkReactiveNode(toRemove, depNode);\n }\n\n // Clear tail pointer to ensure no dangling references\n depNode.depLinkTail = undefined;\n\n // Mark as dirty so it recomputes on next access\n // This is important for computed values that might be accessed again later\n depNode.flag |= ReactiveFlags.DIRTY;\n\n // Development mode verification\n if (__DEV__) {\n // Verify that all links were properly cleared\n if (depNode.depLink) {\n error(\n '[Link] Cascading cleanup failed: depNode still has dependency links. ' +\n 'This indicates a bug in the unlinking logic.',\n );\n }\n }\n }\n }\n\n // Return the next link in the dependency chain for iteration\n return nextDep;\n}\n\ninterface CheckStackNode {\n link: Link;\n prev?: CheckStackNode;\n}\n\n/**\n * Check if the dependency chain is dirty\n *\n * This function determines whether a subscriber node needs to recompute by checking\n * if any of its dependencies (or transitive dependencies) are dirty.\n *\n * ## Algorithm Overview\n *\n * The algorithm performs a depth-first traversal of the dependency graph using an\n * explicit stack to avoid recursion limits. It handles three main scenarios:\n *\n * 1. **DIRTY dependencies**: If any dependency is marked DIRTY, the subscriber is dirty\n * 2. **PENDING dependencies**: Dependencies that might be dirty - need deeper checking\n * 3. **Clean dependencies**: Dependencies that are confirmed clean\n *\n * ## Why Use an Explicit Stack?\n *\n * JavaScript has a limited call stack (~10,000 frames). In complex reactive systems,\n * dependency chains can be arbitrarily deep (e.g., computed1 → computed2 → ... → computedN).\n * Using an explicit stack allows us to handle unlimited depth without stack overflow.\n *\n * ## Algorithm Steps\n *\n * 1. Initialize stack with the subscriber's dependency chain\n * 2. For each dependency in the chain:\n * - If DIRTY: Mark path as dirty and return true\n * - If PENDING + MUTABLE: Push its dependencies onto stack for deeper checking\n * - Otherwise: Clear PENDING flag (confirmed clean)\n * 3. Track PENDING nodes encountered during traversal\n * 4. If dirty found: Mark all PENDING nodes on path as DIRTY\n * 5. If no dirty found: Clear all PENDING flags\n *\n * ## Edge Cases Handled\n *\n * - **Diamond dependencies**: A node with multiple paths to the same dependency\n * - The algorithm correctly handles this by checking all paths\n * - **Circular dependencies**: Prevented by the RECURSED flag in propagation\n * - **Deep chains**: Handled by explicit stack instead of recursion\n * - **Multiple subscribers**: Uses shallowPropagate to update sibling subscribers\n *\n * ## Performance Characteristics\n *\n * - Time complexity: O(n) where n is the total number of dependencies in the chain\n * - Space complexity: O(d) where d is the maximum depth of the dependency graph\n * - Early exit: Returns immediately when first DIRTY dependency is found\n *\n * @param link - The starting Link of the dependency chain to check\n * @param sub - The subscriber node that owns this dependency chain\n * @returns true if any dependency is dirty (subscriber needs recomputation), false otherwise\n *\n * @example\n * ```typescript\n * // Simple case: signal → computed\n * const s = signal(1);\n * const c = computed(() => s.value * 2);\n * s.value = 2; // Marks s as DIRTY\n * // When accessing c.value, checkDirty(c.depLink, c) returns true\n *\n * // Complex case: diamond dependency\n * const s = signal(1);\n * const c1 = computed(() => s.value * 2);\n * const c2 = computed(() => s.value + 1);\n * const c3 = computed(() => c1.value + c2.value);\n * // c3 depends on both c1 and c2, which both depend on s\n * // checkDirty correctly handles both paths to s\n * ```\n */\nexport function checkDirty(link: Link, sub: ReactiveNode): boolean {\n let stack: CheckStackNode | undefined;\n let checkDepth = 0;\n let dirty = false;\n\n // eslint-disable-next-line no-restricted-syntax\n top: do {\n let currentDirty = false;\n\n if (sub.flag & ReactiveFlags.DIRTY) {\n currentDirty = true;\n } else {\n const dep = link.depNode;\n const depFlags = dep.flag;\n\n if (\n (depFlags & (ReactiveFlags.MUTABLE | ReactiveFlags.DIRTY)) ===\n (ReactiveFlags.MUTABLE | ReactiveFlags.DIRTY)\n ) {\n const subs = dep.subLink;\n if (subs && subs.nextSubLink) {\n shallowPropagate(subs);\n }\n currentDirty = true;\n } else if (\n (depFlags & (ReactiveFlags.MUTABLE | ReactiveFlags.PENDING)) ===\n (ReactiveFlags.MUTABLE | ReactiveFlags.PENDING)\n ) {\n if (dep.depLink) {\n stack = { link, prev: stack };\n link = dep.depLink;\n sub = dep;\n ++checkDepth;\n continue top;\n } else {\n dep.flag &= ~ReactiveFlags.PENDING;\n }\n } else if (depFlags & ReactiveFlags.PENDING) {\n dep.flag &= ~ReactiveFlags.PENDING;\n }\n }\n\n if (!currentDirty && link.nextDepLink !== undefined) {\n link = link.nextDepLink;\n continue top;\n }\n\n dirty = currentDirty;\n\n while (checkDepth--) {\n link = stack!.link;\n stack = stack!.prev;\n sub = link.subNode;\n const checkedDep = link.depNode;\n\n if (dirty) {\n checkedDep.flag = (checkedDep.flag & ~ReactiveFlags.PENDING) | ReactiveFlags.DIRTY;\n } else {\n checkedDep.flag &= ~ReactiveFlags.PENDING;\n }\n\n if (checkedDep.flag & ReactiveFlags.DIRTY) {\n dirty = true;\n }\n\n if (!dirty && link.nextDepLink !== undefined) {\n link = link.nextDepLink;\n continue top;\n }\n }\n\n if (dirty) {\n sub.flag = (sub.flag & ~ReactiveFlags.PENDING) | ReactiveFlags.DIRTY;\n } else {\n sub.flag &= ~ReactiveFlags.PENDING;\n }\n\n return dirty;\n // eslint-disable-next-line no-constant-condition\n } while (true);\n}\n\n/**\n * Shallow propagate for Signal getters\n *\n * Called from Signal.value getter when the signal's shouldUpdate() returns true,\n * to mark direct PENDING subscribers as DIRTY without triggering full propagation.\n * This is a simpler/faster path than the Computed shallowPropagate in propagation.ts\n * because it directly writes DIRTY, bypassing notify() and its scheduling guards.\n *\n * The full propagation.ts version (used by Computed) additionally handles WATCHING\n * nodes by routing through enqueueEffect — a path we don't need here because\n * Signal's setter already called propagate() to mark/queue downstream effects.\n *\n * @param link - The starting Link of the subscriber chain\n */\nexport function shallowPropagate(link: Link | undefined): void {\n while (link) {\n const sub = link.subNode;\n const flags = sub.flag;\n\n // Only promote nodes that are PENDING (computed might need recheck) —\n // nodes already DIRTY don't need promotion, clean nodes aren't in PENDING.\n if ((flags & (ReactiveFlags.PENDING | ReactiveFlags.DIRTY)) === ReactiveFlags.PENDING) {\n sub.flag = flags | ReactiveFlags.DIRTY;\n }\n\n link = link.nextSubLink;\n }\n}\n\n/**\n * Set the active subscriber\n *\n * @param sub - The new active subscriber\n * @returns The previous active subscriber\n */\nexport function setActiveSub(sub?: ReactiveNode): ReactiveNode | undefined {\n const prev = activeSub;\n activeSub = sub;\n return prev;\n}\n\n/**\n * Start tracking dependencies\n *\n * Called before Effect/Computed execution.\n * Increments version number, stale Links will be cleaned up.\n *\n * @param sub - The subscriber node to track\n * @returns The previous active subscriber\n */\nexport function startTracking(sub: ReactiveNode): ReactiveNode | undefined {\n // Increment version number to mark new tracking cycle\n currentLinkVersion++;\n\n // Reset tracking state\n sub.depLinkTail = undefined;\n\n // Clear recursion and dirty flags, set recursion check flag\n sub.flag =\n (sub.flag & ~(ReactiveFlags.RECURSED | ReactiveFlags.DIRTY | ReactiveFlags.PENDING)) |\n ReactiveFlags.RECURSED_CHECK;\n\n return setActiveSub(sub);\n}\n\n/**\n * End tracking dependencies\n *\n * Called after Effect/Computed execution.\n * Cleans up stale Links (version number less than current version).\n *\n * @param sub - The tracked subscriber node\n * @param prevSub - The previous active subscriber\n */\nexport function endTracking(sub: ReactiveNode, prevSub: ReactiveNode | undefined): void {\n // Restore previous active subscriber\n activeSub = prevSub;\n\n // Clean up stale Links\n const depsTail = sub.depLinkTail;\n let toRemove = depsTail ? depsTail.nextDepLink : sub.depLink;\n\n while (toRemove) {\n toRemove = unlinkReactiveNode(toRemove, sub);\n }\n\n // Clear recursion check flag\n sub.flag &= ~ReactiveFlags.RECURSED_CHECK;\n}\n\n/**\n * Execute function with tracking disabled\n *\n * During function execution, accessing Signals won't establish dependencies.\n *\n * @param fn - The function to execute\n * @returns The function's return value\n */\nexport function untrack<T>(fn: () => T): T {\n const prevSub = setActiveSub(undefined);\n const prevUntracking = isUntracking;\n isUntracking = true;\n\n try {\n return fn();\n } finally {\n isUntracking = prevUntracking;\n setActiveSub(prevSub);\n }\n}\n\n/**\n * Validate if a Link is still valid\n *\n * Checks if the Link is still in the subscriber's dependency chain.\n * Used to prevent propagation through stale Links.\n *\n * @param checkLink - The Link to validate\n * @param sub - The subscriber node\n * @returns true if the Link is valid\n */\nexport function isValidLink(checkLink: Link, sub: ReactiveNode): boolean {\n let link = sub.depLinkTail;\n\n while (link) {\n if (link === checkLink) {\n return true;\n }\n link = link.prevDepLink;\n }\n\n return false;\n}\n\n/**\n * Global dependency map for reactive objects\n *\n * This WeakMap stores the dependency relationships for reactive objects (created by reactive()).\n * Structure: WeakMap<target, Map<key, Set<ReactiveNode>>>\n *\n * - WeakMap allows garbage collection of unused reactive objects\n * - Map stores per-property dependencies\n * - Set stores all subscribers for each property\n *\n * This is separate from the Link-based dependency tracking used by Signal/Computed/Effect.\n * It's specifically for tracking property access on reactive objects.\n */\nconst targetMap = new WeakMap<object, Map<string | symbol, Set<ReactiveNode>>>();\nlet triggerVersion = 0;\n\nfunction collectTriggeredEffects(\n dep: Set<ReactiveNode> | undefined,\n effects: ReactiveNode[],\n version: number,\n): void {\n if (!dep) {\n return;\n }\n\n dep.forEach(effect => {\n // Prune stopped effects to prevent long-term stale dependency growth\n if (effect.flag & ReactiveFlags.WATCHING && !(effect as Effect)._active) {\n dep.delete(effect);\n return;\n }\n\n if (effect._triggerVersion === version) {\n return;\n }\n effect._triggerVersion = version;\n effects.push(effect);\n });\n}\n\n/**\n * Track a dependency on a reactive object property\n *\n * This function establishes a dependency relationship between the currently active\n * subscriber (effect/computed) and a specific property of a reactive object.\n *\n * ## When is this called?\n *\n * - When accessing a property on a reactive object: `reactiveObj.prop`\n * - When accessing array elements: `reactiveArray[0]`\n * - When calling array methods: `reactiveArray.length`, `reactiveArray.includes()`\n * - When iterating collections: `for (const item of reactiveArray)`\n *\n * ## How it works\n *\n * 1. Check if there's an active subscriber (effect/computed currently executing)\n * 2. Get or create the dependency map for the target object\n * 3. Get or create the dependency set for the specific property\n * 4. Add the active subscriber to the set\n * 5. Call debug hook if in development mode\n *\n * ## Relationship with Link-based tracking\n *\n * This function is used for reactive objects, while linkReactiveNode() is used for\n * Signal/Computed dependencies. Both systems work together:\n *\n * ```typescript\n * const obj = reactive({ count: 0 });\n * const sig = signal(1);\n *\n * effect(() => {\n * console.log(obj.count); // Uses track()\n * console.log(sig.value); // Uses linkReactiveNode()\n * });\n * ```\n *\n * ## Performance considerations\n *\n * - WeakMap lookup: O(1) average case\n * - Map lookup: O(1) average case\n * - Set.has() and Set.add(): O(1) average case\n * - Overall: O(1) for tracking a single property\n *\n * @param target - The reactive object being accessed\n * @param key - The property key being accessed (string, number, or symbol)\n *\n * @example\n * ```typescript\n * const state = reactive({ count: 0, name: 'Alice' });\n *\n * effect(() => {\n * // track(state, 'count') is called automatically\n * console.log(state.count);\n * });\n *\n * // Changing count will trigger the effect\n * state.count++; // trigger(state, 'SET', 'count', 1)\n * ```\n */\nexport function track(target: object, key: string | symbol): void {\n // Only track if there's an active subscriber (effect/computed currently executing)\n // and tracking is not disabled (not in untrack() call)\n if (!activeSub || isUntracking) {\n return;\n }\n\n // Each target object has a Map of its property dependencies\n let depsMap = targetMap.get(target);\n if (!depsMap) {\n depsMap = new Map();\n targetMap.set(target, depsMap);\n }\n\n // Each property has a Set of subscribers that depend on it\n let dep = depsMap.get(key);\n if (!dep) {\n dep = new Set();\n depsMap.set(key, dep);\n }\n\n // Set.add() is idempotent so no need for a redundant has() check.\n // Only invoke the debug hook when it's a genuinely new dependency.\n const sizeBefore = __DEV__ ? dep.size : 0;\n dep.add(activeSub);\n\n // In development mode, notify debugging tools about the dependency\n if (__DEV__ && dep.size !== sizeBefore && isFunction(activeSub.onTrack)) {\n activeSub.onTrack({\n effect: activeSub,\n target,\n type: 'get',\n key,\n });\n }\n}\n\n/**\n * Trigger updates for subscribers of a reactive object property\n *\n * This function notifies all subscribers (effects/computed) that depend on a specific\n * property of a reactive object that the property has changed.\n *\n * ## When is this called?\n *\n * - When setting a property: `reactiveObj.prop = value` → trigger(obj, 'SET', 'prop', value)\n * - When adding a property: `reactiveObj.newProp = value` → trigger(obj, 'ADD', 'newProp', value)\n * - When deleting a property: `delete reactiveObj.prop` → trigger(obj, 'DELETE', 'prop')\n * - When clearing a collection: `reactiveArray.length = 0` → trigger(obj, 'CLEAR')\n * - When mutating arrays: `reactiveArray.push(item)` → trigger(obj, 'SET', 'length', newLength)\n *\n * ## Operation Types\n *\n * - **SET**: Property value changed (most common)\n * - **ADD**: New property added (affects iteration)\n * - **DELETE**: Property removed (affects iteration)\n * - **CLEAR**: Collection cleared (affects iteration)\n *\n * ## Iteration Dependencies\n\n * @param target - The reactive object that changed\n * @param type - The type of operation: 'SET' | 'ADD' | 'DELETE' | 'CLEAR'\n * @param key - The property key that changed (optional for CLEAR operations)\n * @param newValue - The new value (optional, used for debugging)\n *\n * @example\n * ```typescript\n * const state = reactive({ count: 0, items: [1, 2, 3] });\n *\n * effect(() => {\n * console.log(state.count); // Depends on 'count'\n * });\n *\n * effect(() => {\n * console.log(state.items.length); // Depends on 'items' and iteration\n * });\n *\n * // Triggers first effect only\n * state.count = 1; // trigger(state, 'SET', 'count', 1)\n *\n * // Triggers second effect (changes length and iteration)\n * state.items.push(4); // trigger(state.items, 'SET', 'length', 4)\n * // trigger(state.items, 'ADD', '3', 4)\n * ```\n */\nexport function trigger(\n target: object,\n type: string,\n key?: string | symbol | (string | symbol)[],\n newValue?: unknown,\n): void {\n // If this target has no tracked dependencies, nothing to do\n const depsMap = targetMap.get(target);\n if (!depsMap) {\n return;\n }\n\n const effects: ReactiveNode[] = [];\n const version = ++triggerVersion;\n\n // Collect all effects that depend on the specific property that changed\n if (key !== undefined) {\n if (Array.isArray(key)) {\n for (const element of key) {\n collectTriggeredEffects(depsMap.get(element), effects, version);\n }\n } else {\n collectTriggeredEffects(depsMap.get(key), effects, version);\n }\n }\n\n // For operations that affect iteration (ADD/DELETE/CLEAR), we need to trigger\n // effects that iterate over the collection\n\n if (type === 'ADD' || type === 'DELETE' || type === 'CLEAR') {\n const iterationKey = Array.isArray(target) ? ARRAY_ITERATE_KEY : ITERATE_KEY;\n collectTriggeredEffects(depsMap.get(iterationKey), effects, version);\n }\n\n // Process each effect that needs to be notified\n for (const effect of effects) {\n // In development mode, notify debugging tools about the trigger\n if (__DEV__ && isFunction(effect.onTrigger)) {\n effect.onTrigger({\n effect,\n target,\n type,\n key,\n newValue,\n });\n }\n\n // Effects and Computed values need different handling\n\n if (effect.flag & ReactiveFlags.WATCHING) {\n (effect as Effect).notify?.();\n } else if (effect.flag & ReactiveFlags.MUTABLE) {\n effect.flag |= ReactiveFlags.DIRTY;\n if (effect.subLink) {\n propagate(effect.subLink);\n }\n }\n }\n}\n","import {\n hasChanged,\n hasOwn,\n isArray,\n isMap,\n isObject,\n isSet,\n isStringNumber,\n isWeakMap,\n isWeakSet,\n} from '@estjs/shared';\nimport {\n ARRAY_ITERATE_KEY,\n ARRAY_KEY,\n COLLECTION_KEY,\n SignalFlags,\n TriggerOpTypes,\n WEAK_COLLECTION_KEY,\n} from './constants';\nimport { isSignal } from './signal';\nimport { track, trigger } from './link';\n\n// Use WeakMap to cache created reactive proxies to avoid duplicate creation.\nconst reactiveCaches = new WeakMap<object, object>();\n\n/**\n * Return the raw underlying value of a reactive proxy or signal.\n * Recursively unwraps nested reactive objects and arrays.\n *\n * @param value - Reactive or signal value.\n * @returns Raw value without any reactive wrapping.\n */\nexport function toRaw<T>(value: T): T {\n if (!value || !isObject(value)) {\n return value as T;\n }\n\n const raw = value[SignalFlags.RAW];\n if (raw) {\n // Recursively unwrap in case the raw value is also reactive\n return toRaw(raw);\n }\n\n // Check if it's a signal and unwrap without triggering dependencies\n if (isSignal(value)) {\n return toRaw(value.peek()) as T;\n }\n\n // For all other cases (non-reactive objects, arrays, collections, etc.), return as-is\n // Arrays, Maps, Sets, etc. that aren't reactive proxies are already \"raw\"\n return value as T;\n}\n\nconst arrayInstrumentations = createArrayInstrumentations();\n\n/**\n * Create enhanced versions of array methods that include dependency tracking.\n * Includes search, modification, and iteration methods.\n *\n * @returns An object that maps method keys to enhanced functions.\n */\nfunction createArrayInstrumentations() {\n const instrumentations: Record<string | symbol, Function> = {};\n\n // Search methods: track array iteration and handle reactive object arguments\n ['includes', 'indexOf', 'lastIndexOf'].forEach(key => {\n instrumentations[key] = function (this: unknown[], ...args: unknown[]) {\n const arr = toRaw(this) as any[];\n // Track iteration access to the entire array\n track(arr, ARRAY_ITERATE_KEY);\n\n // First try with the original arguments\n let res = arr[key as keyof typeof arr](...args);\n\n // If lookup fails and we have arguments, try with raw values\n // This handles cases where reactive objects are passed as search values\n if ((res === -1 || res === false) && args.length > 0) {\n const rawArgs = args.map(arg => toRaw(arg));\n res = arr[key as keyof typeof arr](...rawArgs);\n }\n\n return res;\n };\n });\n\n // Search methods that return elements: track iteration and maintain reactivity\n ['find', 'findIndex', 'findLast', 'findLastIndex'].forEach(key => {\n instrumentations[key] = function (this: unknown[], ...args: unknown[]) {\n const arr = toRaw(this) as any[];\n const isShallowMode = isShallow(this);\n\n // Track iteration access to the entire array\n track(arr, ARRAY_ITERATE_KEY);\n\n const res = arr[key as keyof typeof arr](...args);\n\n // For find/findLast, make result reactive if needed\n if ((key === 'find' || key === 'findLast') && isObject(res) && !isShallowMode) {\n return reactiveImpl(res);\n }\n\n return res;\n };\n });\n\n // Mutation methods: trigger array changes\n ['push', 'pop', 'shift', 'unshift', 'splice', 'sort', 'reverse', 'fill', 'copyWithin'].forEach(\n key => {\n instrumentations[key] = function (this: unknown[], ...args: unknown[]) {\n const arr = toRaw(this);\n // Call the method using Array.prototype to ensure it works correctly\n const res = Array.prototype[key].apply(arr, args);\n // Trigger both array content and iteration watchers in a single pass\n trigger(arr, TriggerOpTypes.SET, [ARRAY_KEY, ARRAY_ITERATE_KEY]);\n return res;\n };\n },\n );\n\n // ES2023 methods that return new arrays: track access and maintain reactivity\n ['toReversed', 'toSorted', 'toSpliced'].forEach(key => {\n instrumentations[key] = function (this: unknown[], ...args: unknown[]) {\n const arr = toRaw(this);\n const isShallowMode = isShallow(this);\n\n // Track iteration access to the entire array\n track(arr, ARRAY_ITERATE_KEY);\n\n // For toSpliced, track all individual elements since they're being accessed\n if (key === 'toSpliced') {\n for (let i = 0, l = arr.length; i < l; i++) {\n track(arr, `${i}`);\n }\n }\n\n // Call the native method\n const res = Array.prototype[key].apply(arr, args);\n\n // Return directly if result is not an array\n if (!Array.isArray(res)) {\n return res;\n }\n\n // Make object elements reactive (deep or shallow based on parent mode)\n return res.map(item => (isObject(item) ? reactiveImpl(item, isShallowMode) : item));\n };\n });\n\n // Methods that return new arrays but don't modify original: track and maintain reactivity\n ['concat', 'slice', 'filter', 'map', 'flatMap', 'flat'].forEach(key => {\n instrumentations[key] = function (this: unknown[], ...args: unknown[]) {\n const arr = toRaw(this);\n\n // Track iteration access\n track(arr, ARRAY_ITERATE_KEY);\n\n // Call the native method\n const res = Array.prototype[key].apply(arr, args);\n\n return res;\n };\n });\n\n // Methods that return strings: only track, no reactivity needed\n ['join', 'toString', 'toLocaleString'].forEach(key => {\n instrumentations[key] = function (this: unknown[], ...args: unknown[]) {\n const arr = toRaw(this);\n // Track iteration access\n track(arr, ARRAY_ITERATE_KEY);\n return Array.prototype[key].apply(arr, args);\n };\n });\n\n // Iterator methods: track access and maintain reactivity\n ['values', 'keys', 'entries', Symbol.iterator].forEach(key => {\n instrumentations[key] = function (this: unknown[]) {\n const arr = toRaw(this);\n const isShallowMode = isShallow(this);\n\n // Track changes to the entire array\n track(arr, ARRAY_KEY);\n\n const rawIterator = key === Symbol.iterator ? arr[Symbol.iterator]() : arr[key]();\n\n return {\n next() {\n const { value, done } = rawIterator.next();\n\n if (done) {\n return { value, done };\n }\n\n // Handle entries (returns [index, value] or [value, value] for Set)\n if (Array.isArray(value)) {\n return {\n value: value.map(v => (isObject(v) ? reactiveImpl(v, isShallowMode) : v)),\n done,\n };\n }\n\n // Handle values and keys - make objects reactive\n return {\n value: isObject(value) ? reactiveImpl(value, isShallowMode) : value,\n done,\n };\n },\n [Symbol.iterator]() {\n return this;\n },\n };\n };\n });\n\n return instrumentations;\n}\n\n/**\n * Proxy handler for reactive arrays.\n * Intercepts get and set operations to perform dependency tracking and trigger changes.\n *\n * @param shallow - Indicates whether reactivity should be shallow.\n * @returns Object containing array get and set traps.\n */\nconst arrayHandlers = (shallow: boolean) => ({\n get: (target: any, key: string | symbol, receiver: any) => {\n // Intercept operation to get the raw object.\n if (key === SignalFlags.RAW) {\n return target;\n }\n // Intercept operation to check if it's a reactive object.\n if (key === SignalFlags.IS_REACTIVE) {\n return true;\n }\n // Intercept operation to check if it's shallow.\n if (key === SignalFlags.IS_SHALLOW) {\n return shallow;\n }\n // If it's an enhanced method, return the enhanced version.\n if (hasOwn(arrayInstrumentations, key)) {\n return arrayInstrumentations[key];\n }\n\n const value = Reflect.get(target, key, receiver);\n\n // If accessing a numeric index, track that index.\n if (isStringNumber(key)) {\n track(target, key);\n }\n // Track general access to the array.\n track(target, ARRAY_KEY);\n\n // If value is object and needs deep reactivity, return its reactive version.\n if (isObject(value) && !shallow) {\n return reactiveImpl(value);\n }\n return value;\n },\n set: (target: any, key: string | symbol, value: unknown, receiver: any) => {\n const oldValue = Reflect.get(target, key, receiver);\n const result = Reflect.set(target, key, value, receiver);\n if (hasChanged(value, oldValue)) {\n // For numeric indices, we need to trigger multiple dependencies\n if (isStringNumber(key)) {\n trigger(target, TriggerOpTypes.SET, [key, ARRAY_ITERATE_KEY, ARRAY_KEY]);\n } else {\n // For non-numeric keys (like 'length'), just trigger that key\n trigger(target, TriggerOpTypes.SET, key);\n }\n }\n return result;\n },\n});\n\nconst shallowArrayHandlers = arrayHandlers(true);\nconst deepArrayHandlers = arrayHandlers(false);\n\n// Proxy handler for Map and Set collections.\nconst collectionHandlers: ProxyHandler<Map<unknown, unknown> | Set<unknown>> = {\n get(target, key: string | symbol) {\n if (key === SignalFlags.IS_REACTIVE) {\n return true;\n }\n if (key === SignalFlags.RAW) {\n return target;\n }\n // Return enhanced method or original method.\n return Reflect.get(\n hasOwn(collectionInstrumentations, key) ? collectionInstrumentations : target,\n key,\n target,\n );\n },\n};\n\n// Proxy handler for WeakMap and WeakSet collections.\nconst weakCollectionHandlers: ProxyHandler<WeakMap<object, unknown> | WeakSet<object>> = {\n get(target, key: string | symbol) {\n if (key === SignalFlags.IS_REACTIVE) {\n return true;\n }\n if (key === SignalFlags.RAW) {\n return target;\n }\n // Return enhanced method or original method.\n return Reflect.get(\n hasOwn(weakInstrumentations, key) && key in target ? weakInstrumentations : target,\n key,\n target,\n );\n },\n};\n\n// Enhanced versions of Map and Set collection methods.\nconst collectionInstrumentations = {\n get(this: Map<unknown, unknown>, key: unknown) {\n const target = toRaw(this);\n // Track access to the collection\n track(target, COLLECTION_KEY);\n\n const value = target.get(key);\n\n // For deep reactive mode, wrap object values in reactive proxy\n if (isObject(value) && !isShallow(this)) {\n return reactiveImpl(value);\n }\n\n return value;\n },\n set(this: Map<unknown, unknown>, key: unknown, value: unknown) {\n const target = toRaw(this);\n const hadKey = target.has(key);\n const oldValue = target.get(key);\n\n // Store raw value to avoid nested reactive wrapping\n const rawValue = toRaw(value);\n target.set(key, rawValue);\n\n // Only trigger if value actually changed or key is new\n if (!hadKey || hasChanged(oldValue, rawValue)) {\n trigger(target, TriggerOpTypes.SET, COLLECTION_KEY);\n }\n\n return this; // Return the reactive proxy, not the raw target\n },\n add(this: Set<unknown>, value: unknown) {\n const target = toRaw(this);\n // Store raw value to avoid nested reactive wrapping\n const rawValue = toRaw(value);\n const hadValue = target.has(rawValue);\n\n target.add(rawValue);\n\n // Trigger even if value already exists, as this is still a write operation\n // This ensures consistency with reactive tracking\n if (!hadValue) {\n trigger(target, TriggerOpTypes.ADD, COLLECTION_KEY);\n } else {\n // Even if value exists, trigger SET to notify watchers\n trigger(target, TriggerOpTypes.SET, COLLECTION_KEY);\n }\n\n return this; // Return the reactive proxy, not the raw target\n },\n has(key: unknown) {\n const target = toRaw(this);\n // Track access to the collection\n track(target, COLLECTION_KEY);\n\n // Try with original key first, then with raw key\n // This handles reactive objects as keys\n const hasKey = target.has(key);\n if (!hasKey && isObject(key)) {\n return target.has(toRaw(key));\n }\n\n return hasKey;\n },\n delete(key: unknown) {\n const target = toRaw(this);\n const hadKey = target.has(key);\n\n // Try deleting with original key first\n let result = target.delete(key);\n\n // If failed and key is an object, try with raw key\n if (!result && isObject(key)) {\n result = target.delete(toRaw(key));\n }\n\n // Only trigger if something was actually deleted\n if (hadKey || result) {\n trigger(target, TriggerOpTypes.DELETE, COLLECTION_KEY);\n }\n\n return result;\n },\n clear() {\n const target = toRaw(this);\n const hadItems = target.size > 0;\n const result = target.clear();\n\n // Only trigger if collection had items\n if (hadItems) {\n trigger(target, TriggerOpTypes.CLEAR, COLLECTION_KEY);\n }\n\n return result;\n },\n forEach(\n this: Map<unknown, unknown> | Set<unknown>,\n callback: (value: unknown, key: unknown, map: Map<unknown, unknown> | Set<unknown>) => void,\n thisArg?: unknown,\n ) {\n const target = toRaw(this);\n const isShallowMode = isShallow(this);\n\n // Track access to the collection\n track(target, COLLECTION_KEY);\n\n // Wrap callback to provide reactive values in deep mode\n target.forEach((value: unknown, key: unknown) => {\n const wrappedValue = isShallowMode || !isObject(value) ? value : reactiveImpl(value);\n const wrappedKey = isShallowMode || !isObject(key) ? key : reactiveImpl(key);\n\n callback.call(thisArg, wrappedValue, wrappedKey, this);\n });\n },\n [Symbol.iterator](this: Map<unknown, unknown> | Set<unknown>) {\n const target = toRaw(this);\n const isShallowMode = isShallow(this);\n\n // Track access to the collection\n track(target, COLLECTION_KEY);\n\n const rawIterator = target[Symbol.iterator]();\n\n return {\n next() {\n const { value, done } = rawIterator.next();\n\n if (done) {\n return { value, done };\n }\n\n // In shallow mode, return as-is\n if (isShallowMode) {\n return { value, done };\n }\n\n // For Map entries [key, value], wrap both if they're objects\n if (Array.isArray(value)) {\n return {\n value: value.map(v => (isObject(v) ? reactiveImpl(v) : v)),\n done,\n };\n }\n\n // For Set values, wrap if object\n return {\n value: isObject(value) ? reactiveImpl(value) : value,\n done,\n };\n },\n [Symbol.iterator]() {\n return this;\n },\n };\n },\n get size() {\n const target = toRaw(this);\n // Track access to size property\n track(target, COLLECTION_KEY);\n return target.size;\n },\n keys(this: Map<unknown, unknown> | Set<unknown>) {\n const target = toRaw(this);\n const isShallowMode = isShallow(this);\n\n // Track access to the collection\n track(target, COLLECTION_KEY);\n\n const rawIterator = target.keys();\n\n return {\n next() {\n const { value, done } = rawIterator.next();\n\n if (done) {\n return { value, done };\n }\n\n // Wrap keys if they're objects and in deep mode\n return {\n value: isShallowMode || !isObject(value) ? value : reactiveImpl(value),\n done,\n };\n },\n [Symbol.iterator]() {\n return this;\n },\n };\n },\n values(this: Map<unknown, unknown> | Set<unknown>) {\n const target = toRaw(this);\n const isShallowMode = isShallow(this);\n\n // Track access to the collection\n track(target, COLLECTION_KEY);\n\n const rawIterator = target.values();\n\n return {\n next() {\n const { value, done } = rawIterator.next();\n\n if (done) {\n return { value, done };\n }\n\n // Wrap values if they're objects and in deep mode\n return {\n value: isShallowMode || !isObject(value) ? value : reactiveImpl(value),\n done,\n };\n },\n [Symbol.iterator]() {\n return this;\n },\n };\n },\n entries(this: Map<unknown, unknown> | Set<unknown>) {\n const target = toRaw(this);\n const isShallowMode = isShallow(this);\n\n // Track access to the collection\n track(target, COLLECTION_KEY);\n\n const rawIterator = target.entries();\n\n return {\n next() {\n const { value, done } = rawIterator.next();\n\n if (done) {\n return { value, done };\n }\n\n // In shallow mode, return as-is\n if (isShallowMode) {\n return { value, done };\n }\n\n // Wrap both key and value if they're objects\n return {\n value: value.map((v: unknown) => (isObject(v) ? reactiveImpl(v) : v)),\n done,\n };\n },\n [Symbol.iterator]() {\n return this;\n },\n };\n },\n};\n\n// Enhanced versions of WeakMap and WeakSet collection methods.\nconst weakInstrumentations = {\n get(this: WeakMap<object, unknown>, key: object) {\n const target = toRaw(this);\n // Track access to the weak collection\n track(target, WEAK_COLLECTION_KEY);\n\n // Try with original key first\n let value = target.get(key);\n\n // If not found and key is reactive, try with raw key\n if (value === undefined && isReactive(key)) {\n value = target.get(toRaw(key));\n }\n\n // For deep reactive mode, wrap object values in reactive proxy\n if (isObject(value) && !isShallow(this)) {\n return reactiveImpl(value);\n }\n\n return value;\n },\n set(this: WeakMap<object, unknown>, key: object, value: unknown) {\n const target = toRaw(this);\n const rawKey = toRaw(key);\n const hadKey = target.has(rawKey);\n const oldValue = target.get(rawKey);\n\n // Store raw value to avoid nested reactive wrapping\n const rawValue = toRaw(value);\n target.set(rawKey, rawValue);\n\n // Only trigger if value actually changed or key is new\n if (!hadKey || hasChanged(oldValue, rawValue)) {\n trigger(target, TriggerOpTypes.SET, WEAK_COLLECTION_KEY);\n }\n\n return this; // Return the reactive proxy, not the raw target\n },\n add(this: WeakSet<object>, value: object) {\n const target = toRaw(this);\n const rawValue = toRaw(value);\n const hadValue = target.has(rawValue);\n\n target.add(rawValue);\n\n // Only trigger if value is new\n if (!hadValue) {\n trigger(target, TriggerOpTypes.ADD, WEAK_COLLECTION_KEY);\n }\n\n return this; // Return the reactive proxy, not the raw target\n },\n has(key: object) {\n const target = toRaw(this);\n // Track access to the weak collection\n track(target, WEAK_COLLECTION_KEY);\n\n // Try with original key first\n let hasKey = target.has(key);\n\n // If not found and key is reactive, try with raw key\n if (!hasKey && isReactive(key)) {\n hasKey = target.has(toRaw(key));\n }\n\n return hasKey;\n },\n delete(key: object) {\n const target = toRaw(this);\n const rawKey = toRaw(key);\n const hadKey = target.has(rawKey);\n\n const result = target.delete(rawKey);\n\n // Only trigger if something was actually deleted\n if (hadKey || result) {\n trigger(target, TriggerOpTypes.DELETE, WEAK_COLLECTION_KEY);\n }\n\n return result;\n },\n};\n\n/**\n * Proxy handler for plain objects (non-collection types).\n * Intercepts get, set, and delete operations to manage reactivity.\n *\n * @param shallow - Indicates whether to create shallow reactive proxy.\n * @returns Object containing get, set, and delete traps.\n */\nconst objectHandlers = (shallow: boolean) => ({\n get(target: object, key: string | symbol, receiver: object) {\n if (key === SignalFlags.RAW) {\n return target;\n }\n if (key === SignalFlags.IS_REACTIVE) {\n return true;\n }\n if (key === SignalFlags.IS_SHALLOW) {\n return shallow;\n }\n\n const value = Reflect.get(target, key, receiver);\n\n // Auto-unwrap signals.\n const valueUnwrapped = isSignal(value) ? value.value : value;\n\n // Collect dependencies for accessed properties.\n track(target, key);\n\n // If needed, recursively wrap the value in a reactive proxy.\n if (isObject(valueUnwrapped) && !shallow) {\n return reactiveImpl(valueUnwrapped);\n }\n return valueUnwrapped;\n },\n set: (target: object, key: string | symbol, value: unknown, receiver: object) => {\n const oldValue = Reflect.get(target, key, receiver);\n // When setting value, ensure the raw value is set.\n const result = Reflect.set(target, key, toRaw(value), receiver);\n if (hasChanged(value, oldValue)) {\n trigger(target, TriggerOpTypes.SET, key, value);\n }\n return result;\n },\n deleteProperty: (target: object, key: string | symbol) => {\n const hadKey = hasOwn(target, key);\n const result = Reflect.deleteProperty(target, key);\n if (hadKey && result) {\n trigger(target, TriggerOpTypes.DELETE, key, undefined);\n }\n return result;\n },\n});\n\nconst shallowObjectHandlers = objectHandlers(true);\nconst deepObjectHandlers = objectHandlers(false);\n\nexport function reactiveImpl<T extends object>(target: T, shallow = false): T {\n if (!isObject(target)) {\n return target;\n }\n\n // If target object is already reactive, return directly.\n if (isReactive(target)) {\n return target;\n }\n\n // Check if proxy already exists in cache.\n const existingProxy = reactiveCaches.get(target);\n if (existingProxy) {\n return existingProxy as T;\n }\n\n // Choose appropriate handler based on target type.\n let handler;\n if (isArray(target)) {\n handler = shallow ? shallowArrayHandlers : deepArrayHandlers;\n } else if (isSet(target) || isMap(target)) {\n handler = collectionHandlers;\n } else if (isWeakMap(target) || isWeakSet(target)) {\n handler = weakCollectionHandlers;\n } else {\n handler = shallow ? shallowObjectHandlers : deepObjectHandlers;\n }\n\n // Create and cache proxy.\n const proxy = new Proxy(target, handler);\n reactiveCaches.set(target, proxy);\n return proxy;\n}\n\n/**\n * Check if the target object is reactive.\n *\n * @param target - The object to check.\n * @returns True if the object is reactive, false otherwise.\n */\nexport function isReactive(target: unknown): boolean {\n return !!(target && target[SignalFlags.IS_REACTIVE]);\n}\n\n/**\n * Create a reactive proxy for the given target object. If the object is already reactive, return directly.\n *\n * @template T - The type of the object to make reactive\n * @param target - The object to make reactive\n * @returns The reactive proxy of the target object\n *\n * @example\n * ```typescript\n * const state = reactive({ count: 0, nested: { value: 1 } });\n * // Both state.count and state.nested.value are reactive\n * ```\n */\nexport function reactive<T extends object>(target: T): T {\n //If already reactive, return directly to prevent double wrapping\n if (isReactive(target)) {\n return target;\n }\n\n // If target is a signal, warn and unwrap it\n if (isSignal(target)) {\n // Return the signal as-is since signals are already reactive\n return target;\n }\n\n return reactiveImpl(target);\n}\n\n/**\n * Create a shallow reactive proxy for the given object. Only root-level properties are reactive.\n *\n * @template T - The type of the object to make shallow reactive\n * @param target - The object to make shallow reactive\n * @returns The shallow reactive proxy of the object\n *\n * @example\n * ```typescript\n * const state = shallowReactive({ count: 0, nested: { value: 1 } });\n * // Only state.count is reactive, not state.nested.value\n * ```\n */\nexport function shallowReactive<T extends object>(target: T): T {\n // If already reactive, check if it's shallow\n if (isReactive(target)) {\n return target;\n }\n\n // If target is a signal, warn and unwrap it\n if (isSignal(target)) {\n // Return the signal as-is since signals are already reactive\n return target;\n }\n\n return reactiveImpl(target, true);\n}\n\n/**\n * Check if the target object is a shallow reactive proxy.\n *\n * @param value - The object to check.\n * @returns True if the object is shallow reactive, false otherwise.\n */\nexport function isShallow(value: unknown): boolean {\n return !!(value && value[SignalFlags.IS_SHALLOW]);\n}\n\n/**\n * Return a reactive proxy for the given value (if possible).\n * If the given value is not an object, return the original value itself.\n *\n * @param value - The value that needs a reactive proxy created for it.\n */\nexport const toReactive = <T extends unknown>(value: T): T =>\n isObject(value) ? reactive(value) : value;\n\n/**\n * Type alias representing a reactive object.\n *\n * @template T - The type of the original object.\n */\nexport type Reactive<T extends object> = T;\n","import { hasChanged, isObject, warn } from '@estjs/shared';\nimport { activeSub, linkReactiveNode, shallowPropagate } from './link';\nimport { ReactiveFlags, SignalFlags } from './constants';\nimport { isReactive, reactive, shallowReactive, toRaw } from './reactive';\nimport { propagate } from './propagation';\nimport type { Link, ReactiveNode } from './link';\n\n/**\n * Signal is a reactive primitive that holds a value and notifies subscribers when the value changes.\n * It provides methods for reading, writing, and observing value changes.\n *\n * @template T - The type of value held by the Signal\n */\nexport interface Signal<T> {\n /**\n * The current value of the Signal. Reading this property tracks dependencies,\n * and writing to it notifies subscribers of changes.\n */\n value: T;\n\n /**\n * Get the current value without establishing a dependency relationship.\n * Useful when you need to read the value without tracking dependencies.\n *\n * @returns The current value\n */\n peek(): T;\n\n /**\n * Set a new value without notifying subscribers.\n * Used for batching multiple updates together.\n *\n * @param value - The new value to set\n */\n set(value: T): void;\n\n /**\n * Update the value using a function that receives the current value.\n * This is an atomic operation that only notifies subscribers once.\n *\n * @param updater - A function that receives the current value and returns the new value\n */\n update(updater: (prev: T) => T): void;\n}\n\n/**\n * A more precise type for the value held by a signal.\n * This type helps TypeScript understand the type of the unwrapped value.\n *\n * @template T - The type of value held by the signal\n */\nexport type SignalValue<T> = T extends Signal<infer V> ? V : never;\n/**\n * Extract the value type from a Signal\n *\n * @template T - The Signal type\n *\n * @example\n * ```typescript\n * import { signal, type SignalType } from '@estjs/signals';\n *\n * const count = signal(0);\n * type CountValue = SignalType<typeof count>; // number\n * ```\n */\nexport type SignalType<T> = T extends Signal<infer V> ? V : never;\n\n/**\n * Internal implementation of the Signal interface.\n * This class manages reactive state and handles dependency tracking.\n\n * @template T - The type of value held by the Signal\n */\n\nexport class SignalImpl<T> implements ReactiveNode {\n // Implement ReactiveNode interface\n depLink?: Link | undefined;\n subLink?: Link | undefined;\n depLinkTail?: Link | undefined;\n subLinkTail?: Link | undefined;\n flag: ReactiveFlags = ReactiveFlags.MUTABLE; // Initial state is \"mutable\"\n\n // _oldValue is deliberately NOT initialized here so that `'_oldValue' in instance`\n // returns false until the first value change — the test suite directly checks this.\n protected _oldValue!: T; // on-demand, only present after first change\n protected _rawValue: T; // Store raw (non-proxied) new value\n\n _value: T; // Store current value (may be a reactive proxy)\n\n private readonly [SignalFlags.IS_SHALLOW]: boolean; // Mark whether it's shallow reactive\n\n // @ts-ignore: used internally by isSignal typeguard\n private readonly [SignalFlags.IS_SIGNAL] = true as const;\n\n /**\n * Create a new Signal with the given initial value.\n *\n * @param value - Initial value\n * @param shallow - Whether only the top level should be reactive\n */\n constructor(value?: T, shallow = false) {\n // Optimization: Don't initialize _oldValue in constructor\n // It will be created on-demand in shouldUpdate()\n\n // Extract raw value correctly in constructor to ensure _rawValue is never a proxy\n const unwrapped = toRaw(value);\n this._rawValue = unwrapped as T;\n\n this[SignalFlags.IS_SHALLOW] = shallow;\n\n // Fast path: if primitive, no proxy needed\n if (!isObject(unwrapped)) {\n this._value = unwrapped as T;\n } else {\n // If value is already reactive, reuse it directly instead of lookup\n if (isReactive(value)) {\n this._value = value as T;\n } else {\n this._value = (\n shallow ? shallowReactive(unwrapped as object) : reactive(unwrapped as object)\n ) as T;\n }\n }\n }\n\n // dep getter, returns itself for dependency collection\n get dep(): this {\n return this;\n }\n\n get value(): T {\n const sub = activeSub;\n if (sub) {\n linkReactiveNode(this, sub);\n }\n\n // Optimization: Cache flag and subLink to local variables to reduce property access\n const flags = this.flag;\n if (flags & ReactiveFlags.DIRTY && this.shouldUpdate()) {\n // Cache subLink locally to avoid repeated property access\n const subs = this.subLink;\n if (subs) {\n shallowPropagate(subs);\n }\n }\n\n return this._value;\n }\n\n // value setter, triggers update when value changes\n set value(newValue: T) {\n // If the new value is another signal, unwrap it\n if (isSignal(newValue)) {\n if (__DEV__) {\n warn(\n 'Setting a signal value to another signal is not recommended. ' +\n 'The value will be unwrapped automatically.',\n );\n }\n newValue = (newValue as Signal<T>).peek() as T;\n }\n\n // Keep a reference to the caller-supplied value (may already be a reactive proxy)\n // before stripping it to raw, so we can reuse the existing proxy if present.\n const originalValue = newValue;\n const rawValue = toRaw(newValue);\n\n if (!hasChanged(this._rawValue, rawValue)) {\n return;\n }\n\n this._oldValue = this._rawValue;\n this._rawValue = rawValue;\n this.flag |= ReactiveFlags.DIRTY;\n\n if (!isObject(rawValue)) {\n // Primitive: no proxy needed\n this._value = rawValue as T;\n } else if (isReactive(originalValue)) {\n // The caller already handed us a reactive proxy — reuse it directly.\n // This avoids an unnecessary WeakMap lookup in reactiveCaches.\n this._value = originalValue as T;\n } else {\n // Plain object/array: wrap in a reactive proxy (cached by reactiveCaches).\n const shallow = this[SignalFlags.IS_SHALLOW];\n this._value = (\n shallow ? shallowReactive(rawValue as object) : reactive(rawValue as object)\n ) as T;\n }\n\n const subs = this.subLink;\n if (subs) {\n propagate(subs);\n }\n }\n\n // Check if the value should be updated\n shouldUpdate(): boolean {\n this.flag &= ~ReactiveFlags.DIRTY;\n\n // _oldValue is only assigned in the setter (on-demand), so `'_oldValue' in this` is false\n // until the first actual change. This preserves the test-verified optimization.\n if (!('_oldValue' in this)) {\n return true;\n }\n\n const changed = hasChanged(this._oldValue as T, this._rawValue);\n this._oldValue = this._rawValue;\n return changed;\n }\n\n // Get current value without triggering dependency tracking\n peek(): T {\n return this._value;\n }\n\n // set method is an alias for the value setter\n set(value: T): void {\n this.value = value;\n }\n\n // Update value using an updater function\n update(updater: (prev: T) => T): void {\n const nextValue = updater(this.peek());\n // Handle case where updater function returns a signal\n if (isSignal(nextValue)) {\n if (__DEV__) {\n warn(\n 'Returning a signal from an update function is not recommended. The value will be unwrapped.',\n );\n }\n this.value = nextValue.peek() as T;\n } else {\n this.value = nextValue;\n }\n }\n}\n\n/**\n * Create a new signal with the given initial value.\n * The signal will track all nested properties of object values.\n *\n * @template T - The type of value to store in the signal\n * @param value - Initial value (defaults to undefined)\n * @returns A new signal instance\n *\n * @example\n * ```typescript\n * const count = signal(0);\n * const user = signal({ name: 'John' });\n * const empty = signal(); // undefined\n * ```\n */\nexport function signal<T>(value: Signal<T>): Signal<T>;\nexport function signal<T>(value?: T): Signal<T>;\nexport function signal<T>(value?: T) {\n // If the value is already a signal, return it directly to avoid duplicate creation\n if (isSignal(value)) {\n if (__DEV__) {\n warn(\n 'Creating a signal with another signal is not recommended. The value will be unwrapped.',\n );\n }\n return value as T;\n }\n return new SignalImpl(value);\n}\n/**\n * Create a new shallow signal with the given initial value.\n * Only the top-level properties of object values are reactive.\n *\n * @template T - The type of value to store in the signal\n * @param value - Initial value (defaults to undefined)\n * @returns A new shallow signal instance\n *\n * @example\n * ```typescript\n * const state = shallowSignal({ nested: { value: 1 } });\n * // Only state.nested is reactive, not state.nested.value\n * ```\n */\nexport function shallowSignal<T>(value?: T): Signal<T> {\n // If the value is a signal, extract its value\n if (isSignal(value)) {\n value = value.peek() as T;\n }\n return new SignalImpl(value, true);\n}\n\n/**\n * Type guard to check if a value is a Signal instance.\n *\n * @template T - The type of value held by the signal\n * @param value - The value to check\n * @returns true if the value is a Signal instance\n */\nexport function isSignal<T>(value: unknown): value is Signal<T> {\n return !!value && !!value[SignalFlags.IS_SIGNAL];\n}\n","import { error, warn } from '@estjs/shared';\n\n/**\n * Represents a task (job) that can be scheduled for execution\n */\nexport type Job = () => void;\n\n/**\n * Represents a callback function that should be executed before the main task queue\n */\nexport type PreFlushCallback = () => void;\n\n/**\n * Represents the possible flush timing strategies for effects\n *\n * - 'pre': Execute before the main queue (useful for component updates)\n * - 'post': Execute after the main queue (default behavior)\n * - 'sync': Execute immediately and synchronously (use sparingly)\n */\nexport type FlushTiming = 'pre' | 'post' | 'sync';\n\n// Main task queue storing jobs waiting to be executed\n// Using Set for automatic deduplication\nconst queue: Set<Job> = new Set();\n\n// Pre-flush callback queue, cleared before main task queue execution\n// Using Set for automatic deduplication\nconst activePreFlushCbs: Set<PreFlushCallback> = new Set();\n\n// Resolved Promise used to schedule tasks into the microtask queue\nconst p = Promise.resolve();\n\n// Flag to prevent duplicate flush scheduling, ensuring only one schedule per event loop\nlet isFlushPending = false;\n\n/**\n * Schedules a function to be executed in the next microtask\n *\n * Returns a Promise that resolves in the next microtask.\n * Passing fn chains it onto the shared resolved promise — cheaper than\n * constructing a new Promise + queueMicrotask pair.\n *\n * @param fn - Optional function to execute\n * @returns A Promise that resolves after the function execution\n */\nexport function nextTick(fn?: () => void): Promise<void> {\n return fn ? p.then(fn) : p;\n}\n\n/**\n * Adds a job to the main queue and ensures it will be executed\n *\n * Jobs are automatically deduplicated - the same job reference won't be added multiple times.\n * This is useful for batching updates and avoiding redundant work.\n * @param job - The job to enqueue\n */\nexport function queueJob(job: Job): void {\n queue.add(job); // Set automatically deduplicates\n queueFlush();\n}\n\n/**\n * Schedules a queue flush in the next microtask if one hasn't been scheduled yet\n *\n * @internal\n */\nfunction queueFlush(): void {\n if (!isFlushPending) {\n isFlushPending = true;\n nextTick(flushJobs);\n }\n}\n\n/**\n * Adds a callback to be executed before the main queue processing\n *\n * Pre-flush callbacks are useful for setup work that needs to run before effects,\n * such as computing derived values or preparing state.\n * @param cb - The callback to execute before the main queue\n */\nexport function queuePreFlushCb(cb: PreFlushCallback): void {\n activePreFlushCbs.add(cb); // Set automatically deduplicates\n queueFlush();\n}\n\n/**\n * Executes all enqueued jobs and pre-flush callbacks\n *\n * This function runs in a microtask and processes the entire queue.\n * Jobs are executed in order, with error handling to prevent one failing job from blocking others.\n *\n * ## Cleanup Process\n *\n * 1. Reset flush pending flag\n * 2. Execute pre-flush callbacks and clear their queue\n * 3. Execute main jobs and clear their queue\n * 4. Handle jobs queued during flush\n *\n * ## Memory Management\n *\n * - Jobs queued during flush are executed in the same cycle\n * - Error handling prevents one failing job from blocking others\n * - All temporary state is cleared after execution\n *\n * @internal\n */\nexport function flushJobs(): void {\n isFlushPending = false;\n\n // Execute pre-flush callbacks first\n flushPreFlushCbs();\n\n // Process jobs until queue is empty.\n // Iterate the Set directly (before clearing) rather than Array.from() to avoid\n // a full copy allocation each tick. Jobs added during execution are picked up\n // in the next while-iteration.\n while (queue.size > 0) {\n for (const job of queue) {\n try {\n job();\n } catch (_error) {\n if (__DEV__) {\n error('Error executing queued job:', _error);\n }\n }\n }\n queue.clear();\n }\n}\n\n/**\n * Executes all pre-flush callbacks\n *\n * Pre-flush callbacks are executed before the main job queue.\n * This is useful for setup work that needs to run before effects.\n *\n * ## Cleanup Process\n *\n * 1. Copy callbacks to array\n * 2. Clear the callback queue immediately\n * 3. Execute all callbacks with error handling\n *\n * @internal\n */\nfunction flushPreFlushCbs(): void {\n // Convert Set to array and clear the Set immediately\n // This allows new callbacks to be queued during execution\n const callbacks = Array.from(activePreFlushCbs);\n activePreFlushCbs.clear();\n\n // Execute all callbacks with error handling\n for (const callback of callbacks) {\n try {\n callback();\n } catch (_error) {\n if (__DEV__) {\n error('Error executing pre-flush callback:', _error);\n }\n }\n }\n}\n\n/**\n * Creates a scheduler function for an effect based on the specified flush timing\n *\n * This is used internally by the effect system to control when effects execute:\n * - 'sync': Immediate execution (blocking)\n * - 'pre': Before main queue (setup phase)\n * - 'post': After main queue (cleanup/side effects)\n * @param effect - The effect function to schedule\n * @param flush - When to execute the effect\n * @returns A scheduler function that will run the effect at the appropriate time\n */\nexport function createScheduler(\n effect: () => void,\n flush: FlushTiming,\n): () => void | Promise<void> {\n switch (flush) {\n case 'sync':\n return () => effect();\n case 'pre':\n return () => queuePreFlushCb(effect);\n case 'post':\n return () => queueJob(effect);\n default:\n if (__DEV__) {\n warn(`Invalid flush timing: ${flush}. Defaulting to 'post'.`);\n }\n return () => queueJob(effect);\n }\n}\n","import { warn } from '@estjs/shared';\nimport { flushJobs } from './scheduler';\n/**\n * Batch update depth\n *\n * Supports nested batch calls.\n * Effects are only flushed when the outermost batch ends.\n */\nlet batchDepth = 0;\n\n/**\n * Execute a function in batch mode\n *\n * Executes the function in a batch context, where all Signal changes\n * are deferred and processed together after the batch ends.\n *\n * @param fn - The function to execute in batch mode\n * @returns The return value of the function\n *\n * @example\n * ```typescript\n * const x = signal(0);\n * const y = signal(0);\n *\n * effect(() => {\n * console.log('Sum:', x.value + y.value);\n * });\n *\n * // Without batch - Effect executes 2 times\n * x.value = 1; // Effect executes\n * y.value = 2; // Effect executes\n *\n * // With batch - Effect executes only 1 time\n * batch(() => {\n * x.value = 10;\n * y.value = 20;\n * }); // Effect executes once\n * ```\n */\nexport function batch<T>(fn: () => T): T {\n startBatch();\n try {\n return fn();\n } finally {\n endBatch();\n }\n}\n\n/**\n * Start batch update\n *\n * Increases batch depth.\n * During batch, Effects won't execute immediately.\n */\nexport function startBatch(): void {\n batchDepth++;\n}\n\n/**\n * End batch update\n *\n * Decreases batch depth.\n * When depth reaches zero, flush all queued Effects.\n *\n * ## Cleanup Process\n *\n * When the outermost batch ends:\n * 1. Flush all queued jobs (effects execute)\n * 2. Job queue is automatically cleared by flushJobs()\n * 3. Temporary flags (QUEUED, DIRTY) are cleared by effect execution\n *\n * ## Development Mode Checks\n *\n * In development mode, this function performs additional validation:\n * - Detects unbalanced batch calls (endBatch without startBatch)\n * - Prevents batchDepth from becoming negative\n * - Provides clear error messages to help debug batch management issues\n */\nexport function endBatch(): void {\n // Development mode: Check for unbalanced batch calls\n if (__DEV__ && batchDepth === 0) {\n warn(\n '[Batch] endBatch() called without matching startBatch(). ' +\n 'This indicates unbalanced batch calls in your code. ' +\n 'Make sure every startBatch() has a corresponding endBatch(), ' +\n 'or use the batch() function which handles this automatically.',\n );\n return;\n }\n\n // Decrement batch depth\n batchDepth--;\n\n // When outermost batch ends, flush all queued effects\n if (batchDepth === 0) {\n flushJobs();\n }\n}\n\n/**\n * Check if currently in batch update mode\n *\n * @returns true if currently in batch\n */\nexport function isBatching(): boolean {\n return batchDepth > 0;\n}\n\n/**\n * Get current batch depth\n *\n * Mainly used for debugging.\n *\n * @returns Current batch nesting depth\n */\nexport function getBatchDepth(): number {\n return batchDepth;\n}\n","import { error, isFunction, warn } from '@estjs/shared';\nimport { EffectFlags, ReactiveFlags, SignalFlags } from './constants';\nimport { checkDirty, endTracking, startTracking, unlinkReactiveNode } from './link';\nimport { isBatching } from './batch';\nimport { createScheduler, queueJob } from './scheduler';\nimport type { Computed } from './computed';\nimport type { Signal } from './signal';\nimport type { Reactive } from './reactive';\nimport type { DebuggerEvent, Link, ReactiveNode } from './link';\nimport type { FlushTiming } from './scheduler';\n\n/**\n * Unwrap a Signal, Computed, or Reactive type to get the underlying value type\n *\n * @template T - The wrapped type\n *\n * @example\n * ```typescript\n * import type { Signal, Computed, Reactive, Unwrap } from '@estjs/signals';\n *\n * type Count = Unwrap<Signal<number>>; // number\n * type User = Unwrap<Reactive<{ name: string }>>; // { name: string }\n * type Double = Unwrap<Computed<number>>; // number\n * ```\n */\nexport type Unwrap<T> =\n T extends Signal<infer V>\n ? V\n : T extends Computed<infer V>\n ? V\n : T extends Reactive<infer V extends object>\n ? V\n : T;\n\n/**\n * Effect function type\n */\nexport type EffectFunction<T = any> = () => T;\n\n/**\n * Effect scheduler function type\n */\nexport type EffectScheduler = (effect: EffectImpl) => void;\n\n/**\n * Effect options configuration\n */\nexport interface EffectOptions {\n /**\n * Custom scheduler for controlling when the effect runs\n * Can be a function or a timing string ('sync', 'pre', 'post')\n */\n scheduler?: EffectScheduler | FlushTiming;\n\n /**\n * Alias for scheduler - controls when the effect runs\n * Can be 'sync', 'pre', or 'post'\n */\n flush?: FlushTiming;\n\n /**\n * Callback invoked when the effect is stopped\n * Useful for cleanup operations\n */\n onStop?: () => void;\n\n /**\n * Debug callback invoked when a dependency is tracked\n * Only called in development mode\n *\n * @param event - Information about the tracked dependency\n *\n * @example\n * ```typescript\n * effect(() => {\n * console.log(signal.value);\n * }, {\n * onTrack(event) {\n * console.log('Tracked:', event.type, event.key);\n * }\n * });\n * ```\n */\n onTrack?: (event: DebuggerEvent) => void;\n\n /**\n * Debug callback invoked when the effect is triggered by a dependency change\n * Only called in development mode\n *\n * @param event - Information about what triggered the effect\n *\n * @example\n * ```typescript\n * effect(() => {\n * console.log(signal.value);\n * }, {\n * onTrigger(event) {\n * console.log('Triggered by:', event.type, event.key, event.newValue);\n * }\n * });\n * ```\n */\n onTrigger?: (event: DebuggerEvent) => void;\n}\n\n/**\n * Effect runner function with attached effect instance\n */\nexport interface EffectRunner<T = any> {\n (): T;\n effect: EffectImpl<T>;\n stop: () => void;\n}\n\n/**\n * Effect implementation class\n *\n * Implements the ReactiveNode interface, acting as a subscriber in the reactive system.\n *\n * Core features:\n * - Automatically tracks dependent reactive values\n * - Automatically re-executes when dependencies change\n * - Supports custom scheduling strategies\n * - Complete lifecycle management\n *\n * @template T - The return type of the effect function\n */\nexport class EffectImpl<T = any> implements ReactiveNode {\n // ReactiveNode interface implementation\n depLink?: Link;\n subLink?: Link;\n depLinkTail?: Link;\n subLinkTail?: Link;\n flag: ReactiveFlags = ReactiveFlags.WATCHING | ReactiveFlags.DIRTY;\n\n // @ts-ignore: used internally by isEffect typeguard\n private readonly [SignalFlags.IS_EFFECT] = true as const;\n\n // Core properties\n readonly fn: EffectFunction<T>;\n private _flushScheduler?: (effect?) => void | Promise<void>;\n\n // State management\n _active = true;\n\n onTrack?: (event: DebuggerEvent) => void;\n onTrigger?: (event: DebuggerEvent) => void;\n onStop?: () => void;\n /**\n * Create an Effect instance\n *\n * @param fn - The effect function\n * @param options - Configuration options\n */\n constructor(fn: EffectFunction<T>, options?: EffectOptions) {\n this.fn = fn;\n\n if (options) {\n // Use flush as an alias for scheduler if provided\n const scheduler = options.scheduler ?? options.flush;\n if (scheduler) {\n this._flushScheduler = isFunction(scheduler)\n ? () => scheduler(this)\n : createScheduler(() => this.run(), scheduler);\n }\n\n if (options.onStop) this.onStop = options.onStop;\n\n // For development debugging hooks, we assign them directly to the instance\n // if provided, so the link.ts checking logic can find them without an extra optional chain.\n if (__DEV__) {\n if (options.onTrack) this.onTrack = options.onTrack;\n if (options.onTrigger) this.onTrigger = options.onTrigger;\n }\n }\n }\n\n /**\n * Check if the Effect is active\n */\n get active(): boolean {\n return this._active;\n }\n\n /**\n * Check if the Effect is dirty (needs re-execution)\n */\n get dirty(): boolean {\n const flags = this.flag;\n\n // Explicitly marked as dirty\n if (flags & ReactiveFlags.DIRTY) {\n return true;\n }\n\n // Pending state, need to check dependencies\n if (flags & ReactiveFlags.PENDING) {\n if (this.depLink && checkDirty(this.depLink, this)) {\n // Use bitwise operations to set DIRTY and clear PENDING in one operation\n this.flag = (flags & ~ReactiveFlags.PENDING) | ReactiveFlags.DIRTY;\n return true;\n }\n // Dependencies unchanged, clear pending flag using cached flags\n this.flag = flags & ~ReactiveFlags.PENDING;\n }\n\n return false;\n }\n\n /**\n * Pause Effect execution\n *\n * When an effect is paused:\n * - It stops responding to dependency changes\n * - Notifications are ignored (see notify method)\n * - DIRTY and PENDING flags are still set when dependencies change\n * - The effect remains active and maintains its dependency links\n *\n * Use cases:\n * - Temporarily disable effects during bulk updates\n * - Prevent effects from running during initialization\n * - Control when side effects should execute\n *\n * @example\n * ```typescript\n * const count = signal(0);\n * const runner = effect(() => console.log(count.value));\n *\n * runner.effect.pause();\n * count.value = 1; // Effect won't run\n * count.value = 2; // Effect won't run\n * runner.effect.resume(); // Effect runs once with latest value\n * ```\n */\n pause(): void {\n this.flag |= EffectFlags.PAUSED;\n }\n\n /**\n * Resume Effect execution\n *\n * When an effect is resumed:\n * - The PAUSED flag is cleared\n * - If dependencies changed during pause (DIRTY or PENDING flags set),\n * the effect executes immediately via notify()\n * - If no changes occurred, the effect simply becomes active again\n *\n * State management:\n * - Clears PAUSED flag atomically\n * - Checks for accumulated DIRTY/PENDING flags\n * - Triggers execution if needed\n *\n * @example\n * ```typescript\n * const count = signal(0);\n * const runner = effect(() => console.log(count.value));\n *\n * runner.effect.pause();\n * count.value = 1; // Queued\n * count.value = 2; // Queued\n * runner.effect.resume(); // Executes once with count.value = 2\n * ```\n */\n resume(): void {\n const flags = this.flag;\n const nextFlags = flags & ~EffectFlags.PAUSED;\n\n this.flag = nextFlags;\n\n // Check if there are pending updates that accumulated during pause\n const wasDirty = (nextFlags & ReactiveFlags.DIRTY) !== 0;\n const wasPending = (nextFlags & ReactiveFlags.PENDING) !== 0;\n\n if (wasDirty || wasPending) {\n this.notify();\n }\n }\n\n /**\n * Execute the Effect function\n *\n * Core execution flow:\n * 1. Check if active\n * 2. Clear dirty flag\n * 3. Start tracking dependencies\n * 4. Execute user function\n * 5. End tracking, clean up stale dependencies\n\n * @returns The return value of the effect function\n */\n run(): T {\n // Already stopped, execute without tracking\n if (!this._active) {\n return this.fn();\n }\n\n // Cache flags and use bitwise operations to update multiple flags efficiently\n const flags = this.flag;\n // Clear DIRTY/PENDING flags and set RUNNING to block concurrent notify() calls.\n this.flag = (flags & ~(ReactiveFlags.DIRTY | ReactiveFlags.PENDING)) | EffectFlags.RUNNING;\n\n // Start dependency tracking\n const prevSub = startTracking(this);\n\n try {\n // Execute the effect function\n return this.fn();\n } catch (error) {\n // Execution error, restore dirty flag\n this.flag |= ReactiveFlags.DIRTY;\n\n throw error;\n } finally {\n // Clear RUNNING flag\n this.flag &= ~EffectFlags.RUNNING;\n // End tracking, clean up stale dependencies\n endTracking(this, prevSub);\n }\n }\n\n private _job?: () => void;\n\n /**\n * Get or create the job function for this effect\n */\n private getJob(): () => void {\n if (!this._job) {\n this._job = () => this.run();\n }\n return this._job;\n }\n\n /**\n * Notify that the Effect needs to execute\n *\n * Called by dependent reactive values.\n * Decides whether to execute immediately or defer based on scheduling strategy.\n */\n notify(): void {\n // Cache flags for efficient checking\n const flags = this.flag;\n\n // Early exit: already stopped, paused, currently running, or already dirty—ignore notification.\n if (!this._active || flags & (EffectFlags.PAUSED | EffectFlags.RUNNING | ReactiveFlags.DIRTY)) {\n return;\n }\n\n // Mark as dirty\n this.flag = flags | ReactiveFlags.DIRTY;\n\n // Trigger callback\n if (__DEV__ && this?.onTrigger) {\n this.onTrigger({\n effect: this,\n target: {},\n type: 'set',\n });\n }\n\n if (this._flushScheduler) {\n this._flushScheduler?.();\n } else if (isBatching()) {\n // When in batch, queue for execution\n queueJob(this.getJob());\n } else {\n // In normal case, execute immediately and synchronously\n this.run();\n }\n }\n\n /**\n * Stop the Effect\n *\n * After stopping:\n * - No longer responds to dependency changes\n * - Disconnects all dependency links\n * - Clears cached job function\n * - Calls onStop callback\n * - Verifies complete cleanup in development mode\n */\n stop(): void {\n if (!this._active) {\n if (__DEV__) {\n warn('[Effect] Attempting to stop an already stopped effect.');\n }\n return;\n }\n\n this._active = false;\n\n // Disconnect all dependency links\n // This removes this effect from all signals/computed it depends on\n let dep = this.depLink;\n while (dep) {\n dep = unlinkReactiveNode(dep, this);\n }\n\n // Disconnect all subscription links\n // This removes any subscribers that depend on this effect (rare but possible)\n let sub = this.subLink;\n while (sub) {\n sub = unlinkReactiveNode(sub);\n }\n\n // Clear cached job function to free memory\n this._job = undefined;\n this._flushScheduler = undefined;\n\n // Clear link tail pointers to ensure no dangling references\n this.depLinkTail = undefined;\n this.subLinkTail = undefined;\n\n // Verify cleanup in development mode\n if (__DEV__) {\n // Verify all links are properly cleared\n if (this.depLink) {\n error(\n '[Effect] Cleanup verification failed: depLink not cleared. ' +\n 'This indicates a memory leak in the dependency tracking system.',\n );\n }\n if (this.subLink) {\n error(\n '[Effect] Cleanup verification failed: subLink not cleared. ' +\n 'This indicates a memory leak in the subscription system.',\n );\n }\n }\n\n // Call stop callback\n if (this?.onStop) {\n this.onStop();\n }\n }\n}\n\n/**\n * Create and immediately execute an Effect\n *\n * @param fn - The effect function\n * @param options - Configuration options\n * @returns Effect runner\n *\n * @example\n * ```typescript\n * const count = signal(0);\n *\n * // Basic usage\n * const runner = effect(() => {\n * console.log('Count:', count.value);\n * });\n *\n * count.value = 1; // Automatically executes, prints 'Count: 1'\n *\n * // Manual execution\n * runner();\n *\n * // Stop\n * runner.effect.stop();\n *\n * // Custom scheduling\n * effect(() => {\n * console.log(count.value);\n * }, {\n * scheduler: (eff) => {\n * setTimeout(() => eff.run(), 100);\n * }\n * });\n * ```\n */\nexport function effect<T = any>(fn: EffectFunction<T>, options?: EffectOptions): EffectRunner<T> {\n const effectInstance = new EffectImpl(fn, options);\n\n try {\n // Execute immediately once\n effectInstance.run();\n } catch (_error) {\n // First execution failed, stop Effect and rethrow\n effectInstance.stop();\n if (__DEV__) {\n error(\n '[Effect] Effect failed during initial execution and has been stopped. ' +\n 'Fix the error in your effect function.',\n _error,\n );\n }\n throw _error;\n }\n\n // Create runner function\n const runner: any = () => effectInstance.run();\n runner.effect = effectInstance;\n runner.stop = () => effectInstance.stop();\n\n return runner as EffectRunner<T>;\n}\n\n/**\n * Stop Effect execution\n *\n * @param runner - The effect runner\n */\nexport function stop(runner: EffectRunner): void {\n runner.effect.stop();\n}\n\n/**\n * Type guard - Check if value is an Effect\n *\n * @param value - The value to check\n * @returns true if value is an Effect\n */\nexport function isEffect(value: any): value is EffectImpl {\n return !!(value && value[SignalFlags.IS_EFFECT]);\n}\n\n/**\n * Memoized effect function type\n *\n * @template T - State type\n * @param prevState - State from previous execution\n * @returns New state\n */\nexport type MemoEffectFn<T> = (prevState: T) => T;\n\n/**\n * Create a memoized Effect\n *\n * A memoized effect remembers the return value from the previous execution\n * and passes it as a parameter on the next execution.\n *\n * Use cases:\n * - Incremental DOM updates\n * - Avoiding duplicate operations\n * - State persistence\n * - Difference detection\n *\n * @param fn - The memoized function\n * @param initialState - Initial state\n * @param options - Configuration options\n * @returns Effect runner\n *\n * @example\n * ```typescript\n * const width = signal(100);\n *\n * // Only update DOM when width changes\n * memoEffect(prev => {\n * const current = width.value;\n *\n * if (current !== prev.width) {\n * element.style.width = `${current}px`;\n * prev.width = current;\n * }\n *\n * return prev;\n * }, { width: 0 });\n * ```\n */\nexport function memoEffect<T>(\n fn: MemoEffectFn<T>,\n initialState: T,\n options?: EffectOptions,\n): EffectRunner<void> {\n let currentState = initialState;\n\n const effectFn = () => {\n // Pass current state each time\n // fn may modify the passed object, so the return value is the update state\n const result = fn(currentState);\n currentState = result;\n };\n\n return effect(effectFn, options);\n}\n","import { error, hasChanged, isFunction, isPlainObject, warn } from '@estjs/shared';\nimport { ReactiveFlags, SignalFlags } from './constants';\nimport { activeSub, checkDirty, endTracking, linkReactiveNode, startTracking } from './link';\nimport { shallowPropagate } from './propagation';\nimport type { DebuggerEvent, Link, ReactiveNode } from './link';\n\n/**\n * Computed getter function type\n */\nexport type ComputedGetter<T> = () => T;\n\n/**\n * Computed setter function type\n */\nexport type ComputedSetter<T> = (value: T) => void;\n\n/**\n * Computed options configuration\n */\nexport interface ComputedOptions<T> {\n /** Getter function to compute the value */\n get: ComputedGetter<T>;\n\n /** Optional setter function to make the computed writable */\n set?: ComputedSetter<T>;\n\n /**\n * Debug callback invoked when a dependency is tracked\n * Only called in development mode\n *\n * @param event - Information about the tracked dependency\n */\n onTrack?: (event: DebuggerEvent) => void;\n\n /**\n * Debug callback invoked when the computed is triggered by a dependency change\n * Only called in development mode\n *\n * @param event - Information about what triggered the recomputation\n */\n onTrigger?: (event: DebuggerEvent) => void;\n}\n\n/**\n * Computed interface\n */\nexport interface Computed<T> {\n readonly value: T;\n peek(): T;\n}\n/**\n * Extract the value type from a Computed\n *\n * @template T - The Computed type\n *\n * @example\n * ```typescript\n * import { computed, type ComputedType } from '@estjs/signals';\n *\n * const doubled = computed(() => count.value * 2);\n * type DoubledValue = ComputedType<typeof doubled>; // number\n * ```\n */\nexport type ComputedType<T> = T extends Computed<infer V> ? V : never;\n\n/**\n * Sentinel symbol used to represent \"no value\" state in computed\n * Using a Symbol ensures it cannot conflict with any actual computed value\n */\nconst NO_VALUE = Symbol('computed-no-value');\n\n/**\n * Computed implementation class\n *\n * Implements both Computed and ReactiveNode interfaces.\n * Features:\n * - Lazy evaluation: only computes when accessed\n * - Smart caching: returns cached value when dependencies haven't changed\n * - Automatic tracking: automatically tracks dependencies during computation\n *\n * @template T - The type of the computed value\n */\nexport class ComputedImpl<T = any> implements Computed<T>, ReactiveNode {\n // ReactiveNode interface implementation\n depLink?: Link;\n subLink?: Link;\n depLinkTail?: Link;\n subLinkTail?: Link;\n flag: ReactiveFlags = ReactiveFlags.MUTABLE | ReactiveFlags.DIRTY;\n\n // @ts-ignore: used internally by isComputed typeguard\n private readonly [SignalFlags.IS_COMPUTED] = true as const;\n\n // Core properties\n readonly getter: ComputedGetter<T>;\n readonly setter?: ComputedSetter<T>;\n\n // Debug hooks\n readonly onTrack?: (event: DebuggerEvent) => void;\n readonly onTrigger?: (event: DebuggerEvent) => void;\n\n // Cache\n // Use symbol sentinel to distinguish \"no value\" from undefined/null values\n private _value: T | typeof NO_VALUE = NO_VALUE;\n\n /**\n * Create a Computed instance\n *\n * @param getter - The computation function\n * @param setter - Optional setter function\n * @param onTrack - Optional debug callback for dependency tracking\n * @param onTrigger - Optional debug callback for triggers\n */\n constructor(\n getter: ComputedGetter<T>,\n setter?: ComputedSetter<T>,\n onTrack?: (event: DebuggerEvent) => void,\n onTrigger?: (event: DebuggerEvent) => void,\n ) {\n this.getter = getter;\n this.setter = setter;\n this.onTrack = onTrack;\n this.onTrigger = onTrigger;\n this.flag |= ReactiveFlags.DIRTY;\n }\n\n get value(): T {\n // Track dependencies if accessed within an effect or computed\n if (activeSub) {\n linkReactiveNode(this, activeSub);\n }\n\n // Cache flag and hasValue to reduce property access\n const flags = this.flag;\n const hasValue = this._value !== NO_VALUE;\n\n if (hasValue && !(flags & (ReactiveFlags.DIRTY | ReactiveFlags.PENDING))) {\n return this._value as T;\n }\n\n // Dirty state or no value: must recompute\n if (!hasValue || flags & ReactiveFlags.DIRTY) {\n this.recompute();\n return this._value as T;\n }\n\n // Pending state: check if dependencies actually changed\n if (flags & ReactiveFlags.PENDING) {\n if (this.depLink && checkDirty(this.depLink, this)) {\n // Dependencies changed, recompute\n this.recompute();\n } else {\n // Dependencies unchanged, clear pending flag using cached flags\n this.flag = flags & ~ReactiveFlags.PENDING;\n }\n }\n\n return this._value as T;\n }\n\n /**\n * Set value (only effective when setter is provided)\n *\n * @param newValue - The new value\n */\n set value(newValue: T) {\n if (this.setter) {\n this.setter(newValue);\n } else if (__DEV__) {\n warn(\n '[Computed] Cannot set readonly computed value. ' +\n 'Provide a setter in the computed options to make it writable.\\n' +\n 'Example: computed({ get: () => value, set: (v) => { ... } })',\n );\n }\n }\n\n /**\n * Read value without tracking dependencies\n *\n * @returns Current value\n */\n peek(): T {\n if (this._value === NO_VALUE) {\n this.recompute();\n }\n return this._value as T;\n }\n\n /**\n * Recompute the value\n *\n * computation logic:\n * 1. Start tracking dependencies\n * 2. Execute getter function\n * 3. Check if value changed using optimized comparison\n * 4. If changed, update cache and notify subscribers\n * 5. End tracking, clean up stale dependencies\n * @private\n */\n private recompute(): void {\n // Store old value for change detection\n // Use NO_VALUE sentinel to distinguish initial state from undefined/null values\n const oldValue = this._value;\n const hadValue = oldValue !== NO_VALUE;\n\n // Start tracking dependencies\n const prevSub = startTracking(this);\n\n try {\n // Execute computation\n const newValue = this.getter();\n\n // Cache current flags and subLink for efficient bitwise operations and reduced property access\n const flags = this.flag;\n const subs = this.subLink;\n // Pre-calculate the mask for clearing DIRTY and PENDING flags in single operation\n const clearMask = ~(ReactiveFlags.DIRTY | ReactiveFlags.PENDING);\n\n // - If no previous value, always consider it changed\n // - Otherwise use hasChanged for proper comparison (handles NaN, etc.)\n const valueChanged = !hadValue || hasChanged(oldValue, newValue);\n\n if (valueChanged) {\n // Update cache\n this._value = newValue;\n\n // Clear DIRTY and PENDING flags in single operation using cached flags\n this.flag = flags & clearMask;\n\n // Debug hook: notify about the trigger\n if (__DEV__ && this.onTrigger) {\n this.onTrigger({\n effect: this,\n target: this,\n type: 'set',\n key: 'value',\n newValue,\n });\n }\n\n // Notify subscribers only when value actually changed\n // This prevents unnecessary propagation\n // Use cached subLink to avoid property access\n if (subs) {\n shallowPropagate(subs);\n }\n } else {\n // Value unchanged, only clear flags using cached flags\n // No need to propagate since subscribers already have correct value\n this.flag = flags & clearMask;\n }\n } catch (_error) {\n // On error, ensure DIRTY and PENDING flags are cleared first to prevent stuck state\n const clearMask = ~(ReactiveFlags.DIRTY | ReactiveFlags.PENDING);\n this.flag &= clearMask;\n\n // Force recompute on next access instead of setting DIRTY.\n this._value = NO_VALUE;\n\n if (__DEV__) {\n error(\n '[Computed] Error occurred while computing value.\\n' +\n 'The computed will retry on next access.\\n' +\n 'Common causes:\\n' +\n ' - Accessing undefined properties\\n' +\n ' - Circular dependencies\\n' +\n ' - Exceptions in getter function\\n' +\n 'Check your getter function for errors.',\n _error,\n );\n }\n\n throw _error;\n } finally {\n // End tracking, clean up stale dependencies\n // This removes links to dependencies that are no longer accessed\n endTracking(this, prevSub);\n }\n }\n\n /**\n * Check if update is needed\n *\n * Internal use, called by reactive system.\n *\n * @returns true if value changed\n */\n shouldUpdate(): boolean {\n const hadValue = this._value !== NO_VALUE;\n const oldValue = this._value;\n\n this.recompute();\n\n if (!hadValue) {\n return true;\n }\n\n return hasChanged(this._value, oldValue);\n }\n}\n\n/**\n * Create a Computed value\n *\n * @param getterOrOptions - Computation function or configuration object\n * @returns Computed instance\n *\n * @example\n * ```typescript\n * // Read-only computed\n * const count = signal(0);\n * const doubled = computed(() => count.value * 2);\n *\n * console.log(doubled.value); // 0\n * count.value = 5;\n * console.log(doubled.value); // 10\n *\n * // Writable computed\n * const firstName = signal('John');\n * const lastName = signal('Doe');\n *\n * const fullName = computed({\n * get: () => `${firstName.value} ${lastName.value}`,\n * set: (value) => {\n * const [first, last] = value.split(' ');\n * firstName.value = first;\n * lastName.value = last;\n * }\n * });\n *\n * fullName.value = 'Jane Smith';\n * console.log(firstName.value); // 'Jane'\n * ```\n */\nexport function computed<T>(\n getterOrOptions: ComputedGetter<T> | ComputedOptions<T>,\n): ComputedImpl<T> {\n // Guard: Prevent passing computed to computed\n if (isComputed(getterOrOptions)) {\n if (__DEV__) {\n warn(\n '[Computed] Creating a computed from another computed is not recommended. ' +\n 'The existing computed will be returned to avoid unnecessary wrapping.',\n );\n }\n return getterOrOptions as unknown as ComputedImpl<T>;\n }\n\n // Validate input\n if (!getterOrOptions) {\n throw new Error(\n '[Computed] Invalid argument: computed() requires a getter function or options object.',\n );\n }\n\n if (isFunction(getterOrOptions)) {\n return new ComputedImpl(getterOrOptions);\n }\n\n if (isPlainObject(getterOrOptions)) {\n const { get, set, onTrack, onTrigger } = getterOrOptions;\n\n if (!get) {\n throw new Error(\n '[Computed] Invalid options: getter function is required.\\n' +\n 'Usage: computed({ get: () => value, set: (v) => { ... } })',\n );\n }\n\n if (!isFunction(get)) {\n throw new TypeError(\n '[Computed] Invalid options: getter must be a function.\\n' + `Received: ${typeof get}`,\n );\n }\n\n return new ComputedImpl(get, set, onTrack, onTrigger);\n }\n\n throw new Error(\n '[Computed] Invalid argument: expected a function or options object.\\n' +\n `Received: ${typeof getterOrOptions}`,\n );\n}\n\n/**\n * Type guard - Check if value is Computed\n *\n * @param value - The value to check\n * @returns true if value is Computed\n */\nexport function isComputed<T>(value: unknown): value is Computed<T> {\n return !!value && !!value[SignalFlags.IS_COMPUTED];\n}\n","import { isFunction, warn } from '@estjs/shared';\nimport { batch, computed, reactive } from './';\n\n/**\n * Represents a store's state object.\n * Must be a plain object containing the store's reactive state.\n */\nexport type State = Record<string, any>;\n\n/**\n * Represents a store's getters object.\n * Each getter is a function that receives the state and returns a computed value.\n */\nexport type Getters<S extends State> = Record<string, (state: S) => any>;\n\n/**\n * Represents a store's actions object.\n * Each action is a function that can modify the store's state.\n */\nexport type Actions = Record<string, (...args: any[]) => any>;\n\n/**\n * Configuration options for creating a store.\n *\n * @template S - The type of the store's state\n * @template G - The type of the store's getters\n * @template A - The type of the store's actions\n */\nexport interface StoreOptions<S extends State, G extends Getters<S>, A extends Actions> {\n /** The initial state of the store */\n state: S;\n /** Computed values derived from the state */\n getters?: G;\n /** Methods that can modify the store's state */\n actions?: A;\n}\n\n/**\n * Payload for patching store state.\n * Must be a partial object matching the store's state shape.\n */\nexport type PatchPayload<S> = Partial<S>;\n\n/**\n * Callback function for store subscriptions and action notifications.\n */\nexport type StoreCallback<S> = (state: S) => void;\n\n/**\n * Built-in actions available on all stores.\n *\n * @template S - The type of the store's state\n */\nexport interface StoreActions<S extends State> {\n /**\n * Updates multiple state properties at once.\n * Triggers a single update notification.\n *\n * @param payload - Object containing state updates\n */\n patch$: (payload: PatchPayload<S>) => void;\n\n /**\n * Subscribes to state changes.\n * The callback is called whenever the state changes.\n *\n * @param callback - Function to call on state changes\n */\n subscribe$: (callback: StoreCallback<S>) => void;\n\n /**\n * Unsubscribes from state changes.\n *\n * @param callback - The callback to remove\n */\n unsubscribe$: (callback: StoreCallback<S>) => void;\n\n /**\n * Subscribes to action executions.\n * The callback is called whenever an action is executed.\n *\n * @param callback - Function to call on action execution\n */\n onAction$: (callback: StoreCallback<S>) => void;\n\n /**\n * Resets the store state to its initial values.\n */\n reset$: () => void;\n}\n\n/**\n * Computed values from getters.\n *\n * @template G - The type of the store's getters\n */\ntype GetterValues<G extends Getters<any>> = {\n [K in keyof G]: ReturnType<G[K]>;\n};\n\n/**\n * Creates a store from options (state, getters, and actions).\n *\n * @template S - The type of the store's state\n * @template G - The type of the store's getters\n * @template A - The type of the store's actions\n * @param options - Store configuration options\n * @returns The store instance\n * @internal\n */\nfunction createOptionsStore<S extends State, G extends Getters<S>, A extends Actions>(\n options: StoreOptions<S, G, A>,\n) {\n if (__DEV__ && !options.state) {\n warn('Store state is required');\n throw new Error('Store state is required');\n }\n\n const { state, getters, actions } = options;\n const initState = { ...state };\n const reactiveState = reactive(state);\n\n const subscriptions = new Set<StoreCallback<S>>();\n const actionCallbacks = new Set<StoreCallback<S>>();\n\n /**\n * Helper function to notify all subscribers and action callbacks.\n * This reduces code duplication in patch$ and reset$ methods.\n */\n const notifySubscribers = (state: S): void => {\n subscriptions.forEach(callback => callback(state));\n actionCallbacks.forEach(callback => callback(state));\n };\n\n const defaultActions: StoreActions<S> = {\n patch$(payload: PatchPayload<S>) {\n if (__DEV__ && !payload) {\n warn('Patch payload is required');\n return;\n }\n\n // Use batch for better performance\n batch(() => {\n Object.assign(reactiveState, payload);\n });\n\n // Notify all subscribers\n notifySubscribers(reactiveState);\n },\n\n subscribe$(callback: StoreCallback<S>) {\n if (__DEV__ && !callback) {\n warn('Subscribe callback is required');\n return;\n }\n subscriptions.add(callback);\n },\n\n unsubscribe$(callback: StoreCallback<S>) {\n subscriptions.delete(callback);\n },\n\n onAction$(callback: StoreCallback<S>) {\n if (__DEV__ && !callback) {\n warn('Action callback is required');\n return;\n }\n actionCallbacks.add(callback);\n },\n\n reset$() {\n // Use batch for better performance\n batch(() => {\n Object.assign(reactiveState, initState);\n });\n\n // Notify all subscribers\n notifySubscribers(reactiveState);\n },\n };\n\n const store = {\n ...reactiveState,\n state: reactiveState,\n ...defaultActions,\n } as S & GetterValues<G> & A & StoreActions<S> & { state: S };\n\n // Add getters as computed properties\n if (getters) {\n for (const key in getters) {\n const getter = getters[key];\n if (!getter) continue;\n\n Object.defineProperty(store, key, {\n get: () => computed(() => getter.call(store, reactiveState)).value,\n enumerable: true,\n configurable: true,\n });\n }\n }\n\n // Add actions with automatic notification\n if (actions) {\n for (const key in actions) {\n const action = actions[key];\n if (action) {\n Reflect.set(store, key, (...args: unknown[]) => {\n const result = action.apply(reactiveState, args);\n actionCallbacks.forEach(callback => callback(reactiveState));\n return result;\n });\n }\n }\n }\n\n return store;\n}\n/**\n * Creates store options from a class definition.\n *\n * @template S - The type of the store's state\n * @param StoreClass - The store class\n * @returns Store options derived from the class\n * @internal\n */\nfunction createClassStore<S extends State>(\n StoreClass: new () => S,\n): StoreOptions<\n S,\n Record<string, (...args: any[]) => any>,\n Record<string, (...args: any[]) => any>\n> {\n const instance = new StoreClass();\n const state = Object.create(null);\n const getters: Record<string, (...args: any[]) => any> = {};\n const actions: Record<string, (...args: any[]) => any> = {};\n\n // Extract instance properties as state\n Object.getOwnPropertyNames(instance).forEach(key => {\n state[key] = instance[key];\n });\n\n // Extract prototype methods and getters\n Object.getOwnPropertyNames(StoreClass.prototype).forEach(key => {\n const descriptor = Object.getOwnPropertyDescriptor(StoreClass.prototype, key);\n if (descriptor) {\n if (typeof descriptor.get === 'function') {\n getters[key] = function (this: S) {\n return descriptor.get!.call(this);\n };\n } else if (typeof descriptor.value === 'function' && key !== 'constructor') {\n actions[key] = function (this: S, ...args: any[]) {\n return descriptor.value.apply(this, args);\n };\n }\n }\n });\n\n return {\n state,\n getters,\n actions,\n };\n}\n\n/**\n * Store definition type that can be either a class or an options object.\n */\ntype StoreDefinition<S extends State, G extends Getters<S>, A extends Actions> =\n | (new () => S)\n | ({\n state: S;\n getters?: G;\n actions?: A;\n } & ThisType<S & GetterValues<G> & A & StoreActions<S>>);\n\n/**\n * Creates a new store with the given definition.\n * The store can be defined either as a class or as an options object.\n *\n * @template S - The type of the store's state\n * @template G - The type of the store's getters\n * @template A - The type of the store's actions\n * @param storeDefinition - The store definition (class or options)\n * @returns A function that creates a new store instance\n *\n * @example\n * ```ts\n * // Options-based store\n * const useCounter = createStore({\n * state: { count: 0 },\n * getters: {\n * double: state => state.count * 2\n * },\n * actions: {\n * increment() {\n * this.count++;\n * }\n * }\n * });\n *\n * // Class-based store\n * class Counter {\n * count = 0;\n *\n * get double() {\n * return this.count * 2;\n * }\n *\n * increment() {\n * this.count++;\n * }\n * }\n *\n * const useCounter = createStore(Counter);\n * ```\n */\nexport function createStore<S extends State, G extends Getters<S>, A extends Actions>(\n storeDefinition: StoreDefinition<S, G, A>,\n): () => S & GetterValues<G> & A & StoreActions<S> & { state: S } {\n if (__DEV__ && !storeDefinition) {\n warn('Store definition is required');\n throw new Error('Store definition is required');\n }\n\n return () => {\n let options: StoreOptions<S, G, A>;\n\n if (isFunction(storeDefinition)) {\n options = createClassStore(storeDefinition) as StoreOptions<S, G, A>;\n } else {\n options = storeDefinition;\n }\n\n const store = createOptionsStore(options) as S &\n GetterValues<G> &\n A &\n StoreActions<S> & { state: S };\n\n // For class-based stores, bind methods to the store\n if (isFunction(storeDefinition) && options.actions) {\n Object.keys(options.actions).forEach(key => {\n Reflect.set(store, key, options.actions![key].bind(store));\n });\n }\n\n return store;\n };\n}\n","import { hasChanged } from '@estjs/shared';\nimport { ReactiveFlags, SignalFlags } from './constants';\nimport { activeSub, linkReactiveNode } from './link';\nimport { propagate } from './propagation';\nimport { type Signal, SignalImpl, isSignal } from './signal';\n\n/**\n * A Ref is a special type of Signal used primarily for DOM element references.\n * It provides methods to read, write, and observe changes to the value.\n *\n * @template T - The type of value held by the ref\n */\nexport interface Ref<T> extends Signal<T> {\n /**\n * The current value of the ref. Reading this property will track dependencies,\n * and writing to it will notify subscribers of changes.\n */\n value: T;\n}\n\n/**\n * Internal implementation of the Ref interface.\n * This class extends SignalImpl but only overrides the get value() method\n * to provide direct access to the underlying value without reactive wrapping.\n *\n * @template T - The type of value held by the ref\n * @internal\n */\nclass RefImpl<T> extends SignalImpl<T> implements Ref<T> {\n // @ts-ignore: used internally by isRef typeguard\n private readonly [SignalFlags.IS_REF] = true;\n\n /**\n * Creates a new ref with the given initial value.\n *\n * @param value - The initial value\n */\n constructor(value: T) {\n super(value, true);\n }\n\n get value(): T {\n const sub = activeSub;\n if (sub) {\n linkReactiveNode(this, sub);\n }\n // ref just returns the value without reactive wrapping\n return this._value;\n }\n\n set value(newValue: T) {\n // Handle nested signals by unwrapping them\n if (isSignal(newValue)) {\n newValue = newValue.peek() as T;\n }\n if (isRef(newValue)) {\n newValue = newValue.value as T;\n }\n\n // Only trigger updates if the value has actually changed\n if (hasChanged(this._value, newValue)) {\n this._rawValue = newValue;\n this._value = newValue;\n this.flag |= ReactiveFlags.DIRTY;\n\n if (this.subLink) {\n propagate(this.subLink);\n }\n }\n }\n}\n\n/**\n * Creates a new ref with the given initial value.\n * Unlike signals, refs don't create reactive proxies for object values.\n *\n * @template T - The type of value to store in the ref\n * @param value - The initial value\n * @returns A new ref instance\n *\n * @example\n * ```ts\n * const divRef = ref();\n * <div ref={divRef}></div>\n * ```\n */\nexport function ref<T>(value: T = undefined as unknown as T): Ref<T> {\n if (isRef(value)) {\n return value as Ref<T>;\n }\n\n if (isSignal(value)) {\n return new RefImpl(value.peek() as T);\n }\n\n return new RefImpl(value);\n}\n\n/**\n * Type guard to check if a value is a Ref instance.\n *\n * @template T - The type of value held by the ref\n * @param value - The value to check\n * @returns True if the value is a Ref instance\n */\nexport function isRef<T>(value: unknown): value is Ref<T> {\n return !!value && !!value[SignalFlags.IS_REF];\n}\n","import { hasChanged, isFunction, isMap, isObject, isSet } from '@estjs/shared';\nimport { queueJob } from './scheduler';\nimport { isSignal } from './signal';\nimport { isReactive } from './reactive';\nimport { isComputed } from './computed';\nimport { effect } from './effect';\nimport type { Effect } from './propagation';\n\n// A unique initial value used to identify if watcher is running for the first time.\nconst INITIAL_WATCHER_VALUE = {};\n\ninterface WatchOptions {\n immediate?: boolean; // Whether to execute callback immediately once\n deep?: boolean; // Whether to deeply traverse source to track nested changes\n}\n\n/** Watch source type, can be value, ref/signal, getter function or array. */\ntype WatchSource<T = any> = T | { value: T } | (() => T);\n\ntype WatchCallback<T = any> = (newValue: T, oldValue: T | undefined) => void;\n\n// Use WeakMap to store cleanup functions for each effect.\nconst cleanupMap = new WeakMap<Effect, (() => void)[]>();\n\n/**\n * Recursively traverse a value, accessing all its properties to trigger dependency tracking.\n * @param value - The value to traverse.\n * @param seen - Set used to prevent circular references.\n * @returns The original value.\n */\nfunction traverse(value: any, seen = new Set()) {\n // If not an object or already traversed, stop.\n if (!isObject(value) || seen.has(value)) {\n return value;\n }\n\n seen.add(value);\n // If it's a signal or computed, traverse its .value.\n if (isSignal(value) || isComputed(value)) {\n return traverse(value.value, seen);\n }\n // If it's an array, traverse all its elements.\n if (Array.isArray(value)) {\n for (const element of value) {\n traverse(element, seen);\n }\n // If it's a Map, traverse all its values, and access keys and values to track changes.\n } else if (isMap(value)) {\n value.forEach((v: any) => {\n traverse(v, seen);\n });\n value.keys();\n value.values();\n // If it's a Set, traverse all its values to track changes.\n } else if (isSet(value)) {\n value.forEach((v: any) => {\n traverse(v, seen);\n });\n value.values();\n // If it's a plain object, traverse all its keys.\n } else {\n Object.keys(value).forEach(key => {\n traverse(value[key], seen);\n });\n }\n\n return value;\n}\n\n/**\n * Create a deep clone of a value for comparison purposes.\n * Handles plain objects, arrays, Map, Set, and primitives.\n * @param value - The value to clone.\n * @returns A deep clone of the value.\n */\nfunction cloneValue<T>(value: T): T {\n if (!isObject(value)) {\n return value;\n }\n\n if (Array.isArray(value)) {\n return value.map(item => cloneValue(item)) as unknown as T;\n }\n\n if (isMap(value)) {\n const cloned = new Map();\n value.forEach((v, k) => {\n cloned.set(k, cloneValue(v));\n });\n return cloned as unknown as T;\n }\n\n if (isSet(value)) {\n const cloned = new Set();\n value.forEach(v => {\n cloned.add(cloneValue(v));\n });\n return cloned as unknown as T;\n }\n\n // Plain object\n const cloned: any = {};\n for (const key of Object.keys(value as object)) {\n cloned[key] = cloneValue(value[key]);\n }\n return cloned as T;\n}\n\n/**\n * Resolve watch sources of various forms into a standard getter function.\n * @param source - The watch source passed by the user.\n * @returns A getter function that returns the current source value.\n */\nfunction resolveSource<T>(source: WatchSource<T>): () => T {\n // If source is an array, return a getter that traverses the array and unwraps each element.\n if (Array.isArray(source)) {\n return () =>\n source.map(s => {\n if (isSignal(s) || isComputed(s)) {\n return s.value;\n }\n if (isReactive(s)) {\n return traverse(s);\n }\n if (isFunction(s)) {\n return s();\n }\n return s;\n }) as unknown as T;\n }\n\n // If source is a function, use it directly as getter.\n if (isFunction(source)) {\n return source as () => T;\n }\n\n // If source is a signal, return a getter that reads its .value.\n if (isSignal(source)) {\n return () => source.value as unknown as T;\n }\n\n // If source is a ref-like object, return a getter that reads its .value.\n if (isObject(source) && 'value' in source) {\n return () => source.value as T;\n }\n\n // If source is a reactive object, return a getter that deeply traverses it.\n if (isReactive(source)) {\n return () => traverse(source) as unknown as T;\n }\n\n // Otherwise, source is a plain value, return a getter that directly returns the value.\n return () => source as T;\n}\n\n/**\n * Watch one or more reactive data sources and execute callback when sources change.\n * @param source - The source(s) to watch.\n * @param callback - The callback function to execute when source changes.\n * @param options - Configuration options like immediate and deep.\n * @returns A function to stop watching.\n */\nexport function watch<T = any>(\n source: WatchSource<T>,\n callback: WatchCallback<T>,\n options: WatchOptions = {},\n): () => void {\n const { immediate = false, deep = false } = options;\n // Initialize oldValue as a special object to determine if it's the first execution.\n let oldValue: any = INITIAL_WATCHER_VALUE;\n let cleanup: (() => void) | undefined;\n\n // Resolve source to a getter function.\n const getter = resolveSource(source);\n\n // job is the function that actually executes the callback, called by the scheduler.\n const job = () => {\n const currentEffect = runner.effect;\n if (!currentEffect.run) {\n return;\n }\n\n // Run effect to get new value.\n const newValue = currentEffect.run();\n\n // Execute the previously registered cleanup function before calling callback.\n if (cleanup) {\n cleanup();\n }\n\n // If value has changed, execute callback.\n if (hasChanged(newValue, oldValue)) {\n callback(newValue, oldValue === INITIAL_WATCHER_VALUE ? undefined : (oldValue as T));\n // Update oldValue for next comparison (clone to snapshot current state).\n oldValue = cloneValue(newValue);\n }\n };\n\n // Create an effect to track getter dependencies.\n const runner = effect(\n () => {\n const value = getter();\n // If deep watching, recursively traverse value to track all nested properties.\n if (deep) {\n traverse(value);\n }\n return value;\n },\n {\n // Use scheduler to queue job, implementing async and debouncing.\n scheduler: () => queueJob(job),\n },\n );\n\n // If immediate is set, execute job immediately once.\n if (immediate) {\n job();\n } else {\n // Otherwise, run effect once first to collect initial value as oldValue.\n oldValue = cloneValue(runner.effect.run());\n }\n\n // Return a stop function.\n return () => {\n runner.stop();\n // Execute cleanup function if exists.\n if (cleanup) {\n cleanup();\n }\n // Clean up all cleanup functions associated with this effect.\n const cleanups = cleanupMap.get(runner.effect);\n if (cleanups) {\n cleanups.forEach(fn => fn());\n cleanupMap.delete(runner.effect);\n }\n };\n}\n"]}
1
+ {"version":3,"sources":["../src/constants.ts","../src/propagation.ts","../src/link.ts","../src/reactive.ts","../src/signal.ts","../src/scheduler.ts","../src/batch.ts","../src/effect.ts","../src/computed.ts","../src/store.ts","../src/ref.ts","../src/watch.ts"],"names":["TriggerOpTypes","ARRAY_KEY","COLLECTION_KEY","WEAK_COLLECTION_KEY","ITERATE_KEY","ARRAY_ITERATE_KEY","enqueueEffect","effect","_a","propagate","link","next","stack","top","sub","watcherBit","flags","isValidLink","subSubs","nextSub","shallowPropagate","currentLinkVersion","activeSub","isUntracking","Dep","map","key","value","linkReactiveNode","depNode","subNode","prevDep","nextDep","prevSub","newLink","unlinkReactiveNode","linkNode","toRemove","checkDirty","checkDepth","dirty","currentDirty","dep","depFlags","subs","checkedDep","setActiveSub","prev","startTracking","endTracking","depsTail","untrack","fn","prevUntracking","checkLink","targetMap","triggerVersion","collectTriggeredEffects","effects","version","track","target","depsMap","trigger","type","newValue","element","iterationKey","reactiveCaches","toRaw","isObject","raw","isSignal","arrayInstrumentations","createArrayInstrumentations","instrumentations","args","arr","res","rawArgs","arg","isShallowMode","isShallow","reactiveImpl","i","l","item","rawIterator","done","v","arrayHandlers","shallow","receiver","hasOwn","isStringNumber","oldValue","result","hasChanged","shallowArrayHandlers","deepArrayHandlers","collectionHandlers","collectionInstrumentations","weakCollectionHandlers","weakInstrumentations","hadKey","rawValue","hadValue","hasKey","hadItems","callback","thisArg","wrappedValue","wrappedKey","isReactive","rawKey","objectHandlers","valueUnwrapped","shallowObjectHandlers","deepObjectHandlers","existingProxy","handler","isArray","isSet","isMap","isWeakMap","isWeakSet","proxy","reactive","shallowReactive","toReactive","SignalImpl","unwrapped","shouldWrapReactiveValue","originalValue","changed","updater","nextValue","isPlainObject","signal","shallowSignal","queue","activePreFlushCbs","p","isFlushPending","nextTick","queueJob","job","queueFlush","flushJobs","queuePreFlushCb","cb","flushPreFlushCbs","_error","callbacks","createScheduler","flush","batchDepth","batch","startBatch","endBatch","isBatching","getBatchDepth","EffectImpl","options","scheduler","isFunction","nextFlags","wasDirty","wasPending","error","_b","_c","_d","effectInstance","runner","stop","isEffect","memoEffect","initialState","currentState","NO_VALUE","ComputedImpl","getter","setter","onTrack","onTrigger","hasValue","clearMask","computed","getterOrOptions","isComputed","get","set","createOptionsStore","state","getters","actions","initState","__spreadValues","reactiveState","subscriptions","actionCallbacks","notifySubscribers","defaultActions","payload","store","getterValue","action","createClassStore","StoreClass","instance","descriptor","createStore","storeDefinition","RefImpl","isRef","ref","INITIAL_WATCHER_VALUE","_traverseSeen","traverse","seen","resolveSingleSource","source","resolveSource","s","g","watch","immediate","deep","currentEffect"],"mappings":"mfA0EO,IAAMA,CAAAA,CAAiB,CAC5B,GAAA,CAAK,KAAA,CACL,GAAA,CAAK,KAAA,CACL,MAAA,CAAQ,SACR,KAAA,CAAO,OACT,EAoCO,IAAMC,CAAAA,CAA2B,MAAA,CAA+B,EAAE,CAAA,CAG5DC,CAAAA,CAAgC,MAAA,CAAoC,EAAE,CAAA,CAGtEC,CAAAA,CAAqC,MAAA,CAAwC,EAAE,CAAA,CAG/EC,EAAAA,CAA6B,MAAA,CAAiC,EAAE,CAAA,CAStE,IAAMC,CAAAA,CAAmC,MAAA,CAAuC,EAAE,CAAA,CCpHlF,SAASC,CAAAA,CAAcC,CAAAA,CAAsB,CAjBpD,IAAAC,CAAAA,CAAAA,CAkBEA,CAAAA,CAAAD,CAAAA,EAAA,IAAA,CAAA,MAAA,CAAAA,CAAAA,CAAQ,MAAA,GAAR,MAA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CAAAA,CAAShM,CAAK,CAAA,CAETA,CACT,EACA,CAEE,SAAA,CAAW,IAAMsH,CAAAA,CAASC,CAAG,CAC/B,CACF,CAAA,CAGA,OAAIiF,CAAAA,CACFjF,CAAAA,GAGAnD,CAAAA,CAAsB+E,CAAAA,CAAO,OAAO,GAAA,EAAI,CAInC,IAAM,CACXA,CAAAA,CAAO,IAAA,GACT,CACF","file":"signals.esm.js","sourcesContent":["/**\r\n * Reactive node state flags\r\n */\r\nexport const enum ReactiveFlags {\r\n /** No state flags */\r\n NONE = 0,\r\n\r\n /**\r\n * Mutable flag - The node's value can change\r\n *\r\n * Signal and Computed are mutable, triggering propagation when their values change.\r\n * Immutable nodes (like constants) don't set this flag.\r\n */\r\n // eslint-disable-next-line unicorn/prefer-math-trunc\r\n MUTABLE = 1 << 0, // 0b00000001 = 1\r\n\r\n /**\r\n * Watching flag - The node is being watched by an Effect\r\n *\r\n * Set when an Effect depends on this node.\r\n * Used to determine whether to add the Effect to the execution queue.\r\n */\r\n WATCHING = 1 << 1, // 0b00000010 = 2\r\n\r\n /**\r\n * Recursion check flag - Currently checking for circular dependencies\r\n *\r\n * Set during the checkDirty process to detect and handle circular dependencies.\r\n * Prevents infinite recursion.\r\n */\r\n RECURSED_CHECK = 1 << 2, // 0b00000100 = 4\r\n\r\n /**\r\n * Recursed flag - Already in the recursion chain\r\n *\r\n * Marks that the node has already appeared in the current propagation path.\r\n * Used to handle complex dependency graph structures.\r\n */\r\n RECURSED = 1 << 3, // 0b00001000 = 8\r\n\r\n /**\r\n * Dirty flag - The node's value has changed but hasn't propagated yet\r\n *\r\n * Set when a Signal value changes.\r\n * Also set when Computed detects dependency changes.\r\n * Indicates need to recompute or notify subscribers.\r\n */\r\n DIRTY = 1 << 4, // 0b00010000 = 16\r\n\r\n /**\r\n * Pending flag - The node may need updating\r\n *\r\n * Set during propagation, indicating the node's dependencies may have become dirty.\r\n * Need to call checkDirty to confirm if update is actually needed.\r\n */\r\n PENDING = 1 << 5, // 0b00100000 = 32\r\n\r\n /**\r\n * Queued flag - Effect has been added to the execution queue\r\n *\r\n * Prevents the same Effect from being added to the queue multiple times.\r\n * This flag is cleared before queue execution.\r\n */\r\n QUEUED = 1 << 6, // 0b01000000 = 64\r\n}\r\n\r\n// Define specific flags for effects\r\nexport enum EffectFlags {\r\n ALLOW_RECURSE = 1 << 7, // Allow recursive calls\r\n PAUSED = 1 << 8, // Paused\r\n RUNNING = 1 << 9, // Currently executing (was previously overloading STOP)\r\n STOP = 1 << 10, // Permanently stopped\r\n}\r\n// Define operation type constants\r\nexport const TriggerOpTypes = {\r\n SET: 'SET',\r\n ADD: 'ADD',\r\n DELETE: 'DELETE',\r\n CLEAR: 'CLEAR',\r\n} as const;\r\n\r\n/**\r\n * Internal flags used to mark and identify different types of reactive objects.\r\n * These flags are attached as properties to objects to indicate their reactive characteristics.\r\n */\r\nexport enum SignalFlags {\r\n /** Mark an object as reactive */\r\n IS_REACTIVE = '_IS_REACTIVE',\r\n\r\n /** Mark an object as readonly */\r\n IS_READONLY = '_IS_READONLY',\r\n\r\n /** Mark an object as shallow reactive (only top-level properties are reactive) */\r\n IS_SHALLOW = '_IS_SHALLOW',\r\n\r\n /** Used to access the raw (non-reactive) version of an object */\r\n RAW = '_RAW',\r\n\r\n /** Mark an object as a signal */\r\n IS_SIGNAL = '_IS_SIGNAL',\r\n\r\n /** Mark an object as a computed property */\r\n IS_COMPUTED = '_IS_COMPUTED',\r\n\r\n /** Mark an object as a ref */\r\n IS_REF = '_IS_REF',\r\n\r\n /** Mark an object as an effect */\r\n IS_EFFECT = '_IS_EFFECT',\r\n}\r\n\r\n/** Symbol used to track signal value changes */\r\nexport const SIGNAL_KEY: unique symbol = Symbol(__DEV__ ? 'Signal_Key' : '');\r\n\r\n/** Symbol used to track array operation changes */\r\nexport const ARRAY_KEY: unique symbol = Symbol(__DEV__ ? 'Array_Key' : '');\r\n\r\n/** Symbol used to track regular collection (Map/Set) operation changes */\r\nexport const COLLECTION_KEY: unique symbol = Symbol(__DEV__ ? 'Collection_Key' : '');\r\n\r\n/** Symbol used to track weak collection (WeakMap/WeakSet) operation changes */\r\nexport const WEAK_COLLECTION_KEY: unique symbol = Symbol(__DEV__ ? 'WeakCollection_Key' : '');\r\n\r\n/** Symbol used to track iteration operations */\r\nexport const ITERATE_KEY: unique symbol = Symbol(__DEV__ ? 'Iterate_Key' : '');\r\n\r\n/** Symbol used to track Map key iteration operations */\r\nexport const MAP_KEY_ITERATE_KEY: unique symbol = Symbol(__DEV__ ? 'MapKeyIterate_Key' : '');\r\n\r\n/** Symbol used to track computed property dependencies */\r\nexport const COMPUTED_KEY: unique symbol = Symbol(__DEV__ ? 'Computed_Key' : '');\r\n\r\n/** Unique symbol used to track array iteration */\r\nexport const ARRAY_ITERATE_KEY: unique symbol = Symbol(__DEV__ ? 'Array_Iterate_Key' : '');\r\n\r\nexport type TRACKING_KEY =\r\n | typeof SIGNAL_KEY\r\n | typeof ARRAY_KEY\r\n | typeof COLLECTION_KEY\r\n | typeof WEAK_COLLECTION_KEY\r\n | typeof ITERATE_KEY\r\n | typeof MAP_KEY_ITERATE_KEY\r\n | typeof COMPUTED_KEY;\r\n","import { ReactiveFlags } from './constants';\nimport { type Link, type ReactiveNode, isValidLink } from './link';\n\n/**\n * Effect interface used internally for propagation\n */\nexport interface Effect extends ReactiveNode {\n notify(): void;\n _active?: boolean;\n}\n\n/**\n * Enqueue an Effect for execution.\n *\n * @param effect - The Effect to enqueue.\n * @returns {void}\n */\nexport function enqueueEffect(effect: Effect): void {\n effect?.notify?.();\n}\n\n/**\n * Clear propagation flags (PENDING, RECURSED, RECURSED_CHECK) from a node.\n *\n * @param node - The reactive node to clear flags on.\n * @returns {void}\n */\nexport function clearPropagationFlags(node: ReactiveNode): void {\n node.flag &= ~(ReactiveFlags.PENDING | ReactiveFlags.RECURSED | ReactiveFlags.RECURSED_CHECK);\n}\n\n/**\n * Propagate changes through the reactive graph.\n *\n * @param link - Starting Link of the subscriber chain.\n * @returns {void}\n */\nexport function propagate(link: Link): void {\n let next: Link | undefined = link.nextSubLink;\n let stack: { value: Link | undefined; prev: typeof stack } | undefined;\n\n // eslint-disable-next-line no-restricted-syntax\n top: do {\n const sub = link.subNode;\n const watcherBit = sub.flag & ReactiveFlags.WATCHING;\n let flags = sub.flag;\n\n if (\n !(\n flags &\n (ReactiveFlags.DIRTY |\n ReactiveFlags.PENDING |\n ReactiveFlags.RECURSED |\n ReactiveFlags.RECURSED_CHECK)\n )\n ) {\n // Case 1: Clean state → mark PENDING\n sub.flag = flags | ReactiveFlags.PENDING;\n if (watcherBit) {\n enqueueEffect(sub as unknown as Effect);\n }\n } else if (!(flags & (ReactiveFlags.RECURSED | ReactiveFlags.RECURSED_CHECK))) {\n // Case 2: Already processed (DIRTY or PENDING alone) → stop downward\n flags = ReactiveFlags.NONE;\n } else if (!(flags & ReactiveFlags.RECURSED_CHECK)) {\n // Case 3: RECURSED set but not checking → clear RECURSED, mark PENDING\n sub.flag = (flags & ~ReactiveFlags.RECURSED) | ReactiveFlags.PENDING;\n } else if (!(flags & (ReactiveFlags.DIRTY | ReactiveFlags.PENDING)) && isValidLink(link, sub)) {\n // Case 4: RECURSED_CHECK set, clean, valid link → allow propagation through recursion\n sub.flag = flags | (ReactiveFlags.RECURSED | ReactiveFlags.PENDING);\n if (watcherBit) {\n enqueueEffect(sub as unknown as Effect);\n }\n flags &= ReactiveFlags.MUTABLE;\n } else {\n // Case 5: Already DIRTY/PENDING in RECURSED_CHECK → stop\n flags = ReactiveFlags.NONE;\n }\n\n if (flags & ReactiveFlags.MUTABLE) {\n // MUTABLE (Computed): descend into its subscribers\n const subSubs = sub.subLink;\n if (subSubs !== undefined) {\n // alien-signals pattern: save the CURRENT 'next' (sibling at outer level) to stack\n // before diving into this node's own subscriber chain.\n const nextSub = subSubs.nextSubLink;\n if (nextSub !== undefined) {\n // comp has multiple subscribers: save next and start at first\n stack = { value: next, prev: stack };\n next = nextSub;\n }\n link = subSubs;\n continue;\n }\n }\n\n // Advance to next sibling or restore from stack\n if ((link = next!) !== undefined) {\n next = link.nextSubLink;\n continue;\n }\n\n while (stack !== undefined) {\n link = stack.value!;\n stack = stack.prev;\n if (link !== undefined) {\n next = link.nextSubLink;\n continue top;\n }\n }\n\n break;\n // eslint-disable-next-line no-constant-condition\n } while (true);\n}\n\n/**\n * Shallow propagate from a Computed value to its direct subscribers.\n *\n * @param link - Starting Link of the subscriber chain.\n * @returns {void}\n */\nexport function shallowPropagate(link: Link | undefined): void {\n while (link) {\n const sub = link.subNode;\n const flags = sub.flag;\n\n if ((flags & (ReactiveFlags.PENDING | ReactiveFlags.DIRTY)) === ReactiveFlags.PENDING) {\n // PENDING but not DIRTY: upgrade to DIRTY and notify if not mid-run\n sub.flag = flags | ReactiveFlags.DIRTY;\n\n if (\n (flags & (ReactiveFlags.WATCHING | ReactiveFlags.RECURSED_CHECK)) ===\n ReactiveFlags.WATCHING\n ) {\n enqueueEffect(sub as unknown as Effect);\n }\n }\n // DIRTY already → already handled. Neither PENDING nor DIRTY → clean, skip.\n\n link = link.nextSubLink;\n }\n}\n","import { error, isFunction } from '@estjs/shared';\nimport { ARRAY_ITERATE_KEY, ITERATE_KEY, ReactiveFlags, SignalFlags } from './constants';\nimport { type Effect, propagate } from './propagation';\n\n/**\n * Link - Bidirectional connection in the dependency graph\n *\n * A Link connects two ReactiveNodes:\n * - depNode: The dependency node (data source)\n * - subNode: The subscriber node (data consumer)\n *\n * Links form doubly-linked lists in two directions:\n * 1. Subscriber Chain: Connects all subscribers of the same dependency\n * 2. Dependency Chain: Connects all dependencies of the same subscriber\n *\n * @example\n * ```\n * Signal A ←─┐\n * ├─→ Effect X\n * Signal B ←─┘\n *\n * Link1: A → X (A's subscriber chain, X's dependency chain)\n * Link2: B → X (B's subscriber chain, X's dependency chain)\n * ```\n */\nexport interface Link {\n /**\n * Version number\n *\n * Used to detect stale Links.\n * The global version number increments each time dependency tracking starts.\n * Links with old versions will be cleaned up.\n *\n */\n version: number;\n\n /**\n * Dependency node - The data source being depended on\n * Examples: Signal, Computed\n */\n depNode: ReactiveNode;\n\n /**\n * Subscriber node - The consumer of the data\n * Examples: Effect, Computed\n */\n subNode: ReactiveNode;\n\n // Connects multiple subscribers of the same depNode\n\n /** Previous subscriber Link */\n prevSubLink?: Link;\n\n /** Next subscriber Link */\n nextSubLink?: Link;\n\n // Connects multiple dependencies of the same subNode\n\n /** Previous dependency Link */\n prevDepLink?: Link;\n\n /** Next dependency Link */\n nextDepLink?: Link;\n}\n\n/**\n * Debugger event types for tracking reactive operations\n */\nexport type DebuggerEventType = 'get' | 'set' | 'add' | 'delete' | 'clear' | 'iterate';\n\n/**\n * Debugger event for tracking reactive operations\n *\n * This event is passed to onTrack and onTrigger callbacks to provide\n * detailed information about reactive operations for debugging purposes.\n *\n * @example\n * ```typescript\n * effect(() => {\n * console.log(signal.value);\n * }, {\n * onTrack(event) {\n * console.log('Tracked:', event.type, event.key);\n * },\n * onTrigger(event) {\n * console.log('Triggered:', event.type, event.key, event.newValue);\n * }\n * });\n * ```\n */\nexport interface DebuggerEvent {\n /** The effect or computed that is tracking/being triggered */\n effect: ReactiveNode;\n /** The reactive object being accessed or modified */\n target: object;\n /** The type of operation */\n type: DebuggerEventType | string;\n /** The property key being accessed or modified (optional) */\n key?: any;\n /** The new value being set (optional, only for trigger events) */\n newValue?: any;\n}\n\n/**\n * ReactiveNode - Reactive node interface\n *\n * All objects participating in the reactive system implement this interface.\n * Includes Signal, Computed, Effect, Reactive objects, etc.\n *\n * Nodes form a dependency graph through Links:\n * - depLink: List of nodes I depend on\n * - subLink: List of nodes that depend on me\n */\nexport interface ReactiveNode {\n /**\n * Dependency chain head - The first node I depend on\n *\n * Traverse all dependencies through nextDepLink.\n */\n depLink?: Link;\n\n /**\n * Subscriber chain head - The first node that depends on me\n *\n * Traverse all subscribers through nextSubLink.\n */\n subLink?: Link;\n\n /**\n * Dependency chain tail - The last node I depend on\n *\n * Used for O(1) time complexity linked list append operations.\n */\n depLinkTail?: Link;\n\n /**\n * Subscriber chain tail - The last node that depends on me\n *\n * Used for O(1) time complexity linked list append operations.\n */\n subLinkTail?: Link;\n\n /**\n * State flags\n * @see ReactiveFlags\n */\n flag: ReactiveFlags;\n\n /**\n * Optional debugging hook called when dependencies are tracked\n */\n onTrack?: (event: DebuggerEvent) => void;\n\n /**\n * Optional debugging hook called when reactive changes are triggered.\n */\n onTrigger?: (event: DebuggerEvent) => void;\n\n /**\n * When true, this node is a pure dependency (leaf); it should not receive\n * a DIRTY flag during invalidation because it has no derived value to recompute.\n */\n isDep?: boolean;\n\n /**\n * Deduplication stamp used during batch notification.\n * Prevents the same effect from being pushed into the pending queue twice.\n */\n _triggerVersion?: number;\n}\n\n/**\n * Current Link version number\n *\n * Increments each time dependency tracking starts.\n * Used to identify and clean up stale Links.\n */\nlet currentLinkVersion = 0;\n\n/**\n * Currently active subscriber\n *\n * Set to the current node when Effect/Computed executes.\n * When a Signal is accessed, it automatically establishes a Link with activeSub.\n */\nexport let activeSub: ReactiveNode | undefined;\n\n/**\n * Whether tracking is disabled\n *\n * The untrack() function temporarily sets this to true.\n * During this time, accessing Signals won't establish dependencies.\n */\nlet isUntracking = false;\n\n/**\n * Reactive-object property dependency node.\n *\n * Each tracked property on a reactive target owns one Dep instance, which\n * participates in the same Link graph as Signal / Computed / Effect nodes.\n * When the last subscriber leaves, the property entry removes itself from its\n * containing deps map via the `subLink` setter.\n */\nclass Dep implements ReactiveNode {\n readonly isDep = true;\n depLink?: Link;\n depLinkTail?: Link;\n subLinkTail?: Link;\n flag: ReactiveFlags = ReactiveFlags.NONE;\n\n private _subLink?: Link;\n\n constructor(\n private readonly map: Map<string | symbol, Dep>,\n private readonly key: string | symbol,\n ) {}\n\n get subLink(): Link | undefined {\n return this._subLink;\n }\n\n set subLink(value: Link | undefined) {\n this._subLink = value;\n if (value === undefined) {\n this.map.delete(this.key);\n }\n }\n}\n\n/**\n * Get whether currently in untrack mode.\n *\n * @returns True if currently in untrack mode.\n */\nexport function getIsUntracking(): boolean {\n return isUntracking;\n}\n\n/**\n * Link a dependency node to a subscriber node.\n *\n * This function establishes a bidirectional link between a dependency (e.g., Signal)\n * and a subscriber (e.g., Effect or Computed). It's called automatically when a\n * reactive value is accessed during effect/computed execution.\n *\n * @param depNode - The dependency node (data source).\n * @param subNode - The subscriber node (data consumer).\n * @returns The link connecting the two nodes, or undefined if in untrack mode.\n */\nexport function linkReactiveNode(depNode: ReactiveNode, subNode: ReactiveNode): Link | undefined {\n // If in untrack mode, don't establish any dependencies\n // This is used by untrack() to access reactive values without creating dependencies\n if (isUntracking) {\n return undefined;\n }\n\n const prevDep = subNode.depLinkTail;\n if (prevDep && prevDep.depNode === depNode) {\n // Same dependency as last time - return existing Link immediately\n // This is the fastest path: single pointer comparison\n return prevDep;\n }\n\n const nextDep = prevDep ? prevDep.nextDepLink : subNode.depLink;\n if (nextDep && nextDep.depNode === depNode) {\n // Found a reusable Link! Update its version to mark it as \"still in use\"\n // Links with old versions will be cleaned up by endTracking()\n nextDep.version = currentLinkVersion;\n // Move the tail pointer forward to this Link\n subNode.depLinkTail = nextDep;\n return nextDep;\n }\n\n const prevSub = depNode.subLinkTail;\n if (prevSub && prevSub.version === currentLinkVersion && prevSub.subNode === subNode) {\n // This Link was just created in the current tracking cycle\n // Update subscriber's tail to point to it\n subNode.depLinkTail = prevSub;\n return prevSub;\n }\n\n // No reusable Link found - need to create a new one\n // This happens on first execution or when dependency order changes\n const newLink: Link = {\n version: currentLinkVersion,\n depNode,\n subNode,\n // Subscriber chain pointers (horizontal)\n prevSubLink: prevSub,\n nextSubLink: undefined,\n // Dependency chain pointers (vertical)\n prevDepLink: prevDep,\n nextDepLink: nextDep,\n };\n\n // Insert the new Link into the subscriber's dependency chain\n // This maintains the doubly-linked list structure\n if (nextDep) {\n // There's a Link after this position - update its back pointer\n nextDep.prevDepLink = newLink;\n }\n if (prevDep) {\n // There's a Link before this position - update its forward pointer\n prevDep.nextDepLink = newLink;\n } else {\n // This is the first dependency - update the head pointer\n subNode.depLink = newLink;\n }\n\n // Insert the new Link into the dependency's subscriber chain\n if (prevSub) {\n // There are existing subscribers - append to the end\n prevSub.nextSubLink = newLink;\n } else {\n // This is the first subscriber - update the head pointer\n depNode.subLink = newLink;\n }\n\n // Tail pointers enable O(1) append operations\n // Without them, we'd need O(n) traversal to find the end of the list\n depNode.subLinkTail = newLink;\n subNode.depLinkTail = newLink;\n\n // In development mode, notify debugging tools about the new dependency\n if (__DEV__) {\n if (subNode.onTrack && isFunction(subNode?.onTrack)) {\n subNode.onTrack({\n effect: subNode,\n target: depNode,\n type: 'get',\n key: undefined,\n });\n }\n }\n\n return newLink;\n}\n\n/**\n * Remove a dependency link.\n *\n * This function removes a link from the dependency graph, updating all pointers\n * in both the subscriber's dependency chain and the dependency's subscriber chain.\n *\n * @param linkNode - The link to remove.\n * @param subNode - The subscriber node (defaults to linkNode.subNode).\n * @returns The next link in the dependency chain (for iteration).\n */\nexport function unlinkReactiveNode(\n linkNode: Link,\n subNode: ReactiveNode = linkNode.subNode,\n): Link | undefined {\n const depNode = linkNode.depNode;\n const prevSub = linkNode.prevSubLink;\n const nextSub = linkNode.nextSubLink;\n const prevDep = linkNode.prevDepLink;\n const nextDep = linkNode.nextDepLink;\n\n // Update the doubly-linked list pointers in the subscriber's dependency chain\n // This removes the link from the vertical chain (all dependencies of subNode)\n if (nextDep) {\n nextDep.prevDepLink = prevDep;\n } else {\n // This was the tail - update tail pointer\n subNode.depLinkTail = prevDep;\n }\n if (prevDep) {\n prevDep.nextDepLink = nextDep;\n } else {\n // This was the head - update head pointer\n subNode.depLink = nextDep;\n }\n\n // Update the doubly-linked list pointers in the dependency's subscriber chain\n // This removes the link from the horizontal chain (all subscribers of depNode)\n if (nextSub) {\n nextSub.prevSubLink = prevSub;\n } else {\n // This was the tail - update tail pointer\n depNode.subLinkTail = prevSub;\n }\n if (prevSub) {\n prevSub.nextSubLink = nextSub;\n } else {\n // This was the head - update head pointer and check for cascading cleanup\n depNode.subLink = nextSub;\n\n // If depNode has no more subscribers, it doesn't need to track its dependencies\n // This is a critical optimization for memory management\n if (nextSub === undefined) {\n // No more subscribers - clean up all dependencies recursively\n let toRemove = depNode.depLink;\n while (toRemove) {\n toRemove = unlinkReactiveNode(toRemove, depNode);\n }\n\n // Clear tail pointer to ensure no dangling references\n depNode.depLinkTail = undefined;\n\n // Mark as dirty so it recomputes on next access.\n // Dep nodes are leaf nodes with no value to recompute, so skip them.\n if (!depNode.isDep) {\n depNode.flag |= ReactiveFlags.DIRTY;\n }\n\n // Development mode verification\n if (__DEV__) {\n // Verify that all links were properly cleared\n if (depNode.depLink) {\n error(\n '[Link] Cascading cleanup failed: depNode still has dependency links. ' +\n 'This indicates a bug in the unlinking logic.',\n );\n }\n }\n }\n }\n\n // Return the next link in the dependency chain for iteration\n return nextDep;\n}\n\ninterface CheckStackNode {\n link: Link;\n prev?: CheckStackNode;\n}\n\n/**\n * Check if the dependency chain is dirty\n *\n * This function determines whether a subscriber node needs to recompute by checking\n * if any of its dependencies (or transitive dependencies) are dirty.\n *\n * ## Algorithm Overview\n *\n * The algorithm performs a depth-first traversal of the dependency graph using an\n * explicit stack to avoid recursion limits. It handles three main scenarios:\n *\n * 1. **DIRTY dependencies**: If any dependency is marked DIRTY, the subscriber is dirty\n * 2. **PENDING dependencies**: Dependencies that might be dirty - need deeper checking\n * 3. **Clean dependencies**: Dependencies that are confirmed clean\n *\n * ## Why Use an Explicit Stack?\n *\n * JavaScript has a limited call stack (~10,000 frames). In complex reactive systems,\n * dependency chains can be arbitrarily deep (e.g., computed1 → computed2 → ... → computedN).\n * Using an explicit stack allows us to handle unlimited depth without stack overflow.\n *\n * ## Algorithm Steps\n *\n * 1. Initialize stack with the subscriber's dependency chain\n * 2. For each dependency in the chain:\n * - If DIRTY: Mark path as dirty and return true\n * - If PENDING + MUTABLE: Push its dependencies onto stack for deeper checking\n * - Otherwise: Clear PENDING flag (confirmed clean)\n * 3. Track PENDING nodes encountered during traversal\n * 4. If dirty found: Mark all PENDING nodes on path as DIRTY\n * 5. If no dirty found: Clear all PENDING flags\n *\n * ## Edge Cases Handled\n *\n * - **Diamond dependencies**: A node with multiple paths to the same dependency\n * - The algorithm correctly handles this by checking all paths\n * - **Circular dependencies**: Prevented by the RECURSED flag in propagation\n * - **Deep chains**: Handled by explicit stack instead of recursion\n * - **Multiple subscribers**: Uses shallowPropagate to update sibling subscribers\n *\n * ## Performance Characteristics\n *\n * - Time complexity: O(n) where n is the total number of dependencies in the chain\n * - Space complexity: O(d) where d is the maximum depth of the dependency graph\n * - Early exit: Returns immediately when first DIRTY dependency is found\n *\n * @param link - The starting Link of the dependency chain to check.\n * @param sub - The subscriber node that owns this dependency chain.\n * @returns True if any dependency is dirty (subscriber needs recomputation), false otherwise.\n *\n * @example\n * ```typescript\n * // Simple case: signal → computed\n * const s = signal(1);\n * const c = computed(() => s.value * 2);\n * s.value = 2; // Marks s as DIRTY\n * // When accessing c.value, checkDirty(c.depLink, c) returns true\n *\n * // Complex case: diamond dependency\n * const s = signal(1);\n * const c1 = computed(() => s.value * 2);\n * const c2 = computed(() => s.value + 1);\n * const c3 = computed(() => c1.value + c2.value);\n * // c3 depends on both c1 and c2, which both depend on s\n * // checkDirty correctly handles both paths to s\n * ```\n */\nexport function checkDirty(link: Link, sub: ReactiveNode): boolean {\n let stack: CheckStackNode | undefined;\n let checkDepth = 0;\n let dirty = false;\n\n // eslint-disable-next-line no-restricted-syntax\n top: do {\n let currentDirty = false;\n\n if (sub.flag & ReactiveFlags.DIRTY) {\n currentDirty = true;\n } else {\n const dep = link.depNode;\n const depFlags = dep.flag;\n\n if (\n (depFlags & (ReactiveFlags.MUTABLE | ReactiveFlags.DIRTY)) ===\n (ReactiveFlags.MUTABLE | ReactiveFlags.DIRTY)\n ) {\n const subs = dep.subLink;\n if (subs && subs.nextSubLink) {\n shallowPropagate(subs);\n }\n currentDirty = true;\n } else if (\n (depFlags & (ReactiveFlags.MUTABLE | ReactiveFlags.PENDING)) ===\n (ReactiveFlags.MUTABLE | ReactiveFlags.PENDING)\n ) {\n if (dep.depLink) {\n stack = { link, prev: stack };\n link = dep.depLink;\n sub = dep;\n ++checkDepth;\n continue top;\n } else {\n dep.flag &= ~ReactiveFlags.PENDING;\n }\n } else if (depFlags & ReactiveFlags.PENDING) {\n dep.flag &= ~ReactiveFlags.PENDING;\n }\n }\n\n if (!currentDirty && link.nextDepLink !== undefined) {\n link = link.nextDepLink;\n continue top;\n }\n\n dirty = currentDirty;\n\n while (checkDepth--) {\n link = stack!.link;\n stack = stack!.prev;\n sub = link.subNode;\n const checkedDep = link.depNode;\n\n if (dirty) {\n checkedDep.flag = (checkedDep.flag & ~ReactiveFlags.PENDING) | ReactiveFlags.DIRTY;\n } else {\n checkedDep.flag &= ~ReactiveFlags.PENDING;\n }\n\n if (checkedDep.flag & ReactiveFlags.DIRTY) {\n dirty = true;\n }\n\n if (!dirty && link.nextDepLink !== undefined) {\n link = link.nextDepLink;\n continue top;\n }\n }\n\n if (dirty) {\n sub.flag = (sub.flag & ~ReactiveFlags.PENDING) | ReactiveFlags.DIRTY;\n } else {\n sub.flag &= ~ReactiveFlags.PENDING;\n }\n\n return dirty;\n // eslint-disable-next-line no-constant-condition\n } while (true);\n}\n\n/**\n * Shallow propagate for Signal getters.\n *\n * @param link - The starting Link of the subscriber chain.\n */\nexport function shallowPropagate(link: Link | undefined): void {\n while (link) {\n const sub = link.subNode;\n const flags = sub.flag;\n\n // Only promote nodes that are PENDING (computed might need recheck) —\n // nodes already DIRTY don't need promotion, clean nodes aren't in PENDING.\n if ((flags & (ReactiveFlags.PENDING | ReactiveFlags.DIRTY)) === ReactiveFlags.PENDING) {\n sub.flag = flags | ReactiveFlags.DIRTY;\n }\n\n link = link.nextSubLink;\n }\n}\n\n/**\n * Set the active subscriber.\n *\n * @param sub - The new active subscriber.\n * @returns The previous active subscriber.\n */\nexport function setActiveSub(sub?: ReactiveNode): ReactiveNode | undefined {\n const prev = activeSub;\n activeSub = sub;\n return prev;\n}\n\n/**\n * Start tracking dependencies.\n *\n * @param sub - The subscriber node to track.\n * @returns The previous active subscriber.\n */\nexport function startTracking(sub: ReactiveNode): ReactiveNode | undefined {\n // Increment version number to mark new tracking cycle\n currentLinkVersion++;\n\n // Reset tracking state\n sub.depLinkTail = undefined;\n\n // Clear recursion and dirty flags, set recursion check flag\n sub.flag =\n (sub.flag & ~(ReactiveFlags.RECURSED | ReactiveFlags.DIRTY | ReactiveFlags.PENDING)) |\n ReactiveFlags.RECURSED_CHECK;\n\n return setActiveSub(sub);\n}\n\n/**\n * End tracking dependencies.\n *\n * @param sub - The tracked subscriber node.\n * @param prevSub - The previous active subscriber.\n */\nexport function endTracking(sub: ReactiveNode, prevSub: ReactiveNode | undefined): void {\n // Restore previous active subscriber\n activeSub = prevSub;\n\n // Clean up stale Links\n const depsTail = sub.depLinkTail;\n let toRemove = depsTail ? depsTail.nextDepLink : sub.depLink;\n\n while (toRemove) {\n toRemove = unlinkReactiveNode(toRemove, sub);\n }\n\n // Clear recursion check flag\n sub.flag &= ~ReactiveFlags.RECURSED_CHECK;\n}\n\n/**\n * Execute function with tracking disabled.\n *\n * @param fn - The function to execute.\n * @returns {T} The function's return value.\n */\nexport function untrack<T>(fn: () => T): T {\n const prevSub = setActiveSub(undefined);\n const prevUntracking = isUntracking;\n isUntracking = true;\n\n try {\n return fn();\n } finally {\n isUntracking = prevUntracking;\n setActiveSub(prevSub);\n }\n}\n\n/**\n * Validate if a Link is still valid.\n *\n * @param checkLink - The Link to validate.\n * @param sub - The subscriber node.\n * @returns True if the Link is valid.\n */\nexport function isValidLink(checkLink: Link, sub: ReactiveNode): boolean {\n let link = sub.depLinkTail;\n\n while (link) {\n if (link === checkLink) {\n return true;\n }\n link = link.prevDepLink;\n }\n\n return false;\n}\n\n/**\n * Global dependency map for reactive objects\n *\n * This WeakMap stores the dependency relationships for reactive objects (created by reactive()).\n * Structure: WeakMap<target, Map<key, Set<ReactiveNode>>>\n *\n * - WeakMap allows garbage collection of unused reactive objects\n * - Map stores per-property dependencies\n * - Set stores all subscribers for each property\n *\n * This is separate from the Link-based dependency tracking used by Signal/Computed/Effect.\n * It's specifically for tracking property access on reactive objects.\n */\nconst targetMap = new WeakMap<object, Map<string | symbol, Dep>>();\nlet triggerVersion = 0;\n\n/**\n * Collects triggered subscribers from a reactive-property dep node.\n *\n * @param dep - The property dep node.\n * @param effects - The effects array to push to.\n * @param version - The trigger version.\n */\nfunction collectTriggeredEffects(\n dep: Dep | undefined,\n effects: ReactiveNode[],\n version: number,\n): void {\n if (!dep) {\n return;\n }\n\n for (let link = dep.subLink; link; link = link.nextSubLink) {\n const effect = link.subNode;\n if (effect._triggerVersion === version) {\n continue;\n }\n effect._triggerVersion = version;\n effects.push(effect);\n }\n}\n\n/**\n * Track a dependency on a reactive object property.\n *\n * @param target - The reactive object being accessed.\n * @param key - The property key being accessed (string, number, or symbol).\n *\n * @example\n * ```typescript\n * const state = reactive({ count: 0, name: 'Alice' });\n *\n * effect(() => {\n * // track(state, 'count') is called automatically\n * console.log(state.count);\n * });\n *\n * // Changing count will trigger the effect\n * state.count++; // trigger(state, 'SET', 'count', 1)\n * ```\n */\nexport function track(target: object, key: string | symbol): void {\n // Only track if there's an active subscriber (effect/computed currently executing)\n // and tracking is not disabled (not in untrack() call)\n if (!activeSub || isUntracking) {\n return;\n }\n\n // Each target object has a Map of its property dependencies\n let depsMap = targetMap.get(target);\n if (!depsMap) {\n depsMap = new Map();\n targetMap.set(target, depsMap);\n }\n\n // Each property has a dedicated Dep node that participates in the same\n // Link graph as signals / computeds / effects.\n let dep = depsMap.get(key);\n if (!dep) {\n dep = new Dep(depsMap, key);\n depsMap.set(key, dep);\n }\n\n linkReactiveNode(dep, activeSub);\n}\n\n/**\n * Trigger updates for subscribers of a reactive object property.\n *\n * This function notifies all subscribers (effects/computed) that depend on a specific\n * property of a reactive object that the property has changed.\n *\n * ## When is this called?\n *\n * - When setting a property: `reactiveObj.prop = value` → trigger(obj, 'SET', 'prop', value)\n * - When adding a property: `reactiveObj.newProp = value` → trigger(obj, 'ADD', 'newProp', value)\n * - When deleting a property: `delete reactiveObj.prop` → trigger(obj, 'DELETE', 'prop')\n * - When clearing a collection: `reactiveArray.length = 0` → trigger(obj, 'CLEAR')\n * - When mutating arrays: `reactiveArray.push(item)` → trigger(obj, 'SET', 'length', newLength)\n *\n * ## Operation Types\n *\n * - **SET**: Property value changed (most common)\n * - **ADD**: New property added (affects iteration)\n * - **DELETE**: Property removed (affects iteration)\n * - **CLEAR**: Collection cleared (affects iteration)\n *\n * ## Iteration Dependencies\n *\n * @param target - The reactive object that changed.\n * @param type - The type of operation: 'SET' | 'ADD' | 'DELETE' | 'CLEAR'.\n * @param key - The property key that changed (optional for CLEAR operations).\n * @param newValue - The new value.\n *\n * @example\n * ```typescript\n * const state = reactive({ count: 0, items: [1, 2, 3] });\n *\n * effect(() => {\n * console.log(state.count); // Depends on 'count'\n * });\n *\n * effect(() => {\n * console.log(state.items.length); // Depends on 'items' and iteration\n * });\n *\n * // Triggers first effect only\n * state.count = 1; // trigger(state, 'SET', 'count', 1)\n *\n * // Triggers second effect (changes length and iteration)\n * state.items.push(4); // trigger(state.items, 'SET', 'length', 4)\n * // trigger(state.items, 'ADD', '3', 4)\n * ```\n */\n/**\n * Trigger updates for subscribers of a reactive object property.\n *\n * @param target - The reactive object that changed.\n * @param type - The type of operation: 'SET' | 'ADD' | 'DELETE' | 'CLEAR'.\n * @param key - The property key that changed (optional for CLEAR operations).\n * @param newValue - The new value.\n * @returns {void}\n */\nexport function trigger(\n target: object,\n type: string,\n key?: string | symbol | (string | symbol)[],\n newValue?: unknown,\n): void {\n // If this target has no tracked dependencies, nothing to do\n const depsMap = targetMap.get(target);\n if (!depsMap) {\n return;\n }\n\n const effects: ReactiveNode[] = [];\n const version = ++triggerVersion;\n\n // Collect all effects that depend on the specific property that changed\n if (key !== undefined) {\n if (Array.isArray(key)) {\n for (const element of key) {\n collectTriggeredEffects(depsMap.get(element), effects, version);\n }\n } else {\n collectTriggeredEffects(depsMap.get(key), effects, version);\n }\n }\n\n // For operations that affect iteration (ADD/DELETE/CLEAR), we need to trigger\n // effects that iterate over the collection\n\n if (type === 'ADD' || type === 'DELETE' || type === 'CLEAR') {\n const iterationKey = Array.isArray(target) ? ARRAY_ITERATE_KEY : ITERATE_KEY;\n collectTriggeredEffects(depsMap.get(iterationKey), effects, version);\n }\n\n // Process each effect that needs to be notified\n for (const effect of effects) {\n // In development mode, notify debugging tools about the trigger\n if (__DEV__ && isFunction(effect.onTrigger)) {\n effect.onTrigger({\n effect,\n target,\n type,\n key,\n newValue,\n });\n }\n\n // Effects and Computed values need different handling\n\n if (effect.flag & ReactiveFlags.WATCHING) {\n (effect as Effect).notify?.();\n } else if (effect.flag & ReactiveFlags.MUTABLE) {\n effect.flag |= ReactiveFlags.DIRTY;\n if (effect.subLink) {\n propagate(effect.subLink);\n }\n }\n }\n}\n\n/**\n * Internal test helper: returns the number of subscribers currently linked to\n * a reactive target property dep.\n */\nexport function getTargetDepSize(target: object, key: string | symbol): number {\n const rawTarget =\n (target as Record<string, unknown> | null)?.[SignalFlags.RAW] instanceof Object\n ? ((target as Record<string, unknown>)[SignalFlags.RAW] as object)\n : target;\n const dep = targetMap.get(rawTarget)?.get(key);\n if (!dep) {\n return 0;\n }\n\n let size = 0;\n for (let link = dep.subLink; link; link = link.nextSubLink) {\n size++;\n }\n return size;\n}\n","import {\n hasChanged,\n hasOwn,\n isArray,\n isMap,\n isObject,\n isSet,\n isStringNumber,\n isWeakMap,\n isWeakSet,\n} from '@estjs/shared';\nimport {\n ARRAY_ITERATE_KEY,\n ARRAY_KEY,\n COLLECTION_KEY,\n SignalFlags,\n TriggerOpTypes,\n WEAK_COLLECTION_KEY,\n} from './constants';\nimport { isSignal } from './signal';\nimport { track, trigger } from './link';\n\n// Use WeakMap to cache created reactive proxies to avoid duplicate creation.\nconst reactiveCaches = new WeakMap<object, object>();\n\n/**\n * Return the raw underlying value of a reactive proxy or signal.\n * Recursively unwraps nested reactive objects and arrays.\n *\n * @param value - Reactive or signal value.\n * @returns {T} Raw value without any reactive wrapping.\n */\nexport function toRaw<T>(value: T): T {\n if (!value || !isObject(value)) {\n return value as T;\n }\n\n const raw = value[SignalFlags.RAW];\n if (raw) {\n // Recursively unwrap in case the raw value is also reactive\n return toRaw(raw);\n }\n\n // Check if it's a signal and unwrap without triggering dependencies\n if (isSignal(value)) {\n return toRaw(value.peek()) as T;\n }\n\n // For all other cases (non-reactive objects, arrays, collections, etc.), return as-is\n // Arrays, Maps, Sets, etc. that aren't reactive proxies are already \"raw\"\n return value as T;\n}\n\nconst arrayInstrumentations = createArrayInstrumentations();\n\n/**\n * Create enhanced versions of array methods that include dependency tracking.\n * Includes search, modification, and iteration methods.\n *\n * @returns An object that maps method keys to enhanced functions.\n */\nfunction createArrayInstrumentations() {\n const instrumentations: Record<string | symbol, Function> = {};\n\n // Search methods: track array iteration and handle reactive object arguments\n ['includes', 'indexOf', 'lastIndexOf'].forEach((key) => {\n instrumentations[key] = function (this: unknown[], ...args: unknown[]) {\n const arr = toRaw(this) as any[];\n // Track iteration access to the entire array\n track(arr, ARRAY_ITERATE_KEY);\n\n // First try with the original arguments\n let res = arr[key as keyof typeof arr](...args);\n\n // If lookup fails and we have arguments, try with raw values\n // This handles cases where reactive objects are passed as search values\n if ((res === -1 || res === false) && args.length > 0) {\n const rawArgs = args.map((arg) => toRaw(arg));\n res = arr[key as keyof typeof arr](...rawArgs);\n }\n\n return res;\n };\n });\n\n // Search methods that return elements: track iteration and maintain reactivity\n ['find', 'findIndex', 'findLast', 'findLastIndex'].forEach((key) => {\n instrumentations[key] = function (this: unknown[], ...args: unknown[]) {\n const arr = toRaw(this) as any[];\n const isShallowMode = isShallow(this);\n\n // Track iteration access to the entire array\n track(arr, ARRAY_ITERATE_KEY);\n\n const res = arr[key as keyof typeof arr](...args);\n\n // For find/findLast, make result reactive if needed\n if ((key === 'find' || key === 'findLast') && isObject(res) && !isShallowMode) {\n return reactiveImpl(res);\n }\n\n return res;\n };\n });\n\n // Mutation methods: trigger array changes\n ['push', 'pop', 'shift', 'unshift', 'splice', 'sort', 'reverse', 'fill', 'copyWithin'].forEach(\n (key) => {\n instrumentations[key] = function (this: unknown[], ...args: unknown[]) {\n const arr = toRaw(this);\n // Call the method using Array.prototype to ensure it works correctly\n const res = Array.prototype[key].apply(arr, args);\n // Trigger both array content and iteration watchers in a single pass\n trigger(arr, TriggerOpTypes.SET, [ARRAY_KEY, ARRAY_ITERATE_KEY]);\n return res;\n };\n },\n );\n\n // ES2023 methods that return new arrays: track access and maintain reactivity\n ['toReversed', 'toSorted', 'toSpliced'].forEach((key) => {\n instrumentations[key] = function (this: unknown[], ...args: unknown[]) {\n const arr = toRaw(this);\n const isShallowMode = isShallow(this);\n\n // Track iteration access to the entire array\n track(arr, ARRAY_ITERATE_KEY);\n\n // For toSpliced, track all individual elements since they're being accessed\n if (key === 'toSpliced') {\n for (let i = 0, l = arr.length; i < l; i++) {\n track(arr, `${i}`);\n }\n }\n\n // Call the native method\n const res = Array.prototype[key].apply(arr, args);\n\n // Return directly if result is not an array\n if (!Array.isArray(res)) {\n return res;\n }\n\n // Make object elements reactive (deep or shallow based on parent mode)\n return res.map((item) => (isObject(item) ? reactiveImpl(item, isShallowMode) : item));\n };\n });\n\n // Methods that return new arrays but don't modify original: track and maintain reactivity.\n //\n // IMPORTANT: we `apply` on `this` (the reactive proxy), not on the raw\n // array. This way every element access inside the native implementation\n // goes through the proxy's get trap, which (for deep reactive arrays)\n // returns reactive proxies of the items. That preserves reactivity for\n // callers doing e.g. `data.value.slice()[i].label = '...'` or passing\n // the resulting array to `.set()`. Running on the raw array would leak\n // raw, non-reactive items and silently break downstream bindings.\n ['concat', 'slice', 'filter', 'map', 'flatMap', 'flat'].forEach((key) => {\n instrumentations[key] = function (this: unknown[], ...args: unknown[]) {\n const arr = toRaw(this);\n // Track iteration access\n track(arr, ARRAY_ITERATE_KEY);\n // Call the native method on the proxy (this), not the raw array, so\n // element reads go through the reactive get trap.\n return Array.prototype[key].apply(this, args);\n };\n });\n\n // Methods that return strings: only track, no reactivity needed\n ['join', 'toString', 'toLocaleString'].forEach((key) => {\n instrumentations[key] = function (this: unknown[], ...args: unknown[]) {\n const arr = toRaw(this);\n // Track iteration access\n track(arr, ARRAY_ITERATE_KEY);\n return Array.prototype[key].apply(arr, args);\n };\n });\n\n // Iterator methods: track access and maintain reactivity\n ['values', 'keys', 'entries', Symbol.iterator].forEach((key) => {\n instrumentations[key] = function (this: unknown[]) {\n const arr = toRaw(this);\n const isShallowMode = isShallow(this);\n\n // Track changes to the entire array\n track(arr, ARRAY_KEY);\n\n const rawIterator = key === Symbol.iterator ? arr[Symbol.iterator]() : arr[key]();\n\n return {\n /**\n * Returns the next iterator result.\n */\n next() {\n const { value, done } = rawIterator.next();\n\n if (done) {\n return { value, done };\n }\n\n // Handle entries (returns [index, value] or [value, value] for Set)\n if (Array.isArray(value)) {\n return {\n value: value.map((v) => (isObject(v) ? reactiveImpl(v, isShallowMode) : v)),\n done,\n };\n }\n\n // Handle values and keys - make objects reactive\n return {\n value: isObject(value) ? reactiveImpl(value, isShallowMode) : value,\n done,\n };\n },\n /**\n * Returns an iterator for the current collection.\n */\n [Symbol.iterator]() {\n return this;\n },\n };\n };\n });\n\n return instrumentations;\n}\n\n/**\n * Proxy handler for reactive arrays.\n * Intercepts get and set operations to perform dependency tracking and trigger changes.\n *\n * @param shallow - Indicates whether reactivity should be shallow.\n * @returns {any} Object containing array get and set traps.\n */\nconst arrayHandlers = (shallow: boolean) => ({\n get: (target: any, key: string | symbol, receiver: any) => {\n // Intercept operation to get the raw object.\n if (key === SignalFlags.RAW) {\n return target;\n }\n // Intercept operation to check if it's a reactive object.\n if (key === SignalFlags.IS_REACTIVE) {\n return true;\n }\n // Intercept operation to check if it's shallow.\n if (key === SignalFlags.IS_SHALLOW) {\n return shallow;\n }\n // If it's an enhanced method, return the enhanced version.\n if (hasOwn(arrayInstrumentations, key)) {\n return arrayInstrumentations[key];\n }\n\n const value = Reflect.get(target, key, receiver);\n\n // If accessing a numeric index, track that index.\n if (isStringNumber(key)) {\n track(target, key);\n }\n // Track general access to the array.\n track(target, ARRAY_KEY);\n\n // If value is object and needs deep reactivity, return its reactive version.\n if (isObject(value) && !shallow) {\n return reactiveImpl(value);\n }\n return value;\n },\n set: (target: any, key: string | symbol, value: unknown, receiver: any) => {\n const oldValue = Reflect.get(target, key, receiver);\n const result = Reflect.set(target, key, value, receiver);\n if (hasChanged(value, oldValue)) {\n // For numeric indices, we need to trigger multiple dependencies\n if (isStringNumber(key)) {\n trigger(target, TriggerOpTypes.SET, [key, ARRAY_ITERATE_KEY, ARRAY_KEY]);\n } else {\n // For non-numeric keys (like 'length'), just trigger that key\n trigger(target, TriggerOpTypes.SET, key);\n }\n }\n return result;\n },\n});\n\nconst shallowArrayHandlers = arrayHandlers(true);\nconst deepArrayHandlers = arrayHandlers(false);\n\n// Proxy handler for Map and Set collections.\nconst collectionHandlers: ProxyHandler<Map<unknown, unknown> | Set<unknown>> = {\n /**\n * Exposes collection proxy flags and instrumented methods.\n */\n get(target, key: string | symbol) {\n if (key === SignalFlags.IS_REACTIVE) {\n return true;\n }\n if (key === SignalFlags.RAW) {\n return target;\n }\n // Return enhanced method or original method.\n return Reflect.get(\n hasOwn(collectionInstrumentations, key) ? collectionInstrumentations : target,\n key,\n target,\n );\n },\n};\n\n// Proxy handler for WeakMap and WeakSet collections.\nconst weakCollectionHandlers: ProxyHandler<WeakMap<object, unknown> | WeakSet<object>> = {\n /**\n * Exposes weak-collection proxy flags and instrumented methods.\n */\n get(target, key: string | symbol) {\n if (key === SignalFlags.IS_REACTIVE) {\n return true;\n }\n if (key === SignalFlags.RAW) {\n return target;\n }\n // Return enhanced method or original method.\n return Reflect.get(\n hasOwn(weakInstrumentations, key) && key in target ? weakInstrumentations : target,\n key,\n target,\n );\n },\n};\n\n// Enhanced versions of Map and Set collection methods.\nconst collectionInstrumentations = {\n /**\n * Reads a Map entry with dependency tracking.\n */\n get(this: Map<unknown, unknown>, key: unknown) {\n const target = toRaw(this);\n // Track access to the collection\n track(target, COLLECTION_KEY);\n\n const value = target.get(key);\n\n // For deep reactive mode, wrap object values in reactive proxy\n if (isObject(value) && !isShallow(this)) {\n return reactiveImpl(value);\n }\n\n return value;\n },\n /**\n * Sets the requested value.\n */\n set(this: Map<unknown, unknown>, key: unknown, value: unknown) {\n const target = toRaw(this);\n const hadKey = target.has(key);\n const oldValue = target.get(key);\n\n // Store raw value to avoid nested reactive wrapping\n const rawValue = toRaw(value);\n target.set(key, rawValue);\n\n // Only trigger if value actually changed or key is new\n if (!hadKey || hasChanged(oldValue, rawValue)) {\n trigger(target, TriggerOpTypes.SET, COLLECTION_KEY);\n }\n\n return this; // Return the reactive proxy, not the raw target\n },\n /**\n * Adds the requested value.\n */\n add(this: Set<unknown>, value: unknown) {\n const target = toRaw(this);\n // Store raw value to avoid nested reactive wrapping\n const rawValue = toRaw(value);\n const hadValue = target.has(rawValue);\n\n target.add(rawValue);\n\n // Only trigger when the Set membership actually changes.\n if (!hadValue) {\n trigger(target, TriggerOpTypes.ADD, COLLECTION_KEY);\n }\n\n return this; // Return the reactive proxy, not the raw target\n },\n /**\n * Returns whether the requested value exists.\n */\n has(key: unknown) {\n const target = toRaw(this);\n // Track access to the collection\n track(target, COLLECTION_KEY);\n\n // Try with original key first, then with raw key\n // This handles reactive objects as keys\n const hasKey = target.has(key);\n if (!hasKey && isObject(key)) {\n return target.has(toRaw(key));\n }\n\n return hasKey;\n },\n /**\n * Deletes the requested value.\n */\n delete(key: unknown) {\n const target = toRaw(this);\n const hadKey = target.has(key);\n\n // Try deleting with original key first\n let result = target.delete(key);\n\n // If failed and key is an object, try with raw key\n if (!result && isObject(key)) {\n result = target.delete(toRaw(key));\n }\n\n // Only trigger if something was actually deleted\n if (hadKey || result) {\n trigger(target, TriggerOpTypes.DELETE, COLLECTION_KEY);\n }\n\n return result;\n },\n /**\n * Clears the current collection.\n */\n clear() {\n const target = toRaw(this);\n const hadItems = target.size > 0;\n const result = target.clear();\n\n // Only trigger if collection had items\n if (hadItems) {\n trigger(target, TriggerOpTypes.CLEAR, COLLECTION_KEY);\n }\n\n return result;\n },\n /**\n * Iterates over each collection entry.\n */\n forEach(\n this: Map<unknown, unknown> | Set<unknown>,\n callback: (value: unknown, key: unknown, map: Map<unknown, unknown> | Set<unknown>) => void,\n thisArg?: unknown,\n ) {\n const target = toRaw(this);\n const isShallowMode = isShallow(this);\n\n // Track access to the collection\n track(target, COLLECTION_KEY);\n\n // Wrap callback to provide reactive values in deep mode\n target.forEach((value: unknown, key: unknown) => {\n const wrappedValue = isShallowMode || !isObject(value) ? value : reactiveImpl(value);\n const wrappedKey = isShallowMode || !isObject(key) ? key : reactiveImpl(key);\n\n callback.call(thisArg, wrappedValue, wrappedKey, this);\n });\n },\n /**\n * Returns an iterator for the current collection.\n */\n [Symbol.iterator](this: Map<unknown, unknown> | Set<unknown>) {\n const target = toRaw(this);\n const isShallowMode = isShallow(this);\n\n // Track access to the collection\n track(target, COLLECTION_KEY);\n\n const rawIterator = target[Symbol.iterator]();\n\n return {\n /**\n * Returns the next iterator result.\n */\n next() {\n const { value, done } = rawIterator.next();\n\n if (done) {\n return { value, done };\n }\n\n // In shallow mode, return as-is\n if (isShallowMode) {\n return { value, done };\n }\n\n // For Map entries [key, value], wrap both if they're objects\n if (Array.isArray(value)) {\n return {\n value: value.map((v) => (isObject(v) ? reactiveImpl(v) : v)),\n done,\n };\n }\n\n // For Set values, wrap if object\n return {\n value: isObject(value) ? reactiveImpl(value) : value,\n done,\n };\n },\n /**\n * Returns an iterator for the current collection.\n */\n [Symbol.iterator]() {\n return this;\n },\n };\n },\n /**\n * Returns the current collection size.\n */\n get size() {\n const target = toRaw(this);\n // Track access to size property\n track(target, COLLECTION_KEY);\n return target.size;\n },\n /**\n * Returns an iterator over the current keys.\n */\n keys(this: Map<unknown, unknown> | Set<unknown>) {\n const target = toRaw(this);\n const isShallowMode = isShallow(this);\n\n // Track access to the collection\n track(target, COLLECTION_KEY);\n\n const rawIterator = target.keys();\n\n return {\n /**\n * Returns the next iterator result.\n */\n next() {\n const { value, done } = rawIterator.next();\n\n if (done) {\n return { value, done };\n }\n\n // Wrap keys if they're objects and in deep mode\n return {\n value: isShallowMode || !isObject(value) ? value : reactiveImpl(value),\n done,\n };\n },\n /**\n * Returns an iterator for the current collection.\n */\n [Symbol.iterator]() {\n return this;\n },\n };\n },\n /**\n * Returns an iterator over the current values.\n */\n values(this: Map<unknown, unknown> | Set<unknown>) {\n const target = toRaw(this);\n const isShallowMode = isShallow(this);\n\n // Track access to the collection\n track(target, COLLECTION_KEY);\n\n const rawIterator = target.values();\n\n return {\n /**\n * Returns the next iterator result.\n */\n next() {\n const { value, done } = rawIterator.next();\n\n if (done) {\n return { value, done };\n }\n\n // Wrap values if they're objects and in deep mode\n return {\n value: isShallowMode || !isObject(value) ? value : reactiveImpl(value),\n done,\n };\n },\n /**\n * Returns an iterator for the current collection.\n */\n [Symbol.iterator]() {\n return this;\n },\n };\n },\n /**\n * Returns an iterator over the current entries.\n */\n entries(this: Map<unknown, unknown> | Set<unknown>) {\n const target = toRaw(this);\n const isShallowMode = isShallow(this);\n\n // Track access to the collection\n track(target, COLLECTION_KEY);\n\n const rawIterator = target.entries();\n\n return {\n /**\n * Returns the next iterator result.\n */\n next() {\n const { value, done } = rawIterator.next();\n\n if (done) {\n return { value, done };\n }\n\n // In shallow mode, return as-is\n if (isShallowMode) {\n return { value, done };\n }\n\n // Wrap both key and value if they're objects\n return {\n value: value.map((v: unknown) => (isObject(v) ? reactiveImpl(v) : v)),\n done,\n };\n },\n /**\n * Returns an iterator for the current collection.\n */\n [Symbol.iterator]() {\n return this;\n },\n };\n },\n};\n\n// Enhanced versions of WeakMap and WeakSet collection methods.\nconst weakInstrumentations = {\n /**\n * Reads a WeakMap entry with dependency tracking.\n */\n get(this: WeakMap<object, unknown>, key: object) {\n const target = toRaw(this);\n // Track access to the weak collection\n track(target, WEAK_COLLECTION_KEY);\n\n // Try with original key first\n let value = target.get(key);\n\n // If not found and key is reactive, try with raw key\n if (value === undefined && isReactive(key)) {\n value = target.get(toRaw(key));\n }\n\n // For deep reactive mode, wrap object values in reactive proxy\n if (isObject(value) && !isShallow(this)) {\n return reactiveImpl(value);\n }\n\n return value;\n },\n /**\n * Sets the requested value.\n */\n set(this: WeakMap<object, unknown>, key: object, value: unknown) {\n const target = toRaw(this);\n const rawKey = toRaw(key);\n const hadKey = target.has(rawKey);\n const oldValue = target.get(rawKey);\n\n // Store raw value to avoid nested reactive wrapping\n const rawValue = toRaw(value);\n target.set(rawKey, rawValue);\n\n // Only trigger if value actually changed or key is new\n if (!hadKey || hasChanged(oldValue, rawValue)) {\n trigger(target, TriggerOpTypes.SET, WEAK_COLLECTION_KEY);\n }\n\n return this; // Return the reactive proxy, not the raw target\n },\n /**\n * Adds the requested value.\n */\n add(this: WeakSet<object>, value: object) {\n const target = toRaw(this);\n const rawValue = toRaw(value);\n const hadValue = target.has(rawValue);\n\n target.add(rawValue);\n\n // Only trigger if value is new\n if (!hadValue) {\n trigger(target, TriggerOpTypes.ADD, WEAK_COLLECTION_KEY);\n }\n\n return this; // Return the reactive proxy, not the raw target\n },\n /**\n * Returns whether the requested value exists.\n */\n has(key: object) {\n const target = toRaw(this);\n // Track access to the weak collection\n track(target, WEAK_COLLECTION_KEY);\n\n // Try with original key first\n let hasKey = target.has(key);\n\n // If not found and key is reactive, try with raw key\n if (!hasKey && isReactive(key)) {\n hasKey = target.has(toRaw(key));\n }\n\n return hasKey;\n },\n /**\n * Deletes the requested value.\n */\n delete(key: object) {\n const target = toRaw(this);\n const rawKey = toRaw(key);\n const hadKey = target.has(rawKey);\n\n const result = target.delete(rawKey);\n\n // Only trigger if something was actually deleted\n if (hadKey || result) {\n trigger(target, TriggerOpTypes.DELETE, WEAK_COLLECTION_KEY);\n }\n\n return result;\n },\n};\n\n/**\n * Proxy handler for plain objects (non-collection types).\n * Intercepts get, set, and delete operations to manage reactivity.\n *\n * @param shallow - Indicates whether to create shallow reactive proxy.\n * @returns {any} Object containing get, set, and delete traps.\n */\nconst objectHandlers = (shallow: boolean) => ({\n /**\n * Reads an object property, unwraps signals, and tracks the access.\n */\n get(target: object, key: string | symbol, receiver: object) {\n if (key === SignalFlags.RAW) {\n return target;\n }\n if (key === SignalFlags.IS_REACTIVE) {\n return true;\n }\n if (key === SignalFlags.IS_SHALLOW) {\n return shallow;\n }\n\n const value = Reflect.get(target, key, receiver);\n\n // Auto-unwrap signals.\n const valueUnwrapped = isSignal(value) ? value.value : value;\n\n // Collect dependencies for accessed properties.\n track(target, key);\n\n // If needed, recursively wrap the value in a reactive proxy.\n if (isObject(valueUnwrapped) && !shallow) {\n return reactiveImpl(valueUnwrapped);\n }\n return valueUnwrapped;\n },\n set: (target: object, key: string | symbol, value: unknown, receiver: object) => {\n const oldValue = Reflect.get(target, key, receiver);\n // When setting value, ensure the raw value is set.\n const result = Reflect.set(target, key, toRaw(value), receiver);\n if (hasChanged(value, oldValue)) {\n trigger(target, TriggerOpTypes.SET, key, value);\n }\n return result;\n },\n deleteProperty: (target: object, key: string | symbol) => {\n const hadKey = hasOwn(target, key);\n const result = Reflect.deleteProperty(target, key);\n if (hadKey && result) {\n trigger(target, TriggerOpTypes.DELETE, key, undefined);\n }\n return result;\n },\n});\n\n// Pre-create handler objects at module load time so reactiveImpl never\n// allocates a new handler on each call (Fix-3).\nconst shallowObjectHandlers = objectHandlers(true);\nconst deepObjectHandlers = objectHandlers(false);\n\n/**\n * Creates or reuses the appropriate reactive proxy for a target.\n *\n * @param target - The object to make reactive.\n * @param shallow - Whether to create a shallow reactive proxy.\n * @returns {T} The reactive proxy of the target object.\n */\nexport function reactiveImpl<T extends object>(target: T, shallow = false): T {\n if (!isObject(target)) {\n return target;\n }\n\n // If target object is already reactive, return directly.\n if (isReactive(target)) {\n return target;\n }\n\n // Check if proxy already exists in cache.\n const existingProxy = reactiveCaches.get(target);\n if (existingProxy) {\n return existingProxy as T;\n }\n\n // Choose appropriate handler based on target type.\n let handler;\n if (isArray(target)) {\n handler = shallow ? shallowArrayHandlers : deepArrayHandlers;\n } else if (isSet(target) || isMap(target)) {\n handler = collectionHandlers;\n } else if (isWeakMap(target) || isWeakSet(target)) {\n handler = weakCollectionHandlers;\n } else {\n handler = shallow ? shallowObjectHandlers : deepObjectHandlers;\n }\n\n // Create and cache proxy.\n const proxy = new Proxy(target, handler);\n reactiveCaches.set(target, proxy);\n return proxy;\n}\n\n/**\n * Check if the target object is reactive.\n *\n * @param target - The object to check.\n * @returns {boolean} True if the object is reactive, false otherwise.\n */\nexport function isReactive(target: unknown): boolean {\n return !!(target && target[SignalFlags.IS_REACTIVE]);\n}\n\n/**\n * Create a reactive proxy for the given target object. If the object is already reactive, return directly.\n *\n * @template T - The type of the object to make reactive.\n * @param target - The object to make reactive.\n * @returns {T} The reactive proxy of the target object.\n *\n * @example\n * ```typescript\n * const state = reactive({ count: 0, nested: { value: 1 } });\n * // Both state.count and state.nested.value are reactive\n * ```\n */\nexport function reactive<T extends object>(target: T): T {\n //If already reactive, return directly to prevent double wrapping\n if (isReactive(target)) {\n return target;\n }\n\n // If target is a signal, warn and unwrap it\n if (isSignal(target)) {\n // Return the signal as-is since signals are already reactive\n return target;\n }\n\n return reactiveImpl(target);\n}\n\n/**\n * Create a shallow reactive proxy for the given object. Only root-level properties are reactive.\n *\n * @template T - The type of the object to make shallow reactive.\n * @param target - The object to make shallow reactive.\n * @returns {T} The shallow reactive proxy of the object.\n *\n * @example\n * ```typescript\n * const state = shallowReactive({ count: 0, nested: { value: 1 } });\n * // Only state.count is reactive, not state.nested.value\n * ```\n */\nexport function shallowReactive<T extends object>(target: T): T {\n // If already reactive, check if it's shallow\n if (isReactive(target)) {\n return target;\n }\n\n // If target is a signal, warn and unwrap it\n if (isSignal(target)) {\n // Return the signal as-is since signals are already reactive\n return target;\n }\n\n return reactiveImpl(target, true);\n}\n\n/**\n * Check if the target object is a shallow reactive proxy.\n *\n * @param value - The object to check.\n * @returns {boolean} True if the object is shallow reactive, false otherwise.\n */\nexport function isShallow(value: unknown): boolean {\n return !!(value && value[SignalFlags.IS_SHALLOW]);\n}\n\n/**\n * Return a reactive proxy for the given value (if possible).\n * If the given value is not an object, return the original value itself.\n *\n * @param value - The value that needs a reactive proxy created for it.\n * @returns {T} The reactive proxy of the value, or the original value.\n */\nexport const toReactive = <T extends unknown>(value: T): T =>\n isObject(value) ? reactive(value) : value;\n\n/**\n * Type alias representing a reactive object.\n *\n * @template T - The type of the original object.\n */\nexport type Reactive<T extends object> = T;\n","import {\n hasChanged,\n isArray,\n isMap,\n isObject,\n isPlainObject,\n isSet,\n isWeakMap,\n isWeakSet,\n warn,\n} from '@estjs/shared';\nimport { activeSub, linkReactiveNode, shallowPropagate } from './link';\nimport { ReactiveFlags, SignalFlags } from './constants';\nimport { isReactive, reactive, shallowReactive, toRaw } from './reactive';\nimport { propagate } from './propagation';\nimport type { Link, ReactiveNode } from './link';\n\n/**\n * Signal is a reactive primitive that holds a value and notifies subscribers when the value changes.\n * It provides methods for reading, writing, and observing value changes.\n *\n * @template T - The type of value held by the Signal\n */\nexport interface Signal<T> {\n /**\n * The current value of the Signal. Reading this property tracks dependencies,\n * and writing to it notifies subscribers of changes.\n */\n value: T;\n\n /**\n * Get the current value without establishing a dependency relationship.\n * Useful when you need to read the value without tracking dependencies.\n *\n * @returns The current value\n */\n peek(): T;\n\n /**\n * Set a new value without notifying subscribers.\n * Used for batching multiple updates together.\n *\n * @param value - The new value to set\n */\n set(value: T): void;\n\n /**\n * Update the value using a function that receives the current value.\n * This is an atomic operation that only notifies subscribers once.\n *\n * @param updater - A function that receives the current value and returns the new value\n */\n update(updater: (prev: T) => T): void;\n}\n\n/**\n * A more precise type for the value held by a signal.\n * This type helps TypeScript understand the type of the unwrapped value.\n *\n * @template T - The type of value held by the signal\n */\nexport type SignalValue<T> = T extends Signal<infer V> ? V : never;\n/**\n * Extract the value type from a Signal\n *\n * @template T - The Signal type\n *\n * @example\n * ```typescript\n * import { signal, type SignalType } from '@estjs/signals';\n *\n * const count = signal(0);\n * type CountValue = SignalType<typeof count>; // number\n * ```\n */\nexport type SignalType<T> = T extends Signal<infer V> ? V : never;\n\n/**\n * Internal implementation of the Signal interface.\n * This class manages reactive state and handles dependency tracking.\n\n * @template T - The type of value held by the Signal\n */\n\nexport class SignalImpl<T> implements ReactiveNode {\n // Implement ReactiveNode interface\n depLink?: Link | undefined;\n subLink?: Link | undefined;\n depLinkTail?: Link | undefined;\n subLinkTail?: Link | undefined;\n flag: ReactiveFlags = ReactiveFlags.MUTABLE; // Initial state is \"mutable\"\n\n // _oldValue is deliberately NOT initialized here so that `'_oldValue' in instance`\n // returns false until the first value change — the test suite directly checks this.\n protected _oldValue!: T; // on-demand, only present after first change\n protected _rawValue: T; // Store raw (non-proxied) new value\n\n _value: T; // Store current value (may be a reactive proxy)\n\n private readonly [SignalFlags.IS_SHALLOW]: boolean; // Mark whether it's shallow reactive\n\n // @ts-ignore\n private readonly [SignalFlags.IS_SIGNAL] = true as const; // Mark as Signal\n\n /**\n * Create a new Signal with the given initial value.\n *\n * @param value - Initial value\n * @param shallow - Whether only the top level should be reactive\n */\n constructor(value?: T, shallow = false) {\n // Optimization: Don't initialize _oldValue in constructor\n // It will be created on-demand in shouldUpdate()\n\n // Extract raw value correctly in constructor to ensure _rawValue is never a proxy\n const unwrapped = toRaw(value);\n this._rawValue = unwrapped as T;\n\n this[SignalFlags.IS_SHALLOW] = shallow;\n\n // Fast path: if primitive, no proxy needed\n if (!shouldWrapReactiveValue(unwrapped)) {\n this._value = unwrapped as T;\n } else {\n // If value is already reactive, reuse it directly instead of lookup\n if (isReactive(value)) {\n this._value = value as T;\n } else {\n this._value = (\n shallow ? shallowReactive(unwrapped as object) : reactive(unwrapped as object)\n ) as T;\n }\n }\n }\n\n /**\n * Returns the dependency node used for tracking.\n *\n * @returns {this} The dependency node.\n */\n get dep(): this {\n return this;\n }\n\n /**\n * Returns the current value.\n *\n * @returns {T} The current value.\n */\n get value(): T {\n const sub = activeSub;\n if (sub) {\n linkReactiveNode(this, sub);\n }\n\n // Optimization: Cache flag and subLink to local variables to reduce property access\n const flags = this.flag;\n if (flags & ReactiveFlags.DIRTY && this.shouldUpdate()) {\n // Cache subLink locally to avoid repeated property access\n const subs = this.subLink;\n if (subs) {\n shallowPropagate(subs);\n }\n }\n\n return this._value;\n }\n\n /**\n * Updates the current value.\n *\n * @param newValue - The new value to set.\n */\n set value(newValue: T) {\n // If the new value is another signal, unwrap it\n if (isSignal(newValue)) {\n if (__DEV__) {\n warn(\n 'Setting a signal value to another signal is not recommended. ' +\n 'The value will be unwrapped automatically.',\n );\n }\n newValue = (newValue as Signal<T>).peek() as T;\n }\n\n // Keep a reference to the caller-supplied value (may already be a reactive proxy)\n // before stripping it to raw, so we can reuse the existing proxy if present.\n const originalValue = newValue;\n const rawValue = toRaw(newValue);\n\n if (!hasChanged(this._rawValue, rawValue)) {\n return;\n }\n\n this._oldValue = this._rawValue;\n this._rawValue = rawValue;\n this.flag |= ReactiveFlags.DIRTY;\n\n if (!shouldWrapReactiveValue(rawValue)) {\n // Primitive: no proxy needed\n this._value = rawValue as T;\n } else if (isReactive(originalValue)) {\n // The caller already handed us a reactive proxy — reuse it directly.\n // This avoids an unnecessary WeakMap lookup in reactiveCaches.\n this._value = originalValue as T;\n } else {\n // Plain object/array: wrap in a reactive proxy (cached by reactiveCaches).\n const shallow = this[SignalFlags.IS_SHALLOW];\n this._value = (\n shallow ? shallowReactive(rawValue as object) : reactive(rawValue as object)\n ) as T;\n }\n\n const subs = this.subLink;\n if (subs) {\n propagate(subs);\n }\n }\n\n /**\n * Check if the value should be updated.\n *\n * @returns {boolean} True if the value should be updated.\n */\n shouldUpdate(): boolean {\n this.flag &= ~ReactiveFlags.DIRTY;\n\n // _oldValue is only assigned in the setter (on-demand), so `'_oldValue' in this` is false\n // until the first actual change. This preserves the test-verified optimization.\n if (!('_oldValue' in this)) {\n return true;\n }\n\n const changed = hasChanged(this._oldValue as T, this._rawValue);\n this._oldValue = this._rawValue;\n return changed;\n }\n\n /**\n * Get current value without triggering dependency tracking.\n *\n * @returns {T} The current value.\n */\n peek(): T {\n return this._value;\n }\n\n /**\n * Sets the requested value.\n *\n * @param value - The new value to set.\n * @returns {void}\n */\n set(value: T): void {\n this.value = value;\n }\n\n /**\n * Update value using an updater function.\n *\n * @param updater - A function that receives the current value and returns the new value.\n * @returns {void}\n */\n update(updater: (prev: T) => T): void {\n const nextValue = updater(this.peek());\n // Handle case where updater function returns a signal\n if (isSignal(nextValue)) {\n if (__DEV__) {\n warn(\n 'Returning a signal from an update function is not recommended. The value will be unwrapped.',\n );\n }\n this.value = nextValue.peek() as T;\n } else {\n this.value = nextValue;\n }\n }\n}\n\n/**\n * Checks whether a value should be wrapped in a reactive proxy.\n *\n * @param value - The value to check.\n * @returns True if it should be wrapped.\n */\nfunction shouldWrapReactiveValue(value: unknown): value is object {\n if (!isObject(value)) return false;\n return (\n isArray(value) ||\n isMap(value) ||\n isSet(value) ||\n isWeakMap(value) ||\n isWeakSet(value) ||\n isPlainObject(value)\n );\n}\n\n/**\n * Create a new signal with the given initial value.\n * The signal will track all nested properties of object values.\n *\n * @template T - The type of value to store in the signal.\n * @param value - Initial value (defaults to undefined).\n * @returns A new signal instance.\n *\n * @example\n * ```typescript\n * const count = signal(0);\n * const user = signal({ name: 'John' });\n * const empty = signal(); // undefined\n * ```\n */\nexport function signal<T>(value?: T): Signal<T> {\n // If the value is already a signal, return it directly to avoid duplicate creation\n if (isSignal(value)) {\n if (__DEV__) {\n warn(\n 'Creating a signal with another signal is not recommended. The value will be unwrapped.',\n );\n }\n return value as Signal<T>;\n }\n return new SignalImpl(value);\n}\n\n/**\n * Create a new shallow signal with the given initial value.\n * Only the top-level properties of object values are reactive.\n *\n * @template T - The type of value to store in the signal.\n * @param value - Initial value (defaults to undefined).\n * @returns A new shallow signal instance.\n *\n * @example\n * ```typescript\n * const state = shallowSignal({ nested: { value: 1 } });\n * // Only state.nested is reactive, not state.nested.value\n * ```\n */\nexport function shallowSignal<T>(value?: T): Signal<T> {\n // If the value is a signal, extract its value\n if (isSignal(value)) {\n value = value.peek() as T;\n }\n return new SignalImpl(value, true);\n}\n\n/**\n * Type guard to check if a value is a Signal instance.\n *\n * @template T - The type of value held by the signal.\n * @param value - The value to check.\n * @returns true if the value is a Signal instance.\n */\nexport function isSignal<T>(value: unknown): value is Signal<T> {\n return !!value && !!value[SignalFlags.IS_SIGNAL];\n}\n","import { error, warn } from '@estjs/shared';\n\n/**\n * Represents a task (job) that can be scheduled for execution\n */\nexport type Job = () => void;\n\n/**\n * Represents a callback function that should be executed before the main task queue\n */\nexport type PreFlushCallback = () => void;\n\n/**\n * Represents the possible flush timing strategies for effects\n *\n * - 'pre': Execute before the main queue (useful for component updates)\n * - 'post': Execute after the main queue (default behavior)\n * - 'sync': Execute immediately and synchronously (use sparingly)\n */\nexport type FlushTiming = 'pre' | 'post' | 'sync';\n\n// Main task queue storing jobs waiting to be executed\n// Using Set for automatic deduplication\nconst queue: Set<Job> = new Set();\n\n// Pre-flush callback queue, cleared before main task queue execution\n// Using Set for automatic deduplication\nconst activePreFlushCbs: Set<PreFlushCallback> = new Set();\n\n// Resolved Promise used to schedule tasks into the microtask queue\nconst p = Promise.resolve();\n\n// Flag to prevent duplicate flush scheduling, ensuring only one schedule per event loop\nlet isFlushPending = false;\n\n/**\n * Schedules a function to be executed in the next microtask.\n *\n * @param fn - Optional function to execute.\n * @returns A Promise that resolves after the function execution.\n */\nexport function nextTick(fn?: () => void): Promise<void> {\n return fn ? p.then(fn) : p;\n}\n\n/**\n * Adds a job to the main queue and ensures it will be executed.\n *\n * @param job - The job to enqueue.\n */\nexport function queueJob(job: Job): void {\n queue.add(job); // Set automatically deduplicates\n queueFlush();\n}\n\n/**\n * Schedules a queue flush in the next microtask if one hasn't been scheduled yet.\n *\n * @returns {void}\n */\nfunction queueFlush(): void {\n if (!isFlushPending) {\n isFlushPending = true;\n nextTick(flushJobs);\n }\n}\n\n/**\n * Adds a callback to be executed before the main queue processing.\n *\n * @param cb - The callback to execute before the main queue.\n */\nexport function queuePreFlushCb(cb: PreFlushCallback): void {\n activePreFlushCbs.add(cb); // Set automatically deduplicates\n queueFlush();\n}\n\n/**\n * Executes all enqueued jobs and pre-flush callbacks.\n *\n * @returns {void}\n */\nexport function flushJobs(): void {\n isFlushPending = false;\n\n // Execute pre-flush callbacks first\n flushPreFlushCbs();\n\n // Process jobs until queue is empty.\n // Iterate the Set directly (before clearing) rather than Array.from() to avoid\n // a full copy allocation each tick. Jobs added during execution are picked up\n // in the next while-iteration.\n while (queue.size > 0) {\n for (const job of queue) {\n try {\n job();\n } catch (_error) {\n if (__DEV__) {\n error('Error executing queued job:', _error);\n }\n }\n }\n queue.clear();\n }\n}\n\n/**\n * Executes all pre-flush callbacks.\n *\n * @returns {void}\n */\nfunction flushPreFlushCbs(): void {\n // Convert Set to array and clear the Set immediately\n // This allows new callbacks to be queued during execution\n const callbacks = Array.from(activePreFlushCbs);\n activePreFlushCbs.clear();\n\n // Execute all callbacks with error handling\n for (const callback of callbacks) {\n try {\n callback();\n } catch (_error) {\n if (__DEV__) {\n error('Error executing pre-flush callback:', _error);\n }\n }\n }\n}\n\n/**\n * Creates a scheduler function for an effect based on the specified flush timing.\n *\n * @param effect - The effect function to schedule.\n * @param flush - When to execute the effect ('pre', 'post', or 'sync').\n * @returns A scheduler function that will run the effect at the appropriate time.\n */\nexport function createScheduler(\n effect: () => void,\n flush: FlushTiming,\n): () => void | Promise<void> {\n switch (flush) {\n case 'sync':\n return () => effect();\n case 'pre':\n return () => queuePreFlushCb(effect);\n case 'post':\n return () => queueJob(effect);\n default:\n if (__DEV__) {\n warn(`Invalid flush timing: ${flush}. Defaulting to 'post'.`);\n }\n return () => queueJob(effect);\n }\n}\n","import { warn } from '@estjs/shared';\nimport { flushJobs } from './scheduler';\n/**\n * Batch update depth\n *\n * Supports nested batch calls.\n * Effects are only flushed when the outermost batch ends.\n */\nlet batchDepth = 0;\n\n/**\n * Execute a function in batch mode.\n *\n * @param fn - The function to execute in batch mode.\n * @returns The return value of the function.\n *\n * @example\n * ```typescript\n * const x = signal(0);\n * const y = signal(0);\n *\n * effect(() => {\n * console.log('Sum:', x.value + y.value);\n * });\n *\n * // Without batch - Effect executes 2 times\n * x.value = 1; // Effect executes\n * y.value = 2; // Effect executes\n *\n * // With batch - Effect executes only 1 time\n * batch(() => {\n * x.value = 10;\n * y.value = 20;\n * }); // Effect executes once\n * ```\n */\nexport function batch<T>(fn: () => T): T {\n startBatch();\n try {\n return fn();\n } finally {\n endBatch();\n }\n}\n\n/**\n * Start batch update.\n *\n * @returns {void}\n */\nexport function startBatch(): void {\n batchDepth++;\n}\n\n/**\n * End batch update.\n *\n * @returns {void}\n */\nexport function endBatch(): void {\n // Development mode: Check for unbalanced batch calls\n if (__DEV__ && batchDepth === 0) {\n warn(\n '[Batch] endBatch() called without matching startBatch(). ' +\n 'This indicates unbalanced batch calls in your code. ' +\n 'Make sure every startBatch() has a corresponding endBatch(), ' +\n 'or use the batch() function which handles this automatically.',\n );\n return;\n }\n\n // Decrement batch depth\n batchDepth--;\n\n // When outermost batch ends, flush all queued effects\n if (batchDepth === 0) {\n flushJobs();\n }\n}\n\n/**\n * Check if currently in batch update mode.\n *\n * @returns True if currently in batch mode.\n */\nexport function isBatching(): boolean {\n return batchDepth > 0;\n}\n\n/**\n * Get current batch depth.\n *\n * @returns Current batch nesting depth.\n */\nexport function getBatchDepth(): number {\n return batchDepth;\n}\n","import { error, isFunction, warn } from '@estjs/shared';\nimport { EffectFlags, ReactiveFlags, SignalFlags } from './constants';\nimport { checkDirty, endTracking, startTracking, unlinkReactiveNode } from './link';\nimport { isBatching } from './batch';\nimport { createScheduler, queueJob } from './scheduler';\nimport type { Computed } from './computed';\nimport type { Signal } from './signal';\nimport type { Reactive } from './reactive';\nimport type { DebuggerEvent, Link, ReactiveNode } from './link';\nimport type { FlushTiming } from './scheduler';\n\n/**\n * Unwrap a Signal, Computed, or Reactive type to get the underlying value type\n *\n * @template T - The wrapped type\n *\n * @example\n * ```typescript\n * import type { Signal, Computed, Reactive, Unwrap } from '@estjs/signals';\n *\n * type Count = Unwrap<Signal<number>>; // number\n * type User = Unwrap<Reactive<{ name: string }>>; // { name: string }\n * type Double = Unwrap<Computed<number>>; // number\n * ```\n */\nexport type Unwrap<T> =\n T extends Signal<infer V>\n ? V\n : T extends Computed<infer V>\n ? V\n : T extends Reactive<infer V extends object>\n ? V\n : T;\n\n/**\n * Effect function type\n */\nexport type EffectFunction<T = any> = () => T;\n\n/**\n * Effect scheduler function type\n */\nexport type EffectScheduler = (effect: EffectImpl) => void;\n\n/**\n * Effect options configuration\n */\nexport interface EffectOptions {\n /**\n * Custom scheduler for controlling when the effect runs\n * Can be a function or a timing string ('sync', 'pre', 'post')\n */\n scheduler?: EffectScheduler | FlushTiming;\n\n /**\n * Alias for scheduler - controls when the effect runs\n * Can be 'sync', 'pre', or 'post'\n */\n flush?: FlushTiming;\n\n /**\n * Callback invoked when the effect is stopped\n * Useful for cleanup operations\n */\n onStop?: () => void;\n\n /**\n * Debug callback invoked when a dependency is tracked\n * Only called in development mode\n *\n * @param event - Information about the tracked dependency\n *\n * @example\n * ```typescript\n * effect(() => {\n * console.log(signal.value);\n * }, {\n * onTrack(event) {\n * console.log('Tracked:', event.type, event.key);\n * }\n * });\n * ```\n */\n onTrack?: (event: DebuggerEvent) => void;\n\n /**\n * Debug callback invoked when the effect is triggered by a dependency change\n * Only called in development mode\n *\n * @param event - Information about what triggered the effect\n *\n * @example\n * ```typescript\n * effect(() => {\n * console.log(signal.value);\n * }, {\n * onTrigger(event) {\n * console.log('Triggered by:', event.type, event.key, event.newValue);\n * }\n * });\n * ```\n */\n onTrigger?: (event: DebuggerEvent) => void;\n}\n\n/**\n * Effect runner function with attached effect instance\n */\nexport interface EffectRunner<T = any> {\n (): T;\n effect: EffectImpl<T>;\n stop: () => void;\n}\n\n/**\n * Effect implementation class\n *\n * Implements the ReactiveNode interface, acting as a subscriber in the reactive system.\n *\n * Core features:\n * - Automatically tracks dependent reactive values\n * - Automatically re-executes when dependencies change\n * - Supports custom scheduling strategies\n * - Complete lifecycle management\n *\n * @template T - The return type of the effect function\n */\nexport class EffectImpl<T = any> implements ReactiveNode {\n // ReactiveNode interface implementation\n depLink?: Link;\n subLink?: Link;\n depLinkTail?: Link;\n subLinkTail?: Link;\n flag: ReactiveFlags = ReactiveFlags.WATCHING | ReactiveFlags.DIRTY;\n\n // @ts-ignore\n private readonly [SignalFlags.IS_EFFECT] = true as const;\n\n // Core properties\n readonly fn: EffectFunction<T>;\n readonly options?: EffectOptions;\n private _flushScheduler?: () => void | Promise<void>;\n\n // Debug callbacks (only in development)\n onTrack?: (event: DebuggerEvent) => void;\n onTrigger?: (event: DebuggerEvent) => void;\n\n // State management\n private _active = true;\n\n /**\n * Create an Effect instance.\n *\n * @param fn - The effect function.\n * @param options - Configuration options.\n */\n constructor(fn: EffectFunction<T>, options?: EffectOptions) {\n this.fn = fn;\n\n if (options) {\n this.options = options;\n // Use flush as an alias for scheduler if provided\n const scheduler = options.flush || options.scheduler;\n\n if (scheduler && !isFunction(scheduler)) {\n this._flushScheduler = createScheduler(() => this.run(), scheduler);\n }\n\n // For development debugging hooks, we assign them directly to the instance\n // if provided, so the link.ts checking logic can find them without an extra optional chain.\n if (__DEV__) {\n if (options.onTrack) this.onTrack = options.onTrack;\n if (options.onTrigger) this.onTrigger = options.onTrigger;\n }\n }\n }\n\n /**\n * Check if the Effect is active.\n *\n * @returns {boolean} True if the effect is active.\n */\n get active(): boolean {\n return this._active;\n }\n\n /**\n * Check if the Effect is dirty (needs re-execution).\n *\n * @returns {boolean} True if the effect is dirty.\n */\n get dirty(): boolean {\n const flags = this.flag;\n\n // Explicitly marked as dirty\n if (flags & ReactiveFlags.DIRTY) {\n return true;\n }\n\n // Pending state, need to check dependencies\n if (flags & ReactiveFlags.PENDING) {\n if (this.depLink && checkDirty(this.depLink, this)) {\n // Use bitwise operations to set DIRTY and clear PENDING in one operation\n this.flag = (flags & ~ReactiveFlags.PENDING) | ReactiveFlags.DIRTY;\n return true;\n }\n // Dependencies unchanged, clear pending flag using cached flags\n this.flag = flags & ~ReactiveFlags.PENDING;\n }\n\n return false;\n }\n\n /**\n * Pause Effect execution.\n *\n * When an effect is paused:\n * - It stops responding to dependency changes.\n * - Notifications are ignored (see notify method).\n * - DIRTY and PENDING flags are still set when dependencies change.\n * - The effect remains active and maintains its dependency links.\n *\n * Use cases:\n * - Temporarily disable effects during bulk updates.\n * - Prevent effects from running during initialization.\n * - Control when side effects should execute.\n *\n * @returns {void}\n */\n pause(): void {\n this.flag |= EffectFlags.PAUSED;\n }\n\n /**\n * Resume Effect execution.\n *\n * When an effect is resumed:\n * - The PAUSED flag is cleared.\n * - If dependencies changed during pause (DIRTY or PENDING flags set),\n * the effect executes immediately via notify().\n * - If no changes occurred, the effect simply becomes active again.\n *\n * State management:\n * - Clears PAUSED flag atomically.\n * - Checks for accumulated DIRTY/PENDING flags.\n * - Triggers execution if needed.\n *\n * @returns {void}\n */\n resume(): void {\n const flags = this.flag;\n const nextFlags = flags & ~EffectFlags.PAUSED;\n\n this.flag = nextFlags;\n\n // Check if there are pending updates that accumulated during pause\n const wasDirty = (nextFlags & ReactiveFlags.DIRTY) !== 0;\n const wasPending = (nextFlags & ReactiveFlags.PENDING) !== 0;\n\n if (wasDirty || wasPending) {\n this.notify();\n }\n }\n\n /**\n * Execute the Effect function.\n *\n * Core execution flow:\n * 1. Check if active\n * 2. Clear dirty flag\n * 3. Start tracking dependencies\n * 4. Execute user function\n * 5. End tracking, clean up stale dependencies\n *\n * @returns {T} The return value of the effect function.\n */\n run(): T {\n // Already stopped, execute without tracking\n if (!this._active) {\n return this.fn();\n }\n\n // Cache flags and use bitwise operations to update multiple flags efficiently\n const flags = this.flag;\n // Clear DIRTY/PENDING flags and set RUNNING to block concurrent notify() calls.\n this.flag = (flags & ~(ReactiveFlags.DIRTY | ReactiveFlags.PENDING)) | EffectFlags.RUNNING;\n\n // Start dependency tracking\n const prevSub = startTracking(this);\n\n try {\n // Execute the effect function\n return this.fn();\n } catch (error) {\n // Execution error, restore dirty flag\n this.flag |= ReactiveFlags.DIRTY;\n\n throw error;\n } finally {\n // Clear RUNNING flag\n this.flag &= ~EffectFlags.RUNNING;\n // End tracking, clean up stale dependencies\n endTracking(this, prevSub);\n }\n }\n\n private _job?: () => void;\n\n /**\n * Get or create the job function for this effect.\n *\n * @returns {() => void} The job function.\n */\n private getJob(): () => void {\n if (!this._job) {\n this._job = () => this.run();\n }\n return this._job;\n }\n\n /**\n * Notify that the Effect needs to execute.\n *\n * Called by dependent reactive values.\n * Decides whether to execute immediately or defer based on scheduling strategy.\n *\n * @returns {void}\n */\n notify(): void {\n // Cache flags for efficient checking\n const flags = this.flag;\n\n // Early exit: already stopped, paused, currently running, or already dirty—ignore notification.\n if (!this._active || flags & (EffectFlags.PAUSED | EffectFlags.RUNNING | ReactiveFlags.DIRTY)) {\n return;\n }\n\n // Mark as dirty\n this.flag = flags | ReactiveFlags.DIRTY;\n\n // Trigger callback\n if (__DEV__ && this.options?.onTrigger) {\n this.options.onTrigger({\n effect: this,\n target: {},\n type: 'set',\n });\n }\n\n // Use scheduler or decide execution method based on batch state\n const scheduler = this.options?.flush || this.options?.scheduler;\n if (scheduler) {\n if (isFunction(scheduler)) {\n scheduler(this);\n } else {\n this._flushScheduler?.();\n }\n } else if (isBatching()) {\n // When in batch, queue for execution\n queueJob(this.getJob());\n } else {\n // In normal case, execute immediately and synchronously\n this.run();\n }\n }\n\n /**\n * Stop the Effect.\n *\n * After stopping:\n * - No longer responds to dependency changes.\n * - Disconnects all dependency links.\n * - Clears cached job function.\n * - Calls onStop callback.\n * - Verifies complete cleanup in development mode.\n *\n * @returns {void}\n */\n stop(): void {\n if (!this._active) {\n if (__DEV__) {\n warn('[Effect] Attempting to stop an already stopped effect.');\n }\n return;\n }\n\n this._active = false;\n\n // Disconnect all dependency links\n // This removes this effect from all signals/computed it depends on\n let dep = this.depLink;\n while (dep) {\n dep = unlinkReactiveNode(dep, this);\n }\n\n // Disconnect all subscription links\n // This removes any subscribers that depend on this effect (rare but possible)\n let sub = this.subLink;\n while (sub) {\n sub = unlinkReactiveNode(sub);\n }\n\n // Clear cached job function to free memory\n this._job = undefined;\n this._flushScheduler = undefined;\n\n // Clear link tail pointers to ensure no dangling references\n this.depLinkTail = undefined;\n this.subLinkTail = undefined;\n\n // Verify cleanup in development mode\n if (__DEV__) {\n // Verify all links are properly cleared\n if (this.depLink) {\n error(\n '[Effect] Cleanup verification failed: depLink not cleared. ' +\n 'This indicates a memory leak in the dependency tracking system.',\n );\n }\n if (this.subLink) {\n error(\n '[Effect] Cleanup verification failed: subLink not cleared. ' +\n 'This indicates a memory leak in the subscription system.',\n );\n }\n }\n\n // Call stop callback\n if (this.options?.onStop) {\n this.options.onStop();\n }\n }\n}\n\n/**\n * Create and immediately execute an Effect.\n *\n * @param fn - The effect function.\n * @param options - Configuration options.\n * @returns {EffectRunner<T>} Effect runner.\n *\n * @example\n * ```typescript\n * const count = signal(0);\n *\n * // Basic usage\n * const runner = effect(() => {\n * console.log('Count:', count.value);\n * });\n *\n * count.value = 1; // Automatically executes, prints 'Count: 1'\n *\n * // Manual execution\n * runner();\n *\n * // Stop\n * runner.effect.stop();\n *\n * // Custom scheduling\n * effect(() => {\n * console.log(count.value);\n * }, {\n * scheduler: (eff) => {\n * setTimeout(() => eff.run(), 100);\n * }\n * });\n * ```\n */\nexport function effect<T = any>(fn: EffectFunction<T>, options?: EffectOptions): EffectRunner<T> {\n const effectInstance = new EffectImpl(fn, options);\n\n try {\n // Execute immediately once\n effectInstance.run();\n } catch (_error) {\n // First execution failed, stop Effect and rethrow\n effectInstance.stop();\n if (__DEV__) {\n error(\n '[Effect] Effect failed during initial execution and has been stopped. ' +\n 'Fix the error in your effect function.',\n _error,\n );\n }\n throw _error;\n }\n\n /**\n * Runs the wrapped effect.\n */\n const runner: any = () => effectInstance.run();\n runner.effect = effectInstance;\n runner.stop = () => effectInstance.stop();\n\n return runner as EffectRunner<T>;\n}\n\n/**\n * Stop Effect execution.\n *\n * @param runner - The effect runner to stop.\n * @returns {void}\n */\nexport function stop(runner: EffectRunner): void {\n runner.effect.stop();\n}\n\n/**\n * Type guard - Check if value is an Effect instance.\n *\n * @param value - The value to check.\n * @returns {boolean} True if value is an Effect instance.\n */\nexport function isEffect(value: any): value is EffectImpl {\n return !!(value && value[SignalFlags.IS_EFFECT]);\n}\n\n/**\n * Memoized effect function type\n *\n * @template T - State type\n * @param prevState - State from previous execution\n * @returns New state\n */\nexport type MemoEffectFn<T> = (prevState: T) => T;\n\n/**\n * Create a memoized Effect.\n *\n * A memoized effect remembers the return value from the previous execution\n * and passes it as a parameter on the next execution.\n *\n * @param fn - The memoized function.\n * @param initialState - Initial state.\n * @param options - Configuration options.\n * @returns {EffectRunner<void>} Effect runner.\n *\n * @example\n * ```typescript\n * const width = signal(100);\n *\n * // Only update DOM when width changes\n * memoEffect(prev => {\n * const current = width.value;\n *\n * if (current !== prev.width) {\n * element.style.width = `${current}px`;\n * prev.width = current;\n * }\n *\n * return prev;\n * }, { width: 0 });\n * ```\n */\nexport function memoEffect<T>(\n fn: MemoEffectFn<T>,\n initialState: T,\n options?: EffectOptions,\n): EffectRunner<void> {\n let currentState = initialState;\n\n /**\n * Executes the effect callback.\n */\n const effectFn = () => {\n // Pass current state each time\n // fn may modify the passed object, so the return value is the update state\n const result = fn(currentState);\n currentState = result;\n };\n\n return effect(effectFn, options);\n}\n","import { error, hasChanged, isFunction, isPlainObject, warn } from '@estjs/shared';\nimport { ReactiveFlags, SignalFlags } from './constants';\nimport { activeSub, checkDirty, endTracking, linkReactiveNode, startTracking } from './link';\nimport { shallowPropagate } from './propagation';\nimport type { DebuggerEvent, Link, ReactiveNode } from './link';\n\n/**\n * Computed getter function type\n */\nexport type ComputedGetter<T> = () => T;\n\n/**\n * Computed setter function type\n */\nexport type ComputedSetter<T> = (value: T) => void;\n\n/**\n * Computed options configuration\n */\nexport interface ComputedOptions<T> {\n /** Getter function to compute the value */\n get: ComputedGetter<T>;\n\n /** Optional setter function to make the computed writable */\n set?: ComputedSetter<T>;\n\n /**\n * Debug callback invoked when a dependency is tracked\n * Only called in development mode\n *\n * @param event - Information about the tracked dependency\n */\n onTrack?: (event: DebuggerEvent) => void;\n\n /**\n * Debug callback invoked when the computed is triggered by a dependency change\n * Only called in development mode\n *\n * @param event - Information about what triggered the recomputation\n */\n onTrigger?: (event: DebuggerEvent) => void;\n}\n\n/**\n * Computed interface\n */\nexport interface Computed<T> {\n readonly value: T;\n peek(): T;\n}\n/**\n * Extract the value type from a Computed\n *\n * @template T - The Computed type\n *\n * @example\n * ```typescript\n * import { computed, type ComputedType } from '@estjs/signals';\n *\n * const doubled = computed(() => count.value * 2);\n * type DoubledValue = ComputedType<typeof doubled>; // number\n * ```\n */\nexport type ComputedType<T> = T extends Computed<infer V> ? V : never;\n\n/**\n * Sentinel symbol used to represent \"no value\" state in computed\n * Using a Symbol ensures it cannot conflict with any actual computed value\n */\nconst NO_VALUE = Symbol('computed-no-value');\n\n/**\n * Computed implementation class\n *\n * Implements both Computed and ReactiveNode interfaces.\n * Features:\n * - Lazy evaluation: only computes when accessed\n * - Smart caching: returns cached value when dependencies haven't changed\n * - Automatic tracking: automatically tracks dependencies during computation\n *\n * @template T - The type of the computed value\n */\nexport class ComputedImpl<T = any> implements Computed<T>, ReactiveNode {\n // ReactiveNode interface implementation\n depLink?: Link;\n subLink?: Link;\n depLinkTail?: Link;\n subLinkTail?: Link;\n flag: ReactiveFlags = ReactiveFlags.MUTABLE | ReactiveFlags.DIRTY;\n\n //@ts-ignore\n private readonly [SignalFlags.IS_COMPUTED] = true as const;\n\n // Core properties\n readonly getter: ComputedGetter<T>;\n readonly setter?: ComputedSetter<T>;\n\n // Debug hooks\n readonly onTrack?: (event: DebuggerEvent) => void;\n readonly onTrigger?: (event: DebuggerEvent) => void;\n\n // Cache\n // Use symbol sentinel to distinguish \"no value\" from undefined/null values\n private _value: T | typeof NO_VALUE = NO_VALUE;\n\n /**\n * Create a Computed instance.\n *\n * @param getter - The computation function.\n * @param setter - Optional setter function.\n * @param onTrack - Optional debug callback for dependency tracking.\n * @param onTrigger - Optional debug callback for triggers.\n */\n constructor(\n getter: ComputedGetter<T>,\n setter?: ComputedSetter<T>,\n onTrack?: (event: DebuggerEvent) => void,\n onTrigger?: (event: DebuggerEvent) => void,\n ) {\n this.getter = getter;\n this.setter = setter;\n this.onTrack = onTrack;\n this.onTrigger = onTrigger;\n this.flag |= ReactiveFlags.DIRTY;\n }\n\n /**\n * Returns the current value.\n *\n * @returns {T} The current value.\n */\n get value(): T {\n // Track dependencies if accessed within an effect or computed\n if (activeSub) {\n linkReactiveNode(this, activeSub);\n }\n\n // Cache flag and hasValue to reduce property access\n const flags = this.flag;\n const hasValue = this._value !== NO_VALUE;\n\n if (hasValue && !(flags & (ReactiveFlags.DIRTY | ReactiveFlags.PENDING))) {\n return this._value as T;\n }\n\n // Dirty state or no value: must recompute\n if (!hasValue || flags & ReactiveFlags.DIRTY) {\n this.recompute();\n return this._value as T;\n }\n\n // Pending state: check if dependencies actually changed\n if (flags & ReactiveFlags.PENDING) {\n if (this.depLink && checkDirty(this.depLink, this)) {\n // Dependencies changed, recompute\n this.recompute();\n } else {\n // Dependencies unchanged, clear pending flag using cached flags\n this.flag = flags & ~ReactiveFlags.PENDING;\n }\n }\n\n return this._value as T;\n }\n\n /**\n * Set value (only effective when setter is provided).\n *\n * @param newValue - The new value.\n */\n set value(newValue: T) {\n if (this.setter) {\n this.setter(newValue);\n } else if (__DEV__) {\n warn(\n '[Computed] Cannot set readonly computed value. ' +\n 'Provide a setter in the computed options to make it writable.\\n' +\n 'Example: computed({ get: () => value, set: (v) => { ... } })',\n );\n }\n }\n\n /**\n * Read value without tracking dependencies.\n *\n * @returns {T} The current value.\n */\n peek(): T {\n if (this._value === NO_VALUE) {\n this.recompute();\n }\n return this._value as T;\n }\n\n /**\n * Recompute the value\n *\n * computation logic:\n * 1. Start tracking dependencies\n * 2. Execute getter function\n * 3. Check if value changed using optimized comparison\n * 4. If changed, update cache and notify subscribers\n * 5. End tracking, clean up stale dependencies\n * @private\n */\n private recompute(): void {\n // Store old value for change detection\n // Use NO_VALUE sentinel to distinguish initial state from undefined/null values\n const oldValue = this._value;\n const hadValue = oldValue !== NO_VALUE;\n\n // Start tracking dependencies\n const prevSub = startTracking(this);\n\n try {\n // Execute computation\n const newValue = this.getter();\n\n // Cache current flags and subLink for efficient bitwise operations and reduced property access\n const flags = this.flag;\n const subs = this.subLink;\n // Pre-calculate the mask for clearing DIRTY and PENDING flags in single operation\n const clearMask = ~(ReactiveFlags.DIRTY | ReactiveFlags.PENDING);\n\n // - If no previous value, always consider it changed\n // - Otherwise use hasChanged for proper comparison (handles NaN, etc.)\n const valueChanged = !hadValue || hasChanged(oldValue, newValue);\n\n if (valueChanged) {\n // Update cache\n this._value = newValue;\n\n // Clear DIRTY and PENDING flags in single operation using cached flags\n this.flag = flags & clearMask;\n\n // Debug hook: notify about the trigger\n if (__DEV__ && this.onTrigger) {\n this.onTrigger({\n effect: this,\n target: this,\n type: 'set',\n key: 'value',\n newValue,\n });\n }\n\n // Notify subscribers only when value actually changed\n // This prevents unnecessary propagation\n // Use cached subLink to avoid property access\n if (subs) {\n shallowPropagate(subs);\n }\n } else {\n // Value unchanged, only clear flags using cached flags\n // No need to propagate since subscribers already have correct value\n this.flag = flags & clearMask;\n }\n } catch (_error) {\n // On error, ensure DIRTY and PENDING flags are cleared first to prevent stuck state\n const clearMask = ~(ReactiveFlags.DIRTY | ReactiveFlags.PENDING);\n this.flag &= clearMask;\n\n // Force recompute on next access instead of setting DIRTY,\n // preventing \"Clean subscriber with Dirty dependency\" illegal state\n // which would otherwise block propagation.\n this._value = NO_VALUE;\n\n if (__DEV__) {\n error(\n '[Computed] Error occurred while computing value.\\n' +\n 'The computed will retry on next access.\\n' +\n 'Common causes:\\n' +\n ' - Accessing undefined properties\\n' +\n ' - Circular dependencies\\n' +\n ' - Exceptions in getter function\\n' +\n 'Check your getter function for errors.',\n _error,\n );\n }\n\n throw _error;\n } finally {\n // End tracking, clean up stale dependencies\n // This removes links to dependencies that are no longer accessed\n endTracking(this, prevSub);\n }\n }\n\n /**\n * Check if update is needed.\n *\n * Internal use, called by reactive system.\n *\n * @returns {boolean} True if value changed.\n */\n shouldUpdate(): boolean {\n const hadValue = this._value !== NO_VALUE;\n const oldValue = this._value;\n\n this.recompute();\n\n if (!hadValue) {\n return true;\n }\n\n return hasChanged(this._value, oldValue);\n }\n}\n\n/**\n * Create a Computed value.\n *\n * @param getterOrOptions - Computation function or configuration object.\n * @returns {ComputedImpl<T>} Computed instance.\n *\n * @example\n * ```typescript\n * // Read-only computed\n * const count = signal(0);\n * const doubled = computed(() => count.value * 2);\n *\n * console.log(doubled.value); // 0\n * count.value = 5;\n * console.log(doubled.value); // 10\n *\n * // Writable computed\n * const firstName = signal('John');\n * const lastName = signal('Doe');\n *\n * const fullName = computed({\n * get: () => `${firstName.value} ${lastName.value}`,\n * set: (value) => {\n * const [first, last] = value.split(' ');\n * firstName.value = first;\n * lastName.value = last;\n * }\n * });\n *\n * fullName.value = 'Jane Smith';\n * console.log(firstName.value); // 'Jane'\n * ```\n */\nexport function computed<T>(\n getterOrOptions: ComputedGetter<T> | ComputedOptions<T>,\n): ComputedImpl<T> {\n // Guard: Prevent passing computed to computed\n if (isComputed(getterOrOptions)) {\n if (__DEV__) {\n warn(\n '[Computed] Creating a computed from another computed is not recommended. ' +\n 'The existing computed will be returned to avoid unnecessary wrapping.',\n );\n }\n return getterOrOptions as unknown as ComputedImpl<T>;\n }\n\n // Validate input\n if (!getterOrOptions) {\n throw new Error(\n '[Computed] Invalid argument: computed() requires a getter function or options object.',\n );\n }\n\n if (isFunction(getterOrOptions)) {\n return new ComputedImpl(getterOrOptions);\n }\n\n if (isPlainObject(getterOrOptions)) {\n const { get, set, onTrack, onTrigger } = getterOrOptions;\n\n if (!get) {\n throw new Error(\n '[Computed] Invalid options: getter function is required.\\n' +\n 'Usage: computed({ get: () => value, set: (v) => { ... } })',\n );\n }\n\n if (!isFunction(get)) {\n throw new TypeError(\n '[Computed] Invalid options: getter must be a function.\\n' + `Received: ${typeof get}`,\n );\n }\n\n return new ComputedImpl(get, set, onTrack, onTrigger);\n }\n\n throw new Error(\n '[Computed] Invalid argument: expected a function or options object.\\n' +\n `Received: ${typeof getterOrOptions}`,\n );\n}\n\n/**\n * Type guard - Check if value is a Computed instance.\n *\n * @template T - The type of value held by the computed instance.\n * @param value - The value to check.\n * @returns {boolean} True if value is a Computed instance.\n */\nexport function isComputed<T>(value: unknown): value is Computed<T> {\n return !!value && !!value[SignalFlags.IS_COMPUTED];\n}\n","import { isFunction, warn } from '@estjs/shared';\nimport { batch, computed, reactive } from '.';\n\n/**\n * Represents a store's state object.\n * Must be a plain object containing the store's reactive state.\n */\nexport type State = Record<string, any>;\n\n/**\n * Represents a store's getters object.\n * Each getter is a function that receives the state and returns a computed value.\n */\nexport type Getters<S extends State> = Record<string, (state: S) => any>;\n\n/**\n * Represents a store's actions object.\n * Each action is a function that can modify the store's state.\n */\nexport type Actions = Record<string, (...args: any[]) => any>;\n\n/**\n * Configuration options for creating a store.\n *\n * @template S - The type of the store's state\n * @template G - The type of the store's getters\n * @template A - The type of the store's actions\n */\nexport interface StoreOptions<S extends State, G extends Getters<S>, A extends Actions> {\n /** The initial state of the store */\n state: S;\n /** Computed values derived from the state */\n getters?: G;\n /** Methods that can modify the store's state */\n actions?: A;\n}\n\n/**\n * Payload for patching store state.\n * Must be a partial object matching the store's state shape.\n */\nexport type PatchPayload<S> = Partial<S>;\n\n/**\n * Callback function for store subscriptions and action notifications.\n */\nexport type StoreCallback<S> = (state: S) => void;\n\n/**\n * Built-in actions available on all stores.\n *\n * @template S - The type of the store's state\n */\nexport interface StoreActions<S extends State> {\n /**\n * Updates multiple state properties at once.\n * Triggers a single update notification.\n *\n * @param payload - Object containing state updates\n */\n patch$: (payload: PatchPayload<S>) => void;\n\n /**\n * Subscribes to state changes.\n * The callback is called whenever the state changes.\n *\n * @param callback - Function to call on state changes\n */\n subscribe$: (callback: StoreCallback<S>) => void;\n\n /**\n * Unsubscribes from state changes.\n *\n * @param callback - The callback to remove\n */\n unsubscribe$: (callback: StoreCallback<S>) => void;\n\n /**\n * Subscribes to action executions.\n * The callback is called whenever an action is executed.\n *\n * @param callback - Function to call on action execution\n */\n onAction$: (callback: StoreCallback<S>) => void;\n\n /**\n * Removes a previously registered action callback.\n *\n * @param callback - The callback to remove.\n */\n offAction$: (callback: StoreCallback<S>) => void;\n\n /**\n * Resets the store state to its initial values.\n */\n reset$: () => void;\n}\n\n/**\n * Computed values from getters.\n *\n * @template G - The type of the store's getters\n */\ntype GetterValues<G extends Getters<any>> = {\n [K in keyof G]: ReturnType<G[K]>;\n};\n\n/**\n * Creates a store from options (state, getters, and actions).\n *\n * @template S - The type of the store's state.\n * @template G - The type of the store's getters.\n * @template A - The type of the store's actions.\n * @param options - Store configuration options.\n * @returns The store instance.\n */\nfunction createOptionsStore<S extends State, G extends Getters<S>, A extends Actions>(\n options: StoreOptions<S, G, A>,\n) {\n if (__DEV__ && !options.state) {\n warn('Store state is required');\n throw new Error('Store state is required');\n }\n\n const { state, getters, actions } = options;\n const initState = { ...state };\n const reactiveState = reactive(state);\n\n const subscriptions = new Set<StoreCallback<S>>();\n const actionCallbacks = new Set<StoreCallback<S>>();\n\n /**\n * Helper function to notify all subscribers and action callbacks.\n * This reduces code duplication in patch$ and reset$ methods.\n */\n const notifySubscribers = (state: S): void => {\n subscriptions.forEach((callback) => callback(state));\n actionCallbacks.forEach((callback) => callback(state));\n };\n\n const defaultActions: StoreActions<S> = {\n /**\n * Applies a partial patch to the reactive store state.\n */\n patch$(payload: PatchPayload<S>) {\n if (__DEV__ && !payload) {\n warn('Patch payload is required');\n return;\n }\n\n // Use batch for better performance\n batch(() => {\n Object.assign(reactiveState, payload);\n });\n\n // Notify all subscribers\n notifySubscribers(reactiveState);\n },\n\n /**\n * Registers a store subscriber callback.\n */\n subscribe$(callback: StoreCallback<S>) {\n if (__DEV__ && !callback) {\n warn('Subscribe callback is required');\n return;\n }\n subscriptions.add(callback);\n },\n\n /**\n * Removes a previously registered store subscriber.\n */\n unsubscribe$(callback: StoreCallback<S>) {\n subscriptions.delete(callback);\n },\n\n /**\n * Registers a callback for store action notifications.\n */\n onAction$(callback: StoreCallback<S>) {\n if (__DEV__ && !callback) {\n warn('Action callback is required');\n return;\n }\n actionCallbacks.add(callback);\n },\n\n /**\n * Removes a previously registered action callback.\n */\n offAction$(callback: StoreCallback<S>) {\n actionCallbacks.delete(callback);\n },\n\n /**\n * Resets the reactive state back to its initial snapshot.\n */\n reset$() {\n // Use batch for better performance\n batch(() => {\n Object.assign(reactiveState, initState);\n });\n\n // Notify all subscribers\n notifySubscribers(reactiveState);\n },\n };\n\n const store = {} as S & GetterValues<G> & A & StoreActions<S> & { state: S };\n\n for (const key of Object.keys(initState) as Array<keyof S & string>) {\n Object.defineProperty(store, key, {\n get: () => reactiveState[key],\n set: (value) => {\n reactiveState[key] = value;\n },\n enumerable: true,\n configurable: true,\n });\n }\n\n Object.defineProperty(store, 'state', {\n value: reactiveState,\n enumerable: true,\n configurable: true,\n writable: true,\n });\n\n Object.assign(store, defaultActions);\n\n // Add getters as computed properties\n if (getters) {\n for (const key in getters) {\n const getter = getters[key];\n if (!getter) continue;\n const getterValue = computed(() => getter.call(store, reactiveState));\n\n Object.defineProperty(store, key, {\n get: () => getterValue.value,\n enumerable: true,\n configurable: true,\n });\n }\n }\n\n // Add actions with automatic notification\n if (actions) {\n for (const key in actions) {\n const action = actions[key];\n if (action) {\n (store as Record<string, any>)[key] = (...args: any[]) => {\n const result = action.apply(store, args);\n actionCallbacks.forEach((callback) => callback(reactiveState));\n return result;\n };\n }\n }\n }\n\n return store;\n}\n/**\n * Creates store options from a class definition.\n *\n * @template S - The type of the store's state.\n * @param StoreClass - The store class to use.\n * @returns Store options derived from the class.\n */\nfunction createClassStore<S extends State>(\n StoreClass: new () => S,\n): StoreOptions<\n S,\n Record<string, (...args: any[]) => any>,\n Record<string, (...args: any[]) => any>\n> {\n const instance = new StoreClass();\n const state = Object.create(null);\n const getters: Record<string, (...args: any[]) => any> = {};\n const actions: Record<string, (...args: any[]) => any> = {};\n\n // Extract instance properties as state\n Object.getOwnPropertyNames(instance).forEach((key) => {\n state[key] = instance[key];\n });\n\n // Extract prototype methods and getters\n Object.getOwnPropertyNames(StoreClass.prototype).forEach((key) => {\n const descriptor = Object.getOwnPropertyDescriptor(StoreClass.prototype, key);\n if (descriptor) {\n if (isFunction(descriptor.get)) {\n getters[key] = function (this: S) {\n return descriptor.get!.call(this);\n };\n } else if (isFunction(descriptor.value) && key !== 'constructor') {\n actions[key] = function (this: S, ...args: any[]) {\n return descriptor.value.apply(this, args);\n };\n }\n }\n });\n\n return {\n state,\n getters,\n actions,\n };\n}\n\n/**\n * Store definition type that can be either a class or an options object.\n */\ntype StoreDefinition<S extends State, G extends Getters<S>, A extends Actions> =\n | (new () => S)\n | ({\n state: S;\n getters?: G;\n actions?: A;\n } & ThisType<S & GetterValues<G> & A & StoreActions<S>>);\n\n/**\n * Creates a new store with the given definition.\n * The store can be defined either as a class or as an options object.\n *\n * @template S - The type of the store's state.\n * @template G - The type of the store's getters.\n * @template A - The type of the store's actions.\n * @param storeDefinition - The store definition (class or options).\n * @returns A function that creates a new store instance.\n *\n * @example\n * ```ts\n * // Options-based store\n * const useCounter = createStore({\n * state: { count: 0 },\n * getters: {\n * double: state => state.count * 2\n * },\n * actions: {\n * increment() {\n * this.count++;\n * }\n * }\n * });\n *\n * // Class-based store\n * class Counter {\n * count = 0;\n *\n * get double() {\n * return this.count * 2;\n * }\n *\n * increment() {\n * this.count++;\n * }\n * }\n *\n * const useCounter = createStore(Counter);\n * ```\n */\nexport function createStore<S extends State, G extends Getters<S>, A extends Actions>(\n storeDefinition: StoreDefinition<S, G, A>,\n): () => S & GetterValues<G> & A & StoreActions<S> & { state: S } {\n if (__DEV__ && !storeDefinition) {\n warn('Store definition is required');\n throw new Error('Store definition is required');\n }\n\n return () => {\n let options: StoreOptions<S, G, A>;\n\n if (isFunction(storeDefinition)) {\n options = createClassStore(storeDefinition) as StoreOptions<S, G, A>;\n } else {\n options = storeDefinition;\n }\n\n return createOptionsStore(options) as S & GetterValues<G> & A & StoreActions<S> & { state: S };\n };\n}\n","import { hasChanged } from '@estjs/shared';\nimport { ReactiveFlags, SignalFlags } from './constants';\nimport { activeSub, linkReactiveNode } from './link';\nimport { propagate } from './propagation';\nimport { type Signal, SignalImpl, isSignal } from './signal';\n\n/**\n * A Ref is a special type of Signal used primarily for DOM element references.\n * It provides methods to read, write, and observe changes to the value.\n *\n * @template T - The type of value held by the ref\n */\nexport interface Ref<T> extends Signal<T> {\n /**\n * The current value of the ref. Reading this property will track dependencies,\n * and writing to it will notify subscribers of changes.\n */\n value: T;\n}\n\n/**\n * Internal implementation of the Ref interface.\n * This class extends SignalImpl but only overrides the get value() method\n * to provide direct access to the underlying value without reactive wrapping.\n *\n * @template T - The type of value held by the ref\n * @internal\n */\nclass RefImpl<T> extends SignalImpl<T> implements Ref<T> {\n // @ts-ignore\n private readonly [SignalFlags.IS_REF] = true;\n\n /**\n * Creates a new ref with the given initial value.\n *\n * @param value - The initial value\n */\n constructor(value: T) {\n super(value, true);\n }\n\n /**\n * Returns the current value.\n *\n * @returns {T} The current value.\n */\n get value(): T {\n const sub = activeSub;\n if (sub) {\n linkReactiveNode(this, sub);\n }\n // ref just returns the value without reactive wrapping\n return this._value;\n }\n\n /**\n * Updates the current value.\n *\n * @param newValue - The new value.\n */\n set value(newValue: T) {\n // Handle nested signals by unwrapping them\n if (isSignal(newValue)) {\n newValue = newValue.peek() as T;\n }\n if (isRef(newValue)) {\n newValue = newValue.value as T;\n }\n\n // Only trigger updates if the value has actually changed\n if (hasChanged(this._value, newValue)) {\n this._rawValue = newValue;\n this._value = newValue;\n this.flag |= ReactiveFlags.DIRTY;\n\n if (this.subLink) {\n propagate(this.subLink);\n }\n }\n }\n}\n\n/**\n * Creates a new ref with the given initial value.\n * Unlike signals, refs don't create reactive proxies for object values.\n *\n * @template T - The type of value to store in the ref.\n * @param value - The initial value.\n * @returns A new ref instance.\n *\n * @example\n * ```ts\n * const divRef = ref();\n * <div ref={divRef}></div>\n * ```\n */\nexport function ref<T>(value: T = undefined as unknown as T): Ref<T> {\n if (isRef(value)) {\n return value as Ref<T>;\n }\n\n if (isSignal(value)) {\n return new RefImpl(value.peek() as T);\n }\n\n return new RefImpl(value);\n}\n\n/**\n * Type guard to check if a value is a Ref instance.\n *\n * @template T - The type of value held by the ref.\n * @param value - The value to check.\n * @returns True if the value is a Ref instance.\n */\nexport function isRef<T>(value: unknown): value is Ref<T> {\n return !!value && !!value[SignalFlags.IS_REF];\n}\n","import { hasChanged, isFunction, isMap, isObject, isSet } from '@estjs/shared';\nimport { queueJob } from './scheduler';\nimport { isSignal } from './signal';\nimport { isReactive } from './reactive';\nimport { isComputed } from './computed';\nimport { effect } from './effect';\n\n// A unique initial value used to identify if watcher is running for the first time.\nconst INITIAL_WATCHER_VALUE = {};\n\n// Watch function options interface.\ninterface WatchOptions {\n immediate?: boolean; // Whether to execute callback immediately once\n deep?: boolean; // Whether to deeply traverse source to track nested changes\n}\n\n// Watch source type, can be value, ref/signal, getter function or array.\ntype WatchSource<T = any> = T | { value: T } | (() => T);\n// Watch callback function type.\ntype WatchCallback<T = any> = (newValue: T, oldValue: T | undefined) => void;\n\n/**\n * Module-level Set reused across all traverse() calls to avoid per-call allocation.\n * It is cleared at the start of each top-level traverse invocation.\n * NOTE: traverse must never be called recursively from outside; it always resets on entry.\n */\nconst _traverseSeen = new Set<any>();\n\n/**\n * Recursively traverse a value, accessing all its properties to trigger dependency tracking.\n *\n * @param value - The value to traverse.\n * @param seen - Internal cycle-detection set.\n * @returns The original value.\n */\nfunction traverse(value: any, seen?: Set<any>) {\n // Top-level call: reset the shared Set to avoid cross-call contamination.\n if (!seen) {\n _traverseSeen.clear();\n seen = _traverseSeen;\n }\n\n // If not an object or already traversed, stop.\n if (!isObject(value) || seen.has(value)) {\n return value;\n }\n\n seen.add(value);\n // If it's a signal or computed, traverse its .value.\n if (isSignal(value) || isComputed(value)) {\n return traverse(value.value, seen);\n }\n // If it's an array, traverse all its elements.\n if (Array.isArray(value)) {\n for (const element of value) {\n traverse(element, seen);\n }\n // If it's a Map, traverse all its values, and access keys and values to track changes.\n } else if (isMap(value)) {\n value.forEach((v: any) => {\n traverse(v, seen);\n });\n value.keys();\n value.values();\n // If it's a Set, traverse all its values to track changes.\n } else if (isSet(value)) {\n value.forEach((v: any) => {\n traverse(v, seen);\n });\n value.values();\n // If it's a plain object, traverse all its keys.\n } else {\n Object.keys(value).forEach((key) => {\n traverse(value[key], seen);\n });\n }\n\n return value;\n}\n\n/**\n * Create a clone of a value for comparison purposes.\n *\n * @param value - The value to clone.\n * @returns The value itself.\n */\nfunction cloneValue<T>(value: T): T {\n // Avoid deep cloning to fix major performance bottleneck (Issue 8).\n // For primitive values or when returning the same reference, this is sufficient.\n return value;\n}\n\n/**\n * Resolve a single (non-array) watch source into a standard getter function.\n *\n * @param source - The watch source.\n * @returns A getter function.\n */\nfunction resolveSingleSource<T>(source: WatchSource<T>): () => T {\n // Function source: use directly.\n if (isFunction(source)) {\n return source as () => T;\n }\n // Signal or computed: read .value.\n if (isSignal(source) || isComputed(source)) {\n return () => source.value as T;\n }\n // Reactive object: deep traverse.\n if (isReactive(source)) {\n return () => traverse(source) as unknown as T;\n }\n // Plain value: identity getter.\n return () => source as T;\n}\n\n/**\n * Resolve watch sources of various forms into a standard getter function.\n *\n * @param source - The watch source passed by the user.\n * @returns A getter function that returns the current source value.\n */\nfunction resolveSource<T>(source: WatchSource<T>): () => T {\n if (Array.isArray(source)) {\n // Pre-build per-element getters; call sites only allocate the output array.\n const getters = (source as WatchSource[]).map((s) => resolveSingleSource(s));\n return () => getters.map((g) => g()) as unknown as T;\n }\n return resolveSingleSource(source);\n}\n\n/**\n * Watch one or more reactive data sources and execute callback when sources change.\n *\n * @param source - The source(s) to watch.\n * @param callback - The callback function to execute when source changes.\n * @param options - Configuration options like immediate and deep.\n * @returns {Function} A function to stop watching.\n */\nexport function watch<T = any>(\n source: WatchSource<T>,\n callback: WatchCallback<T>,\n options: WatchOptions = {},\n): () => void {\n const { immediate = false, deep = false } = options;\n // Initialize oldValue as a special object to determine if it's the first execution.\n let oldValue: any = INITIAL_WATCHER_VALUE;\n\n // Resolve source to a getter function.\n const getter = resolveSource(source);\n\n /**\n * Runs the scheduled watch job.\n */\n const job = () => {\n const currentEffect = runner.effect;\n if (!currentEffect.run) {\n return;\n }\n\n // Run effect to get new value.\n const newValue = currentEffect.run();\n\n if (deep || isObject(newValue) || hasChanged(newValue, oldValue)) {\n callback(newValue, oldValue === INITIAL_WATCHER_VALUE ? undefined : (oldValue as T));\n // Update oldValue for next comparison (clone to snapshot current state).\n oldValue = cloneValue(newValue);\n }\n };\n\n // Create an effect to track getter dependencies.\n const runner = effect(\n () => {\n const value = getter();\n // If deep watching, recursively traverse value to track all nested properties.\n if (deep) {\n traverse(value);\n }\n return value;\n },\n {\n // Use scheduler to queue job, implementing async and debouncing.\n scheduler: () => queueJob(job),\n },\n );\n\n // If immediate is set, execute job immediately once.\n if (immediate) {\n job();\n } else {\n // Otherwise, run effect once first to collect initial value as oldValue.\n oldValue = cloneValue(runner.effect.run());\n }\n\n // Return a stop function.\n return () => {\n runner.stop();\n };\n}\n"]}