@but212/atom-effect 0.29.0 → 0.30.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/atom-effect.min.js +1 -1
- package/dist/atom-effect.min.js.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +222 -115
- package/dist/index.mjs +732 -738
- package/dist/index.mjs.map +1 -1
- package/package.json +7 -7
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"atom-effect.min.js","names":[],"sources":["../src/constants.ts","../src/errors.ts","../src/utils/debug.ts","../src/core/buffers.ts","../src/core/tracking.ts","../src/core/base.ts","../src/symbols.ts","../src/core/scheduler.ts","../src/core/atom.ts","../src/utils/type-guards.ts","../src/core/computed.ts","../src/core/effect.ts","../src/core/lens.ts"],"sourcesContent":["/**\n * Async operation states.\n */\nexport const AsyncState = {\n IDLE: 'idle',\n PENDING: 'pending',\n RESOLVED: 'resolved',\n REJECTED: 'rejected',\n} as const;\n\n/**\n * Effect flags.\n */\nexport const EFFECT_STATE_FLAGS = {\n DISPOSED: 1 << 0,\n EXECUTING: 1 << 3,\n} as const;\n\n/**\n * Computed flags.\n */\nexport const COMPUTED_STATE_FLAGS = {\n DISPOSED: 1 << 0,\n /** Marker bit: identifies this node as a computed. */\n IS_COMPUTED: 1 << 1,\n DIRTY: 1 << 3,\n IDLE: 1 << 4,\n PENDING: 1 << 5,\n RESOLVED: 1 << 6,\n REJECTED: 1 << 7,\n RECOMPUTING: 1 << 8,\n HAS_ERROR: 1 << 9,\n /** Flagged when explicitly invalidated. Bypasses fast-path dirty checks. */\n FORCE_COMPUTE: 1 << 10,\n} as const;\n\n/**\n * Writable Atom Flags.\n */\nexport const ATOM_STATE_FLAGS = {\n DISPOSED: 1 << 0,\n SYNC: 1 << 3,\n NOTIFICATION_SCHEDULED: 1 << 4,\n} as const;\n\n/**\n * Scheduler configuration.\n */\nexport const SCHEDULER_CONFIG = {\n // Infinite loop protection\n MAX_EXECUTIONS_PER_SECOND: 1000,\n MAX_EXECUTIONS_PER_EFFECT: 100,\n\n // Batch processing limits to prevent blocking the main thread for too long\n MAX_EXECUTIONS_PER_FLUSH: 10000,\n MAX_FLUSH_ITERATIONS: 1000,\n MIN_FLUSH_ITERATIONS: 10,\n\n // Memory management\n BATCH_QUEUE_SHRINK_THRESHOLD: 1000,\n} as const;\n\n/**\n * Debugging thresholds.\n */\nexport const DEBUG_CONFIG = {\n WARN_INFINITE_LOOP: true,\n EFFECT_FREQUENCY_WINDOW: 1000,\n} as const;\n\n/**\n * Computed configuration.\n */\nexport const COMPUTED_CONFIG = {\n MAX_PROMISE_ID: Number.MAX_SAFE_INTEGER - 1,\n} as const;\n\n/**\n * Epoch sentinel values.\n */\nexport const EPOCH_CONSTANTS = {\n /** Uninitialized epoch marker. Used as initial value before any flush has occurred. */\n UNINITIALIZED: -1,\n /** Minimum valid epoch value after a counter reset. */\n MIN: 1,\n} as const;\n\n/**\n * V8 Small Integer (SMI) max value.\n */\nexport const SMI_MAX = 0x3fffffff;\n\n/**\n * Development environment flag.\n */\nexport const IS_DEV =\n (typeof process !== 'undefined' && process.env && process.env.NODE_ENV !== 'production') ||\n (typeof __DEV__ !== 'undefined' && !!__DEV__);\n\n// Fallback declaration for __DEV__ if not present in environment\ndeclare const __DEV__: boolean;\n\nexport const EMPTY_ERROR_ARRAY: readonly Error[] = Object.freeze([]);\n","/**\n * Base error class.\n */\nexport class AtomError extends Error {\n override name = 'AtomError';\n\n constructor(\n message: string,\n public cause: Error | null = null,\n public recoverable = true\n ) {\n super(message);\n }\n}\n\n/** Computed error. */\nexport class ComputedError extends AtomError {\n override name = 'ComputedError';\n\n constructor(message: string, cause: Error | null = null) {\n super(message, cause, true);\n }\n}\n\n/** Effect error. */\nexport class EffectError extends AtomError {\n override name = 'EffectError';\n\n constructor(message: string, cause: Error | null = null) {\n super(message, cause, false);\n }\n}\n\n/** Scheduler error. */\nexport class SchedulerError extends AtomError {\n override name = 'SchedulerError';\n\n constructor(message: string, cause: Error | null = null) {\n super(message, cause, false);\n }\n}\n\n/**\n * Error message registry.\n */\nexport const ERROR_MESSAGES = {\n // Computed Errors\n COMPUTED_MUST_BE_FUNCTION: 'Computed target must be a function',\n COMPUTED_ASYNC_PENDING_NO_DEFAULT: 'Async computation pending with no default value',\n COMPUTED_COMPUTATION_FAILED: 'Computation execution failed',\n COMPUTED_ASYNC_COMPUTATION_FAILED: 'Async computation execution failed',\n COMPUTED_CIRCULAR_DEPENDENCY: 'Circular dependency detected',\n COMPUTED_DISPOSED: 'Attempted to access disposed computed',\n\n // Atom Errors\n ATOM_SUBSCRIBER_MUST_BE_FUNCTION: 'Subscriber must be a function or Subscriber object',\n ATOM_INDIVIDUAL_SUBSCRIBER_FAILED: 'Subscriber execution failed',\n\n // Effect Errors\n EFFECT_MUST_BE_FUNCTION: 'Effect target must be a function',\n EFFECT_EXECUTION_FAILED: 'Effect execution failed',\n EFFECT_CLEANUP_FAILED: 'Effect cleanup failed',\n EFFECT_DISPOSED: 'Attempted to run disposed effect',\n\n // Scheduler Errors\n SCHEDULER_FLUSH_OVERFLOW: (max: number, dropped: number): string =>\n `Maximum flush iterations (${max}) exceeded. ${dropped} jobs dropped. Possible infinite loop.`,\n\n // System / Debug\n CALLBACK_ERROR_IN_ERROR_HANDLER: 'Exception encountered in onError handler',\n\n // Effect frequency\n EFFECT_FREQUENCY_LIMIT_EXCEEDED:\n 'Effect executed too frequently within 1 second. Suspected infinite loop.',\n\n SCHEDULER_CALLBACK_MUST_BE_FUNCTION: 'Scheduler callback must be a function',\n SCHEDULER_END_BATCH_WITHOUT_START: 'endBatch() called without matching startBatch(). Ignoring.',\n BATCH_CALLBACK_MUST_BE_FUNCTION: 'Batch callback must be a function',\n} as const;\n\n/**\n * Wraps error.\n *\n * @param error - Raw error.\n * @param ErrorClass - Error class.\n * @param context - Error context.\n */\nexport function wrapError(\n error: unknown,\n ErrorClass: typeof AtomError,\n context: string\n): AtomError {\n // 1. Skip if already wrapped\n if (error instanceof AtomError) {\n return error;\n }\n\n // 2. Handle native Error instances\n if (error instanceof Error) {\n const type = error.name || error.constructor.name || 'Error';\n return new ErrorClass(`${type} (${context}): ${error.message}`, error);\n }\n\n // 3. Handle unexpected types (string, number, etc.)\n return new ErrorClass(`Unexpected error (${context}): ${String(error)}`);\n}\n","import { DEBUG_CONFIG, IS_DEV } from '@/constants';\nimport type { DebugConfig, DependencyId } from '@/types';\n\n// Debug symbols\nexport const DEBUG_NAME = Symbol('AtomEffect.DebugName');\nexport const DEBUG_ID = Symbol('AtomEffect.Id');\nexport const DEBUG_TYPE = Symbol('AtomEffect.Type');\nexport const NO_DEFAULT_VALUE = Symbol('AtomEffect.NoDefaultValue');\n\n/**\n * Debug controller implementation.\n */\nclass DebugController implements DebugConfig {\n public enabled = IS_DEV;\n public warnInfiniteLoop = DEBUG_CONFIG.WARN_INFINITE_LOOP;\n\n public warn(cond: boolean, msg: string): void {\n if (!IS_DEV || !this.enabled || !cond) return;\n console.warn(`[Atom Effect] ${msg}`);\n }\n\n public attachDebugInfo(obj: object, type: string, id: DependencyId): void {\n if (!IS_DEV || !this.enabled) return;\n\n const t = obj as Record<symbol, unknown>;\n t[DEBUG_NAME] = `${type}_${id}`;\n t[DEBUG_ID] = id;\n t[DEBUG_TYPE] = type;\n }\n\n public getDebugName(obj: object | null): string | undefined {\n if (obj == null) return undefined;\n return (obj as Record<symbol, unknown>)[DEBUG_NAME] as string | undefined;\n }\n\n public getDebugType(obj: object | null): string | undefined {\n if (obj == null) return undefined;\n return (obj as Record<symbol, unknown>)[DEBUG_TYPE] as string | undefined;\n }\n}\n\n/**\n * Global debug controller singleton.\n */\nexport const debug: DebugConfig = new DebugController();\n\n/**\n * ID counter.\n */\nlet nextId = 1;\n\n/**\n * Generates ID.\n */\nexport const generateId = (): DependencyId => nextId++ | 0;\n","// ── SlotBuffer ──────────────────────────────────────────────────────────\n\n/**\n * Inline-slot subscriber container.\n *\n * Stores up to 4 items directly as object properties\n * (zero array allocation). Spills to an overflow array only when the\n * inline slots are exhausted.\n *\n * Design goals:\n * - **Cache locality**: hot-path data lives on the same V8 object.\n * - **Logical deletion**: `remove()` nulls a slot and decrements `_count`.\n * Physical compaction is deferred to `compact()`.\n * - **O(1) overflow reuse**: free-index stack avoids linear gap scan.\n *\n * @template T - Slot element type (e.g. `Subscription<V>`).\n */\nexport class SlotBuffer<T> {\n // ── Inline slots ──────────────────────────────────────────────────────\n // Always declared to lock V8 hidden class shape.\n _s0: T | null = null;\n _s1: T | null = null;\n _s2: T | null = null;\n _s3: T | null = null;\n\n // ── Bookkeeping ───────────────────────────────────────────────────────\n /** Active (non-null) element count across slots + overflow. */\n _count = 0;\n\n /** Lazy-allocated overflow array for subscribers beyond inline capacity. */\n _overflow: (T | null)[] | null = null;\n\n /** Free overflow indices for O(1) gap reuse (lazy-allocated). */\n _freeIndices: number[] | null = null;\n\n // ── Public API ────────────────────────────────────────────────────────\n\n /** Number of active (non-null) elements. */\n get size(): number {\n return this._count;\n }\n\n getAt(index: number): T | null {\n if (index < 4) {\n switch (index) {\n case 0:\n return this._s0;\n case 1:\n return this._s1;\n case 2:\n return this._s2;\n case 3:\n return this._s3;\n }\n }\n const ov = this._overflow;\n if (ov !== null) {\n const el = ov[index - 4];\n return el === undefined ? null : el;\n }\n return null;\n }\n\n /** Overwrites an item at a specific index. */\n setAt(index: number, item: T | null): void {\n switch (index) {\n case 0:\n this._s0 = item;\n break;\n case 1:\n this._s1 = item;\n break;\n case 2:\n this._s2 = item;\n break;\n case 3:\n this._s3 = item;\n break;\n default: {\n this._overflow ??= [];\n this._overflow[index - 4] = item;\n }\n }\n\n if (index >= this._count) {\n this._count = index + 1;\n }\n }\n\n truncateFrom(index: number): void {\n const count = this._count;\n if (index >= count) return;\n\n // 1. Unroll Inline Slots Cleanup: Simplified sequential check\n if (index <= 3) {\n if (index <= 0) {\n const s = this._s0;\n if (s != null) {\n this._onItemRemoved(s);\n this._s0 = null;\n }\n }\n if (index <= 1) {\n const s = this._s1;\n if (s != null) {\n this._onItemRemoved(s);\n this._s1 = null;\n }\n }\n if (index <= 2) {\n const s = this._s2;\n if (s != null) {\n this._onItemRemoved(s);\n this._s2 = null;\n }\n }\n if (index <= 3) {\n const s = this._s3;\n if (s != null) {\n this._onItemRemoved(s);\n this._s3 = null;\n }\n }\n }\n\n // 2. Overflow Cleanup\n const ov = this._overflow;\n if (ov !== null && count > 4) {\n const offsetIdx = index > 4 ? index - 4 : 0;\n const len = ov.length;\n for (let i = offsetIdx; i < len; i++) {\n const item = ov[i];\n if (item != null) {\n this._onItemRemoved(item);\n ov[i] = null;\n }\n }\n\n if (index <= 4) {\n ov.length = 0;\n this._overflow = null;\n } else {\n ov.length = index - 4;\n }\n }\n\n // 3. Invalidate free indices (they may point to truncated positions)\n if (this._freeIndices !== null) {\n this._freeIndices = null;\n }\n\n this._count = index;\n }\n\n /**\n * Protected hook called whenever an item is logically removed from the buffer.\n * Allows subclasses (like DepSlotBuffer) to perform cleanup (unsubscribing)\n * without allocating temporary closures in hot paths.\n */\n protected _onItemRemoved(_item: T): void {\n // Base implementation does nothing\n }\n\n /**\n * Adds an item.\n *\n * Prefers filling a null inline slot (including previously-cleared ones)\n * before spilling to the overflow array. Uses O(1) free-index stack\n * for overflow gap reuse.\n */\n add(item: T): void {\n // Fast path: fill inline slots first\n if (this._s0 === null) {\n this._s0 = item;\n this._count++;\n return;\n }\n if (this._s1 === null) {\n this._s1 = item;\n this._count++;\n return;\n }\n if (this._s2 === null) {\n this._s2 = item;\n this._count++;\n return;\n }\n if (this._s3 === null) {\n this._s3 = item;\n this._count++;\n return;\n }\n\n // Overflow path with O(1) free-index reuse\n this._addToOverflow(item);\n }\n\n /**\n * Internal helper to add an item directly to the overflow array,\n * bypassing inline slot checks. Used by DepSlotBuffer for relocation.\n *\n * @internal\n */\n protected _addToOverflow(item: T): void {\n const ov = this._overflow;\n if (ov === null) {\n this._overflow = [item];\n } else {\n const free = this._freeIndices;\n if (free !== null && free.length > 0) {\n ov[free.pop()!] = item;\n } else {\n ov.push(item);\n }\n }\n this._count++;\n }\n\n /**\n * Removes the first occurrence of {@link item} via identity comparison.\n *\n * The slot is nulled out (logical deletion). Call {@link compact}\n * after notification traversal to reclaim the gaps.\n *\n * @returns `true` if the item was found and removed.\n */\n remove(item: T): boolean {\n if (this._s0 === item) {\n this._s0 = null;\n this._count--;\n return true;\n }\n if (this._s1 === item) {\n this._s1 = null;\n this._count--;\n return true;\n }\n if (this._s2 === item) {\n this._s2 = null;\n this._count--;\n return true;\n }\n if (this._s3 === item) {\n this._s3 = null;\n this._count--;\n return true;\n }\n\n const ov = this._overflow;\n if (ov == null) return false;\n\n for (let i = 0, len = ov.length; i < len; i++) {\n if (ov[i] === item) {\n ov[i] = null;\n this._count--;\n // Track freed index for O(1) reuse\n let free = this._freeIndices;\n if (free === null) {\n free = this._freeIndices = [];\n }\n free.push(i);\n return true;\n }\n }\n return false;\n }\n\n has(item: T): boolean {\n const count = this._count;\n if (count === 0) return false;\n\n // 1. Inline Slots\n if (this._s0 === item || this._s1 === item || this._s2 === item || this._s3 === item) {\n return true;\n }\n\n // 2. Overflow Scan\n const ov = this._overflow;\n if (ov != null) {\n for (let i = 0, len = ov.length; i < len; i++) {\n if (ov[i] === item) return true;\n }\n }\n return false;\n }\n\n /**\n * Iterates over all non-null elements.\n *\n * Safe to call during notification — newly-added or removed items\n * during iteration follow the same snapshot semantics as the old\n * array-based approach (length captured upfront for overflow).\n */\n forEach(fn: (item: T) => void): void {\n const count = this._count;\n if (count === 0) return;\n\n let executed = 0;\n // 1. Inline slots\n const s0 = this._s0;\n if (s0 != null) {\n fn(s0);\n if (++executed === count) return;\n }\n const s1 = this._s1;\n if (s1 != null) {\n fn(s1);\n if (++executed === count) return;\n }\n const s2 = this._s2;\n if (s2 != null) {\n fn(s2);\n if (++executed === count) return;\n }\n const s3 = this._s3;\n if (s3 != null) {\n fn(s3);\n if (++executed === count) return;\n }\n\n // 2. Overflow\n const ov = this._overflow;\n if (ov != null) {\n for (let i = 0, len = ov.length; i < len; i++) {\n const el = ov[i];\n if (el != null) {\n fn(el);\n if (++executed === count) return;\n }\n }\n }\n }\n\n /**\n * Iterates with index-based access for length-captured traversal.\n *\n * Returns the total number of slots to iterate (inline + overflow).\n * Used by `_notifySubscribers` for length-captured iteration.\n */\n forEachIndexed(fn: (item: T) => void): number {\n const count = this._count;\n if (count === 0) return 0;\n\n // 1. Inline slots\n let executed = 0;\n const s0 = this._s0;\n if (s0 != null) {\n fn(s0);\n if (++executed === count) return executed;\n }\n const s1 = this._s1;\n if (s1 != null) {\n fn(s1);\n if (++executed === count) return executed;\n }\n const s2 = this._s2;\n if (s2 != null) {\n fn(s2);\n if (++executed === count) return executed;\n }\n const s3 = this._s3;\n if (s3 != null) {\n fn(s3);\n if (++executed === count) return executed;\n }\n\n // 2. Overflow\n const ov = this._overflow;\n if (ov != null) {\n for (let i = 0, len = ov.length; i < len; i++) {\n const el = ov[i];\n if (el != null) {\n fn(el);\n if (++executed === count) return executed;\n }\n }\n }\n return executed;\n }\n\n /**\n * Compacts the overflow array by removing null gaps.\n *\n * Inline slots are not compacted — they stay null until reused by\n * `add()`. This keeps the V8 hidden class stable.\n */\n compact(): void {\n const ov = this._overflow;\n if (ov === null) return;\n\n let len = ov.length;\n if (len === 0) return;\n\n // Pop-and-swap compaction with proper null handling\n let i = 0;\n while (i < len) {\n if (ov[i] === null) {\n // Pop trailing nulls first to find a valid swap candidate\n while (len > i && ov[len - 1] === null) {\n ov.pop();\n len--;\n }\n // If there's still a valid element beyond i, swap it in\n if (len > i) {\n ov[i] = ov.pop()!;\n len--;\n i++;\n }\n } else {\n i++;\n }\n }\n\n // Invalidate free indices after compaction (positions have shifted)\n this._freeIndices = null;\n\n // Release overflow array when empty\n if (len === 0) {\n this._overflow = null;\n }\n }\n\n /**\n * Clears the buffer and releases all item references for GC.\n */\n clear(): void {\n this._s0 = null;\n this._s1 = null;\n this._s2 = null;\n this._s3 = null;\n this._count = 0;\n\n if (this._overflow !== null) {\n this._overflow.length = 0;\n this._overflow = null;\n }\n this._freeIndices = null;\n }\n\n /**\n * Hard dispose — releases all references for GC.\n */\n dispose(): void {\n this.clear();\n }\n}\n\n// ── DepSlotBuffer ───────────────────────────────────────────────────────\n\nimport type { Dependency } from '@/types';\nimport type { DependencyLink } from './tracking';\n\n/**\n * Specialized inline-slot container for dependency tracking.\n *\n * Inherits from `SlotBuffer` to share the same zero-allocation inline\n * properties (`_s0`...`_s3`). Adds dependency-specific in-place updates,\n * truncation, and a hybrid O(1) Map fallback for mega-node performance.\n */\nexport class DepSlotBuffer extends SlotBuffer<DependencyLink> {\n private _map: Map<Dependency, number> | null = null;\n private readonly _SCAN_THRESHOLD = 32;\n\n /**\n * Indicates if the buffer contains at least one computed dependency.\n */\n hasComputeds = false;\n\n /**\n * Resets tracking metadata for a new evaluation pass.\n * Ensures 'hasComputeds' is clean.\n */\n prepareTracking(): void {\n this.hasComputeds = false;\n }\n\n /**\n * Protected hook called whenever a link is extracted from the buffer.\n * Handles automatic unsubscription without closure allocation.\n */\n protected override _onItemRemoved(link: DependencyLink): void {\n const unsub = link.unsub;\n if (unsub) unsub();\n }\n\n /**\n * Looks for an existing subscription to the given node starting from `trackIndex`.\n * If found, swaps it to `trackIndex`, updates version, and returns true.\n */\n claimExisting(dep: Dependency, trackIndex: number): boolean {\n const count = this._count;\n if (trackIndex >= count) return false;\n\n // 1. Hybrid O(1) Map Fallback for Mega-Nodes\n const remaining = count - trackIndex;\n if (this._map !== null || remaining > this._SCAN_THRESHOLD) {\n return this._claimViaMap(dep, trackIndex);\n }\n\n // 2. Unrolled Fast Path for Inline Slots (0..3)\n // Avoids overhead of getAt/setAt by using switch-fallthrough and direct access.\n if (trackIndex < 4) {\n switch (trackIndex) {\n // biome-ignore lint/suspicious/noFallthroughSwitchClause: intentional fallthrough for sequential search\n case 0: {\n const l = this._s0;\n if (l && l.node === dep && l.unsub) {\n l.version = dep.version;\n return true;\n }\n }\n // biome-ignore lint/suspicious/noFallthroughSwitchClause: intentional fallthrough for sequential search\n case 1: {\n if (count > 1) {\n const l = this._s1;\n if (l && l.node === dep && l.unsub) {\n l.version = dep.version;\n if (trackIndex !== 1) {\n // we know trackIndex is 0 here\n this._s1 = this._s0;\n this._s0 = l;\n }\n return true;\n }\n }\n }\n // biome-ignore lint/suspicious/noFallthroughSwitchClause: intentional fallthrough for sequential search\n case 2: {\n if (count > 2) {\n const l = this._s2;\n if (l && l.node === dep && l.unsub) {\n l.version = dep.version;\n if (trackIndex !== 2) {\n // swap with trackIndex (0 or 1)\n const occ = trackIndex === 0 ? this._s0 : this._s1;\n if (trackIndex === 0) this._s0 = l;\n else this._s1 = l;\n this._s2 = occ;\n }\n return true;\n }\n }\n }\n case 3: {\n if (count > 3) {\n const l = this._s3;\n if (l && l.node === dep && l.unsub) {\n l.version = dep.version;\n if (trackIndex !== 3) {\n // swap with trackIndex (0, 1, or 2)\n let occ: DependencyLink | null;\n if (trackIndex === 0) {\n occ = this._s0;\n this._s0 = l;\n } else if (trackIndex === 1) {\n occ = this._s1;\n this._s1 = l;\n } else {\n occ = this._s2;\n this._s2 = l;\n }\n this._s3 = occ;\n }\n return true;\n }\n }\n }\n }\n }\n\n // 3. Sequential Scan for Overflow\n const ov = this._overflow;\n if (ov) {\n const dv = dep.version;\n const start = trackIndex > 4 ? trackIndex : 4;\n const len = ov.length;\n for (let i = start - 4; i < len; i++) {\n const link = ov[i];\n if (link && link.node === dep && link.unsub) {\n link.version = dv;\n this._swapGeneral(i + 4, trackIndex, link);\n return true;\n }\n }\n }\n\n return false;\n }\n\n private _claimViaMap(dep: Dependency, trackIndex: number): boolean {\n let map = this._map;\n if (map === null) {\n map = this._map = new Map();\n const count = this._count;\n // Partitioned scan to avoid getAt() dispatch in loop\n if (trackIndex < 4) {\n const s0 = this._s0;\n if (trackIndex <= 0 && s0?.unsub) map.set(s0.node, 0);\n const s1 = this._s1;\n if (trackIndex <= 1 && s1?.unsub) map.set(s1.node, 1);\n const s2 = this._s2;\n if (trackIndex <= 2 && s2?.unsub) map.set(s2.node, 2);\n const s3 = this._s3;\n if (trackIndex <= 3 && s3?.unsub) map.set(s3.node, 3);\n }\n const ov = this._overflow;\n if (ov && count > 4) {\n const start = trackIndex > 4 ? trackIndex : 4;\n const len = ov.length;\n for (let i = start - 4; i < len; i++) {\n const link = ov[i];\n if (link?.unsub) map.set(link.node, i + 4);\n }\n }\n }\n\n const existingIndex = map.get(dep);\n if (existingIndex === undefined || existingIndex < trackIndex) return false;\n\n const link = this.getAt(existingIndex);\n if (link == null || !link.unsub) return false;\n\n link.version = dep.version;\n if (existingIndex !== trackIndex) {\n // Inlined swap to avoid dispatch overhead\n let occupant: DependencyLink | null;\n if (trackIndex === 0) occupant = this._s0;\n else if (trackIndex === 1) occupant = this._s1;\n else if (trackIndex === 2) occupant = this._s2;\n else if (trackIndex === 3) occupant = this._s3;\n else occupant = this._overflow![trackIndex - 4] ?? null;\n\n this.setAt(trackIndex, link);\n this.setAt(existingIndex, occupant);\n\n if (occupant?.unsub) map.set(occupant.node, existingIndex);\n map.set(dep, trackIndex);\n }\n return true;\n }\n\n private _swapGeneral(idx: number, trackIndex: number, link: DependencyLink): void {\n if (idx === trackIndex) return;\n\n // Use direct access for the likely case where idx is in overflow\n let occupant: DependencyLink | null;\n if (trackIndex === 0) occupant = this._s0;\n else if (trackIndex === 1) occupant = this._s1;\n else if (trackIndex === 2) occupant = this._s2;\n else if (trackIndex === 3) occupant = this._s3;\n else occupant = this._overflow![trackIndex - 4] ?? null;\n\n this.setAt(trackIndex, link);\n\n if (idx === 0) this._s0 = occupant;\n else if (idx === 1) this._s1 = occupant;\n else if (idx === 2) this._s2 = occupant;\n else if (idx === 3) this._s3 = occupant;\n else {\n const ov = this._overflow!;\n ov[idx - 4] = occupant;\n }\n }\n\n insertNew(trackIndex: number, link: DependencyLink): void {\n const count = this._count;\n if (trackIndex < count) {\n let occupant: DependencyLink | null;\n if (trackIndex === 0) occupant = this._s0;\n else if (trackIndex === 1) occupant = this._s1;\n else if (trackIndex === 2) occupant = this._s2;\n else if (trackIndex === 3) occupant = this._s3;\n else occupant = this._overflow![trackIndex - 4] ?? null;\n\n if (occupant != null) {\n // Direct overflow append avoids inline gap-scan overhead in add()\n // since we know all inline slots are occupied when trackIndex < count.\n this._addToOverflow(occupant);\n if (this._map !== null && occupant.unsub) {\n this._map.set(occupant.node, this._count - 1);\n }\n }\n }\n\n if (trackIndex === 0) this._s0 = link;\n else if (trackIndex === 1) this._s1 = link;\n else if (trackIndex === 2) this._s2 = link;\n else if (trackIndex === 3) this._s3 = link;\n else {\n let ov = this._overflow;\n if (!ov) {\n ov = [];\n this._overflow = ov;\n }\n ov[trackIndex - 4] = link;\n }\n\n if (trackIndex >= count) {\n this._count = trackIndex + 1;\n }\n }\n\n /**\n * Discards all links from the given index onwards.\n * Unsubscribes each link before removing it.\n */\n truncateFrom(index: number): void {\n if (index >= this._count) return;\n\n super.truncateFrom(index);\n\n if (this._map !== null) {\n this._map.clear();\n this._map = null;\n }\n }\n\n /** Unsubscribes from all links and resets the buffer. */\n disposeAll(): void {\n if (this._count > 0) {\n this.truncateFrom(0);\n }\n this.hasComputeds = false;\n }\n\n /**\n * [Safety Guard]\n * remove() is strictly prohibited in DepSlotBuffer to preserve sequential cache paths.\n */\n override remove(_item: DependencyLink): boolean {\n throw new Error(\n 'remove() is strictly prohibited in DepSlotBuffer to preserve sequential cache paths.'\n );\n }\n\n /**\n * [Safety Guard]\n * Compaction is unnecessary since remove() is prohibited.\n */\n override compact(): void {\n // No-op for DepSlotBuffer\n }\n}\n","import type { Dependency, Subscriber } from '@/types';\n\n// ── Tracking Types ──────────────────────────────────────────────────────\n\n/**\n * Dependency consumer.\n */\nexport interface DependencySubscriber {\n /**\n * Registers dependency.\n */\n addDependency(dep: Dependency): void;\n}\n\n/**\n * Executable unit.\n */\nexport interface ExecutableSubscriber {\n execute(): void;\n}\n\n/**\n * Dependency tracker.\n */\nexport interface DependencyTracker extends DependencySubscriber, ExecutableSubscriber {}\n\n/**\n * Trackable function.\n */\nexport type TrackableFunction = (() => void) & DependencySubscriber;\n\n// ── Dependency Link & Subscription ───────────────────────────────────────\n\n/**\n * Dependency graph edge.\n */\nexport class DependencyLink {\n constructor(\n public node: Dependency,\n public version: number,\n // Always initialize to maintain consistent V8 hidden class\n public unsub: (() => void) | undefined = undefined\n ) {}\n}\n\n/**\n * Subscription entry.\n */\nexport class Subscription<T> {\n constructor(\n // Always initialize both properties to maintain consistent V8 hidden class\n public fn: ((newValue?: T, oldValue?: T) => void) | undefined,\n public sub: Subscriber | undefined\n ) {}\n\n notify(newValue?: T, oldValue?: T): void {\n const fn = this.fn;\n if (fn !== undefined) {\n fn(newValue, oldValue);\n return;\n }\n\n const sub = this.sub;\n if (sub !== undefined) {\n sub.execute();\n }\n }\n}\n\n// ── Tracking Context ────────────────────────────────────────────────────\n\n/**\n * Tracking context implementation.\n */\nclass TrackingContext {\n /** Active subscriber. */\n public current: DependencySubscriber | null = null;\n\n /**\n * Executes in context.\n *\n * @param subscriber - The subscriber.\n * @param fn - The logic to execute.\n * @returns The result of `fn`.\n */\n public run<T>(subscriber: DependencySubscriber, fn: () => T): T {\n if (this.current === subscriber) {\n return fn();\n }\n const prev = this.current;\n this.current = subscriber;\n try {\n return fn();\n } finally {\n this.current = prev;\n }\n }\n}\n\n/**\n * Global tracking context singleton.\n */\nexport const trackingContext = new TrackingContext();\n\n/**\n * Tracking context type.\n */\nexport type { TrackingContext };\n\n// ── Untracked ───────────────────────────────────────────────────────────\n\n/**\n * Untracked execution.\n *\n * @param fn - Function to execute.\n * @returns Result of `fn`.\n */\nexport function untracked<T>(fn: () => T): T {\n const ctx = trackingContext;\n const prev = ctx.current;\n\n // Optimized: Fast-path when already untracked\n if (prev === null) {\n return fn();\n }\n\n ctx.current = null;\n try {\n return fn();\n } finally {\n ctx.current = prev;\n }\n}\n","import { COMPUTED_STATE_FLAGS, EPOCH_CONSTANTS, IS_DEV, SMI_MAX } from '@/constants';\nimport { AtomError, ERROR_MESSAGES, wrapError } from '@/errors';\nimport type { DependencyId, Subscriber } from '@/types';\nimport { generateId } from '@/utils/debug';\nimport { type DepSlotBuffer, SlotBuffer } from './buffers';\nimport { Subscription } from './tracking';\n\n/**\n * Unified base class for all reactive nodes (Atoms, Computeds, Effects).\n *\n * Optimized for V8 Hidden Class Monomorphism by having a single, consistent\n * object shape for all reactive logic.\n *\n * @template T - The type of value produced by this node (used for subscriptions).\n */\nexport abstract class ReactiveNode<T> {\n /** [Producer/Consumer] State flags */\n flags: number;\n /** [Producer/Consumer] Version counter */\n version: number;\n /** [Producer/Consumer] Last access epoch */\n _lastSeenEpoch: number;\n /** [Context] Scheduler epoch tag */\n _nextEpoch?: number;\n /** [Debug] Unique ID for identify node in tracking maps */\n readonly id: DependencyId;\n\n /**\n * [Producer] Managed subscribers.\n */\n _slots: SlotBuffer<Subscription<T>> | null;\n\n /** [Producer] Re-entry guard for notification loop. */\n _notifying: number;\n\n /**\n * [Consumer] Managed dependencies.\n */\n _deps: DepSlotBuffer | null;\n /** [Consumer] O(1) Hot-path dependency index for rapid dirty checks. */\n _hotIndex: number;\n\n constructor() {\n this.flags = 0;\n this.version = 0;\n this._lastSeenEpoch = EPOCH_CONSTANTS.UNINITIALIZED;\n this._notifying = 0;\n this._hotIndex = -1;\n this._slots = null;\n this._deps = null;\n this.id = generateId() & SMI_MAX;\n }\n\n /**\n * Whether the node has been disposed.\n * @internal\n */\n get isDisposed(): boolean {\n return (this.flags & COMPUTED_STATE_FLAGS.DISPOSED) !== 0; // Bit 0: DISPOSED\n }\n\n /**\n * Whether the node is a computed atom.\n * @internal\n */\n get isComputed(): boolean {\n return (this.flags & COMPUTED_STATE_FLAGS.IS_COMPUTED) !== 0; // Bit 1: IS_COMPUTED\n }\n\n /**\n * Whether the node currently has an error.\n * @internal\n */\n get hasError(): boolean {\n return false;\n }\n\n // ============================================================================\n // Producer Logic (Subscriber Management)\n // ============================================================================\n\n /**\n * Adds subscriber for notifications.\n */\n subscribe(listener: ((newValue?: T, oldValue?: T) => void) | Subscriber): () => void {\n const isFn = typeof listener === 'function';\n if (!isFn && (!listener || typeof (listener as Subscriber).execute !== 'function')) {\n throw wrapError(\n new TypeError('Invalid subscriber'),\n AtomError,\n ERROR_MESSAGES.ATOM_SUBSCRIBER_MUST_BE_FUNCTION\n );\n }\n\n let slots = this._slots;\n if (!slots) {\n slots = new SlotBuffer<Subscription<T>>();\n this._slots = slots;\n }\n\n // Duplicate check: Unrolled for performance + early exit\n let duplicate = false;\n if (slots._s0 != null && (isFn ? slots._s0.fn === listener : slots._s0.sub === listener)) {\n duplicate = true;\n } else if (\n slots._s1 != null &&\n (isFn ? slots._s1.fn === listener : slots._s1.sub === listener)\n ) {\n duplicate = true;\n } else if (\n slots._s2 != null &&\n (isFn ? slots._s2.fn === listener : slots._s2.sub === listener)\n ) {\n duplicate = true;\n } else if (\n slots._s3 != null &&\n (isFn ? slots._s3.fn === listener : slots._s3.sub === listener)\n ) {\n duplicate = true;\n } else {\n const ov = slots._overflow;\n if (ov != null) {\n for (let i = 0, len = ov.length; i < len; i++) {\n const s = ov[i];\n if (s != null && (isFn ? s.fn === listener : s.sub === listener)) {\n duplicate = true;\n break;\n }\n }\n }\n }\n\n if (duplicate) {\n if (IS_DEV) console.warn(`[atom-effect] Duplicate subscription ignored on node ${this.id}`);\n return () => {};\n }\n\n const link = new Subscription<T>(\n isFn ? (listener as (newValue?: T, oldValue?: T) => void) : undefined,\n !isFn ? (listener as Subscriber) : undefined\n );\n\n slots.add(link);\n return () => this._unsubscribe(link);\n }\n\n protected _unsubscribe(link: Subscription<T>): void {\n const slots = this._slots;\n if (!slots) return;\n\n slots.remove(link);\n if (this._notifying === 0) {\n slots.compact();\n }\n }\n\n /**\n * Returns current subscriber count.\n */\n subscriberCount(): number {\n const slots = this._slots;\n return slots === null ? 0 : slots.size;\n }\n\n /**\n * Notifies all subscribers about a value update.\n */\n protected _notifySubscribers(newValue: T | undefined, oldValue: T | undefined): void {\n const slots = this._slots;\n if (slots === null || slots.size === 0) return;\n\n this._notifying++;\n try {\n // 1. Inline slots: Manual unroll to avoid closure allocation\n let s = slots._s0;\n if (s != null) {\n try {\n s.notify(newValue, oldValue);\n } catch (e) {\n this._logNotifyError(e);\n }\n }\n s = slots._s1;\n if (s != null) {\n try {\n s.notify(newValue, oldValue);\n } catch (e) {\n this._logNotifyError(e);\n }\n }\n s = slots._s2;\n if (s != null) {\n try {\n s.notify(newValue, oldValue);\n } catch (e) {\n this._logNotifyError(e);\n }\n }\n s = slots._s3;\n if (s != null) {\n try {\n s.notify(newValue, oldValue);\n } catch (e) {\n this._logNotifyError(e);\n }\n }\n\n // 2. Overflow scan: Standard loop for performance\n const ov = slots._overflow;\n if (ov != null) {\n for (let i = 0, len = ov.length; i < len; i++) {\n const sub = ov[i];\n if (sub != null) {\n try {\n sub.notify(newValue, oldValue);\n } catch (e) {\n this._logNotifyError(e);\n }\n }\n }\n }\n } finally {\n if (--this._notifying === 0) {\n slots.compact();\n }\n }\n }\n\n private _logNotifyError(err: unknown): void {\n console.error(wrapError(err, AtomError, ERROR_MESSAGES.ATOM_INDIVIDUAL_SUBSCRIBER_FAILED));\n }\n\n // ============================================================================\n // Consumer Logic (Dependency Validation)\n // ============================================================================\n\n /**\n * Determines if the node is dirty by checking its dependency chain.\n * Optimized with O(1) hot-path check.\n */\n protected _isDirty(): boolean {\n const deps = this._deps;\n if (deps === null || deps.size === 0) return false;\n\n // Phase 1: Hot-path Check - O(1)\n const hotIndex = this._hotIndex;\n if (hotIndex !== -1) {\n const hotLink = deps.getAt(hotIndex);\n if (hotLink != null && hotLink.node.version !== hotLink.version) {\n return true;\n }\n }\n\n // Phase 2: Standard Validation - O(N)\n return this._deepDirtyCheck();\n }\n\n /**\n * Deeply validates dependency versions.\n */\n protected abstract _deepDirtyCheck(): boolean;\n}\n","/**\n * Brand symbols for reliable type identification.\n * Prevents false positives from duck-typing with external objects.\n */\nexport const ATOM_BRAND: unique symbol = Symbol.for('atom-effect/atom');\nexport const COMPUTED_BRAND: unique symbol = Symbol.for('atom-effect/computed');\nexport const EFFECT_BRAND: unique symbol = Symbol.for('atom-effect/effect');\n\n/**\n * Positive writable brand — only stamped on truly mutable atoms.\n * Allows future ReadonlyAtom / derived primitives to carry ATOM_BRAND\n * without being misidentified as writable by isWritable().\n */\nexport const WRITABLE_BRAND: unique symbol = Symbol.for('atom-effect/writable');\n","import { IS_DEV, SCHEDULER_CONFIG, SMI_MAX } from '@/constants';\nimport { ERROR_MESSAGES, SchedulerError } from '@/errors';\n\n// ── Epoch & Version Management ──────────────────────────────────────────\n\n// Global epoch counter.\nlet collectorEpoch = 0;\n\n/**\n * Next tracking epoch.\n */\nexport function nextEpoch(): number {\n const next = (collectorEpoch + 1) & SMI_MAX;\n collectorEpoch = next === 0 ? 1 : next;\n return collectorEpoch;\n}\n\n/** Current tracking epoch. */\nexport function currentEpoch(): number {\n return collectorEpoch;\n}\n\n/** Increments a version counter within SMI range. Avoids 0 to reserve it for uninitialized state. */\nexport function nextVersion(v: number): number {\n const next = (v + 1) & SMI_MAX;\n return next === 0 ? 1 : next;\n}\n\nexport let flushExecutionCount = 0;\nlet isFlushing = false;\nlet _flushEpoch = 0;\n\n/** Current flush epoch. */\nexport function currentFlushEpoch(): number {\n return _flushEpoch;\n}\n\n/**\n * Starts flush cycle.\n */\nexport function startFlush(): boolean {\n if (isFlushing) {\n if (IS_DEV) {\n console.warn('startFlush() called during flush - ignored');\n }\n return false;\n }\n\n isFlushing = true;\n _flushEpoch = nextEpoch();\n flushExecutionCount = 0;\n return true;\n}\n\n/** Ends flush cycle. */\nexport function endFlush(): void {\n isFlushing = false;\n}\n\n/**\n * Runs a function within a flush scope.\n * Ensures endFlush() is called even if an error occurs.\n */\nexport function runInFlushScope<T>(fn: () => T): T | undefined {\n if (!startFlush()) {\n return undefined;\n }\n\n try {\n return fn();\n } finally {\n endFlush();\n }\n}\n\n/**\n * Increments execution count.\n * Throws an error if the count exceeds MAX_EXECUTIONS_PER_FLUSH.\n */\nexport function incrementFlushExecutionCount(): number {\n if (!isFlushing) return 0;\n\n const count = ++flushExecutionCount;\n if (count <= SCHEDULER_CONFIG.MAX_EXECUTIONS_PER_FLUSH) {\n return count;\n }\n\n throw new Error(\n `[atom-effect] Infinite loop detected: flush execution count exceeded ${SCHEDULER_CONFIG.MAX_EXECUTIONS_PER_FLUSH}`\n );\n}\n\n/**\n * Resets flush state.\n */\nexport function resetFlushState(): void {\n _flushEpoch = 0;\n flushExecutionCount = 0;\n isFlushing = false;\n}\n\n// ── Scheduler ───────────────────────────────────────────────────────────\n\nexport interface SchedulerJobObject {\n execute(): void;\n /** Next scheduled epoch */\n _nextEpoch?: number;\n}\n\nexport interface SchedulerJobFunction {\n (): void;\n /** Next scheduled epoch */\n _nextEpoch?: number;\n}\n\nexport type SchedulerJob = SchedulerJobFunction | SchedulerJobObject;\n\n/**\n * Scheduler implementation.\n */\nclass Scheduler {\n /** Queue buffer */\n _queueBuffer: [SchedulerJob[], SchedulerJob[]] = [[], []];\n _bufferIndex = 0;\n _size = 0;\n\n /** Epoch counter */\n _epoch = 0;\n\n /** State flags */\n _isProcessing = false;\n _isFlushingSync = false;\n\n /** Batching state */\n _batchDepth = 0;\n _batchQueue: SchedulerJob[] = [];\n _batchQueueSize = 0;\n\n /** Config */\n _maxFlushIterations: number = SCHEDULER_CONFIG.MAX_FLUSH_ITERATIONS;\n\n /** Overflow callback */\n onOverflow: ((droppedCount: number) => void) | null = null;\n\n /** Bound run loop for microtask */\n private readonly _boundRunLoop = this._runLoop.bind(this);\n\n get queueSize(): number {\n return this._size;\n }\n\n get isBatching(): boolean {\n return this._batchDepth > 0;\n }\n\n /**\n * Schedules job.\n */\n schedule(callback: SchedulerJob): void {\n if (IS_DEV) {\n const isFn = typeof callback === 'function';\n const isObj =\n typeof callback === 'object' &&\n callback !== null &&\n typeof (callback as SchedulerJobObject).execute === 'function';\n if (!isFn && !isObj) {\n throw new SchedulerError(ERROR_MESSAGES.SCHEDULER_CALLBACK_MUST_BE_FUNCTION);\n }\n }\n\n // Deduplicate job\n const epoch = this._epoch;\n if (callback._nextEpoch === epoch) return;\n callback._nextEpoch = epoch;\n\n if (this._batchDepth > 0 || this._isFlushingSync) {\n this._batchQueue[this._batchQueueSize++] = callback;\n return;\n }\n\n // Push to current active buffer\n const idx = this._bufferIndex;\n const buffer = this._queueBuffer[idx]!;\n buffer[this._size++] = callback;\n\n // Wake up if sleeping\n if (!this._isProcessing) {\n this._flush();\n }\n }\n\n /**\n * Triggers flush.\n */\n _flush(): void {\n if (this._isProcessing || this._size === 0) return;\n this._isProcessing = true;\n\n queueMicrotask(this._boundRunLoop);\n }\n\n /**\n * Scheduler loop.\n */\n private _runLoop(): void {\n try {\n if (this._size === 0) return;\n\n const started = startFlush();\n this._drainQueue();\n if (started) endFlush();\n } finally {\n this._isProcessing = false;\n // If new jobs arrived during flush (and not batching), re-schedule\n if (this._size > 0 && this._batchDepth === 0) {\n this._flush();\n }\n }\n }\n\n _flushSync(): void {\n this._isFlushingSync = true;\n const started = startFlush();\n try {\n this._mergeBatchQueue();\n this._drainQueue();\n } finally {\n this._isFlushingSync = false;\n if (started) endFlush();\n }\n }\n\n _mergeBatchQueue(): void {\n const queueSize = this._batchQueueSize;\n if (queueSize === 0) return;\n\n // Increment epoch\n const epoch = ++this._epoch;\n const bQueue = this._batchQueue;\n const idx = this._bufferIndex;\n const targetBuffer = this._queueBuffer[idx]!;\n let currentSize = this._size;\n\n // Merge batch using a cached size to avoid property lookups\n for (let i = 0; i < queueSize; i++) {\n const job = bQueue[i]!;\n // Retag jobs only if they belong to a different epoch\n if (job._nextEpoch !== epoch) {\n job._nextEpoch = epoch;\n targetBuffer[currentSize++] = job;\n }\n }\n\n this._size = currentSize;\n this._batchQueueSize = 0;\n // Release references immediately while keeping array capacity\n bQueue.length = 0;\n }\n\n _drainQueue(): void {\n let iterations = 0;\n // Process queue\n while (this._size > 0) {\n // Overflow check\n if (++iterations > this._maxFlushIterations) {\n this._handleFlushOverflow();\n return;\n }\n\n this._processQueue();\n // If batch updates happened during processing, merge them in now\n this._mergeBatchQueue();\n }\n }\n\n _processQueue(): void {\n const idx = this._bufferIndex;\n const jobs = this._queueBuffer[idx]!;\n const count = this._size;\n\n // Swap buffers\n this._bufferIndex = idx ^ 1;\n this._size = 0;\n this._epoch = (this._epoch + 1) | 0;\n\n // Execute jobs\n for (let i = 0; i < count; i++) {\n const job = jobs[i]!;\n try {\n if (typeof job === 'function') {\n job();\n } else {\n job.execute();\n }\n } catch (e) {\n console.error(new SchedulerError('Error occurred during scheduler execution', e as Error));\n }\n }\n // Clear the consumed buffer\n jobs.length = 0;\n }\n\n private _handleFlushOverflow(): void {\n const droppedCount = this._size + this._batchQueueSize;\n const max = this._maxFlushIterations;\n\n console.error(new SchedulerError(ERROR_MESSAGES.SCHEDULER_FLUSH_OVERFLOW(max, droppedCount)));\n\n this._size = 0;\n const idx = this._bufferIndex;\n this._queueBuffer[idx]!.length = 0;\n this._batchQueueSize = 0;\n\n const onOverflow = this.onOverflow;\n if (onOverflow) {\n try {\n onOverflow(droppedCount);\n } catch {}\n }\n }\n\n startBatch(): void {\n this._batchDepth++;\n }\n\n endBatch(): void {\n if (this._batchDepth === 0) {\n if (IS_DEV) console.warn(ERROR_MESSAGES.SCHEDULER_END_BATCH_WITHOUT_START);\n return;\n }\n\n if (--this._batchDepth === 0) {\n this._flushSync();\n }\n }\n\n setMaxFlushIterations(max: number): void {\n if (max < SCHEDULER_CONFIG.MIN_FLUSH_ITERATIONS)\n throw new SchedulerError(\n `Max flush iterations must be at least ${SCHEDULER_CONFIG.MIN_FLUSH_ITERATIONS}`\n );\n this._maxFlushIterations = max;\n }\n}\n\nexport const scheduler = new Scheduler();\n\n// ── Batch ───────────────────────────────────────────────────────────────\n\n/**\n * Batches updates.\n *\n * @param fn - Batch function.\n * @returns - Result of `fn`.\n */\nexport function batch<T>(fn: () => T): T {\n if (typeof fn !== 'function') {\n throw new TypeError(ERROR_MESSAGES.BATCH_CALLBACK_MUST_BE_FUNCTION);\n }\n\n const s = scheduler;\n s.startBatch();\n try {\n return fn();\n } finally {\n s.endBatch();\n }\n}\n","import { ATOM_STATE_FLAGS } from '@/constants';\nimport { ReactiveNode } from '@/core/base';\nimport { ATOM_BRAND, WRITABLE_BRAND } from '@/symbols';\nimport type { AtomOptions, WritableAtom } from '@/types';\nimport { debug } from '@/utils/debug';\nimport { nextVersion, scheduler } from './scheduler';\nimport { trackingContext } from './tracking';\n\n/**\n * Internal {@link WritableAtom} implementation.\n */\nclass AtomImpl<T> extends ReactiveNode<T> implements WritableAtom<T> {\n private _value: T;\n /** Old value for notifications */\n private _pendingOldValue: T | undefined;\n\n /** @internal */\n readonly [ATOM_BRAND] = true;\n /** @internal */\n readonly [WRITABLE_BRAND] = true;\n\n constructor(initialValue: T, sync: boolean) {\n super();\n this._value = initialValue;\n\n if (sync) {\n this.flags |= ATOM_STATE_FLAGS.SYNC;\n }\n\n debug.attachDebugInfo(this, 'atom', this.id);\n }\n\n /** @internal */\n get isNotificationScheduled(): boolean {\n return (this.flags & ATOM_STATE_FLAGS.NOTIFICATION_SCHEDULED) !== 0;\n }\n\n /** @internal */\n get isSync(): boolean {\n return (this.flags & ATOM_STATE_FLAGS.SYNC) !== 0;\n }\n\n get value(): T {\n const ctx = trackingContext.current;\n if (ctx != null) {\n ctx.addDependency(this);\n }\n return this._value;\n }\n\n set value(newValue: T) {\n const oldValue = this._value;\n if (Object.is(oldValue, newValue)) return;\n\n this._value = newValue;\n this.version = nextVersion(this.version);\n\n const flags = this.flags;\n // 1. Double check: schedule pending or no slots\n if ((flags & ATOM_STATE_FLAGS.NOTIFICATION_SCHEDULED) !== 0) return;\n\n const slots = this._slots;\n if (slots == null || slots.size === 0) return;\n\n this._pendingOldValue = oldValue;\n this.flags = flags | ATOM_STATE_FLAGS.NOTIFICATION_SCHEDULED;\n\n // 2. Schedule or flush (inline bitwise)\n if ((flags & ATOM_STATE_FLAGS.SYNC) !== 0 && !scheduler.isBatching) {\n this._flushNotifications();\n } else {\n scheduler.schedule(this);\n }\n }\n\n /**\n * Executes scheduled notification.\n * @internal\n */\n execute(): void {\n this._flushNotifications();\n }\n\n /**\n * Triggers subscribers.\n */\n private _flushNotifications(): void {\n const flags = this.flags;\n // Guard: Combined bitwise check for NOTIFICATION_SCHEDULED and not DISPOSED\n if (\n (flags & (ATOM_STATE_FLAGS.NOTIFICATION_SCHEDULED | ATOM_STATE_FLAGS.DISPOSED)) !==\n ATOM_STATE_FLAGS.NOTIFICATION_SCHEDULED\n ) {\n return;\n }\n\n const oldValue = this._pendingOldValue as T;\n this._pendingOldValue = undefined;\n this.flags = flags & ~ATOM_STATE_FLAGS.NOTIFICATION_SCHEDULED;\n\n this._notifySubscribers(this._value, oldValue);\n }\n\n peek(): T {\n return this._value;\n }\n\n dispose(): void {\n const flags = this.flags;\n if ((flags & ATOM_STATE_FLAGS.DISPOSED) !== 0) return;\n\n this._slots?.clear();\n this.flags = flags | ATOM_STATE_FLAGS.DISPOSED;\n // Release references\n this._value = undefined as T;\n this._pendingOldValue = undefined;\n }\n\n protected override _deepDirtyCheck(): boolean {\n return false;\n }\n\n [Symbol.dispose](): void {\n this.dispose();\n }\n}\n\n/**\n * Creates a reactive atom holding mutable state.\n *\n * @param initialValue - The initial value of the atom.\n * @param options - Configuration options (sync: boolean).\n */\nexport function atom<T>(initialValue: T, options: AtomOptions = {}): WritableAtom<T> {\n return new AtomImpl(initialValue, options.sync ?? false);\n}\n","import { ATOM_BRAND, COMPUTED_BRAND, EFFECT_BRAND, WRITABLE_BRAND } from '@/symbols';\nimport type { ComputedAtom, EffectObject, ReadonlyAtom, WritableAtom } from '@/types';\n\n/**\n * Readonly atom check.\n *\n * @param obj - Object to check.\n */\nexport function isAtom(obj: unknown): obj is ReadonlyAtom {\n return typeof obj === 'object' && obj !== null && ATOM_BRAND in obj;\n}\n\n/**\n * Writable atom check.\n *\n * Uses a dedicated positive brand instead of `!isComputed()` to remain\n * correct if new ReadonlyAtom-style primitives are added in the future.\n */\nexport function isWritable(obj: unknown): obj is WritableAtom {\n return typeof obj === 'object' && obj !== null && WRITABLE_BRAND in obj;\n}\n\n/**\n * Computed atom check.\n */\nexport function isComputed(obj: unknown): obj is ComputedAtom {\n return typeof obj === 'object' && obj !== null && COMPUTED_BRAND in obj;\n}\n\n/**\n * Effect object check.\n */\nexport function isEffect(obj: unknown): obj is EffectObject {\n return typeof obj === 'object' && obj !== null && EFFECT_BRAND in obj;\n}\n\n/**\n * Promise check.\n */\nexport function isPromise<T>(value: unknown): value is Promise<T> {\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof (value as { then?: unknown }).then === 'function'\n );\n}\n","import {\n AsyncState,\n COMPUTED_CONFIG,\n COMPUTED_STATE_FLAGS,\n EMPTY_ERROR_ARRAY,\n EPOCH_CONSTANTS,\n IS_DEV,\n} from '@/constants';\nimport { ReactiveNode } from '@/core/base';\nimport { ComputedError, ERROR_MESSAGES, wrapError } from '@/errors';\nimport { ATOM_BRAND, COMPUTED_BRAND } from '@/symbols';\nimport type {\n AsyncStateType,\n ComputedAtom,\n ComputedOptions,\n Dependency,\n Subscriber,\n} from '@/types';\nimport { debug, NO_DEFAULT_VALUE } from '@/utils/debug';\nimport { isPromise } from '@/utils/type-guards';\nimport { DepSlotBuffer } from './buffers';\nimport { nextEpoch, nextVersion } from './scheduler';\nimport { DependencyLink, trackingContext } from './tracking';\n\nconst {\n IDLE,\n DIRTY,\n PENDING,\n RESOLVED,\n REJECTED,\n HAS_ERROR,\n RECOMPUTING,\n DISPOSED,\n IS_COMPUTED,\n FORCE_COMPUTE,\n} = COMPUTED_STATE_FLAGS;\n\n/**\n * Computed atom implementation.\n */\nclass ComputedAtomImpl<T> extends ReactiveNode<T> implements ComputedAtom<T>, Subscriber {\n /** @internal */\n readonly [ATOM_BRAND] = true;\n /** @internal */\n readonly [COMPUTED_BRAND] = true;\n\n private _value: T;\n private _error: Error | null = null;\n /** Promise tracking ID */\n private _promiseId = 0;\n\n private readonly _equal: (a: T, b: T) => boolean;\n private readonly _fn: () => T | Promise<T>;\n private readonly _defaultValue: T;\n private readonly _onError: ((error: Error) => void) | null;\n\n /** Initialized in constructor. Unified node property. */\n _deps = new DepSlotBuffer();\n\n // Async state\n\n // Dependency collection state\n private _trackEpoch: number = EPOCH_CONSTANTS.UNINITIALIZED;\n private _trackCount = 0;\n\n constructor(fn: () => T | Promise<T>, options: ComputedOptions<T> = {}) {\n if (typeof fn !== 'function') throw new ComputedError(ERROR_MESSAGES.COMPUTED_MUST_BE_FUNCTION);\n super();\n\n this._value = undefined as T;\n // Start dirty so first access triggers computation\n this.flags = IS_COMPUTED | DIRTY | IDLE;\n this._equal = options.equal ?? Object.is;\n this._fn = fn;\n this._defaultValue = 'defaultValue' in options ? options.defaultValue : (NO_DEFAULT_VALUE as T);\n this._onError = options.onError ?? null;\n\n debug.attachDebugInfo(this, 'computed', this.id);\n\n // Eager evaluation if not lazy\n if (options.lazy === false) {\n try {\n this._recompute();\n } catch {\n /* _handleError already stored error and called onError */\n }\n }\n }\n\n /** @internal */\n get isDirty(): boolean {\n return (this.flags & DIRTY) !== 0;\n }\n\n /** @internal */\n get isRejected(): boolean {\n return (this.flags & REJECTED) !== 0;\n }\n\n /** @internal */\n get isRecomputing(): boolean {\n return (this.flags & RECOMPUTING) !== 0;\n }\n\n /** @internal */\n private get _hasErrorInternal(): boolean {\n return (this.flags & HAS_ERROR) !== 0;\n }\n\n private _track(): void {\n trackingContext.current?.addDependency(this);\n }\n\n get value(): T {\n const ctx = trackingContext.current;\n if (ctx != null) ctx.addDependency(this);\n\n let flags = this.flags;\n // 1. Fast path: Stable and Resolved\n if ((flags & (RESOLVED | DIRTY | IDLE)) === RESOLVED) {\n return this._value;\n }\n\n // 2. Exception paths\n if ((flags & DISPOSED) !== 0) throw new ComputedError(ERROR_MESSAGES.COMPUTED_DISPOSED);\n\n if ((flags & RECOMPUTING) !== 0) {\n const def = this._defaultValue;\n if (def !== (NO_DEFAULT_VALUE as T)) return def;\n throw new ComputedError(ERROR_MESSAGES.COMPUTED_CIRCULAR_DEPENDENCY);\n }\n\n // 3. Evaluation path\n if ((flags & (DIRTY | IDLE)) !== 0) {\n const deps = this._deps;\n if (\n (flags & IDLE) === 0 &&\n (flags & FORCE_COMPUTE) === 0 &&\n deps.size > 0 &&\n !this._isDirty()\n ) {\n flags = this.flags &= ~DIRTY;\n } else {\n this._recompute();\n flags = this.flags;\n }\n if ((flags & RESOLVED) !== 0) return this._value;\n }\n\n // 4. Async/Error handling\n const def = this._defaultValue;\n const hasDefault = def !== (NO_DEFAULT_VALUE as T);\n\n if ((flags & PENDING) !== 0) {\n if (hasDefault) return def;\n throw new ComputedError(ERROR_MESSAGES.COMPUTED_ASYNC_PENDING_NO_DEFAULT);\n }\n\n if ((flags & REJECTED) !== 0) {\n if (hasDefault) return def;\n throw this._error;\n }\n\n return this._value;\n }\n\n peek(): T {\n return this._value;\n }\n\n get state(): AsyncStateType {\n const ctx = trackingContext.current;\n if (ctx != null) ctx.addDependency(this);\n const flags = this.flags;\n if ((flags & RESOLVED) !== 0) return AsyncState.RESOLVED;\n if ((flags & PENDING) !== 0) return AsyncState.PENDING;\n if ((flags & REJECTED) !== 0) return AsyncState.REJECTED;\n return AsyncState.IDLE;\n }\n\n get hasError(): boolean {\n const ctx = trackingContext.current;\n if (ctx != null) ctx.addDependency(this);\n\n const flags = this.flags;\n // Inlined checks for REJECTED | HAS_ERROR\n if ((flags & (REJECTED | HAS_ERROR)) !== 0) return true;\n\n const deps = this._deps;\n if (!deps.hasComputeds) return false;\n\n const size = deps.size;\n for (let i = 0; i < size; i++) {\n const link = deps.getAt(i);\n if (link?.node.hasError) return true;\n }\n return false;\n }\n\n get isValid(): boolean {\n return !this.hasError;\n }\n\n get errors(): readonly Error[] {\n const ctx = trackingContext.current;\n if (ctx != null) ctx.addDependency(this);\n\n const selfErr = this._error;\n const deps = this._deps;\n\n // Early exit: no computed dependencies means no bubbling errors\n if (!deps.hasComputeds) {\n if (selfErr == null) return EMPTY_ERROR_ARRAY;\n return Object.freeze([selfErr]);\n }\n\n const collected: Error[] = [];\n if (selfErr != null) collected.push(selfErr);\n\n const size = deps.size;\n for (let i = 0; i < size; i++) {\n const link = deps.getAt(i);\n if (link == null) continue;\n\n const dep = link.node;\n // Inlined isComputed + hasError check\n if ((dep.flags & IS_COMPUTED) !== 0 && dep.hasError) {\n this._collectErrorsFromDep(dep as unknown as ComputedAtom<unknown>, collected);\n }\n }\n\n return collected.length === 0 ? EMPTY_ERROR_ARRAY : Object.freeze(collected);\n }\n\n private _collectErrorsFromDep(computedDep: ComputedAtom<unknown>, collected: Error[]): void {\n const errs = computedDep.errors;\n const len = errs.length;\n for (let j = 0; j < len; j++) {\n const err = errs[j];\n if (err != null && !collected.includes(err)) {\n collected.push(err);\n }\n }\n }\n\n get lastError(): Error | null {\n const ctx = trackingContext.current;\n if (ctx != null) ctx.addDependency(this);\n return this._error;\n }\n\n get isPending(): boolean {\n const ctx = trackingContext.current;\n if (ctx != null) ctx.addDependency(this);\n return (this.flags & PENDING) !== 0;\n }\n\n get isResolved(): boolean {\n const ctx = trackingContext.current;\n if (ctx != null) ctx.addDependency(this);\n return (this.flags & RESOLVED) !== 0;\n }\n\n invalidate(): void {\n this.flags |= FORCE_COMPUTE;\n this._markDirty();\n }\n\n dispose(): void {\n const flags = this.flags;\n if ((flags & DISPOSED) !== 0) return;\n\n this._deps.disposeAll();\n\n if (this._slots != null) {\n this._slots.clear();\n }\n this.flags = DISPOSED | DIRTY | IDLE;\n\n // Release Memory\n this._error = null;\n this._value = undefined as T;\n this._hotIndex = -1;\n }\n\n [Symbol.dispose](): void {\n this.dispose();\n }\n\n addDependency(dep: Dependency): void {\n const trackEpoch = this._trackEpoch;\n if (dep._lastSeenEpoch === trackEpoch) return;\n dep._lastSeenEpoch = trackEpoch;\n\n const trackIndex = this._trackCount++;\n const deps = this._deps;\n const existing = deps.getAt(trackIndex);\n\n // 1. Stable Path: dependency index remains the same\n if (existing != null && existing.node === dep) {\n existing.version = dep.version;\n }\n // 2. Diverged Path: lookup or insert\n else if (deps.claimExisting(dep, trackIndex)) {\n // Version updated inside claimExisting\n }\n // 3. New dependency\n else {\n const link = new DependencyLink(dep, dep.version, dep.subscribe(this));\n deps.insertNew(trackIndex, link);\n }\n\n if ((dep.flags & IS_COMPUTED) !== 0) {\n deps.hasComputeds = true;\n }\n }\n\n private _recompute(): void {\n if (this.isRecomputing) return;\n this.flags = (this.flags | RECOMPUTING) & ~FORCE_COMPUTE;\n\n this._trackEpoch = nextEpoch();\n this._trackCount = 0;\n this._deps.prepareTracking();\n this._hotIndex = -1;\n\n let committed = false;\n try {\n // Execute function\n const result = trackingContext.run(this, this._fn);\n\n // Clean up any remaining trailing dependencies\n this._deps.truncateFrom(this._trackCount);\n\n committed = true;\n\n // Handle Result\n if (isPromise(result)) {\n this._handleAsyncComputation(result);\n } else {\n this._finalizeResolution(result);\n }\n } catch (e) {\n // Commit dependencies on error gracefully\n if (!committed) {\n try {\n this._deps.truncateFrom(this._trackCount);\n } catch (commitErr) {\n if (IS_DEV) {\n console.warn('[atom-effect] _commitDeps failed during error recovery:', commitErr);\n }\n }\n }\n this._handleError(e as Error, ERROR_MESSAGES.COMPUTED_COMPUTATION_FAILED, true);\n } finally {\n // Reset transient state\n this._trackEpoch = EPOCH_CONSTANTS.UNINITIALIZED;\n this._trackCount = 0;\n this.flags &= ~RECOMPUTING;\n }\n }\n\n private _handleAsyncComputation(promise: Promise<T>): void {\n // Set pending, clear idle/dirty/resolved/rejected\n this.flags = (this.flags | PENDING) & ~(IDLE | DIRTY | RESOLVED | REJECTED);\n // Notify pending\n this._notifySubscribers(undefined, undefined);\n\n // Invalidate old promises\n this._promiseId = (this._promiseId + 1) % COMPUTED_CONFIG.MAX_PROMISE_ID;\n const promiseId = this._promiseId;\n\n promise.then(\n (res) => {\n if (promiseId !== this._promiseId) return; // Stale\n\n if (this._isDirty()) {\n return this._markDirty(); // Retry\n }\n\n this._finalizeResolution(res);\n this._notifySubscribers(res, undefined);\n },\n (err) =>\n promiseId === this._promiseId &&\n this._handleError(err, ERROR_MESSAGES.COMPUTED_ASYNC_COMPUTATION_FAILED)\n );\n }\n\n private _handleError(err: unknown, msg: string, throwErr = false): void {\n const error = wrapError(err, ComputedError, msg);\n\n if (!throwErr && !this.isRejected) {\n this.version = nextVersion(this.version);\n }\n\n this._error = error;\n // Set rejected + has_error, clear idle/dirty/pending/resolved\n this.flags = (this.flags & ~(IDLE | DIRTY | PENDING | RESOLVED)) | REJECTED | HAS_ERROR;\n\n if (this._onError) {\n try {\n this._onError(error);\n } catch (e) {\n console.error(ERROR_MESSAGES.CALLBACK_ERROR_IN_ERROR_HANDLER, e);\n }\n }\n\n if (throwErr) throw error;\n this._notifySubscribers(undefined, undefined);\n }\n\n private _finalizeResolution(value: T): void {\n const flags = this.flags;\n // Only bump version if value actually changed or first resolve\n if ((flags & RESOLVED) === 0 || !this._equal(this._value, value)) {\n this.version = nextVersion(this.version);\n }\n\n this._value = value;\n this._error = null;\n // Set resolved, clear idle/dirty/pending/rejected/has_error\n this.flags = (flags | RESOLVED) & ~(IDLE | DIRTY | PENDING | REJECTED | HAS_ERROR);\n }\n\n execute(): void {\n // Subscriber implementation\n this._markDirty();\n }\n\n /** @internal */\n _markDirty(): void {\n const flags = this.flags;\n if ((flags & (RECOMPUTING | DIRTY)) !== 0) return;\n this.flags = flags | DIRTY;\n this._notifySubscribers(undefined, undefined);\n }\n\n /**\n * Deep dirty check for computations.\n */\n protected override _deepDirtyCheck(): boolean {\n const deps = this._deps;\n const prevContext = trackingContext.current;\n trackingContext.current = null;\n\n try {\n const size = deps.size;\n for (let i = 0; i < size; i++) {\n const link = deps.getAt(i);\n if (link == null) continue;\n\n const dep = link.node;\n // Inlined isComputed check\n if ((dep.flags & IS_COMPUTED) !== 0) {\n try {\n // Force computed to re-evaluate so version reflects latest state\n void (dep as { value: unknown }).value;\n } catch {\n if (IS_DEV)\n console.warn(`[atom-effect] Dependency #${dep.id} threw during dirty check`);\n }\n }\n\n if (dep.version !== link.version) {\n this._hotIndex = i;\n return true;\n }\n }\n\n this._hotIndex = -1;\n return false;\n } finally {\n trackingContext.current = prevContext;\n }\n }\n}\n\n/**\n * Creates a computed value.\n * @param fn - Computation function\n * @param options - Options object\n */\nexport function computed<T>(fn: () => T, options?: ComputedOptions<T>): ComputedAtom<T>;\nexport function computed<T>(\n fn: () => Promise<T>,\n options: ComputedOptions<T> & { defaultValue: T }\n): ComputedAtom<T>;\nexport function computed<T>(\n fn: () => T | Promise<T>,\n options: ComputedOptions<T> = {}\n): ComputedAtom<T> {\n return new ComputedAtomImpl(fn, options);\n}\n","import {\n DEBUG_CONFIG,\n EFFECT_STATE_FLAGS,\n EPOCH_CONSTANTS,\n IS_DEV,\n SCHEDULER_CONFIG,\n} from '@/constants';\nimport { ReactiveNode } from '@/core/base';\nimport { EffectError, ERROR_MESSAGES, wrapError } from '@/errors';\nimport { EFFECT_BRAND } from '@/symbols';\nimport type { Dependency, EffectFunction, EffectObject, EffectOptions } from '@/types';\nimport { debug } from '@/utils/debug';\nimport { isPromise } from '@/utils/type-guards';\nimport { DepSlotBuffer } from './buffers';\nimport {\n currentFlushEpoch,\n flushExecutionCount,\n incrementFlushExecutionCount,\n nextEpoch,\n scheduler,\n} from './scheduler';\nimport { DependencyLink, type DependencyTracker, trackingContext } from './tracking';\n\n/**\n * Effect implementation.\n */\nclass EffectImpl extends ReactiveNode<void> implements EffectObject, DependencyTracker {\n /** @internal */\n readonly [EFFECT_BRAND] = true;\n\n private _cleanup: (() => void) | null = null;\n /** Initialized in constructor to maintain God Class object shape */\n _deps = new DepSlotBuffer();\n\n /** Pre-allocated notify callback shared by all subscriptions */\n private readonly _notifyCallback: () => void;\n\n private readonly _onError: ((error: unknown) => void) | null;\n\n // Cycle detection\n private _currentEpoch: number = EPOCH_CONSTANTS.UNINITIALIZED;\n private _lastFlushEpoch: number = EPOCH_CONSTANTS.UNINITIALIZED;\n private _executionsInEpoch: number;\n\n private readonly _fn: EffectFunction;\n private readonly _sync: boolean;\n private readonly _maxExecutions: number;\n private readonly _maxExecutionsPerFlush: number;\n // Frequency tracking (Dev)\n private _executionCount: number;\n private _windowStart: number;\n private _windowCount: number;\n private _execId: number;\n private _trackCount: number;\n\n constructor(fn: EffectFunction, options: EffectOptions = {}) {\n super();\n this._fn = fn;\n this._onError = options.onError ?? null;\n this._sync = options.sync ?? false;\n this._maxExecutions =\n options.maxExecutionsPerSecond ?? SCHEDULER_CONFIG.MAX_EXECUTIONS_PER_SECOND;\n this._maxExecutionsPerFlush =\n options.maxExecutionsPerFlush ?? SCHEDULER_CONFIG.MAX_EXECUTIONS_PER_EFFECT;\n\n this._executionsInEpoch = 0;\n this._executionCount = 0;\n this._windowStart = 0;\n this._windowCount = 0;\n this._execId = 0;\n this._trackCount = 0;\n\n // Pre-allocate callbacks once — eliminates per-dependency closure allocation\n if (this._sync) {\n this._notifyCallback = () => this.execute();\n } else {\n this._notifyCallback = () => scheduler.schedule(this);\n }\n\n debug.attachDebugInfo(this, 'effect', this.id);\n }\n\n public run(): void {\n if (this.isDisposed) {\n throw new EffectError(ERROR_MESSAGES.EFFECT_DISPOSED);\n }\n this.execute(true);\n }\n\n public dispose(): void {\n if (this.isDisposed) return;\n this.flags |= EFFECT_STATE_FLAGS.DISPOSED;\n\n this._execCleanup();\n this._deps?.disposeAll();\n }\n\n [Symbol.dispose](): void {\n this.dispose();\n }\n\n public addDependency(dep: Dependency): void {\n const flags = this.flags;\n if ((flags & EFFECT_STATE_FLAGS.EXECUTING) === 0) return;\n\n const startEpoch = this._currentEpoch;\n if (dep._lastSeenEpoch === startEpoch) return;\n dep._lastSeenEpoch = startEpoch;\n\n const trackIndex = this._trackCount++;\n const deps = this._deps;\n\n // Optimized: Direct access to inline slots for the hottest 4 dependencies\n let existing: DependencyLink | null;\n switch (trackIndex) {\n case 0:\n existing = deps._s0;\n break;\n case 1:\n existing = deps._s1;\n break;\n case 2:\n existing = deps._s2;\n break;\n case 3:\n existing = deps._s3;\n break;\n default:\n existing = deps.getAt(trackIndex);\n }\n\n // 1. Stable Path: dependency index remains the same\n if (existing != null && existing.node === dep) {\n existing.version = dep.version;\n }\n // 2. Diverged Path: lookup or insert\n else if (deps.claimExisting(dep, trackIndex)) {\n // Version updated in claimExisting\n }\n // 3. New dependency\n else {\n this._insertNewDependency(dep, trackIndex);\n }\n\n if (dep.isComputed) {\n deps.hasComputeds = true;\n }\n }\n\n private _insertNewDependency(dep: Dependency, trackIndex: number): void {\n let link: DependencyLink;\n try {\n const unsubscribe = dep.subscribe(this._notifyCallback);\n link = new DependencyLink(dep, dep.version, unsubscribe);\n } catch (error) {\n const wrapped = wrapError(error, EffectError, ERROR_MESSAGES.EFFECT_EXECUTION_FAILED);\n console.error(wrapped);\n if (this._onError) {\n try {\n this._onError(wrapped);\n } catch {}\n }\n link = new DependencyLink(dep, dep.version, undefined);\n }\n\n this._deps!.insertNew(trackIndex, link);\n }\n\n /**\n * Executes effect with tracking.\n */\n public execute(force = false): void {\n const flags = this.flags;\n // Guard: Combined bitwise check for efficiency\n if ((flags & (EFFECT_STATE_FLAGS.DISPOSED | EFFECT_STATE_FLAGS.EXECUTING)) !== 0) return;\n\n // Skip if not dirty or forced\n const deps = this._deps;\n if (!force && deps.size > 0 && !this._isDirty()) return;\n\n this._checkInfiniteLoops();\n\n this.flags = flags | EFFECT_STATE_FLAGS.EXECUTING;\n this._execCleanup();\n\n this._currentEpoch = nextEpoch();\n this._trackCount = 0;\n deps.prepareTracking();\n this._hotIndex = -1;\n\n let committed = false;\n try {\n const result = trackingContext.run(this, this._fn);\n\n // Clean up any remaining trailing dependencies\n deps.truncateFrom(this._trackCount);\n\n committed = true;\n\n // Handle result\n if (isPromise(result)) {\n this._handleAsyncResult(result);\n } else {\n this._cleanup = typeof result === 'function' ? result : null;\n }\n } catch (error) {\n // Commit on error gracefully to maintain state for recovery\n if (!committed) {\n try {\n deps.truncateFrom(this._trackCount);\n } catch (commitErr) {\n if (IS_DEV) {\n console.warn('[atom-effect] _commitDeps failed during error recovery:', commitErr);\n }\n }\n }\n this._handleExecutionError(error);\n this._cleanup = null;\n } finally {\n this.flags &= ~EFFECT_STATE_FLAGS.EXECUTING;\n }\n }\n\n private _handleAsyncResult(promise: Promise<unknown>): void {\n const execId = ++this._execId;\n promise.then(\n (cleanup) => {\n // Guard against race conditions (new execution or disposal happened)\n if (execId !== this._execId || this.isDisposed) {\n if (typeof cleanup === 'function') {\n try {\n cleanup();\n } catch (e) {\n this._handleExecutionError(e, ERROR_MESSAGES.EFFECT_CLEANUP_FAILED);\n }\n }\n return;\n }\n if (typeof cleanup === 'function') this._cleanup = cleanup as () => void;\n },\n (err) => execId === this._execId && this._handleExecutionError(err)\n );\n }\n\n protected override _deepDirtyCheck(): boolean {\n const prevContext = trackingContext.current;\n trackingContext.current = null;\n const deps = this._deps!;\n\n try {\n const size = deps.size;\n for (let i = 0; i < size; i++) {\n const link = deps.getAt(i);\n if (link == null) continue;\n\n const dep = link.node;\n if (dep.isComputed) {\n this._tryPullComputed(dep);\n }\n\n if (dep.version !== link.version) {\n this._hotIndex = i;\n return true;\n }\n }\n return false;\n } finally {\n trackingContext.current = prevContext;\n }\n }\n\n private _tryPullComputed(dep: Dependency): void {\n try {\n // Force computed to re-evaluate so version reflects latest state\n void (dep as { value: unknown }).value;\n } catch {\n if (IS_DEV) {\n console.warn(`[atom-effect] Dependency #${dep.id} threw during dirty check`);\n }\n }\n }\n\n private _execCleanup(): void {\n const cleanup = this._cleanup;\n if (cleanup == null) return;\n this._cleanup = null;\n try {\n cleanup();\n } catch (error) {\n this._handleExecutionError(error, ERROR_MESSAGES.EFFECT_CLEANUP_FAILED);\n }\n }\n\n private _checkInfiniteLoops(): void {\n const epoch = currentFlushEpoch();\n if (this._lastFlushEpoch !== epoch) {\n this._lastFlushEpoch = epoch;\n this._executionsInEpoch = 0;\n }\n\n const executions = ++this._executionsInEpoch;\n if (executions > this._maxExecutionsPerFlush) this._throwInfiniteLoopError('per-effect');\n\n const globalExecutions = incrementFlushExecutionCount();\n if (globalExecutions > SCHEDULER_CONFIG.MAX_EXECUTIONS_PER_FLUSH) {\n this._throwInfiniteLoopError('global');\n }\n\n this._executionCount++;\n\n if (IS_DEV) this._checkFrequencyLimit();\n }\n\n private _checkFrequencyLimit(): void {\n if (!Number.isFinite(this._maxExecutions)) return;\n\n const now = Date.now();\n if (now - this._windowStart >= DEBUG_CONFIG.EFFECT_FREQUENCY_WINDOW) {\n this._windowStart = now;\n this._windowCount = 1;\n return;\n }\n\n if (++this._windowCount > this._maxExecutions) {\n const err = new EffectError(ERROR_MESSAGES.EFFECT_FREQUENCY_LIMIT_EXCEEDED);\n this.dispose();\n this._handleExecutionError(err);\n throw err;\n }\n }\n\n get executionCount(): number {\n return this._executionCount;\n }\n get isExecuting(): boolean {\n return (this.flags & EFFECT_STATE_FLAGS.EXECUTING) !== 0;\n }\n\n private _throwInfiniteLoopError(type: 'per-effect' | 'global'): never {\n const error = new EffectError(\n `Infinite loop detected (${type}): effect executed ${this._executionsInEpoch} times in current flush. Total executions in flush: ${flushExecutionCount}`\n );\n this.dispose();\n console.error(error);\n throw error;\n }\n\n private _handleExecutionError(\n error: unknown,\n message: string = ERROR_MESSAGES.EFFECT_EXECUTION_FAILED\n ): void {\n const errorObj = wrapError(error, EffectError, message);\n console.error(errorObj);\n if (this._onError) {\n try {\n this._onError(errorObj);\n } catch (e) {\n console.error(wrapError(e, EffectError, ERROR_MESSAGES.CALLBACK_ERROR_IN_ERROR_HANDLER));\n }\n }\n }\n}\n\n/**\n * Creates and starts an effect.\n *\n * @param fn - Effect function.\n * @param options - Configuration options.\n * @returns Effect instance.\n */\nexport function effect(fn: EffectFunction, options: EffectOptions = {}): EffectObject {\n if (typeof fn !== 'function') {\n throw new EffectError(ERROR_MESSAGES.EFFECT_MUST_BE_FUNCTION);\n }\n\n const effectInstance = new EffectImpl(fn, options);\n effectInstance.execute();\n\n return effectInstance;\n}\n","import type { Paths, PathValue, WritableAtom } from '../types';\n\n// Note: atom-effect brands are based on Symbol.for, which works across realms\n// and library copies. This allows the lens to behave as a first-class atom\n// to any consumer using the core's branding checks.\nconst ATOM_BRAND = Symbol.for('atom-effect/atom');\nconst WRITABLE_BRAND = Symbol.for('atom-effect/writable');\n\n/**\n * Internal recursive helper for creating deep immutable copies with structural sharing.\n * Only clones nodes along the path where changes occur.\n */\nexport function setDeepValue(obj: unknown, keys: string[], index: number, value: unknown): unknown {\n if (index === keys.length) return value;\n\n const key = keys[index]!;\n const curr = (obj != null && typeof obj === 'object' ? obj : {}) as Record<string, unknown>;\n const old = curr[key];\n const next = setDeepValue(old, keys, index + 1, value);\n\n if (Object.is(old, next)) return obj;\n\n if (Array.isArray(curr)) {\n const arr = curr.slice();\n const idx = Number.parseInt(key, 10);\n if (!Number.isNaN(idx)) {\n arr[idx] = next;\n } else {\n (arr as unknown as Record<string, unknown>)[key] = next;\n }\n return arr;\n }\n return { ...curr, [key]: next };\n}\n\n/**\n * Helper to retrieve a nested value from an object/array at a given path.\n */\nexport function getPathValue(source: unknown, parts: string[]): unknown {\n let res = source;\n const len = parts.length;\n for (let i = 0; i < len; i++) {\n if (res == null) return undefined;\n res = (res as Record<string, unknown>)[parts[i]!];\n }\n return res;\n}\n\n/**\n * Creates a two-way \"lens\" for a specific property path on an object-based atom.\n *\n * @example\n * const store = atom({ user: { name: 'Alice' } });\n * const nameLens = atomLens(store, 'user.name');\n * console.log(nameLens.value); // 'Alice'\n * nameLens.value = 'Bob'; // Updates store.user.name immutably\n */\nexport function atomLens<T extends object, P extends Paths<T>>(\n atom: WritableAtom<T>,\n path: P\n): WritableAtom<PathValue<T, P>> {\n const parts = path.includes('.') ? path.split('.') : [path];\n const unsubs = new Set<() => void>();\n const dispose = () => {\n unsubs.forEach((u) => u());\n unsubs.clear();\n };\n\n return {\n get value() {\n return getPathValue(atom.value, parts) as PathValue<T, P>;\n },\n set value(newVal: PathValue<T, P>) {\n const cur = atom.peek(),\n next = setDeepValue(cur, parts, 0, newVal);\n if (next !== cur) atom.value = next as T;\n },\n peek: () => getPathValue(atom.peek(), parts) as PathValue<T, P>,\n subscribe(listener: (nv: PathValue<T, P>, ov: PathValue<T, P>) => void) {\n const unsub = atom.subscribe((np, op) => {\n const nv = getPathValue(np, parts) as PathValue<T, P>,\n ov = getPathValue(op, parts) as PathValue<T, P>;\n if (!Object.is(nv, ov)) listener(nv, ov);\n });\n unsubs.add(unsub);\n return () => {\n unsub();\n unsubs.delete(unsub);\n };\n },\n subscriberCount: () => unsubs.size,\n dispose,\n [Symbol.dispose]: dispose,\n [ATOM_BRAND]: true,\n [WRITABLE_BRAND]: true,\n } as unknown as WritableAtom<PathValue<T, P>>;\n}\n\n/**\n * Composes an existing lens with a sub-path to create a deeper lens.\n */\nexport const composeLens = <T extends object, P extends Paths<T>>(lens: WritableAtom<T>, path: P) =>\n atomLens(lens, path);\n\n/**\n * Creates a lens factory bound to a specific atom.\n */\nexport const lensFor =\n <T extends object>(atom: WritableAtom<T>) =>\n <P extends Paths<T>>(path: P) =>\n atomLens(atom, path);\n"],"mappings":"kRAGA,IAAa,EAAa,CACxB,KAAM,OACN,QAAS,UACT,SAAU,WACV,SAAU,YAMC,EAAqB,CAChC,SAAU,EACV,UAAW,GAMA,EAAuB,CAClC,SAAU,EAEV,YAAa,EACb,MAAO,EACP,KAAM,GACN,QAAS,GACT,SAAU,GACV,SAAU,IACV,YAAa,IACb,UAAW,IAEX,cAAe,MAMJ,EAAmB,CAC9B,SAAU,EACV,KAAM,EACN,uBAAwB,IAMb,EAAmB,CAE9B,0BAA2B,IAC3B,0BAA2B,IAG3B,yBAA0B,IAC1B,qBAAsB,IACtB,qBAAsB,GAGtB,6BAA8B,KAMnB,EAAe,CAC1B,mBAAoB,GACpB,wBAAyB,KAMd,GAAkB,CAC7B,eAAgB,OAAO,iBAAmB,CAAA,EAM/B,EAAkB,CAE7B,cAAe,GAEf,IAAK,G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,EAAO,EAAgC,EAAM,CAAA,CAAA,EAE/C,OAAO,EAYT,SAAgB,EACd,EACA,EAC+B,CAC/B,MAAM,EAAQ,EAAK,SAAS,GAAA,EAAO,EAAK,MAAM,GAAA,EAAO,CAAC,CAAA,EAChD,EAAS,IAAI,IACb,EAAA,IAAgB,CACpB,EAAO,QAAS,GAAM,EAAA,CAAG,EACzB,EAAO,MAAA,GAGT,MAAO,CACL,IAAI,OAAQ,CACV,OAAO,EAAa,EAAK,MAAO,CAAA,GAElC,IAAI,MAAM,EAAyB,CACjC,MAAM,EAAM,EAAK,KAAA,EACf,EAAO,EAAa,EAAK,EAAO,EAAG,CAAA,EACjC,IAAS,IAAK,EAAK,MAAQ,IAEjC,KAAA,IAAY,EAAa,EAAK,KAAA,EAAQ,CAAA,EACtC,UAAU,EAA8D,CACtE,MAAM,EAAQ,EAAK,UAAA,CAAW,EAAI,IAAO,CACvC,MAAM,EAAK,EAAa,EAAI,CAAA,EAC1B,EAAK,EAAa,EAAI,CAAA,EACnB,OAAO,GAAG,EAAI,CAAA,GAAK,EAAS,EAAI,CAAA,IAEvC,OAAA,EAAO,IAAI,CAAA,EACX,IAAa,CACX,EAAA,EACA,EAAO,OAAO,CAAA,IAGlB,gBAAA,IAAuB,EAAO,KAC9B,QAAA,GACC,OAAO,OAAA,EAAU,GACjB,EAAA,EAAa,IACb,EAAA,EAAiB,IAOtB,IAAa,GAAA,CAAqD,EAAuB,IACvF,EAAS,EAAM,CAAA,EAKJ,GACQ,GACE,GACnB,EAAS,EAAM,CAAA"}
|
|
1
|
+
{"version":3,"file":"atom-effect.min.js","names":[],"sources":["../src/constants.ts","../src/errors.ts","../src/utils/debug.ts","../src/core/buffers.ts","../src/symbols.ts","../src/utils/type-guards.ts","../src/core/tracking.ts","../src/core/base.ts","../src/core/scheduler.ts","../src/core/atom.ts","../src/core/computed.ts","../src/core/effect.ts","../src/core/lens.ts"],"sourcesContent":["/**\n * Internal State Flags for ReactiveNode.\n *\n * Managed as a 31-bit integer field (V8 SMI optimization).\n *\n * Bit Layout:\n * [0-7] - Shared Core (Disposed, Computed marker, etc.)\n * [8-15] - Computed States (Dirty, Recomputing, etc.)\n * [16-23] - Async Lifecycle (Idle, Pending, Resolved, Rejected)\n * [24-30] - Primitive Specific (Atom Sync, Effect Executing, etc.)\n */\nconst FLAGS = {\n // --- Shared Core (0-7) ---\n DISPOSED: 1 << 0,\n IS_COMPUTED: 1 << 1,\n\n // --- Computed Flags (8-15) ---\n DIRTY: 1 << 8,\n RECOMPUTING: 1 << 9,\n HAS_ERROR: 1 << 10,\n FORCE_COMPUTE: 1 << 11,\n\n // --- Async States (16-23) ---\n IDLE: 1 << 16,\n PENDING: 1 << 17,\n RESOLVED: 1 << 18,\n REJECTED: 1 << 19,\n\n // --- Atom Specific (24-27) ---\n ATOM_SYNC: 1 << 24,\n ATOM_NOTIFICATION_SCHEDULED: 1 << 25,\n\n // --- Effect Specific (28-30) ---\n EFFECT_EXECUTING: 1 << 28,\n} as const;\n\n/**\n * Compound Masks for fast bitwise clearing/checking.\n */\nexport const STATE_MASKS = Object.freeze({\n /** Matches all bits related to async states (Idle, Pending, Resolved, Rejected). */\n ASYNC_STATE: FLAGS.IDLE | FLAGS.PENDING | FLAGS.RESOLVED | FLAGS.REJECTED,\n /** Matches all flags that indicate a computed node is dirty or recomputing. */\n COMPUTED_DIRTY_MASK: FLAGS.DIRTY | FLAGS.RECOMPUTING | FLAGS.FORCE_COMPUTE,\n});\n\n/**\n * Async operation states for public API and high-level checks.\n */\nexport const AsyncState = Object.freeze({\n IDLE: 'idle',\n PENDING: 'pending',\n RESOLVED: 'resolved',\n REJECTED: 'rejected',\n});\n\n/**\n * Effect flags.\n */\nexport const EFFECT_STATE_FLAGS = Object.freeze({\n DISPOSED: FLAGS.DISPOSED,\n EXECUTING: FLAGS.EFFECT_EXECUTING,\n});\n\n/**\n * Computed flags.\n */\nexport const COMPUTED_STATE_FLAGS = Object.freeze({\n DISPOSED: FLAGS.DISPOSED,\n IS_COMPUTED: FLAGS.IS_COMPUTED,\n DIRTY: FLAGS.DIRTY,\n IDLE: FLAGS.IDLE,\n PENDING: FLAGS.PENDING,\n RESOLVED: FLAGS.RESOLVED,\n REJECTED: FLAGS.REJECTED,\n RECOMPUTING: FLAGS.RECOMPUTING,\n HAS_ERROR: FLAGS.HAS_ERROR,\n FORCE_COMPUTE: FLAGS.FORCE_COMPUTE,\n});\n\n/**\n * Writable Atom Flags.\n */\nexport const ATOM_STATE_FLAGS = Object.freeze({\n DISPOSED: FLAGS.DISPOSED,\n SYNC: FLAGS.ATOM_SYNC,\n NOTIFICATION_SCHEDULED: FLAGS.ATOM_NOTIFICATION_SCHEDULED,\n});\n\n/**\n * Scheduler configuration.\n */\nexport const SCHEDULER_CONFIG = Object.freeze({\n // Infinite loop protection\n MAX_EXECUTIONS_PER_SECOND: 1000,\n MAX_EXECUTIONS_PER_EFFECT: 100,\n\n // Batch processing limits to prevent blocking the main thread for too long\n MAX_EXECUTIONS_PER_FLUSH: 10000,\n MAX_FLUSH_ITERATIONS: 1000,\n MIN_FLUSH_ITERATIONS: 10,\n\n // Memory management\n BATCH_QUEUE_SHRINK_THRESHOLD: 1000,\n});\n\n/**\n * V8 Small Integer (SMI) max value.\n */\nexport const SMI_MAX = 0x3fffffff;\n\n/**\n * Debugging thresholds.\n */\nexport const DEBUG_CONFIG = Object.freeze({\n WARN_INFINITE_LOOP: true,\n EFFECT_FREQUENCY_WINDOW: 1000,\n LOOP_THRESHOLD: 100,\n});\n\n/**\n * Computed configuration.\n */\nexport const COMPUTED_CONFIG = Object.freeze({\n MAX_PROMISE_ID: SMI_MAX,\n});\n\n/**\n * Epoch sentinel values.\n */\nexport const EPOCH_CONSTANTS = Object.freeze({\n /** Uninitialized epoch marker. Used as initial value before any flush has occurred. */\n UNINITIALIZED: -1,\n /** Minimum valid epoch value after a counter reset. */\n MIN: 1,\n});\n\nlet runtimeDebug = false;\ntry {\n runtimeDebug = !!(\n (typeof globalThis !== 'undefined' &&\n (globalThis as { __ATOM_DEBUG__?: boolean }).__ATOM_DEBUG__) ||\n (typeof sessionStorage !== 'undefined' && sessionStorage.getItem('__ATOM_DEBUG__') === 'true')\n );\n} catch {}\n\n/**\n * Development environment flag.\n */\nexport const IS_DEV =\n (typeof process !== 'undefined' && process.env && process.env.NODE_ENV !== 'production') ||\n (typeof __DEV__ !== 'undefined' && !!__DEV__) ||\n // @ts-expect-error: import.meta.env is Vite-specific and may not be defined in all environments\n (typeof import.meta !== 'undefined' && import.meta.env && import.meta.env.DEV) ||\n runtimeDebug;\n\n// Fallback declarations for global environment variables\ndeclare const __DEV__: boolean;\n\nexport const EMPTY_ERROR_ARRAY: readonly Error[] = Object.freeze([]);\n","/**\n * Structured JSON representation of an AtomError.\n */\nexport interface AtomErrorJSON {\n name: string;\n message: string;\n code?: string | undefined;\n recoverable: boolean;\n stack?: string | undefined;\n cause?: unknown | undefined;\n}\n\n/**\n * Constructor type for Atom errors.\n */\nexport type AtomErrorConstructor = new (\n message: string,\n cause?: unknown,\n recoverable?: boolean,\n code?: string\n) => AtomError;\n\n/**\n * Base error class for the Atom system.\n * Designed for high performance, traceability, and cycle protection.\n */\nexport class AtomError extends Error {\n override readonly name: string = 'AtomError';\n\n constructor(\n message: string,\n public readonly cause: unknown = null,\n public readonly recoverable: boolean = true,\n public readonly code?: string\n ) {\n super(message);\n\n // Maintain a stable object shape for V8\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n }\n\n /**\n * Returns the entire error chain as an array.\n * Includes the circular node if a cycle is detected.\n */\n getChain(): Array<AtomError | Error | unknown> {\n // Fast path: no cause\n if (this.cause === null || this.cause === undefined) {\n return [this];\n }\n\n const chain: Array<AtomError | Error | unknown> = [this];\n const seen = new Set<unknown>([this]);\n let current: unknown = this.cause;\n\n while (current !== null && current !== undefined) {\n const alreadySeen = seen.has(current);\n chain.push(current);\n\n if (alreadySeen) break;\n seen.add(current);\n\n if (current instanceof AtomError) {\n current = current.cause;\n } else if (current instanceof Error && 'cause' in current) {\n current = (current as Error & { cause?: unknown }).cause;\n } else {\n break;\n }\n }\n return chain;\n }\n\n /**\n * Serializes the error to a structured object for logging.\n * Protected against circular references.\n */\n toJSON(seen: Set<unknown> = new Set()): AtomErrorJSON {\n if (seen.has(this)) {\n return {\n name: this.name,\n message: '[Circular Reference]',\n recoverable: this.recoverable,\n code: this.code,\n };\n }\n seen.add(this);\n\n let causeJson: unknown = this.cause;\n if (this.cause instanceof AtomError) {\n causeJson = this.cause.toJSON(seen);\n } else if (this.cause instanceof Error) {\n causeJson = {\n name: this.cause.name,\n message: this.cause.message,\n stack: this.cause.stack,\n cause: (this.cause as Error & { cause?: unknown }).cause,\n };\n }\n\n return {\n name: this.name,\n message: this.message,\n code: this.code,\n recoverable: this.recoverable,\n stack: this.stack,\n cause: causeJson,\n };\n }\n\n /**\n * Internal helper to format wrapped messages consistently.\n */\n static format(source: string, context: string, message: string): string {\n return `${source} (${context}): ${message}`;\n }\n}\n\n/** Thrown when a computation fails. */\nexport class ComputedError extends AtomError {\n override readonly name = 'ComputedError';\n}\n\n/** Thrown when an effect execution or cleanup fails. */\nexport class EffectError extends AtomError {\n override readonly name = 'EffectError';\n constructor(message: string, cause: unknown = null, recoverable = false, code?: string) {\n super(message, cause, recoverable, code);\n }\n}\n\n/** Thrown by the execution engine or scheduler. */\nexport class SchedulerError extends AtomError {\n override readonly name = 'SchedulerError';\n constructor(message: string, cause: unknown = null, recoverable = false, code?: string) {\n super(message, cause, recoverable, code);\n }\n}\n\n/**\n * Registry of standardized error messages.\n */\nexport const ERROR_MESSAGES = {\n // Computed Errors\n COMPUTED_MUST_BE_FUNCTION: 'Computed target must be a function',\n COMPUTED_ASYNC_PENDING_NO_DEFAULT: 'Async computation pending with no default value',\n COMPUTED_COMPUTATION_FAILED: 'Computation execution failed',\n COMPUTED_ASYNC_COMPUTATION_FAILED: 'Async computation execution failed',\n COMPUTED_CIRCULAR_DEPENDENCY: 'Circular dependency detected',\n COMPUTED_DISPOSED: 'Attempted to access disposed computed',\n\n // Atom Errors\n ATOM_SUBSCRIBER_MUST_BE_FUNCTION: 'Subscriber must be a function or Subscriber object',\n ATOM_INDIVIDUAL_SUBSCRIBER_FAILED: 'Subscriber execution failed',\n\n // Effect Errors\n EFFECT_MUST_BE_FUNCTION: 'Effect target must be a function',\n EFFECT_EXECUTION_FAILED: 'Effect execution failed',\n EFFECT_CLEANUP_FAILED: 'Effect cleanup failed',\n EFFECT_DISPOSED: 'Attempted to run disposed effect',\n\n // Scheduler Errors\n SCHEDULER_FLUSH_OVERFLOW: (max: number, dropped: number): string =>\n `Maximum flush iterations (${max}) exceeded. ${dropped} jobs dropped. Possible infinite loop.`,\n\n // System / Debug\n CALLBACK_ERROR_IN_ERROR_HANDLER: 'Exception encountered in onError handler',\n EFFECT_FREQUENCY_LIMIT_EXCEEDED:\n 'Effect executed too frequently within 1 second. Suspected infinite loop.',\n SCHEDULER_CALLBACK_MUST_BE_FUNCTION: 'Scheduler callback must be a function',\n SCHEDULER_END_BATCH_WITHOUT_START: 'endBatch() called without matching startBatch(). Ignoring.',\n BATCH_CALLBACK_MUST_BE_FUNCTION: 'Batch callback must be a function',\n} as const;\n\n/**\n * Wraps any value into the Atom error hierarchy, preserving the trace and context.\n *\n * @param error - The raw error or object thrown.\n * @param ErrorClass - The specific AtomError subclass to use.\n * @param context - Human-readable description of where the error occurred.\n */\nexport function wrapError(\n error: unknown,\n ErrorClass: AtomErrorConstructor,\n context: string\n): AtomError {\n // 1. AtomError (Chainable Trace)\n if (error instanceof AtomError) {\n return new ErrorClass(\n AtomError.format(error.name, context, error.message),\n error,\n error.recoverable,\n error.code\n );\n }\n\n // 2. Native Error\n if (error instanceof Error) {\n const type = error.name || error.constructor.name || 'Error';\n return new ErrorClass(AtomError.format(type, context, error.message), error);\n }\n\n // 3. Unknown Types (Raw Preservation)\n return new ErrorClass(AtomError.format('Unexpected error', context, String(error)), error);\n}\n","import { DEBUG_CONFIG, IS_DEV } from '@/constants';\nimport type { DebugConfig, DependencyId } from '@/types';\n\n/**\n * Debug symbols used to store metadata on objects without interfering with their normal properties.\n * These are exported to allow external inspection or custom debugging tools.\n */\n\n/** Symbol used to store and retrieve a human-readable name for an atom or effect. */\nexport const DEBUG_NAME = Symbol('AtomEffect.DebugName');\n/** Symbol used to store and retrieve the unique internal ID. */\nexport const DEBUG_ID = Symbol('AtomEffect.Id');\n/** Symbol used to store and retrieve the type identifier (e.g., 'atom', 'effect'). */\nexport const DEBUG_TYPE = Symbol('AtomEffect.Type');\n/** Symbol used as a sentinel value to indicate that no default value was provided. */\nexport const NO_DEFAULT_VALUE = Symbol('AtomEffect.NoDefaultValue');\n\n/** Log prefix for Atom Effect console messages. */\nconst PREFIX = '[Atom Effect]';\n\n/**\n * Optimized Debug controller implementation for development environments.\n * Provides active monitoring, logging, and inspection capabilities.\n *\n * @internal\n * @implements {DebugConfig}\n */\nclass DevDebugController implements DebugConfig {\n /** Whether debugging features are currently active. */\n public enabled = true;\n\n /** Whether to warn when a potential infinite loop is detected. */\n public warnInfiniteLoop = DEBUG_CONFIG.WARN_INFINITE_LOOP;\n\n /** Tracks the number of updates per dependency within a single execution scope. */\n private _updateCounts = new Map<DependencyId, number>();\n\n /**\n * Weakly references registered nodes to allow garbage collection while maintaining\n * a list for graph dumping.\n */\n private _nodeRegistry = new Map<DependencyId, WeakRef<object>>();\n\n /** Threshold for triggering an infinite loop warning. */\n private _threshold = DEBUG_CONFIG.LOOP_THRESHOLD;\n\n /** Prevents redundant cleanup scheduling. */\n private _cleanupScheduled = false;\n\n /**\n * Logs a warning message if the condition is met and debugging is enabled.\n *\n * @param cond - The condition to check.\n * @param msg - The message to log if the condition is true.\n */\n public warn = (cond: boolean, msg: string): void => {\n if (this.enabled && cond) console.warn(`${PREFIX} ${msg}`);\n };\n\n /**\n * Registers a node in the internal registry for tracking and graph generation.\n * Uses WeakRef to prevent memory leaks.\n *\n * @param node - The object/node to register, must have a unique DependencyId.\n */\n public registerNode = (node: object & { id: DependencyId }): void => {\n this._nodeRegistry.set(node.id, new WeakRef(node));\n };\n\n /**\n * Attaches debug metadata to a runtime object.\n *\n * @param obj - The object to attach info to.\n * @param type - The type of the node (e.g., 'atom', 'selector', 'effect').\n * @param id - The unique internal identifier.\n * @param customName - Optional user-defined name for easier identification.\n */\n public attachDebugInfo = (\n obj: object,\n type: string,\n id: DependencyId,\n customName?: string\n ): void => {\n if (!this.enabled) return;\n\n Object.defineProperties(obj, {\n [DEBUG_NAME]: { value: customName ?? `${type}_${id}`, configurable: true },\n [DEBUG_ID]: { value: id, configurable: true },\n [DEBUG_TYPE]: { value: type, configurable: true },\n });\n\n this.registerNode(obj as { id: DependencyId });\n };\n\n /**\n * Tracks an update to a dependency and checks for infinite loops.\n * Counts are automatically reset at the end of the current microtask.\n *\n * @param id - The unique identifier of the dependency being updated.\n * @param name - An optional display name for the warning message.\n */\n public trackUpdate = (id: DependencyId, name?: string): void => {\n if (!this.enabled || !this.warnInfiniteLoop) return;\n\n const counts = this._updateCounts;\n const count = (counts.get(id) ?? 0) + 1;\n\n if (count > this._threshold) {\n this.warn(\n true,\n `Infinite loop detected for ${name ?? `dependency ${id}`}. Over ${this._threshold} updates in a single execution scope.`\n );\n } else {\n counts.set(id, count);\n }\n\n if (!this._cleanupScheduled) {\n this._cleanupScheduled = true;\n // Reset counts at the end of the current microtask to prevent memory leaks\n // and false positives across different execution cycles.\n Promise.resolve().then(() => {\n this._updateCounts.clear();\n this._cleanupScheduled = false;\n });\n }\n };\n\n /**\n * Generates a snapshot of the current reactive graph.\n * Automatically prunes dead references from the registry.\n *\n * @returns An array of debug info objects for all currently alive nodes.\n */\n public dumpGraph = (): Record<string, unknown>[] => {\n const result: Record<string, unknown>[] = [];\n for (const [id, ref] of this._nodeRegistry) {\n const node = ref.deref();\n if (node) {\n result.push({\n id,\n name: this.getDebugName(node),\n type: this.getDebugType(node),\n updateCount: this._updateCounts.get(id) ?? 0,\n });\n } else {\n this._nodeRegistry.delete(id);\n this._updateCounts.delete(id);\n }\n }\n return result;\n };\n\n /**\n * Retrieves the debug name from an object if it exists.\n *\n * @param obj - the object to inspect.\n * @returns The human-readable name or undefined.\n */\n public getDebugName = (obj: object | null | undefined): string | undefined => {\n if (!obj) return undefined;\n return (obj as Record<symbol, unknown>)[DEBUG_NAME] as string | undefined;\n };\n\n /**\n * Retrieves the debug type from an object if it exists.\n *\n * @param obj - the object to inspect.\n * @returns The type identifier or undefined.\n */\n public getDebugType = (obj: object | null | undefined): string | undefined => {\n if (!obj) return undefined;\n return (obj as Record<symbol, unknown>)[DEBUG_TYPE] as string | undefined;\n };\n}\n\n/**\n * Inert implementation of the Debug controller for production environments.\n * All operations are no-ops to ensure maximum performance and minimal bundle size.\n *\n * @internal\n * @implements {DebugConfig}\n */\nconst ProdDebugController: DebugConfig = {\n enabled: false,\n warnInfiniteLoop: false,\n warn: () => {},\n registerNode: () => {},\n attachDebugInfo: () => {},\n trackUpdate: () => {},\n dumpGraph: () => [],\n getDebugName: () => undefined,\n getDebugType: () => undefined,\n};\n\n/**\n * The global debug singleton instance.\n * Automatically switches between development and production implementations\n * based on the environment configuration (IS_DEV).\n *\n * In production, this becomes a lightweight object with empty methods,\n * allowing engines to inline or ignore calls, effectively providing zero overhead.\n *\n * @public\n */\nexport const debug: DebugConfig = IS_DEV ? new DevDebugController() : ProdDebugController;\n\n/**\n * Internal counter for generating unique DependencyIds.\n * @private\n */\nlet nextId = 1;\n\n/**\n * Generates a unique, monotonically increasing integer ID.\n * Casts to DependencyId type for internal type safety.\n *\n * @returns A fresh DependencyId.\n * @public\n */\nexport const generateId = (): DependencyId => (nextId++ | 0) as DependencyId;\n","// ── SlotBuffer ──────────────────────────────────────────────────────────\n\n/**\n * A ultra-high-performance, allocation-optimized container for reactive subscribers.\n *\n * Design Philosophy:\n * 1. Inline Storage: Uses 4 object properties (_s0.._s3) to store items directly.\n * Since >90% of reactive nodes have 1-4 subscribers, this avoids array creation entirely.\n * 2. Spill-over Model: Shifts to a lazy-allocated overflow array only when necessary.\n * 3. Size Duality: Distinguishes between Physical Boundary (_count) and Logical Size (_actualCount)\n * to support fast iteration while maintaining hole-reuse capabilities.\n */\nexport class SlotBuffer<T> {\n // Direct property slots for ultra-fast access and zero allocation.\n _s0: T | null = null;\n _s1: T | null = null;\n _s2: T | null = null;\n _s3: T | null = null;\n\n // Bookkeeping fields\n /** Physical high-water mark. Indicates the highest index ever occupied + 1. */\n _count = 0;\n /** Logical element count. Number of non-null items currently in the buffer. */\n _actualCount = 0;\n /** Lazy overflow container for index >= 4. */\n _overflow: (T | null)[] | null = null;\n /** LIFO reuse-stack of freed overflow indices to maintain O(1) addition. */\n _freeIndices: number[] | null = null;\n\n // ── Internal Physical Primitives ──────────────────────────────────────\n\n /**\n * Low-level atomic write.\n * Does NOT update bookkeeping counters. Used as a building block for higher APIs.\n */\n protected _rawWrite(index: number, item: T | null): void {\n if (index < 4) {\n if (index === 0) this._s0 = item;\n else if (index === 1) this._s1 = item;\n else if (index === 2) this._s2 = item;\n else this._s3 = item;\n } else {\n if (this._overflow === null) {\n this._overflow = [];\n }\n const ov = this._overflow;\n const ovIdx = index - 4;\n // Growth-on-demand for sparse writes via setAt()\n ov[ovIdx] = item;\n }\n }\n\n /**\n * Finds the first available hole or appends to the tail.\n * Returns the assigned physical index.\n */\n protected _rawAdd(item: T): number {\n if (this._s0 === null) {\n this._s0 = item;\n return 0;\n }\n if (this._s1 === null) {\n this._s1 = item;\n return 1;\n }\n if (this._s2 === null) {\n this._s2 = item;\n return 2;\n }\n if (this._s3 === null) {\n this._s3 = item;\n return 3;\n }\n\n if (this._overflow === null) {\n this._overflow = [];\n }\n const ov = this._overflow;\n const free = this._freeIndices;\n if (free !== null && free.length > 0) {\n const idx = free.pop()!;\n ov[idx] = item;\n return idx + 4;\n }\n ov.push(item);\n return 4 + ov.length - 1;\n }\n\n /** Atomic swap of two physical slots. Essential for dependency relocation. */\n protected _rawSwap(idxA: number, idxB: number): void {\n if (idxA === idxB) return;\n const valA = this.getAt(idxA);\n const valB = this.getAt(idxB);\n this._rawWrite(idxA, valB);\n this._rawWrite(idxB, valA);\n }\n\n // ── Public API ────────────────────────────────────────────────────────\n\n /** Number of active (non-null) elements. */\n get size(): number {\n return this._actualCount;\n }\n /** Highest physical index + 1. */\n get physicalSize(): number {\n return this._count;\n }\n\n /** Retrieves item at the specified index. O(1). */\n getAt(index: number): T | null {\n if (index < 4) {\n if (index === 0) return this._s0;\n if (index === 1) return this._s1;\n if (index === 2) return this._s2;\n return this._s3;\n }\n const ov = this._overflow;\n return ov?.[index - 4] ?? null;\n }\n\n /**\n * Sets item at index.\n * Forces recalculation of logic size and high-water mark reduction on nullification.\n */\n setAt(index: number, item: T | null): void {\n const old = this.getAt(index);\n if (old === item) return;\n\n this._rawWrite(index, item);\n\n // Sync logical count (Active items tracking)\n if (old === null) this._actualCount++;\n else if (item === null) this._actualCount--;\n\n // Sync physical high-water mark (Iteration boundary tracking)\n if (item !== null && index >= this._count) {\n this._count = index + 1;\n } else if (item === null) {\n this._shrinkPhysicalSizeFrom(index);\n }\n }\n\n /** Shrinks high-water mark recursively from the tail. */\n private _shrinkPhysicalSizeFrom(index: number): void {\n if (index === this._count - 1) {\n this._count--;\n while (this._count > 0 && this.getAt(this._count - 1) == null) {\n this._count--;\n }\n }\n }\n\n /**\n * Truncates the buffer to a specific size.\n * Normalizes the high-water mark even if the current count is 0.\n */\n truncateFrom(index: number): void {\n // 1. Cleanup inline slots\n if (index <= 3) {\n if (index <= 0 && this._s0 !== null) {\n this._onItemRemoved(this._s0);\n this._s0 = null;\n this._actualCount--;\n }\n if (index <= 1 && this._s1 !== null) {\n this._onItemRemoved(this._s1);\n this._s1 = null;\n this._actualCount--;\n }\n if (index <= 2 && this._s2 !== null) {\n this._onItemRemoved(this._s2);\n this._s2 = null;\n this._actualCount--;\n }\n if (index <= 3 && this._s3 !== null) {\n this._onItemRemoved(this._s3);\n this._s3 = null;\n this._actualCount--;\n }\n }\n\n // 2. Cleanup overflow array\n const ov = this._overflow;\n if (ov !== null) {\n const ovStart = index > 4 ? index - 4 : 0;\n const len = ov.length;\n for (let i = ovStart; i < len; i++) {\n const item = ov[i];\n if (item != null) {\n this._onItemRemoved(item);\n ov[i] = null;\n this._actualCount--;\n }\n }\n if (index <= 4) {\n this._overflow = null;\n } else {\n ov.length = index - 4;\n }\n }\n\n this._count = index; // Normalize high-water mark as requested by tracking cycles.\n if (this._actualCount < 0) this._actualCount = 0;\n this._freeIndices = null; // Reset reuse pool during truncation.\n }\n\n /**\n * Internal hook for resource cleanup (e.g. unsubscriptions).\n * @internal For use in DepSlotBuffer only.\n */\n protected _onItemRemoved(_item: T): void {}\n\n /** Appends an item to the buffer. Returns assigned index. O(1). */\n add(item: T): number {\n const idx = this._rawAdd(item);\n if (idx >= this._count) this._count = idx + 1;\n this._actualCount++;\n return idx;\n }\n\n /** Removes an item by reference. O(N). */\n remove(item: T): boolean {\n // Search in priority order: inline first.\n let idx = -1;\n if (this._s0 === item) {\n idx = 0;\n } else if (this._s1 === item) {\n idx = 1;\n } else if (this._s2 === item) {\n idx = 2;\n } else if (this._s3 === item) {\n idx = 3;\n } else {\n const ov = this._overflow;\n if (ov !== null) {\n idx = ov.indexOf(item);\n if (idx !== -1) idx += 4;\n }\n }\n\n if (idx !== -1) {\n this._rawWrite(idx, null);\n this._shrinkPhysicalSizeFrom(idx);\n this._actualCount--;\n if (idx >= 4) {\n if (this._freeIndices === null) {\n this._freeIndices = [];\n }\n this._freeIndices.push(idx - 4);\n }\n return true;\n }\n return false;\n }\n\n /** O(N) presence check. */\n has(item: T): boolean {\n if (this._actualCount === 0) return false;\n if (this._s0 === item || this._s1 === item || this._s2 === item || this._s3 === item)\n return true;\n const ov = this._overflow;\n if (ov !== null) return ov.indexOf(item) !== -1;\n return false;\n }\n\n /** Optimized iteration. Fast-path triggers when buffer is dense (no holes). */\n forEach(fn: (item: T) => void): void {\n const actual = this._actualCount;\n if (actual === 0) return;\n\n if (actual === this._count) {\n if (this._s0 != null) fn(this._s0);\n if (this._s1 != null) fn(this._s1);\n if (this._s2 != null) fn(this._s2);\n if (this._s3 != null) fn(this._s3);\n const ov = this._overflow;\n if (ov !== null) {\n for (let i = 0, len = ov.length; i < len; i++) {\n const item = ov[i];\n if (item != null) fn(item);\n }\n }\n return;\n }\n\n let count = 0;\n const limit = this._count;\n for (let i = 0; i < limit; i++) {\n const item = this.getAt(i);\n if (item != null) {\n fn(item);\n if (++count >= actual) break;\n }\n }\n }\n\n /** Elimination of all holes via in-place shifting. Zero-allocation. */\n compact(): void {\n if (this._actualCount === this._count) return;\n\n let writeIdx = 0;\n const limit = this._count;\n for (let readIdx = 0; readIdx < limit; readIdx++) {\n const item = this.getAt(readIdx);\n if (item != null) {\n if (readIdx !== writeIdx) {\n this._rawWrite(writeIdx, item);\n this._rawWrite(readIdx, null);\n }\n writeIdx++;\n }\n }\n\n this._count = this._actualCount;\n if (this._overflow !== null) {\n if (writeIdx <= 4) this._overflow = null;\n else this._overflow.length = writeIdx - 4;\n }\n this._freeIndices = null;\n }\n\n /** Complete reset and memory release. */\n clear(): void {\n this._s0 = this._s1 = this._s2 = this._s3 = null;\n this._count = 0;\n this._actualCount = 0;\n this._overflow = null;\n this._freeIndices = null;\n }\n\n dispose(): void {\n this.clear();\n }\n}\n\n// ── DepSlotBuffer ───────────────────────────────────────────────────────\n\nimport type { Dependency } from '@/types';\nimport type { DependencyLink } from './tracking';\n\n/**\n * Specialized high-speed buffer for Dependency Tracking Cycles.\n *\n * DESIGN:\n * 1. Ordering: Keeps dependencies in the order of execution to minimize seeks.\n * 2. Relocation: Swaps existing links to current track index to maintain \"Dense-head\" structure.\n * 3. Map Optimization: Switches to Node->Index Map lookup once distance exceeds 32 slots.\n */\nexport class DepSlotBuffer extends SlotBuffer<DependencyLink> {\n private _map: Map<Dependency, number> | null = null;\n private readonly _SCAN_THRESHOLD = 32;\n\n hasComputeds = false;\n prepareTracking(): void {\n this.hasComputeds = false;\n }\n\n protected override _onItemRemoved(link: DependencyLink): void {\n link.unsub?.();\n }\n\n /** Synchronizes the Node->Index Map when setting entries directly. */\n override setAt(index: number, item: DependencyLink | null): void {\n const old = this.getAt(index);\n super.setAt(index, item);\n\n if (this._map !== null) {\n if (old?.unsub) this._map.delete(old.node);\n if (item?.unsub) this._map.set(item.node, index);\n }\n }\n\n /**\n * Finds and reuses a dependency from a previous cycle.\n * If found, it relocates the link to trackIndex via swapping.\n */\n claimExisting(dep: Dependency, trackIndex: number): boolean {\n const length = this._count;\n if (length <= trackIndex) return false;\n\n // 1. Optimistic direct hit check.\n const current = this.getAt(trackIndex);\n if (current && current.node === dep && current.unsub) {\n current.version = dep.version;\n return true;\n }\n\n // 2. High-volume lookup via Map once scope threshold is exceeded.\n if (this._map !== null || length - trackIndex > this._SCAN_THRESHOLD) {\n return this._claimViaMap(dep, trackIndex);\n }\n\n // 3. Sequential search for small scopes (faster than Map hashing).\n for (let i = trackIndex + 1; i < length; i++) {\n const l = this.getAt(i);\n if (l && l.node === dep && l.unsub) {\n l.version = dep.version;\n this._rawSwap(i, trackIndex);\n return true;\n }\n }\n return false;\n }\n\n private _claimViaMap(dep: Dependency, trackIndex: number): boolean {\n if (this._map === null) {\n this._map = this._initMap();\n }\n const map = this._map;\n const existingIndex = map.get(dep);\n if (existingIndex === undefined || existingIndex < trackIndex) return false;\n\n const link = this.getAt(existingIndex);\n // Safety check against external slot corruption.\n if (link == null || !link.unsub) return false;\n\n link.version = dep.version;\n\n if (existingIndex !== trackIndex) {\n const occupant = this.getAt(trackIndex);\n this._rawSwap(existingIndex, trackIndex);\n\n map.set(dep, trackIndex);\n if (occupant?.unsub) map.set(occupant.node, existingIndex);\n }\n return true;\n }\n\n private _initMap(): Map<Dependency, number> {\n const map = new Map<Dependency, number>();\n for (let i = 0; i < this._count; i++) {\n const link = this.getAt(i);\n if (link?.unsub) map.set(link.node, i);\n }\n return map;\n }\n\n /**\n * Inserts a new link at trackIdx.\n * Relocates any current occupant at trackIdx to make room.\n */\n insertNew(trackIdx: number, link: DependencyLink): void {\n const occupant = this.getAt(trackIdx);\n if (occupant !== null) {\n // Moves occupant to the first available hole to preserve its subscription.\n const newIdx = this._rawAdd(occupant);\n if (newIdx >= this._count) this._count = newIdx + 1;\n if (this._map !== null && occupant.unsub) this._map.set(occupant.node, newIdx);\n }\n\n this._rawWrite(trackIdx, link);\n if (trackIdx >= this._count) this._count = trackIdx + 1;\n\n // NET GAIN PRINCIPLE:\n // If occupant was present: occupant moved to null slot (+0) + link added (+1) = +1 total size gain.\n // If occupant was null: link added to null slot (+1) = +1 total size gain.\n this._actualCount++;\n\n if (this._map !== null && link.unsub) this._map.set(link.node, trackIdx);\n }\n\n override add(item: DependencyLink): number {\n const idx = super.add(item);\n if (this._map !== null && item.unsub) this._map.set(item.node, idx);\n return idx;\n }\n\n override remove(_item: DependencyLink): boolean {\n throw new Error('remove() prohibited');\n }\n override compact(): void {}\n\n override truncateFrom(index: number): void {\n super.truncateFrom(index);\n if (this._map !== null) {\n this._map = null; // Clear map cache to avoid memory leaks.\n }\n }\n\n disposeAll(): void {\n this.truncateFrom(0);\n this.hasComputeds = false;\n }\n}\n","/**\n * Global brand symbol for all reactive primitives.\n * Uses a bitwise mask for high-performance type identification.\n */\nexport const BRAND: unique symbol = Symbol.for('atom-effect/brand');\n\n/**\n * Bitwise flags for brand identification.\n */\nexport const BrandFlags = {\n Atom: 1 << 0,\n Writable: 1 << 1,\n Computed: 1 << 2,\n Effect: 1 << 3,\n} as const;\n","import { BRAND, BrandFlags } from '@/symbols';\nimport type { ComputedAtom, EffectObject, ReadonlyAtom, WritableAtom } from '@/types';\n\n/**\n * Internal helper to check for a brand flag on objects or functions.\n * Optimized for high-performance bitwise identification.\n */\nfunction isBranded<T>(obj: unknown, flag: number): obj is T {\n if (!obj) return false;\n const type = typeof obj;\n return (\n (type === 'object' || type === 'function') &&\n // Bitwise AND check on the consolidated BRAND symbol\n !!(((obj as Record<symbol, number>)[BRAND] ?? 0) & flag)\n );\n}\n\n/**\n * Readonly atom check.\n */\nexport function isAtom(obj: unknown): obj is ReadonlyAtom {\n return isBranded(obj, BrandFlags.Atom);\n}\n\n/**\n * Writable atom check.\n */\nexport function isWritable(obj: unknown): obj is WritableAtom {\n return isBranded(obj, BrandFlags.Writable);\n}\n\n/**\n * Computed atom check.\n */\nexport function isComputed(obj: unknown): obj is ComputedAtom {\n return isBranded(obj, BrandFlags.Computed);\n}\n\n/**\n * Effect object check.\n */\nexport function isEffect(obj: unknown): obj is EffectObject {\n return isBranded(obj, BrandFlags.Effect);\n}\n\n/**\n * Promise check.\n * Includes a fast-path for native Promises and supports duck-typed thenables.\n */\nexport function isPromise<T>(value: unknown): value is Promise<T> {\n if (value instanceof Promise) return true;\n if (!value) return false;\n const type = typeof value;\n return (\n (type === 'object' || type === 'function') &&\n typeof (value as { then?: unknown }).then === 'function'\n );\n}\n","import { IS_DEV } from '@/constants';\nimport type { Dependency, Subscriber } from '@/types';\nimport { debug } from '@/utils/debug';\nimport { isPromise } from '@/utils/type-guards';\n\n// ── Tracking Types ──────────────────────────────────────────────────────\n\n/**\n * Dependency consumer.\n * Objects implementing this can be registered as the current tracking target.\n */\nexport interface DependencySubscriber {\n /**\n * Registers a dependency to this subscriber.\n */\n addDependency(dep: Dependency): void;\n}\n\n/**\n * Executable unit.\n * Represents a reactive node or effect that can be re-run.\n */\nexport interface ExecutableSubscriber {\n execute(): void;\n}\n\n/**\n * Dependency tracker.\n * Combines dependency collection and execution capabilities.\n */\nexport interface DependencyTracker extends DependencySubscriber, ExecutableSubscriber {}\n\n/**\n * Trackable function.\n * A function that is also recognized as a dependency consumer.\n */\nexport type TrackableFunction = (() => void) & DependencySubscriber;\n\n// ── Dependency Link & Subscription ───────────────────────────────────────\n\n/**\n * Dependency graph edge.\n * Maintains the link between a subscriber and its dependency.\n */\nexport class DependencyLink {\n constructor(\n public node: Dependency,\n public version: number,\n /**\n * Unsubscribe cleanup function.\n * Default value ensures consistent V8 hidden class shape.\n */\n public unsub: (() => void) | undefined = undefined\n ) {}\n}\n\n/**\n * Subscription entry.\n * Encapsulates the notification logic for a dependency change.\n */\nexport class Subscription<T> {\n constructor(\n /**\n * Optional callback. Always initialized to maintain hidden class.\n */\n public fn: ((newValue?: T, oldValue?: T) => void) | undefined = undefined,\n /**\n * Optional subscriber. Always initialized to maintain hidden class.\n */\n public sub: Subscriber | undefined = undefined\n ) {}\n\n /**\n * Notifies the subscriber of a value change.\n *\n * @remarks\n * Execution is wrapped in `untracked` to prevent context leakage.\n */\n notify(newValue?: T, oldValue?: T): void {\n untracked(() => {\n const fn = this.fn;\n if (fn !== undefined) {\n fn(newValue, oldValue);\n }\n\n const sub = this.sub;\n if (sub !== undefined) {\n sub.execute();\n }\n });\n }\n}\n\n// ── Tracking Context ────────────────────────────────────────────────────\n\n/**\n * Tracking context implementation.\n * Manages the global stack of active dependency collectors.\n */\nclass TrackingContext {\n /** Active subscriber at the top of the stack. */\n public current: DependencySubscriber | null = null;\n\n /**\n * Executes a function within the scope of a specific subscriber.\n *\n * @param subscriber - The subscriber to collect dependencies for.\n * @param fn - The logic to execute.\n * @returns The result of `fn`.\n */\n public run<T>(subscriber: DependencySubscriber, fn: () => T): T {\n // Fast path: already in the correct context\n if (this.current === subscriber) {\n return fn();\n }\n\n const prev = this.current;\n this.current = subscriber;\n\n try {\n const result = fn();\n\n // Async detection: check if the function returned a Promise\n if (IS_DEV) {\n debug.warn(\n isPromise(result),\n 'Detected Promise returned within tracking context. ' +\n 'Dependencies accessed after \"await\" will NOT be tracked. ' +\n 'Consider using synchronous tracking before the async boundary.'\n );\n }\n\n return result;\n } finally {\n // Synchronous restoration is required for safety in multi-tasking environments\n this.current = prev;\n }\n }\n}\n\n/**\n * Global tracking context singleton.\n */\nexport const trackingContext = new TrackingContext();\n\n/**\n * Tracking context type.\n */\nexport type { TrackingContext };\n\n// ── Untracked ───────────────────────────────────────────────────────────\n\n/**\n * Executes a function without dependency tracking.\n *\n * @param fn - Function to execute.\n * @returns Result of `fn`.\n */\nexport function untracked<T>(fn: () => T): T {\n const ctx = trackingContext;\n const prev = ctx.current;\n\n // Optimized: Skip context switching if already untracked\n if (prev === null) {\n return fn();\n }\n\n ctx.current = null;\n try {\n return fn();\n } finally {\n ctx.current = prev;\n }\n}\n","import { COMPUTED_STATE_FLAGS, EPOCH_CONSTANTS, IS_DEV, SMI_MAX } from '@/constants';\nimport { AtomError, ERROR_MESSAGES, wrapError } from '@/errors';\nimport type { DependencyId, Subscriber } from '@/types';\nimport { generateId } from '@/utils/debug';\nimport { type DepSlotBuffer, SlotBuffer } from './buffers';\nimport { Subscription } from './tracking';\n\n/**\n * Unified base class for all reactive nodes (Atoms, Computeds, Effects).\n *\n * Optimized for V8 Hidden Class Monomorphism by having a single, consistent\n * object shape for all reactive logic.\n *\n * @template T - The type of value produced by this node (used for subscriptions).\n */\nexport abstract class ReactiveNode<T> {\n /** [Producer/Consumer] State flags */\n flags: number;\n /** [Producer/Consumer] Version counter */\n version: number;\n /** [Producer/Consumer] Last access epoch */\n _lastSeenEpoch: number;\n /** [Context] Scheduler epoch tag */\n _nextEpoch: number | undefined;\n /** [Debug] Unique ID for identify node in tracking maps */\n readonly id: DependencyId;\n\n /**\n * [Producer] Managed subscribers.\n */\n _slots: SlotBuffer<Subscription<T>> | null;\n\n /** [Producer] Re-entry guard for notification loop. */\n _notifying: number;\n\n /**\n * [Consumer] Managed dependencies.\n */\n _deps: DepSlotBuffer | null;\n /** [Consumer] O(1) Hot-path dependency index for rapid dirty checks. */\n _hotIndex: number;\n\n constructor() {\n this.flags = 0;\n this.version = 0;\n this._lastSeenEpoch = EPOCH_CONSTANTS.UNINITIALIZED;\n this._nextEpoch = undefined;\n this._notifying = 0;\n this._hotIndex = -1;\n this._slots = null;\n this._deps = null;\n this.id = generateId() & SMI_MAX;\n }\n\n /**\n * Whether the node has been disposed.\n * @internal\n */\n get isDisposed(): boolean {\n return (this.flags & COMPUTED_STATE_FLAGS.DISPOSED) !== 0; // Bit 0: DISPOSED\n }\n\n /**\n * Whether the node is a computed atom.\n * @internal\n */\n get isComputed(): boolean {\n return (this.flags & COMPUTED_STATE_FLAGS.IS_COMPUTED) !== 0; // Bit 1: IS_COMPUTED\n }\n\n /**\n * Whether the node currently has an error.\n * @internal\n */\n get hasError(): boolean {\n return false;\n }\n\n // ============================================================================\n // Producer Logic (Subscriber Management)\n // ============================================================================\n\n /**\n * Adds subscriber for notifications.\n */\n subscribe(listener: ((newValue?: T, oldValue?: T) => void) | Subscriber): () => void {\n const isFn = typeof listener === 'function';\n if (!isFn && (!listener || typeof (listener as Subscriber).execute !== 'function')) {\n throw wrapError(\n new TypeError('Invalid subscriber'),\n AtomError,\n ERROR_MESSAGES.ATOM_SUBSCRIBER_MUST_BE_FUNCTION\n );\n }\n\n let slots = this._slots;\n if (!slots) {\n slots = new SlotBuffer<Subscription<T>>();\n this._slots = slots;\n }\n\n // Duplicate check: Unrolled for performance + early exit\n let duplicate = false;\n if (slots._s0 != null && (isFn ? slots._s0.fn === listener : slots._s0.sub === listener)) {\n duplicate = true;\n } else if (\n slots._s1 != null &&\n (isFn ? slots._s1.fn === listener : slots._s1.sub === listener)\n ) {\n duplicate = true;\n } else if (\n slots._s2 != null &&\n (isFn ? slots._s2.fn === listener : slots._s2.sub === listener)\n ) {\n duplicate = true;\n } else if (\n slots._s3 != null &&\n (isFn ? slots._s3.fn === listener : slots._s3.sub === listener)\n ) {\n duplicate = true;\n } else {\n const ov = slots._overflow;\n if (ov != null) {\n for (let i = 0, len = ov.length; i < len; i++) {\n const s = ov[i];\n if (s != null && (isFn ? s.fn === listener : s.sub === listener)) {\n duplicate = true;\n break;\n }\n }\n }\n }\n\n if (duplicate) {\n if (IS_DEV) console.warn(`[atom-effect] Duplicate subscription ignored on node ${this.id}`);\n return () => {};\n }\n\n const link = new Subscription<T>(\n isFn ? (listener as (newValue?: T, oldValue?: T) => void) : undefined,\n !isFn ? (listener as Subscriber) : undefined\n );\n\n slots.add(link);\n return () => this._unsubscribe(link);\n }\n\n protected _unsubscribe(link: Subscription<T>): void {\n const slots = this._slots;\n if (!slots) return;\n\n slots.remove(link);\n if (this._notifying === 0) {\n slots.compact();\n }\n }\n\n /**\n * Returns current subscriber count.\n */\n subscriberCount(): number {\n const slots = this._slots;\n return slots === null ? 0 : slots.size;\n }\n\n /**\n * Notifies all subscribers about a value update.\n */\n protected _notifySubscribers(newValue: T | undefined, oldValue: T | undefined): void {\n const slots = this._slots;\n if (slots === null || slots.size === 0) return;\n\n this._notifying++;\n try {\n // 1. Inline slots: Manual unroll to avoid closure allocation\n let s = slots._s0;\n if (s != null) {\n try {\n s.notify(newValue, oldValue);\n } catch (e) {\n this._logNotifyError(e);\n }\n }\n s = slots._s1;\n if (s != null) {\n try {\n s.notify(newValue, oldValue);\n } catch (e) {\n this._logNotifyError(e);\n }\n }\n s = slots._s2;\n if (s != null) {\n try {\n s.notify(newValue, oldValue);\n } catch (e) {\n this._logNotifyError(e);\n }\n }\n s = slots._s3;\n if (s != null) {\n try {\n s.notify(newValue, oldValue);\n } catch (e) {\n this._logNotifyError(e);\n }\n }\n\n // 2. Overflow scan: Standard loop for performance\n const ov = slots._overflow;\n if (ov != null) {\n for (let i = 0, len = ov.length; i < len; i++) {\n const sub = ov[i];\n if (sub != null) {\n try {\n sub.notify(newValue, oldValue);\n } catch (e) {\n this._logNotifyError(e);\n }\n }\n }\n }\n } finally {\n if (--this._notifying === 0) {\n slots.compact();\n }\n }\n }\n\n private _logNotifyError(err: unknown): void {\n console.error(wrapError(err, AtomError, ERROR_MESSAGES.ATOM_INDIVIDUAL_SUBSCRIBER_FAILED));\n }\n\n // ============================================================================\n // Consumer Logic (Dependency Validation)\n // ============================================================================\n\n /**\n * Determines if the node is dirty by checking its dependency chain.\n * Optimized with O(1) hot-path check.\n */\n protected _isDirty(): boolean {\n const deps = this._deps;\n if (deps === null || deps.size === 0) return false;\n\n // Phase 1: Hot-path Check - O(1)\n const hotIndex = this._hotIndex;\n if (hotIndex !== -1) {\n const hotLink = deps.getAt(hotIndex);\n if (hotLink != null && hotLink.node.version !== hotLink.version) {\n return true;\n }\n }\n\n // Phase 2: Standard Validation - O(N)\n return this._deepDirtyCheck();\n }\n\n /**\n * Deeply validates dependency versions.\n */\n protected abstract _deepDirtyCheck(): boolean;\n}\n","import { IS_DEV, SCHEDULER_CONFIG, SMI_MAX } from '@/constants';\nimport { ERROR_MESSAGES, SchedulerError } from '@/errors';\n\n// ── Epoch & Version Management ──────────────────────────────────────────\n\n/**\n * Global epoch counter used for job deduplication and tracking state consistency.\n */\nlet collectorEpoch = 0;\n\n/**\n * Returns the next tracking epoch.\n * Wraps around using SMI_MAX and reserves 0 for uninitialized state.\n */\nexport function nextEpoch(): number {\n const next = (collectorEpoch + 1) & SMI_MAX;\n collectorEpoch = next === 0 ? 1 : next;\n return collectorEpoch;\n}\n\n/**\n * Returns the current global tracking epoch.\n */\nexport function currentEpoch(): number {\n return collectorEpoch;\n}\n\n/**\n * Increments a version counter within SMI range.\n * Reservations: Avoids 0 to allow it as a 'never updated' marker.\n */\nexport function nextVersion(v: number): number {\n const next = (v + 1) & SMI_MAX;\n return next === 0 ? 1 : next;\n}\n\n/** Current number of executions in the active flush cycle. */\nexport let flushExecutionCount = 0;\nlet isFlushing = false;\nlet _flushEpoch = 0;\n\n/** Returns the epoch associated with the current flush cycle. */\nexport function currentFlushEpoch(): number {\n return _flushEpoch;\n}\n\n/**\n * Starts a new flush cycle.\n * @returns true if the cycle was successfully started, false if already flushing.\n */\nexport function startFlush(): boolean {\n if (isFlushing) {\n if (IS_DEV) {\n console.warn('startFlush() called during flush - ignored');\n }\n return false;\n }\n\n isFlushing = true;\n _flushEpoch = nextEpoch();\n flushExecutionCount = 0;\n return true;\n}\n\n/** Ends the current flush cycle. */\nexport function endFlush(): void {\n isFlushing = false;\n}\n\n/**\n * Runs a function within a managed flush scope.\n * Ensures the flush state is properly incremented and cleaned up.\n *\n * @param fn - The function to execute.\n * @returns The result of the function execution.\n */\nexport function runInFlushScope<T>(fn: () => T): T | undefined {\n const started = startFlush();\n try {\n return fn();\n } finally {\n if (started) endFlush();\n }\n}\n\n/**\n * Track total execution count within a flush.\n * Throws if the count exceeds configured safety limits to prevent hung processes.\n */\nexport function incrementFlushExecutionCount(): number {\n if (!isFlushing) return 0;\n\n const count = ++flushExecutionCount;\n if (count <= SCHEDULER_CONFIG.MAX_EXECUTIONS_PER_FLUSH) {\n return count;\n }\n\n throw new Error(\n `[atom-effect] Infinite loop detected: flush execution count exceeded ${SCHEDULER_CONFIG.MAX_EXECUTIONS_PER_FLUSH}`\n );\n}\n\n/** Resets all global flush-related states to their defaults. */\nexport function resetFlushState(): void {\n _flushEpoch = 0;\n flushExecutionCount = 0;\n isFlushing = false;\n}\n\n// ── Scheduler ───────────────────────────────────────────────────────────\n\nexport interface SchedulerJobObject {\n execute(): void;\n /** Internal tracking for deduplication within the same epoch. */\n _nextEpoch?: number | undefined;\n}\n\n/** Represents a job that can be executed by the scheduler via a function interface. */\nexport interface SchedulerJobFunction {\n (): void;\n /** Internal tracking for deduplication within the same epoch. */\n _nextEpoch?: number | undefined;\n}\n\n/** Union type representing any valid schedulable task. */\nexport type SchedulerJob = SchedulerJobFunction | SchedulerJobObject;\n\n/**\n * Core Scheduler that manages asynchronous and synchronous task execution.\n *\n * Features:\n * - Double buffering for stable queue processing.\n * - Automatic job deduplication via Epoch tagging.\n * - Nested batching support with automatic coalescence.\n * - Microsecond-level scheduling via queueMicrotask.\n */\nclass Scheduler {\n /** Double buffer to allow scheduling new jobs while processing the current queue. */\n private _queueBuffer: [(SchedulerJob | undefined)[], (SchedulerJob | undefined)[]] = [[], []];\n /** Pointer to the currently active buffer for ingestion. */\n private _bufferIndex = 0;\n /** Current size of the active ingestion buffer. */\n private _size = 0;\n /** Current internal epoch for job tagging. */\n private _epoch = 0;\n\n /** Flag indicating the scheduler is currently draining a microtask loop. */\n private _isProcessing = false;\n /** Flag indicating a synchronous flush (batch end) is currently active. */\n private _isFlushingSync = false;\n\n /** Number of active nested batch contexts. */\n private _batchDepth = 0;\n /** Temporary holding area for jobs scheduled during an active batch or sync flush. */\n private _batchQueue: (SchedulerJob | undefined)[] = [];\n /** Current number of jobs in the batch holding area. */\n private _batchQueueSize = 0;\n\n /** Maximum allowed internal loop iterations before assuming an infinite loop. */\n private _maxFlushIterations: number = SCHEDULER_CONFIG.MAX_FLUSH_ITERATIONS;\n\n /** Optional callback fired when the scheduler drops jobs due to overflow. */\n onOverflow: ((droppedCount: number) => void) | null = null;\n\n private readonly _boundRunLoop = this._runLoop.bind(this);\n\n /** Returns the total number of pending jobs (active + batched). */\n get queueSize(): number {\n return this._size + this._batchQueueSize;\n }\n\n /** Returns true if the scheduler is currently within a `batch()` scope. */\n get isBatching(): boolean {\n return this._batchDepth > 0;\n }\n\n /**\n * Schedules a job for execution.\n * Jobs are deduplicated based on the current epoch; if the same job is scheduled twice\n * in the same epoch, the second call is ignored.\n *\n * @param callback - The task to be executed.\n */\n schedule(callback: SchedulerJob): void {\n if (IS_DEV) {\n if (\n typeof callback !== 'function' &&\n (!callback || typeof (callback as SchedulerJobObject).execute !== 'function')\n ) {\n throw new SchedulerError(ERROR_MESSAGES.SCHEDULER_CALLBACK_MUST_BE_FUNCTION);\n }\n }\n\n const epoch = this._epoch;\n if (callback._nextEpoch === epoch) return;\n callback._nextEpoch = epoch;\n\n // If batching or sync flushing, move to batch queue to ensure order and coalescence.\n if (this._batchDepth > 0 || this._isFlushingSync) {\n this._batchQueue[this._batchQueueSize++] = callback;\n return;\n }\n\n const buffer = this._queueBuffer[this._bufferIndex]!;\n buffer[this._size++] = callback;\n\n if (!this._isProcessing) {\n this._flush();\n }\n }\n\n /** Initiates an asynchronous flush via microtask. */\n private _flush(): void {\n if (this._isProcessing || this._size === 0) return;\n this._isProcessing = true;\n queueMicrotask(this._boundRunLoop);\n }\n\n /** Internal microtask execution loop. */\n private _runLoop(): void {\n try {\n if (this._size === 0 && this._batchQueueSize === 0) return;\n\n const started = startFlush();\n this._drainQueue();\n if (started) endFlush();\n } finally {\n this._isProcessing = false;\n }\n }\n\n /** Internal synchronous flush typically triggered at the end of a batch. */\n _flushSync(): void {\n if (this._size === 0 && this._batchQueueSize === 0) return;\n\n const prev = this._isFlushingSync;\n this._isFlushingSync = true;\n const started = startFlush();\n try {\n this._mergeBatchQueue();\n this._drainQueue();\n } finally {\n this._isFlushingSync = prev;\n if (started) endFlush();\n }\n }\n\n /**\n * Merges the temporal batch queue into the main active buffer.\n * Increments the epoch to allow previously executed jobs to be re-scheduled if needed.\n */\n private _mergeBatchQueue(): void {\n const queueSize = this._batchQueueSize;\n if (queueSize === 0) return;\n\n this._epoch = (this._epoch + 1) | 0;\n const epoch = this._epoch;\n const bQueue = this._batchQueue;\n const targetBuffer = this._queueBuffer[this._bufferIndex]!;\n let currentSize = this._size;\n\n for (let i = 0; i < queueSize; i++) {\n const job = bQueue[i]!;\n if (job._nextEpoch !== epoch) {\n job._nextEpoch = epoch;\n targetBuffer[currentSize++] = job;\n }\n bQueue[i] = undefined; // Immediate GC hint\n }\n\n this._size = currentSize;\n this._batchQueueSize = 0;\n // Shrink array if it grew significantly, otherwise keep capacity to avoid re-allocs.\n if (bQueue.length > SCHEDULER_CONFIG.BATCH_QUEUE_SHRINK_THRESHOLD) bQueue.length = 0;\n }\n\n /**\n * Continuous loop that drains both main and batch queues.\n * Processes until all queues are empty or max iterations reached.\n */\n private _drainQueue(): void {\n let iterations = 0;\n while (this._size > 0 || this._batchQueueSize > 0) {\n if (++iterations > this._maxFlushIterations) {\n this._handleFlushOverflow();\n return;\n }\n\n if (this._batchQueueSize > 0) this._mergeBatchQueue();\n if (this._size > 0) this._processQueue();\n }\n }\n\n /** Executes all jobs currently in the primary buffer and swaps buffers. */\n private _processQueue(): void {\n const idx = this._bufferIndex;\n const jobs = this._queueBuffer[idx]!;\n const count = this._size;\n\n // Buffer swapping: ingestion now happens in the previously dormant buffer.\n this._bufferIndex = idx ^ 1;\n this._size = 0;\n this._epoch = (this._epoch + 1) | 0;\n\n for (let i = 0; i < count; i++) {\n const job = jobs[i]!;\n jobs[i] = undefined; // Avoid memory leaks by clearing references immediately.\n try {\n if (typeof job === 'function') {\n job();\n } else {\n job.execute();\n }\n } catch (e) {\n console.error(new SchedulerError('Error occurred during scheduler execution', e as Error));\n }\n }\n }\n\n /** Resets the scheduler state on infinite loop detection and notifies via onOverflow. */\n private _handleFlushOverflow(): void {\n const droppedCount = this._size + this._batchQueueSize;\n console.error(\n new SchedulerError(\n ERROR_MESSAGES.SCHEDULER_FLUSH_OVERFLOW(this._maxFlushIterations, droppedCount)\n )\n );\n\n this._size = 0;\n this._queueBuffer[0]!.length = 0;\n this._queueBuffer[1]!.length = 0;\n this._batchQueueSize = 0;\n this._batchQueue.length = 0;\n\n const onOverflow = this.onOverflow;\n if (onOverflow) {\n try {\n onOverflow(droppedCount);\n } catch {}\n }\n }\n\n /** Enters a new batching depth. */\n startBatch(): void {\n this._batchDepth++;\n }\n\n /**\n * Decrements batching depth. If depth reaches 0, triggers a synchronous flush\n * to apply all coherent updates collected during the batch.\n */\n endBatch(): void {\n if (this._batchDepth === 0) {\n if (IS_DEV) console.warn(ERROR_MESSAGES.SCHEDULER_END_BATCH_WITHOUT_START);\n return;\n }\n\n if (--this._batchDepth === 0) {\n if (!this._isFlushingSync) {\n this._flushSync();\n }\n }\n }\n\n /** Configures the maximum safety iterations for the flush loop. */\n setMaxFlushIterations(max: number): void {\n if (max < SCHEDULER_CONFIG.MIN_FLUSH_ITERATIONS)\n throw new SchedulerError(\n `Max iterations must be at least ${SCHEDULER_CONFIG.MIN_FLUSH_ITERATIONS}`\n );\n this._maxFlushIterations = max;\n }\n}\n\n/** Global scheduler instance. */\nexport const scheduler = new Scheduler();\n\n/**\n * Groups multiple state updates into a single batch, delaying effects and computations\n * until the batch is closed.\n *\n * @param fn - The function containing state updates.\n * @returns The result of the function execution.\n * @throws {TypeError} If fn is not a function.\n */\nexport function batch<T>(fn: () => T): T {\n if (IS_DEV && typeof fn !== 'function') {\n throw new TypeError(ERROR_MESSAGES.BATCH_CALLBACK_MUST_BE_FUNCTION);\n }\n\n scheduler.startBatch();\n try {\n return fn();\n } finally {\n scheduler.endBatch();\n }\n}\n","import { ATOM_STATE_FLAGS } from '@/constants';\nimport { ReactiveNode } from '@/core/base';\nimport { BRAND, BrandFlags } from '@/symbols';\nimport type { AtomOptions, WritableAtom } from '@/types';\nimport { debug } from '@/utils/debug';\nimport { nextVersion, scheduler } from './scheduler';\nimport { trackingContext } from './tracking';\n\n/**\n * Internal {@link WritableAtom} implementation.\n */\nclass AtomImpl<T> extends ReactiveNode<T> implements WritableAtom<T> {\n private _value: T;\n /** Old value for notifications */\n private _pendingOldValue: T | undefined;\n /** Equality comparator */\n private _equal: (a: T, b: T) => boolean;\n\n /** @internal */\n readonly [BRAND] = BrandFlags.Atom | BrandFlags.Writable;\n\n constructor(initialValue: T, options: AtomOptions<T>) {\n super();\n this._value = initialValue;\n this._equal = options.equal ?? Object.is;\n\n if (options.sync) {\n this.flags |= ATOM_STATE_FLAGS.SYNC;\n }\n\n debug.attachDebugInfo(this, 'atom', this.id, options.name);\n }\n\n /** @internal */\n get isNotificationScheduled(): boolean {\n return (this.flags & ATOM_STATE_FLAGS.NOTIFICATION_SCHEDULED) !== 0;\n }\n\n /** @internal */\n get isSync(): boolean {\n return (this.flags & ATOM_STATE_FLAGS.SYNC) !== 0;\n }\n\n get value(): T {\n const ctx = trackingContext.current;\n if (ctx != null) {\n ctx.addDependency(this);\n }\n return this._value;\n }\n\n set value(newValue: T) {\n const oldValue = this._value;\n if (this._equal(oldValue, newValue)) return;\n\n this._value = newValue;\n this.version = nextVersion(this.version);\n debug.trackUpdate(this.id, debug.getDebugName(this));\n\n // 1. Double check: schedule pending or no slots\n if ((this.flags & ATOM_STATE_FLAGS.NOTIFICATION_SCHEDULED) !== 0) return;\n\n const slots = this._slots;\n if (slots == null || slots.size === 0) return;\n\n this._pendingOldValue = oldValue;\n this.flags |= ATOM_STATE_FLAGS.NOTIFICATION_SCHEDULED;\n\n // 2. Schedule or flush (inline bitwise)\n if ((this.flags & ATOM_STATE_FLAGS.SYNC) !== 0 && !scheduler.isBatching) {\n // If not already notifying, start the flush loop.\n // If already notifying, the existing loop will pick up the new flag.\n if (this._notifying === 0) {\n this._flushNotifications();\n }\n } else {\n scheduler.schedule(this);\n }\n }\n\n /**\n * Executes scheduled notification.\n * @internal\n */\n execute(): void {\n this._flushNotifications();\n }\n\n /**\n * Triggers subscribers.\n */\n private _flushNotifications(): void {\n const SCHED_BIT = ATOM_STATE_FLAGS.NOTIFICATION_SCHEDULED;\n const DISP_BIT = ATOM_STATE_FLAGS.DISPOSED;\n const SYNC_BIT = ATOM_STATE_FLAGS.SYNC;\n\n // Loop to handle re-entrant sync updates in breadth-first order\n while ((this.flags & (SCHED_BIT | DISP_BIT)) === SCHED_BIT) {\n const oldValue = this._pendingOldValue as T;\n this._pendingOldValue = undefined;\n this.flags &= ~SCHED_BIT;\n\n // Net-zero check: if value returned to original during batching, skip notification\n if (!this._equal(this._value, oldValue)) {\n this._notifySubscribers(this._value, oldValue);\n }\n\n // Only continue looping if we are in sync mode and not batching.\n // For async mode, the scheduler handles subsequent executions.\n if ((this.flags & SYNC_BIT) === 0 || scheduler.isBatching) {\n break;\n }\n }\n }\n\n peek(): T {\n return this._value;\n }\n\n dispose(): void {\n const flags = this.flags;\n if ((flags & ATOM_STATE_FLAGS.DISPOSED) !== 0) return;\n\n this._slots?.clear();\n this.flags = flags | ATOM_STATE_FLAGS.DISPOSED;\n // Release references\n this._value = undefined as T;\n this._pendingOldValue = undefined;\n this._equal = Object.is; // Reset to default\n }\n\n protected override _deepDirtyCheck(): boolean {\n return false;\n }\n\n [Symbol.dispose](): void {\n this.dispose();\n }\n}\n\n/**\n * Creates a reactive atom holding mutable state.\n *\n * @param initialValue - The initial value of the atom.\n * @param options - Configuration options (sync: boolean).\n */\nexport function atom<T>(initialValue: T, options: AtomOptions = {}): WritableAtom<T> {\n return new AtomImpl(initialValue, options);\n}\n","import {\n AsyncState,\n COMPUTED_CONFIG,\n COMPUTED_STATE_FLAGS,\n EMPTY_ERROR_ARRAY,\n EPOCH_CONSTANTS,\n IS_DEV,\n} from '@/constants';\nimport { ReactiveNode } from '@/core/base';\nimport { ComputedError, ERROR_MESSAGES, wrapError } from '@/errors';\nimport { BRAND, BrandFlags } from '@/symbols';\nimport type {\n AsyncStateType,\n ComputedAtom,\n ComputedOptions,\n Dependency,\n Subscriber,\n} from '@/types';\nimport { debug, NO_DEFAULT_VALUE } from '@/utils/debug';\nimport { isPromise } from '@/utils/type-guards';\nimport { DepSlotBuffer } from './buffers';\nimport { nextEpoch, nextVersion } from './scheduler';\nimport { DependencyLink, trackingContext, untracked } from './tracking';\n\nconst {\n IDLE,\n DIRTY,\n PENDING,\n RESOLVED,\n REJECTED,\n HAS_ERROR,\n RECOMPUTING,\n DISPOSED,\n IS_COMPUTED,\n FORCE_COMPUTE,\n} = COMPUTED_STATE_FLAGS;\n\n/**\n * Computed atom implementation.\n */\nclass ComputedAtomImpl<T> extends ReactiveNode<T> implements ComputedAtom<T>, Subscriber {\n /** @internal */\n readonly [BRAND] = BrandFlags.Atom | BrandFlags.Computed;\n\n private _value: T;\n private _error: Error | null = null;\n /** Promise tracking ID */\n private _promiseId = 0;\n\n private readonly _equal: (a: T, b: T) => boolean;\n private readonly _fn: () => T | Promise<T>;\n private readonly _defaultValue: T;\n private readonly _onError: ((error: Error) => void) | null;\n\n /** Initialized in constructor. Unified node property. */\n _deps = new DepSlotBuffer();\n\n // Async state\n\n // Dependency collection state\n private _trackEpoch: number = EPOCH_CONSTANTS.UNINITIALIZED;\n private _trackCount = 0;\n\n constructor(fn: () => T | Promise<T>, options: ComputedOptions<T> = {}) {\n if (typeof fn !== 'function') throw new ComputedError(ERROR_MESSAGES.COMPUTED_MUST_BE_FUNCTION);\n super();\n\n this._value = undefined as T;\n // Start dirty so first access triggers computation\n this.flags = IS_COMPUTED | DIRTY | IDLE;\n this._equal = options.equal ?? Object.is;\n this._fn = fn;\n this._defaultValue = 'defaultValue' in options ? options.defaultValue : (NO_DEFAULT_VALUE as T);\n this._onError = options.onError ?? null;\n\n debug.attachDebugInfo(this, 'computed', this.id, options.name);\n\n // Eager evaluation if not lazy\n if (options.lazy === false) {\n try {\n this._recompute();\n } catch {\n /* _handleError already stored error and called onError */\n }\n }\n }\n\n /** @internal */\n get isDirty(): boolean {\n return (this.flags & DIRTY) !== 0;\n }\n\n /** @internal */\n get isRejected(): boolean {\n return (this.flags & REJECTED) !== 0;\n }\n\n /** @internal */\n get isRecomputing(): boolean {\n return (this.flags & RECOMPUTING) !== 0;\n }\n\n private get _hasErrorInternal(): boolean {\n return (this.flags & HAS_ERROR) !== 0;\n }\n\n private _track(): void {\n trackingContext.current?.addDependency(this);\n }\n\n get value(): T {\n const ctx = trackingContext.current;\n if (ctx != null) ctx.addDependency(this);\n\n let flags = this.flags;\n // 1. Fast path: Stable and Resolved\n if ((flags & (RESOLVED | DIRTY | IDLE)) === RESOLVED) {\n return this._value;\n }\n\n // 2. Exception paths\n if ((flags & DISPOSED) !== 0) throw new ComputedError(ERROR_MESSAGES.COMPUTED_DISPOSED);\n\n if ((flags & RECOMPUTING) !== 0) {\n const def = this._defaultValue;\n if (def !== (NO_DEFAULT_VALUE as T)) return def;\n throw new ComputedError(ERROR_MESSAGES.COMPUTED_CIRCULAR_DEPENDENCY);\n }\n\n // 3. Evaluation path\n if ((flags & (DIRTY | IDLE)) !== 0) {\n const deps = this._deps;\n if (\n (flags & IDLE) === 0 &&\n (flags & FORCE_COMPUTE) === 0 &&\n deps.size > 0 &&\n !this._isDirty()\n ) {\n flags = this.flags &= ~DIRTY;\n } else {\n this._recompute();\n flags = this.flags;\n }\n if ((flags & RESOLVED) !== 0) return this._value;\n }\n\n // 4. Async/Error handling\n const def = this._defaultValue;\n const hasDefault = def !== (NO_DEFAULT_VALUE as T);\n\n if ((flags & PENDING) !== 0) {\n if (hasDefault) return def;\n throw new ComputedError(ERROR_MESSAGES.COMPUTED_ASYNC_PENDING_NO_DEFAULT);\n }\n\n if ((flags & REJECTED) !== 0) {\n if (hasDefault) return def;\n throw this._error;\n }\n\n return this._value;\n }\n\n peek(): T {\n return this._value;\n }\n\n get state(): AsyncStateType {\n const ctx = trackingContext.current;\n if (ctx != null) ctx.addDependency(this);\n const flags = this.flags;\n if ((flags & RESOLVED) !== 0) return AsyncState.RESOLVED;\n if ((flags & PENDING) !== 0) return AsyncState.PENDING;\n if ((flags & REJECTED) !== 0) return AsyncState.REJECTED;\n return AsyncState.IDLE;\n }\n\n get hasError(): boolean {\n const ctx = trackingContext.current;\n if (ctx != null) ctx.addDependency(this);\n\n const flags = this.flags;\n // Inlined checks for REJECTED | HAS_ERROR\n if ((flags & (REJECTED | HAS_ERROR)) !== 0) return true;\n\n const deps = this._deps;\n if (!deps.hasComputeds) return false;\n\n // Isolate tracking to prevent bubbling dependencies from polluting the current context\n return untracked(() => {\n const size = deps.size;\n for (let i = 0; i < size; i++) {\n const link = deps.getAt(i);\n if (link?.node.hasError) return true;\n }\n return false;\n });\n }\n\n get isValid(): boolean {\n return !this.hasError;\n }\n\n get errors(): readonly Error[] {\n const ctx = trackingContext.current;\n if (ctx != null) ctx.addDependency(this);\n\n const selfErr = this._error;\n const deps = this._deps;\n\n // Early exit: no computed dependencies means no bubbling errors\n if (!deps.hasComputeds) {\n if (selfErr == null) return EMPTY_ERROR_ARRAY;\n return Object.freeze([selfErr]);\n }\n\n const collected: Error[] = [];\n if (selfErr != null) collected.push(selfErr);\n\n // Isolate tracking and accumulate errors recursively\n untracked(() => {\n const size = deps.size;\n for (let i = 0; i < size; i++) {\n const link = deps.getAt(i);\n const depNode = link?.node;\n if (depNode != null && (depNode.flags & IS_COMPUTED) !== 0) {\n this._accumulateErrors(depNode as unknown as ComputedAtomImpl<unknown>, collected);\n }\n }\n });\n\n return collected.length === 0 ? EMPTY_ERROR_ARRAY : Object.freeze(collected);\n }\n\n /**\n * Internal helper to collect unique errors from a computed dependency.\n */\n private _accumulateErrors(dep: ComputedAtomImpl<unknown>, collected: Error[]): void {\n const err = dep._error;\n if (err != null && !collected.includes(err)) {\n collected.push(err);\n }\n\n const deps = dep._deps;\n if (!deps.hasComputeds) return;\n\n const size = deps.size;\n for (let i = 0; i < size; i++) {\n const link = deps.getAt(i);\n const node = link?.node;\n if (node != null && (node.flags & IS_COMPUTED) !== 0) {\n this._accumulateErrors(node as unknown as ComputedAtomImpl<unknown>, collected);\n }\n }\n }\n\n get lastError(): Error | null {\n const ctx = trackingContext.current;\n if (ctx != null) ctx.addDependency(this);\n return this._error;\n }\n\n get isPending(): boolean {\n const ctx = trackingContext.current;\n if (ctx != null) ctx.addDependency(this);\n return (this.flags & PENDING) !== 0;\n }\n\n get isResolved(): boolean {\n const ctx = trackingContext.current;\n if (ctx != null) ctx.addDependency(this);\n return (this.flags & RESOLVED) !== 0;\n }\n\n invalidate(): void {\n this.flags |= FORCE_COMPUTE;\n this._markDirty();\n }\n\n dispose(): void {\n const flags = this.flags;\n if ((flags & DISPOSED) !== 0) return;\n\n this._deps.disposeAll();\n\n if (this._slots != null) {\n this._slots.clear();\n }\n this.flags = DISPOSED | DIRTY | IDLE;\n\n // Release Memory\n this._error = null;\n this._value = undefined as T;\n this._hotIndex = -1;\n }\n\n [Symbol.dispose](): void {\n this.dispose();\n }\n\n addDependency(dep: Dependency): void {\n const trackEpoch = this._trackEpoch;\n if (dep._lastSeenEpoch === trackEpoch) return;\n dep._lastSeenEpoch = trackEpoch;\n\n const trackIndex = this._trackCount++;\n const deps = this._deps;\n const existing = deps.getAt(trackIndex);\n\n // 1. Stable Path: dependency index remains the same\n if (existing != null && existing.node === dep) {\n existing.version = dep.version;\n }\n // 2. Diverged Path: lookup or insert\n else if (deps.claimExisting(dep, trackIndex)) {\n // Version updated inside claimExisting\n }\n // 3. New dependency\n else {\n const link = new DependencyLink(dep, dep.version, dep.subscribe(this));\n deps.insertNew(trackIndex, link);\n }\n\n if ((dep.flags & IS_COMPUTED) !== 0) {\n deps.hasComputeds = true;\n }\n }\n\n private _recompute(): void {\n if (this.isRecomputing) return;\n this.flags = (this.flags | RECOMPUTING) & ~FORCE_COMPUTE;\n\n this._trackEpoch = nextEpoch();\n this._trackCount = 0;\n this._deps.prepareTracking();\n this._hotIndex = -1;\n\n let committed = false;\n try {\n // Execute function\n const result = trackingContext.run(this, this._fn);\n\n // Clean up any remaining trailing dependencies\n this._deps.truncateFrom(this._trackCount);\n\n committed = true;\n\n // Handle Result\n if (isPromise(result)) {\n this._handleAsyncComputation(result);\n } else {\n this._finalizeResolution(result);\n }\n } catch (e) {\n // Commit dependencies on error gracefully\n if (!committed) {\n try {\n this._deps.truncateFrom(this._trackCount);\n } catch (commitErr) {\n if (IS_DEV) {\n console.warn('[atom-effect] _commitDeps failed during error recovery:', commitErr);\n }\n }\n }\n this._handleError(e as Error, ERROR_MESSAGES.COMPUTED_COMPUTATION_FAILED, true);\n } finally {\n // Reset transient state\n this._trackEpoch = EPOCH_CONSTANTS.UNINITIALIZED;\n this._trackCount = 0;\n this.flags &= ~RECOMPUTING;\n }\n }\n\n private _handleAsyncComputation(promise: Promise<T>): void {\n // Set pending, clear idle/dirty/resolved/rejected\n this.flags = (this.flags | PENDING) & ~(IDLE | DIRTY | RESOLVED | REJECTED);\n // Notify pending\n this._notifySubscribers(undefined, undefined);\n\n // Invalidate old promises\n this._promiseId = (this._promiseId + 1) % COMPUTED_CONFIG.MAX_PROMISE_ID;\n const promiseId = this._promiseId;\n\n promise.then(\n (res) => {\n if (promiseId !== this._promiseId) return; // Stale\n\n if (this._isDirty()) {\n return this._markDirty(); // Retry\n }\n\n this._finalizeResolution(res);\n this._notifySubscribers(res, undefined);\n },\n (err) =>\n promiseId === this._promiseId &&\n this._handleError(err, ERROR_MESSAGES.COMPUTED_ASYNC_COMPUTATION_FAILED)\n );\n }\n\n private _handleError(err: unknown, msg: string, throwErr = false): void {\n const error = wrapError(err, ComputedError, msg);\n\n // Always bump version if state changed to rejected or the error instance is different.\n // This ensures bubbling and tracking systems are aware of the transition or change.\n if (!this.isRejected || this._error !== error) {\n this.version = nextVersion(this.version);\n }\n\n this._error = error;\n // Set rejected + has_error, clear idle/dirty/pending/resolved\n this.flags = (this.flags & ~(IDLE | DIRTY | PENDING | RESOLVED)) | REJECTED | HAS_ERROR;\n\n if (this._onError) {\n try {\n this._onError(error);\n } catch (e) {\n console.error(ERROR_MESSAGES.CALLBACK_ERROR_IN_ERROR_HANDLER, e);\n }\n }\n\n // Must notify subscribers BEFORE throwing, otherwise the reactivity chain is broken\n // for synchronous failures.\n this._notifySubscribers(undefined, undefined);\n\n if (throwErr) throw error;\n }\n\n private _finalizeResolution(value: T): void {\n const flags = this.flags;\n // Only bump version if value actually changed or first resolve\n if ((flags & RESOLVED) === 0 || !this._equal(this._value, value)) {\n this.version = nextVersion(this.version);\n }\n\n this._value = value;\n this._error = null;\n // Set resolved, clear idle/dirty/pending/rejected/has_error\n this.flags = (flags | RESOLVED) & ~(IDLE | DIRTY | PENDING | REJECTED | HAS_ERROR);\n }\n\n execute(): void {\n // Subscriber implementation\n this._markDirty();\n }\n\n /** @internal */\n _markDirty(): void {\n const flags = this.flags;\n if ((flags & (RECOMPUTING | DIRTY)) !== 0) return;\n this.flags = flags | DIRTY;\n debug.trackUpdate(this.id, debug.getDebugName(this));\n this._notifySubscribers(undefined, undefined);\n }\n\n /**\n * Deep dirty check for computations.\n */\n protected override _deepDirtyCheck(): boolean {\n const deps = this._deps;\n return untracked(() => {\n const size = deps.size;\n for (let i = 0; i < size; i++) {\n const link = deps.getAt(i);\n if (link == null) continue;\n\n const dep = link.node;\n // Inlined isComputed check\n if ((dep.flags & IS_COMPUTED) !== 0) {\n try {\n // Force computed to re-evaluate so version reflects latest state\n void (dep as { value: unknown }).value;\n } catch {\n if (IS_DEV)\n console.warn(`[atom-effect] Dependency #${dep.id} threw during dirty check`);\n }\n }\n\n if (dep.version !== link.version) {\n this._hotIndex = i;\n return true;\n }\n }\n\n this._hotIndex = -1;\n return false;\n });\n }\n}\n\n/**\n * Creates a computed value.\n * @param fn - Computation function\n * @param options - Options object\n */\nexport function computed<T>(fn: () => T, options?: ComputedOptions<T>): ComputedAtom<T>;\nexport function computed<T>(\n fn: () => Promise<T>,\n options: ComputedOptions<T> & { defaultValue: T }\n): ComputedAtom<T>;\nexport function computed<T>(\n fn: () => T | Promise<T>,\n options: ComputedOptions<T> = {}\n): ComputedAtom<T> {\n return new ComputedAtomImpl(fn, options);\n}\n","import {\n DEBUG_CONFIG,\n EFFECT_STATE_FLAGS,\n EPOCH_CONSTANTS,\n IS_DEV,\n SCHEDULER_CONFIG,\n} from '@/constants';\nimport { ReactiveNode } from '@/core/base';\nimport { EffectError, ERROR_MESSAGES, wrapError } from '@/errors';\nimport { BRAND, BrandFlags } from '@/symbols';\nimport type { Dependency, EffectFunction, EffectObject, EffectOptions } from '@/types';\nimport { debug } from '@/utils/debug';\nimport { isPromise } from '@/utils/type-guards';\nimport { DepSlotBuffer } from './buffers';\nimport {\n currentFlushEpoch,\n flushExecutionCount,\n incrementFlushExecutionCount,\n nextEpoch,\n scheduler,\n} from './scheduler';\nimport { DependencyLink, type DependencyTracker, trackingContext } from './tracking';\n\n/**\n * Effect implementation.\n */\nclass EffectImpl extends ReactiveNode<void> implements EffectObject, DependencyTracker {\n /** @internal */\n readonly [BRAND] = BrandFlags.Effect;\n\n private _cleanup: (() => void) | null = null;\n /** Initialized in constructor to maintain God Class object shape */\n _deps = new DepSlotBuffer();\n\n /** Pre-allocated notify callback shared by all subscriptions */\n private readonly _notifyCallback: () => void;\n\n private readonly _onError: ((error: unknown) => void) | null;\n\n // Cycle detection\n private _currentEpoch: number = EPOCH_CONSTANTS.UNINITIALIZED;\n private _lastFlushEpoch: number = EPOCH_CONSTANTS.UNINITIALIZED;\n private _executionsInEpoch: number;\n\n private readonly _fn: EffectFunction;\n private readonly _sync: boolean;\n private readonly _maxExecutions: number;\n private readonly _maxExecutionsPerFlush: number;\n // Frequency tracking (Dev)\n private _executionCount: number;\n private _windowStart: number;\n private _windowCount: number;\n private _execId: number;\n private _trackCount: number;\n\n constructor(fn: EffectFunction, options: EffectOptions = {}) {\n super();\n this._fn = fn;\n this._onError = options.onError ?? null;\n this._sync = options.sync ?? false;\n this._maxExecutions =\n options.maxExecutionsPerSecond ?? SCHEDULER_CONFIG.MAX_EXECUTIONS_PER_SECOND;\n this._maxExecutionsPerFlush =\n options.maxExecutionsPerFlush ?? SCHEDULER_CONFIG.MAX_EXECUTIONS_PER_EFFECT;\n\n this._executionsInEpoch = 0;\n this._executionCount = 0;\n this._windowStart = 0;\n this._windowCount = 0;\n this._execId = 0;\n this._trackCount = 0;\n\n // Pre-allocate callbacks once — eliminates per-dependency closure allocation\n if (this._sync) {\n this._notifyCallback = () => this.execute();\n } else {\n this._notifyCallback = () => scheduler.schedule(this);\n }\n\n debug.attachDebugInfo(this, 'effect', this.id, options.name);\n }\n\n public run(): void {\n if (this.isDisposed) {\n throw new EffectError(ERROR_MESSAGES.EFFECT_DISPOSED);\n }\n this.execute(true);\n }\n\n public dispose(): void {\n if (this.isDisposed) return;\n this.flags |= EFFECT_STATE_FLAGS.DISPOSED;\n\n this._execCleanup();\n this._deps?.disposeAll();\n }\n\n [Symbol.dispose](): void {\n this.dispose();\n }\n\n public addDependency(dep: Dependency): void {\n const flags = this.flags;\n if ((flags & EFFECT_STATE_FLAGS.EXECUTING) === 0) return;\n\n const startEpoch = this._currentEpoch;\n if (dep._lastSeenEpoch === startEpoch) return;\n dep._lastSeenEpoch = startEpoch;\n\n const trackIndex = this._trackCount++;\n const deps = this._deps;\n\n // Optimized: Direct access to inline slots for the hottest 4 dependencies\n let existing: DependencyLink | null;\n switch (trackIndex) {\n case 0:\n existing = deps._s0;\n break;\n case 1:\n existing = deps._s1;\n break;\n case 2:\n existing = deps._s2;\n break;\n case 3:\n existing = deps._s3;\n break;\n default:\n existing = deps.getAt(trackIndex);\n }\n\n // 1. Stable Path: dependency index remains the same\n if (existing != null && existing.node === dep) {\n existing.version = dep.version;\n }\n // 2. Diverged Path: lookup or insert\n else if (deps.claimExisting(dep, trackIndex)) {\n // Version updated in claimExisting\n }\n // 3. New dependency\n else {\n this._insertNewDependency(dep, trackIndex);\n }\n\n if (dep.isComputed) {\n deps.hasComputeds = true;\n }\n }\n\n private _insertNewDependency(dep: Dependency, trackIndex: number): void {\n let link: DependencyLink;\n try {\n const unsubscribe = dep.subscribe(this._notifyCallback);\n link = new DependencyLink(dep, dep.version, unsubscribe);\n } catch (error) {\n const wrapped = wrapError(error, EffectError, ERROR_MESSAGES.EFFECT_EXECUTION_FAILED);\n console.error(wrapped);\n if (this._onError) {\n try {\n this._onError(wrapped);\n } catch {}\n }\n link = new DependencyLink(dep, dep.version, undefined);\n }\n\n this._deps!.insertNew(trackIndex, link);\n }\n\n /**\n * Executes effect with tracking.\n */\n public execute(force = false): void {\n const flags = this.flags;\n // Guard: Combined bitwise check for efficiency\n if ((flags & (EFFECT_STATE_FLAGS.DISPOSED | EFFECT_STATE_FLAGS.EXECUTING)) !== 0) return;\n\n // Skip if not dirty or forced\n const deps = this._deps;\n if (!force && deps.size > 0 && !this._isDirty()) return;\n\n this._checkInfiniteLoops();\n debug.trackUpdate(this.id, debug.getDebugName(this));\n\n this.flags = flags | EFFECT_STATE_FLAGS.EXECUTING;\n this._execCleanup();\n\n this._currentEpoch = nextEpoch();\n this._trackCount = 0;\n deps.prepareTracking();\n this._hotIndex = -1;\n\n let committed = false;\n try {\n const result = trackingContext.run(this, this._fn);\n\n // Clean up any remaining trailing dependencies\n deps.truncateFrom(this._trackCount);\n\n committed = true;\n\n // Handle result\n if (isPromise(result)) {\n this._handleAsyncResult(result);\n } else {\n this._cleanup = typeof result === 'function' ? result : null;\n }\n } catch (error) {\n // Commit on error gracefully to maintain state for recovery\n if (!committed) {\n try {\n deps.truncateFrom(this._trackCount);\n } catch (commitErr) {\n if (IS_DEV) {\n console.warn('[atom-effect] _commitDeps failed during error recovery:', commitErr);\n }\n }\n }\n this._handleExecutionError(error);\n this._cleanup = null;\n } finally {\n this.flags &= ~EFFECT_STATE_FLAGS.EXECUTING;\n }\n }\n\n private _handleAsyncResult(promise: Promise<unknown>): void {\n const execId = ++this._execId;\n promise.then(\n (cleanup) => {\n // Guard against race conditions (new execution or disposal happened)\n if (execId !== this._execId || this.isDisposed) {\n if (typeof cleanup === 'function') {\n try {\n cleanup();\n } catch (e) {\n this._handleExecutionError(e, ERROR_MESSAGES.EFFECT_CLEANUP_FAILED);\n }\n }\n return;\n }\n if (typeof cleanup === 'function') this._cleanup = cleanup as () => void;\n },\n (err) => execId === this._execId && this._handleExecutionError(err)\n );\n }\n\n protected override _deepDirtyCheck(): boolean {\n const prevContext = trackingContext.current;\n trackingContext.current = null;\n const deps = this._deps!;\n\n try {\n const size = deps.size;\n for (let i = 0; i < size; i++) {\n const link = deps.getAt(i);\n if (link == null) continue;\n\n const dep = link.node;\n if (dep.isComputed) {\n this._tryPullComputed(dep);\n }\n\n if (dep.version !== link.version) {\n this._hotIndex = i;\n return true;\n }\n }\n return false;\n } finally {\n trackingContext.current = prevContext;\n }\n }\n\n private _tryPullComputed(dep: Dependency): void {\n try {\n // Force computed to re-evaluate so version reflects latest state\n void (dep as { value: unknown }).value;\n } catch {\n if (IS_DEV) {\n console.warn(`[atom-effect] Dependency #${dep.id} threw during dirty check`);\n }\n }\n }\n\n private _execCleanup(): void {\n const cleanup = this._cleanup;\n if (cleanup == null) return;\n this._cleanup = null;\n try {\n cleanup();\n } catch (error) {\n this._handleExecutionError(error, ERROR_MESSAGES.EFFECT_CLEANUP_FAILED);\n }\n }\n\n private _checkInfiniteLoops(): void {\n const epoch = currentFlushEpoch();\n if (this._lastFlushEpoch !== epoch) {\n this._lastFlushEpoch = epoch;\n this._executionsInEpoch = 0;\n }\n\n const executions = ++this._executionsInEpoch;\n if (executions > this._maxExecutionsPerFlush) this._throwInfiniteLoopError('per-effect');\n\n const globalExecutions = incrementFlushExecutionCount();\n if (globalExecutions > SCHEDULER_CONFIG.MAX_EXECUTIONS_PER_FLUSH) {\n this._throwInfiniteLoopError('global');\n }\n\n this._executionCount++;\n\n if (IS_DEV) this._checkFrequencyLimit();\n }\n\n private _checkFrequencyLimit(): void {\n if (!Number.isFinite(this._maxExecutions)) return;\n\n const now = Date.now();\n if (now - this._windowStart >= DEBUG_CONFIG.EFFECT_FREQUENCY_WINDOW) {\n this._windowStart = now;\n this._windowCount = 1;\n return;\n }\n\n if (++this._windowCount > this._maxExecutions) {\n const err = new EffectError(ERROR_MESSAGES.EFFECT_FREQUENCY_LIMIT_EXCEEDED);\n this.dispose();\n this._handleExecutionError(err);\n throw err;\n }\n }\n\n get executionCount(): number {\n return this._executionCount;\n }\n get isExecuting(): boolean {\n return (this.flags & EFFECT_STATE_FLAGS.EXECUTING) !== 0;\n }\n\n private _throwInfiniteLoopError(type: 'per-effect' | 'global'): never {\n const error = new EffectError(\n `Infinite loop detected (${type}): effect executed ${this._executionsInEpoch} times in current flush. Total executions in flush: ${flushExecutionCount}`\n );\n this.dispose();\n console.error(error);\n throw error;\n }\n\n private _handleExecutionError(\n error: unknown,\n message: string = ERROR_MESSAGES.EFFECT_EXECUTION_FAILED\n ): void {\n const errorObj = wrapError(error, EffectError, message);\n console.error(errorObj);\n if (this._onError) {\n try {\n this._onError(errorObj);\n } catch (e) {\n console.error(wrapError(e, EffectError, ERROR_MESSAGES.CALLBACK_ERROR_IN_ERROR_HANDLER));\n }\n }\n }\n}\n\n/**\n * Creates and starts an effect.\n *\n * @param fn - Effect function.\n * @param options - Configuration options.\n * @returns Effect instance.\n */\nexport function effect(fn: EffectFunction, options: EffectOptions = {}): EffectObject {\n if (typeof fn !== 'function') {\n throw new EffectError(ERROR_MESSAGES.EFFECT_MUST_BE_FUNCTION);\n }\n\n const effectInstance = new EffectImpl(fn, options);\n effectInstance.execute();\n\n return effectInstance;\n}\n","import { BRAND, BrandFlags } from '@/symbols';\nimport type { Paths, PathValue, WritableAtom } from '../types';\n\n/**\n * Internal recursive helper for creating deep immutable copies with structural sharing.\n * Only clones nodes along the path where changes occur.\n */\nexport function setDeepValue(obj: unknown, keys: string[], index: number, value: unknown): unknown {\n if (index === keys.length) return value;\n\n const key = keys[index]!;\n const curr = (obj != null && typeof obj === 'object' ? obj : {}) as Record<string, unknown>;\n const old = curr[key];\n const next = setDeepValue(old, keys, index + 1, value);\n\n if (Object.is(old, next)) return obj;\n\n if (Array.isArray(curr)) {\n const arr = curr.slice();\n const idx = Number.parseInt(key, 10);\n if (!Number.isNaN(idx)) {\n arr[idx] = next;\n } else {\n (arr as unknown as Record<string, unknown>)[key] = next;\n }\n return arr;\n }\n return { ...curr, [key]: next };\n}\n\n/**\n * Helper to retrieve a nested value from an object/array at a given path.\n */\nexport function getPathValue(source: unknown, parts: string[]): unknown {\n let res = source;\n const len = parts.length;\n for (let i = 0; i < len; i++) {\n if (res == null) return undefined;\n res = (res as Record<string, unknown>)[parts[i]!];\n }\n return res;\n}\n\n/**\n * Creates a two-way \"lens\" for a specific property path on an object-based atom.\n *\n * @example\n * const store = atom({ user: { name: 'Alice' } });\n * const nameLens = atomLens(store, 'user.name');\n * console.log(nameLens.value); // 'Alice'\n * nameLens.value = 'Bob'; // Updates store.user.name immutably\n */\nexport function atomLens<T extends object, P extends Paths<T>>(\n atom: WritableAtom<T>,\n path: P\n): WritableAtom<PathValue<T, P>> {\n const parts = path.includes('.') ? path.split('.') : [path];\n const unsubs = new Set<() => void>();\n const dispose = () => {\n unsubs.forEach((u) => u());\n unsubs.clear();\n };\n\n return {\n get value() {\n return getPathValue(atom.value, parts) as PathValue<T, P>;\n },\n set value(newVal: PathValue<T, P>) {\n const cur = atom.peek(),\n next = setDeepValue(cur, parts, 0, newVal);\n if (next !== cur) atom.value = next as T;\n },\n peek: () => getPathValue(atom.peek(), parts) as PathValue<T, P>,\n subscribe(listener: (nv: PathValue<T, P>, ov: PathValue<T, P>) => void) {\n const unsub = atom.subscribe((np, op) => {\n const nv = getPathValue(np, parts) as PathValue<T, P>,\n ov = getPathValue(op, parts) as PathValue<T, P>;\n if (!Object.is(nv, ov)) listener(nv, ov);\n });\n unsubs.add(unsub);\n return () => {\n unsub();\n unsubs.delete(unsub);\n };\n },\n subscriberCount: () => unsubs.size,\n dispose,\n [Symbol.dispose]: dispose,\n [BRAND]: BrandFlags.Atom | BrandFlags.Writable,\n } as unknown as WritableAtom<PathValue<T, P>>;\n}\n\n/**\n * Composes an existing lens with a sub-path to create a deeper lens.\n */\nexport const composeLens = <T extends object, P extends Paths<T>>(lens: WritableAtom<T>, path: P) =>\n atomLens(lens, path);\n\n/**\n * Creates a lens factory bound to a specific atom.\n */\nexport const lensFor =\n <T extends object>(atom: WritableAtom<T>) =>\n <P extends Paths<T>>(path: P) =>\n atomLens(atom, path);\n"],"mappings":"kRAWA,IAAM,EAAQ,CAEZ,SAAU,EACV,YAAa,EAGb,MAAO,IACP,YAAa,IACb,UAAW,KACX,cAAe,KAGf,KAAM,MACN,QAAS,GAAK,GACd,SAAU,GAAK,GACf,SAAU,GAAK,GAGf,UAAW,GAAK,GAChB,4BAA6B,GAAK,GAGlC,iBAAkB,GAAK,IAMZ,GAAc,OAAO,OAAO,CAEvC,YAAa,EAAM,KAAO,EAAM,QAAU,EAAM,SAAW,EAAM,SAEjE,oBAAqB,EAAM,MAAQ,EAAM,YAAc,EAAM,cAC9D,EAKY,EAAa,OAAO,OAAO,CACtC,KAAM,OACN,QAAS,UACT,SAAU,WACV,SAAU,WACX,EAKY,EAAqB,OAAO,OAAO,CAC9C,SAAU,EAAM,SAChB,UAAW,EAAM,iBAClB,EAKY,EAAuB,OAAO,OAAO,CAChD,SAAU,EAAM,SAChB,YAAa,EAAM,YACnB,MAAO,EAAM,MACb,KAAM,EAAM,KACZ,QAAS,EAAM,QACf,SAAU,EAAM,SAChB,SAAU,EAAM,SAChB,YAAa,EAAM,YACnB,UAAW,EAAM,UACjB,cAAe,EAAM,cACtB,EAKY,EAAmB,OAAO,OAAO,CAC5C,SAAU,EAAM,SAChB,KAAM,EAAM,UACZ,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