@but212/atom-effect 0.3.1 → 0.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -211,13 +211,14 @@ try {
211
211
 
212
212
  | Operation | Performance |
213
213
  | --- | --- |
214
- | Atom creation | ~5.0M ops/sec |
215
- | Atom read/write | ~4.4M ops/sec |
216
- | Computed creation | ~1.84M ops/sec |
217
- | Computed recomputation | ~500K ops/sec |
218
- | Effect execution | ~496K ops/sec |
219
- | Batch update (2 atoms) | ~1.93M ops/sec |
214
+ | Atom creation | ~5.18M ops/sec |
215
+ | Atom read/write | ~4.50M ops/sec |
216
+ | Computed creation | ~1.85M ops/sec |
217
+ | Computed recomputation | ~492K ops/sec |
218
+ | Effect execution | ~508K ops/sec |
219
+ | Batch update (2 atoms) | ~2.03M ops/sec |
220
220
  | Untracked read | ~3.07M ops/sec |
221
+ | Deep chain (100 levels) | ~9.1K ops/sec |
221
222
 
222
223
  See [docs/BENCHMARKS.md](./docs/BENCHMARKS.md) for details.
223
224
 
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const T={IDLE:"idle",PENDING:"pending",RESOLVED:"resolved",REJECTED:"rejected"},U={DISPOSED:1,EXECUTING:2},h={DIRTY:1,IDLE:2,PENDING:4,RESOLVED:8,REJECTED:16,RECOMPUTING:32,HAS_ERROR:64},J={MAX_SIZE:1e3,WARMUP_SIZE:100},F={MAX_EXECUTIONS_PER_SECOND:100,CLEANUP_THRESHOLD:100,MAX_EXECUTIONS_PER_EFFECT:50,MAX_EXECUTIONS_PER_FLUSH:5e3},v={MAX_DEPENDENCIES:1e3,WARN_INFINITE_LOOP:!0},N=1073741823,w=typeof process<"u"&&process.env&&process.env.NODE_ENV!=="production";class d extends Error{constructor(e,t=null,s=!0){super(e),this.name="AtomError",this.cause=t,this.recoverable=s,this.timestamp=new Date}}class g extends d{constructor(e,t=null){super(e,t,!0),this.name="ComputedError"}}class p extends d{constructor(e,t=null){super(e,t,!1),this.name="EffectError"}}class R extends d{constructor(e,t=null){super(e,t,!1),this.name="SchedulerError"}}function C(i,e,t){if(i instanceof TypeError)return new e(`Type error (${t}): ${i.message}`,i);if(i instanceof ReferenceError)return new e(`Reference error (${t}): ${i.message}`,i);if(i instanceof d)return i;const s=i instanceof Error?i.message:String(i),n=i instanceof Error?i:null;return new e(`Unexpected error (${t}): ${s}`,n)}function G(i){return i!=null&&typeof i.then=="function"}const a={COMPUTED_MUST_BE_FUNCTION:"Computed function must be a function",COMPUTED_SUBSCRIBER_MUST_BE_FUNCTION:"Subscriber listener must be a function or Subscriber object",COMPUTED_ASYNC_PENDING_NO_DEFAULT:"Async computation is pending. No default value provided",COMPUTED_COMPUTATION_FAILED:"Computed computation failed",COMPUTED_ASYNC_COMPUTATION_FAILED:"Async computed computation failed",COMPUTED_DEPENDENCY_SUBSCRIPTION_FAILED:"Failed to subscribe to dependency",ATOM_SUBSCRIBER_MUST_BE_FUNCTION:"Subscription listener must be a function or Subscriber object",ATOM_SUBSCRIBER_EXECUTION_FAILED:"Error occurred while executing atom subscribers",ATOM_INDIVIDUAL_SUBSCRIBER_FAILED:"Error during individual atom subscriber execution",EFFECT_MUST_BE_FUNCTION:"Effect function must be a function",EFFECT_EXECUTION_FAILED:"Effect execution failed",EFFECT_CLEANUP_FAILED:"Effect cleanup function execution failed",LARGE_DEPENDENCY_GRAPH:i=>`Large dependency graph detected: ${i} dependencies`,UNSUBSCRIBE_NON_EXISTENT:"Attempted to unsubscribe a non-existent listener",CALLBACK_ERROR_IN_ERROR_HANDLER:"Error occurred during onError callback execution"};let P=0;function X(){return P=(P+1|0)&N,P}let A=0,B=0,O=!1;function q(){return O?(w&&console.warn("Warning: startFlush() called during flush - ignored to prevent infinite loop detection bypass"),!1):(O=!0,A=A+1&N,B=0,!0)}function z(){O=!1}function W(){return O?++B:0}class K{constructor(){this.queueA=[],this.queueB=[],this.queue=this.queueA,this.queueSize=0,this._epoch=0,this.isProcessing=!1,this.isBatching=!1,this.batchDepth=0,this.batchQueue=[],this.batchQueueSize=0,this.isFlushingSync=!1,this.maxFlushIterations=1e3}get phase(){return this.isProcessing||this.isFlushingSync?2:this.isBatching?1:0}schedule(e){if(typeof e!="function")throw new R("Scheduler callback must be a function");e._nextEpoch!==this._epoch&&(e._nextEpoch=this._epoch,this.isBatching||this.isFlushingSync?this.batchQueue[this.batchQueueSize++]=e:(this.queue[this.queueSize++]=e,this.isProcessing||this.flush()))}flush(){if(this.isProcessing||this.queueSize===0)return;this.isProcessing=!0;const e=this.queue,t=this.queueSize;this.queue=this.queue===this.queueA?this.queueB:this.queueA,this.queueSize=0,this._epoch++,queueMicrotask(()=>{const s=q();for(let n=0;n<t;n++)try{e[n]?.()}catch(r){console.error(new R("Error occurred during scheduler execution",r))}e.length=0,this.isProcessing=!1,s&&z(),this.queueSize>0&&!this.isBatching&&this.flush()})}flushSync(){this.isFlushingSync=!0;const e=q();try{if(this._epoch++,this.batchQueueSize>0){for(let s=0;s<this.batchQueueSize;s++){const n=this.batchQueue[s];n._nextEpoch!==this._epoch&&(n._nextEpoch=this._epoch,this.queue[this.queueSize++]=n)}this.batchQueueSize=0}let t=0;for(;this.queueSize>0;){if(++t>this.maxFlushIterations){console.error(new R(`Maximum flush iterations (${this.maxFlushIterations}) exceeded. Possible infinite loop in reactive dependencies. Consider increasing the limit with scheduler.setMaxFlushIterations()`)),this.queueSize=0,this.queue.length=0,this.batchQueueSize=0;break}const s=this.queue,n=this.queueSize;this.queue=this.queue===this.queueA?this.queueB:this.queueA,this.queueSize=0,this._epoch++;for(let r=0;r<n;r++)try{s[r]?.()}catch(c){console.error(new R("Error occurred during batch execution",c))}if(s.length=0,this.batchQueueSize>0){for(let r=0;r<this.batchQueueSize;r++)this.queue[this.queueSize++]=this.batchQueue[r];this.batchQueueSize=0}}}finally{this.isFlushingSync=!1,e&&z()}}startBatch(){this.batchDepth++,this.isBatching=!0}endBatch(){this.batchDepth=Math.max(0,this.batchDepth-1),this.batchDepth===0&&(this.flushSync(),this.isBatching=!1)}setMaxFlushIterations(e){if(e<10)throw new R("Max flush iterations must be at least 10");this.maxFlushIterations=e}}const I=new K;function Z(i){if(typeof i!="function")throw new d("Batch callback must be a function");I.startBatch();try{return i()}catch(e){throw new d("Error occurred during batch execution",e)}finally{I.endBatch()}}const m={current:null,run(i,e){const t=this.current;this.current=i;try{return e()}finally{this.current=t}},getCurrent(){return this.current}};function ee(i){if(typeof i!="function")throw new d("Untracked callback must be a function");const e=m.current;m.current=null;try{return i()}catch(t){throw new d("Error occurred during untracked execution",t)}finally{m.current=e}}const L=Symbol("debugName"),te=Symbol("id"),M=Symbol("type"),j=Symbol("noDefaultValue");function se(i){return i!==null&&typeof i=="object"&&"dependencies"in i&&Array.isArray(i.dependencies)}let V=0;function Y(i,e,t){const s=i;if(s._visitedEpoch!==t){if(s._visitedEpoch=t,i===e)throw new g("Indirect circular dependency detected");if(se(i)){const n=i.dependencies;for(let r=0;r<n.length;r++)Y(n[r],e,t)}}}const E={enabled:typeof process<"u"&&process.env?.NODE_ENV==="development",maxDependencies:v.MAX_DEPENDENCIES,warnInfiniteLoop:v.WARN_INFINITE_LOOP,warn(i,e){this.enabled&&i&&console.warn(`[Atom Effect] ${e}`)},checkCircular(i,e,t){if(i===e)throw new g("Direct circular dependency detected");this.enabled&&(V++,Y(i,e,V))},attachDebugInfo(i,e,t){if(!this.enabled)return;const s=i;s[L]=`${e}_${t}`,s[te]=t,s[M]=e},getDebugName(i){if(i!==null&&typeof i=="object"&&L in i)return i[L]},getDebugType(i){if(i!==null&&typeof i=="object"&&M in i)return i[M]}};let ie=1;const k=()=>ie++;class x{constructor(){this.subscribers=null}add(e){if(this.subscribers||(this.subscribers=[]),this.subscribers.indexOf(e)!==-1)return()=>{};this.subscribers.push(e);let t=!1;return()=>{t||(t=!0,this.remove(e))}}remove(e){if(!this.subscribers)return!1;const t=this.subscribers.indexOf(e);if(t===-1)return!1;const s=this.subscribers.length-1;return t!==s&&(this.subscribers[t]=this.subscribers[s]),this.subscribers.pop(),!0}has(e){return this.subscribers?this.subscribers.indexOf(e)!==-1:!1}forEach(e){if(this.subscribers)for(let t=0;t<this.subscribers.length;t++)e(this.subscribers[t],t)}forEachSafe(e,t){if(this.subscribers)for(let s=0;s<this.subscribers.length;s++)try{e(this.subscribers[s],s)}catch(n){t?t(n):console.error("[SubscriberManager] Error in subscriber callback:",n)}}get size(){return this.subscribers?.length??0}get hasSubscribers(){return this.size>0}clear(){this.subscribers=null}toArray(){return this.subscribers?[...this.subscribers]:[]}}class ne{constructor(e,t){this._isNotificationScheduled=!1,this.id=k()&N,this.version=0,this.flags=0,this._lastSeenEpoch=-1,this._value=e,this._functionSubscribers=new x,this._objectSubscribers=new x,this._sync=t,this._notifyTask=this._flushNotifications.bind(this),E.attachDebugInfo(this,"atom",this.id)}get value(){const e=m.getCurrent();return e!=null&&this._track(e),this._value}set value(e){if(Object.is(this._value,e))return;const t=this._value;this.version=this.version+1&N;const s=this.version;this._value=e,!(!this._functionSubscribers.hasSubscribers&&!this._objectSubscribers.hasSubscribers)&&this._notify(e,t,s)}_track(e){if(typeof e=="function"){const t=e;t.addDependency!==void 0?t.addDependency(this):this._functionSubscribers.add(e)}else{const t=e;t.addDependency!==void 0?t.addDependency(this):t.execute!==void 0&&this._objectSubscribers.add(t)}}_notify(e,t,s){this._isNotificationScheduled||(this._pendingOldValue=t,this._isNotificationScheduled=!0),this._sync&&!I.isBatching?this._flushNotifications():I.schedule(this._notifyTask)}_flushNotifications(){if(!this._isNotificationScheduled)return;const e=this._pendingOldValue,t=this._value;this._pendingOldValue=void 0,this._isNotificationScheduled=!1,this._functionSubscribers.forEachSafe(s=>s(t,e),s=>console.error(new d(a.ATOM_INDIVIDUAL_SUBSCRIBER_FAILED,s))),this._objectSubscribers.forEachSafe(s=>s.execute(),s=>console.error(new d(a.ATOM_INDIVIDUAL_SUBSCRIBER_FAILED,s)))}subscribe(e){if(typeof e=="object"&&e!==null&&"execute"in e)return this._objectSubscribers.add(e);if(typeof e!="function")throw new d(a.ATOM_SUBSCRIBER_MUST_BE_FUNCTION);return this._functionSubscribers.add(e)}peek(){return this._value}dispose(){this._functionSubscribers.clear(),this._objectSubscribers.clear(),this._value=void 0}subscriberCount(){return this._functionSubscribers.size+this._objectSubscribers.size}}function re(i,e={}){return new ne(i,e.sync??!1)}const S=process.env.NODE_ENV!=="production",f=Object.freeze([]),b=Object.freeze([]);class ${constructor(){this.pool=[],this.maxPoolSize=50,this.maxReusableCapacity=256,this.stats=S?{acquired:0,released:0,rejected:{frozen:0,tooLarge:0,poolFull:0}}:null}acquire(){return S&&this.stats&&this.stats.acquired++,this.pool.pop()??[]}release(e,t){if(!(t&&e===t)){if(Object.isFrozen(e)){S&&this.stats&&this.stats.rejected.frozen++;return}if(e.length>this.maxReusableCapacity){S&&this.stats&&this.stats.rejected.tooLarge++;return}if(this.pool.length>=this.maxPoolSize){S&&this.stats&&this.stats.rejected.poolFull++;return}e.length=0,this.pool.push(e),S&&this.stats&&this.stats.released++}}getStats(){if(!S||!this.stats)return null;const{acquired:e,released:t,rejected:s}=this.stats,n=s.frozen+s.tooLarge+s.poolFull;return{acquired:e,released:t,rejected:s,leaked:e-t-n,poolSize:this.pool.length}}reset(){this.pool.length=0,S&&this.stats&&(this.stats.acquired=0,this.stats.released=0,this.stats.rejected={frozen:0,tooLarge:0,poolFull:0})}}const D=new $,y=new $;class Q{constructor(e,t={}){if(typeof e!="function")throw new g(a.COMPUTED_MUST_BE_FUNCTION);if(this.id=k()&N,this.version=0,this.flags=0,this._lastSeenEpoch=-1,this._value=void 0,this._stateFlags=h.DIRTY|h.IDLE,this._error=null,this._promiseId=0,this._equal=t.equal??Object.is,this._fn=e,this._defaultValue="defaultValue"in t?t.defaultValue:j,this._hasDefaultValue=this._defaultValue!==j,this._onError=t.onError??null,this.MAX_PROMISE_ID=Number.MAX_SAFE_INTEGER-1,this._functionSubscribers=new x,this._objectSubscribers=new x,this._dependencies=f,this._unsubscribes=b,this._recomputeJob=()=>{if(this._isDirty())try{this._recompute()}catch{}},this._notifyJob=()=>{this._functionSubscribers.forEachSafe(s=>s(),s=>console.error(s)),this._objectSubscribers.forEachSafe(s=>s.execute(),s=>console.error(s))},this._trackable=Object.assign(()=>this._markDirty(),{addDependency:s=>{}}),E.attachDebugInfo(this,"computed",this.id),E.enabled){const s=this;s.subscriberCount=()=>this._functionSubscribers.size+this._objectSubscribers.size,s.isDirty=()=>this._isDirty(),s.dependencies=this._dependencies,s.stateFlags=this._getFlagsAsString()}if(t.lazy===!1)try{this._recompute()}catch{}}get value(){if((this._stateFlags&(h.RESOLVED|h.DIRTY))===h.RESOLVED)return this._registerTracking(),this._value;const t=this._computeValue();return this._registerTracking(),t}subscribe(e){if(typeof e=="object"&&e!==null&&"execute"in e)return this._objectSubscribers.add(e);if(typeof e!="function")throw new g(a.COMPUTED_SUBSCRIBER_MUST_BE_FUNCTION);return this._functionSubscribers.add(e)}peek(){return this._value}get state(){return this._getAsyncState()}get hasError(){return this._isRejected()}get lastError(){return this._error}get isPending(){return this._isPending()}get isResolved(){return this._isResolved()}invalidate(){this._markDirty()}dispose(){if(this._unsubscribes!==b){for(let e=0;e<this._unsubscribes.length;e++){const t=this._unsubscribes[e];t&&t()}y.release(this._unsubscribes),this._unsubscribes=b}this._dependencies!==f&&(D.release(this._dependencies),this._dependencies=f),this._functionSubscribers.clear(),this._objectSubscribers.clear(),this._stateFlags=h.DIRTY|h.IDLE,this._error=null,this._value=void 0,this._promiseId=(this._promiseId+1)%this.MAX_PROMISE_ID}_isDirty(){return(this._stateFlags&h.DIRTY)!==0}_setDirty(){this._stateFlags|=h.DIRTY}_clearDirty(){this._stateFlags&=-2}_isIdle(){return(this._stateFlags&h.IDLE)!==0}_setIdle(){this._stateFlags|=h.IDLE,this._stateFlags&=-29}_isPending(){return(this._stateFlags&h.PENDING)!==0}_setPending(){this._stateFlags|=h.PENDING,this._stateFlags&=-27}_isResolved(){return(this._stateFlags&h.RESOLVED)!==0}_setResolved(){this._stateFlags|=h.RESOLVED,this._stateFlags&=-87}_isRejected(){return(this._stateFlags&h.REJECTED)!==0}_setRejected(){this._stateFlags|=h.REJECTED|h.HAS_ERROR,this._stateFlags&=-15}_isRecomputing(){return(this._stateFlags&h.RECOMPUTING)!==0}_setRecomputing(e){const t=h.RECOMPUTING;this._stateFlags=this._stateFlags&~t|-Number(e)&t}_getAsyncState(){return this._isPending()?T.PENDING:this._isResolved()?T.RESOLVED:this._isRejected()?T.REJECTED:T.IDLE}_getFlagsAsString(){const e=[];return this._isDirty()&&e.push("DIRTY"),this._isIdle()&&e.push("IDLE"),this._isPending()&&e.push("PENDING"),this._isResolved()&&e.push("RESOLVED"),this._isRejected()&&e.push("REJECTED"),this._isRecomputing()&&e.push("RECOMPUTING"),e.join(" | ")}_computeValue(){return this._isRecomputing()?this._value:this._isPending()?this._handlePending():this._isRejected()?this._handleRejected():(this._isDirty()||this._isIdle())&&(this._recompute(),this._isPending())?this._handlePending():this._value}_recompute(){if(!this._isDirty()&&this._isResolved())return;this._setRecomputing(!0);const e=this._dependencies,t=D.acquire(),s=X();let n=0;const r=_=>{_._lastSeenEpoch!==s&&(_._lastSeenEpoch=s,n<t.length?t[n]=_:t.push(_),n++)},c=this._trackable.addDependency;this._trackable.addDependency=r;let o=!1;try{const _=m.run(this._trackable,this._fn);if(t.length=n,G(_)){this._syncDependencies(e,t,this._unsubscribes,s),this._dependencies=t,o=!0,this._handleAsyncComputation(_),this._setRecomputing(!1);return}this._syncDependencies(e,t,this._unsubscribes,s),this._dependencies=t,o=!0,this._handleSyncResult(_)}catch(_){t.length=n,this._syncDependencies(e,t,this._unsubscribes,s),this._dependencies=t,this._handleComputationError(_)}finally{this._trackable.addDependency=c,o?e!==f&&D.release(e):D.release(t)}}_syncDependencies(e,t,s,n){if(e!==f&&s!==b)for(let c=0;c<e.length;c++){const o=e[c];o&&(o._tempUnsub=s[c])}const r=y.acquire();r.length=t.length;for(let c=0;c<t.length;c++){const o=t[c];o&&(o._tempUnsub?(r[c]=o._tempUnsub,o._tempUnsub=void 0):(E.checkCircular(o,this),r[c]=o.subscribe(this)))}if(e!==f)for(let c=0;c<e.length;c++){const o=e[c];o?._tempUnsub&&(o._tempUnsub(),o._tempUnsub=void 0)}s!==b&&y.release(s),this._unsubscribes=r}_handleSyncResult(e){const t=!this._isResolved()||!this._equal(this._value,e);this._value=e,this._clearDirty(),this._setResolved(),this._error=null,this._setRecomputing(!1),t&&this._notifySubscribers()}_handleAsyncComputation(e){this._setPending(),this._promiseId=this._promiseId>=this.MAX_PROMISE_ID?1:this._promiseId+1;const t=this._promiseId;e.then(s=>{t===this._promiseId&&this._handleAsyncResolution(s)}).catch(s=>{t===this._promiseId&&this._handleAsyncRejection(s)})}_handleAsyncResolution(e){const t=!this._isResolved()||!this._equal(this._value,e);this._value=e,this._clearDirty(),this._setResolved(),this._error=null,this._setRecomputing(!1),t&&this._notifySubscribers()}_handleAsyncRejection(e){const t=C(e,g,a.COMPUTED_ASYNC_COMPUTATION_FAILED);if(this._error=t,this._setRejected(),this._clearDirty(),this._setRecomputing(!1),this._onError&&typeof this._onError=="function")try{this._onError(t)}catch(s){console.error(a.CALLBACK_ERROR_IN_ERROR_HANDLER,s)}this._notifySubscribers()}_handleComputationError(e){const t=C(e,g,a.COMPUTED_COMPUTATION_FAILED);if(this._error=t,this._setRejected(),this._clearDirty(),this._setRecomputing(!1),this._onError&&typeof this._onError=="function")try{this._onError(t)}catch(s){console.error(a.CALLBACK_ERROR_IN_ERROR_HANDLER,s)}throw t}_handlePending(){if(this._hasDefaultValue)return this._defaultValue;throw new g(a.COMPUTED_ASYNC_PENDING_NO_DEFAULT)}_handleRejected(){if(this._error?.recoverable&&this._hasDefaultValue)return this._defaultValue;throw this._error}execute(){this._markDirty()}_markDirty(){this._isRecomputing()||this._isDirty()||(this._setDirty(),this._setIdle(),(this._functionSubscribers.hasSubscribers||this._objectSubscribers.hasSubscribers)&&I.schedule(this._recomputeJob))}_notifySubscribers(){!this._functionSubscribers.hasSubscribers&&!this._objectSubscribers.hasSubscribers||I.schedule(this._notifyJob)}_registerTracking(){const e=m.getCurrent();if(e)if(typeof e=="object"&&e!==null&&e.addDependency)e.addDependency(this);else if(typeof e=="function"){const t=e;t.addDependency?t.addDependency(this):this._functionSubscribers.add(e)}else e.execute&&this._objectSubscribers.add(e)}}Object.freeze(Q.prototype);function ce(i,e={}){return new Q(i,e)}class ue{constructor(e,t={}){this.run=()=>{if(this.isDisposed)throw new p(a.EFFECT_MUST_BE_FUNCTION);this.execute()},this.dispose=()=>{if(!this.isDisposed){if(this._setDisposed(),this._safeCleanup(),this._unsubscribes!==b){for(let s=0;s<this._unsubscribes.length;s++){const n=this._unsubscribes[s];n&&n()}y.release(this._unsubscribes),this._unsubscribes=b}this._dependencies!==f&&(D.release(this._dependencies),this._dependencies=f)}},this.addDependency=s=>{if(this.isExecuting&&this._nextDeps&&this._nextUnsubs){const n=s,r=this._currentEpoch;if(n._lastSeenEpoch===r)return;n._lastSeenEpoch=r,this._nextDeps.push(n),n._tempUnsub?(this._nextUnsubs.push(n._tempUnsub),n._tempUnsub=void 0):this._subscribeTo(n)}},this.execute=()=>{if(this.isDisposed||this.isExecuting)return;this._checkInfiniteLoop(),this._setExecuting(!0),this._safeCleanup();const s=this._dependencies,n=this._unsubscribes,r=D.acquire(),c=y.acquire(),o=X();if(s!==f&&n!==b)for(let u=0;u<s.length;u++){const l=s[u];l&&(l._tempUnsub=n[u])}this._nextDeps=r,this._nextUnsubs=c,this._currentEpoch=o;let _=!1;try{const u=m.run(this,this._fn);this._dependencies=r,this._unsubscribes=c,_=!0,this._checkLoopWarnings(),G(u)?u.then(l=>{!this.isDisposed&&typeof l=="function"&&(this._cleanup=l)}).catch(l=>{console.error(C(l,p,a.EFFECT_EXECUTION_FAILED))}):this._cleanup=typeof u=="function"?u:null}catch(u){_=!0,console.error(C(u,p,a.EFFECT_EXECUTION_FAILED)),this._cleanup=null}finally{if(this._setExecuting(!1),this._nextDeps=null,this._nextUnsubs=null,_){if(s!==f){for(let u=0;u<s.length;u++){const l=s[u];l?._tempUnsub&&(l._tempUnsub(),l._tempUnsub=void 0)}D.release(s)}n!==b&&y.release(n)}else{D.release(r);for(let u=0;u<c.length;u++)c[u]?.();if(y.release(c),s!==f)for(let u=0;u<s.length;u++){const l=s[u];l&&(l._tempUnsub=void 0)}}}},this._id=k()&N,this._flags=0,this._currentEpoch=-1,this._fn=e,this._sync=t.sync??!1,this._maxExecutions=t.maxExecutionsPerSecond??F.MAX_EXECUTIONS_PER_SECOND,this._maxExecutionsPerFlush=t.maxExecutionsPerFlush??F.MAX_EXECUTIONS_PER_EFFECT,this._trackModifications=t.trackModifications??!1,this._cleanup=null,this._dependencies=f,this._unsubscribes=b,this._nextDeps=null,this._nextUnsubs=null,this._lastFlushEpoch=-1,this._executionsInEpoch=0,this._history=w?[]:null,this._executionCount=0,E.attachDebugInfo(this,"effect",this._id)}_subscribeTo(e){try{const t=e.subscribe(()=>{this._trackModifications&&this.isExecuting&&(e._modifiedAtEpoch=this._currentEpoch),this._sync?this.execute():I.schedule(this.execute)});this._nextUnsubs&&this._nextUnsubs.push(t)}catch(t){console.error(C(t,p,a.EFFECT_EXECUTION_FAILED)),this._nextUnsubs&&this._nextUnsubs.push(()=>{})}}get isDisposed(){return(this._flags&U.DISPOSED)!==0}get executionCount(){return this._executionCount}get isExecuting(){return(this._flags&U.EXECUTING)!==0}_setDisposed(){this._flags|=U.DISPOSED}_setExecuting(e){const t=U.EXECUTING;this._flags=this._flags&~t|-Number(e)&t}_safeCleanup(){if(this._cleanup&&typeof this._cleanup=="function"){try{this._cleanup()}catch(e){console.error(C(e,p,a.EFFECT_CLEANUP_FAILED))}this._cleanup=null}}_checkInfiniteLoop(){if(this._lastFlushEpoch!==A&&(this._lastFlushEpoch=A,this._executionsInEpoch=0),this._executionsInEpoch++,this._executionsInEpoch>this._maxExecutionsPerFlush&&this._throwInfiniteLoopError("per-effect"),W()>F.MAX_EXECUTIONS_PER_FLUSH&&this._throwInfiniteLoopError("global"),this._executionCount++,this._history){const e=Date.now();this._history.push(e),this._history.length>F.MAX_EXECUTIONS_PER_SECOND+10&&this._history.shift(),this._checkTimestampLoop(e)}}_checkTimestampLoop(e){const t=this._history;if(!t||this._maxExecutions<=0)return;const s=e-1e3;let n=0;for(let r=t.length-1;r>=0&&!(t[r]<s);r--)n++;if(n>this._maxExecutions){const r=new p(`Effect executed ${n} times within 1 second. Infinite loop suspected`);if(this.dispose(),console.error(r),w)throw r}}_throwInfiniteLoopError(e){const t=new p(`Infinite loop detected (${e}): effect executed ${this._executionsInEpoch} times in current flush. Total executions in flush: ${B}`);throw this.dispose(),console.error(t),t}_checkLoopWarnings(){if(this._trackModifications&&E.enabled){const e=this._dependencies;for(let t=0;t<e.length;t++){const s=e[t];s&&s._modifiedAtEpoch===this._currentEpoch&&E.warn(!0,`Effect is reading a dependency (${E.getDebugName(s)||"unknown"}) that it just modified. Infinite loop may occur`)}}}}function he(i,e={}){if(typeof i!="function")throw new p(a.EFFECT_MUST_BE_FUNCTION);const t=new ue(i,e);return t.execute(),t}function H(i){return i!==null&&typeof i=="object"&&"value"in i&&"subscribe"in i&&typeof i.subscribe=="function"}function oe(i){if(E.enabled){const e=E.getDebugType(i);if(e)return e==="computed"}return H(i)&&"invalidate"in i&&typeof i.invalidate=="function"}function ae(i){return i!==null&&typeof i=="object"&&"dispose"in i&&"run"in i&&typeof i.dispose=="function"&&typeof i.run=="function"}exports.AsyncState=T;exports.AtomError=d;exports.ComputedError=g;exports.DEBUG_CONFIG=v;exports.DEBUG_RUNTIME=E;exports.EffectError=p;exports.POOL_CONFIG=J;exports.SCHEDULER_CONFIG=F;exports.SchedulerError=R;exports.atom=re;exports.batch=Z;exports.computed=ce;exports.effect=he;exports.isAtom=H;exports.isComputed=oe;exports.isEffect=ae;exports.scheduler=I;exports.untracked=ee;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const U={IDLE:"idle",PENDING:"pending",RESOLVED:"resolved",REJECTED:"rejected"},P={DISPOSED:1,EXECUTING:2},u={DIRTY:1,IDLE:2,PENDING:4,RESOLVED:8,REJECTED:16,RECOMPUTING:32,HAS_ERROR:64},se={MAX_SIZE:1e3,WARMUP_SIZE:100},F={MAX_EXECUTIONS_PER_SECOND:100,CLEANUP_THRESHOLD:100,MAX_EXECUTIONS_PER_EFFECT:50,MAX_EXECUTIONS_PER_FLUSH:5e3},k={MAX_DEPENDENCIES:1e3,WARN_INFINITE_LOOP:!0},A=1073741823,E=typeof process<"u"&&process.env&&process.env.NODE_ENV!=="production";class d extends Error{constructor(e,t=null,s=!0){super(e),this.name="AtomError",this.cause=t,this.recoverable=s,this.timestamp=new Date}}class I extends d{constructor(e,t=null){super(e,t,!0),this.name="ComputedError"}}class g extends d{constructor(e,t=null){super(e,t,!1),this.name="EffectError"}}class N extends d{constructor(e,t=null){super(e,t,!1),this.name="SchedulerError"}}function T(i,e,t){if(i instanceof TypeError)return new e(`Type error (${t}): ${i.message}`,i);if(i instanceof ReferenceError)return new e(`Reference error (${t}): ${i.message}`,i);if(i instanceof d)return i;const s=i instanceof Error?i.message:String(i),n=i instanceof Error?i:null;return new e(`Unexpected error (${t}): ${s}`,n)}function Q(i){return i!=null&&typeof i.then=="function"}const l={COMPUTED_MUST_BE_FUNCTION:"Computed function must be a function",COMPUTED_SUBSCRIBER_MUST_BE_FUNCTION:"Subscriber listener must be a function or Subscriber object",COMPUTED_ASYNC_PENDING_NO_DEFAULT:"Async computation is pending. No default value provided",COMPUTED_COMPUTATION_FAILED:"Computed computation failed",COMPUTED_ASYNC_COMPUTATION_FAILED:"Async computed computation failed",COMPUTED_DEPENDENCY_SUBSCRIPTION_FAILED:"Failed to subscribe to dependency",ATOM_SUBSCRIBER_MUST_BE_FUNCTION:"Subscription listener must be a function or Subscriber object",ATOM_SUBSCRIBER_EXECUTION_FAILED:"Error occurred while executing atom subscribers",ATOM_INDIVIDUAL_SUBSCRIBER_FAILED:"Error during individual atom subscriber execution",EFFECT_MUST_BE_FUNCTION:"Effect function must be a function",EFFECT_EXECUTION_FAILED:"Effect execution failed",EFFECT_CLEANUP_FAILED:"Effect cleanup function execution failed",LARGE_DEPENDENCY_GRAPH:i=>`Large dependency graph detected: ${i} dependencies`,UNSUBSCRIBE_NON_EXISTENT:"Attempted to unsubscribe a non-existent listener",CALLBACK_ERROR_IN_ERROR_HANDLER:"Error occurred during onError callback execution"},w=Symbol("debugName"),ie=Symbol("id"),V=Symbol("type"),G=Symbol("noDefaultValue");function ne(i){return i!==null&&typeof i=="object"&&"dependencies"in i&&Array.isArray(i.dependencies)}let X=0;function H(i,e,t){const s=i;if(s._visitedEpoch!==t){if(s._visitedEpoch=t,i===e)throw new I("Indirect circular dependency detected");if(ne(i)){const n=i.dependencies;for(let r=0;r<n.length;r++)H(n[r],e,t)}}}const b={enabled:typeof process<"u"&&process.env?.NODE_ENV==="development",maxDependencies:k.MAX_DEPENDENCIES,warnInfiniteLoop:k.WARN_INFINITE_LOOP,warn(i,e){this.enabled&&i&&console.warn(`[Atom Effect] ${e}`)},checkCircular(i,e,t){if(i===e)throw new I("Direct circular dependency detected");this.enabled&&(X++,H(i,e,X))},attachDebugInfo(i,e,t){if(!this.enabled)return;const s=i;s[w]=`${e}_${t}`,s[ie]=t,s[V]=e},getDebugName(i){if(i!==null&&typeof i=="object"&&w in i)return i[w]},getDebugType(i){if(i!==null&&typeof i=="object"&&V in i)return i[V]}};let re=1;const ce=()=>re++;class J{constructor(){this.id=ce()&A,this.flags=0}}class W extends J{constructor(){super(),this.version=0,this._lastSeenEpoch=-1}subscribe(e){if(typeof e=="object"&&e!==null&&"execute"in e)return this._objectSubscribers.add(e);if(typeof e!="function")throw new d(l.ATOM_SUBSCRIBER_MUST_BE_FUNCTION);return this._functionSubscribers.add(e)}subscriberCount(){return this._functionSubscribers.size+this._objectSubscribers.size}_notifySubscribers(e,t){this._functionSubscribers.forEachSafe(s=>s(e,t),s=>console.error(new d(l.ATOM_INDIVIDUAL_SUBSCRIBER_FAILED,s))),this._objectSubscribers.forEachSafe(s=>s.execute(),s=>console.error(new d(l.ATOM_INDIVIDUAL_SUBSCRIBER_FAILED,s)))}}let B=0;function K(){return B=(B+1|0)&A,B}let v=0,z=0,L=!1;function Y(){return L?(E&&console.warn("Warning: startFlush() called during flush - ignored to prevent infinite loop detection bypass"),!1):(L=!0,v=v+1&A,z=0,!0)}function $(){L=!1}function oe(){return L?++z:0}class ue{constructor(){this.queueA=[],this.queueB=[],this.queue=this.queueA,this.queueSize=0,this._epoch=0,this.isProcessing=!1,this.isBatching=!1,this.batchDepth=0,this.batchQueue=[],this.batchQueueSize=0,this.isFlushingSync=!1,this.maxFlushIterations=1e3}get phase(){return this.isProcessing||this.isFlushingSync?2:this.isBatching?1:0}schedule(e){if(typeof e!="function")throw new N("Scheduler callback must be a function");e._nextEpoch!==this._epoch&&(e._nextEpoch=this._epoch,this.isBatching||this.isFlushingSync?this.batchQueue[this.batchQueueSize++]=e:(this.queue[this.queueSize++]=e,this.isProcessing||this.flush()))}flush(){if(this.isProcessing||this.queueSize===0)return;this.isProcessing=!0;const e=this.queue,t=this.queueSize;this.queue=this.queue===this.queueA?this.queueB:this.queueA,this.queueSize=0,this._epoch++,queueMicrotask(()=>{const s=Y();for(let n=0;n<t;n++)try{e[n]?.()}catch(r){console.error(new N("Error occurred during scheduler execution",r))}e.length=0,this.isProcessing=!1,s&&$(),this.queueSize>0&&!this.isBatching&&this.flush()})}flushSync(){this.isFlushingSync=!0;const e=Y();try{if(this._epoch++,this.batchQueueSize>0){for(let s=0;s<this.batchQueueSize;s++){const n=this.batchQueue[s];n._nextEpoch!==this._epoch&&(n._nextEpoch=this._epoch,this.queue[this.queueSize++]=n)}this.batchQueueSize=0}let t=0;for(;this.queueSize>0;){if(++t>this.maxFlushIterations){console.error(new N(`Maximum flush iterations (${this.maxFlushIterations}) exceeded. Possible infinite loop.`)),this.queueSize=0,this.queue.length=0,this.batchQueueSize=0;break}const s=this.queue,n=this.queueSize;this.queue=this.queue===this.queueA?this.queueB:this.queueA,this.queueSize=0,this._epoch++;for(let r=0;r<n;r++)try{s[r]?.()}catch(c){console.error(new N("Error occurred during batch execution",c))}if(s.length=0,this.batchQueueSize>0){for(let r=0;r<this.batchQueueSize;r++)this.queue[this.queueSize++]=this.batchQueue[r];this.batchQueueSize=0}}}finally{this.isFlushingSync=!1,e&&$()}}startBatch(){this.batchDepth++,this.isBatching=!0}endBatch(){this.batchDepth=Math.max(0,this.batchDepth-1),this.batchDepth===0&&(this.flushSync(),this.isBatching=!1)}setMaxFlushIterations(e){if(e<10)throw new N("Max flush iterations must be at least 10");this.maxFlushIterations=e}}const x=new ue;function he(i){if(typeof i!="function")throw new d("Batch callback must be a function");x.startBatch();try{return i()}catch(e){throw new d("Error occurred during batch execution",e)}finally{x.endBatch()}}const R={current:null,run(i,e){const t=this.current;this.current=i;try{return e()}finally{this.current=t}},getCurrent(){return this.current}};function Z(i){if(typeof i!="function")throw new d("Untracked callback must be a function");const e=R.current;R.current=null;try{return i()}catch(t){throw new d("Error occurred during untracked execution",t)}finally{R.current=e}}class M{constructor(){this.subscribers=null}add(e){if(this.subscribers||(this.subscribers=[]),this.subscribers.indexOf(e)!==-1)return()=>{};this.subscribers.push(e);let t=!1;return()=>{t||(t=!0,this.remove(e))}}remove(e){if(!this.subscribers)return!1;const t=this.subscribers.indexOf(e);if(t===-1)return!1;const s=this.subscribers.length-1;return t!==s&&(this.subscribers[t]=this.subscribers[s]),this.subscribers.pop(),!0}has(e){return this.subscribers?this.subscribers.indexOf(e)!==-1:!1}forEach(e){if(this.subscribers)for(let t=0;t<this.subscribers.length;t++)e(this.subscribers[t],t)}forEachSafe(e,t){if(this.subscribers)for(let s=0;s<this.subscribers.length;s++)try{e(this.subscribers[s],s)}catch(n){t?t(n):console.error("[SubscriberManager] Error in subscriber callback:",n)}}get size(){return this.subscribers?.length??0}get hasSubscribers(){return this.size>0}clear(){this.subscribers=null}toArray(){return this.subscribers?[...this.subscribers]:[]}}class le extends W{constructor(e,t){super(),this._isNotificationScheduled=!1,this._value=e,this._functionSubscribersStore=new M,this._objectSubscribersStore=new M,this._sync=t,this._notifyTask=this._flushNotifications.bind(this),b.attachDebugInfo(this,"atom",this.id)}get _functionSubscribers(){return this._functionSubscribersStore}get _objectSubscribers(){return this._objectSubscribersStore}get value(){const e=R.getCurrent();return e!=null&&this._track(e),this._value}set value(e){if(Object.is(this._value,e))return;const t=this._value;this.version=this.version+1&A;const s=this.version;this._value=e,!(!this._functionSubscribersStore.hasSubscribers&&!this._objectSubscribersStore.hasSubscribers)&&this._notify(e,t,s)}_track(e){if(typeof e=="function"){const t=e;t.addDependency!==void 0?t.addDependency(this):this._functionSubscribersStore.add(e)}else{const t=e;t.addDependency!==void 0?t.addDependency(this):t.execute!==void 0&&this._objectSubscribersStore.add(t)}}_notify(e,t,s){this._isNotificationScheduled||(this._pendingOldValue=t,this._isNotificationScheduled=!0),this._sync&&!x.isBatching?this._flushNotifications():x.schedule(this._notifyTask)}_flushNotifications(){if(!this._isNotificationScheduled)return;const e=this._pendingOldValue,t=this._value;this._pendingOldValue=void 0,this._isNotificationScheduled=!1,this._notifySubscribers(t,e)}peek(){return this._value}dispose(){this._functionSubscribersStore.clear(),this._objectSubscribersStore.clear(),this._value=void 0}}function ae(i,e={}){return new le(i,e.sync??!1)}const _=Object.freeze([]),p=Object.freeze([]),f=Object.freeze([]);class j{constructor(){this.pool=[],this.maxPoolSize=50,this.maxReusableCapacity=256,this.stats=E?{acquired:0,released:0,rejected:{frozen:0,tooLarge:0,poolFull:0}}:null}acquire(){return E&&this.stats&&this.stats.acquired++,this.pool.pop()??[]}release(e,t){if(!(t&&e===t)){if(Object.isFrozen(e)){E&&this.stats&&this.stats.rejected.frozen++;return}if(e.length>this.maxReusableCapacity){E&&this.stats&&this.stats.rejected.tooLarge++;return}if(this.pool.length>=this.maxPoolSize){E&&this.stats&&this.stats.rejected.poolFull++;return}e.length=0,this.pool.push(e),E&&this.stats&&this.stats.released++}}getStats(){if(!E||!this.stats)return null;const{acquired:e,released:t,rejected:s}=this.stats,n=s.frozen+s.tooLarge+s.poolFull;return{acquired:e,released:t,rejected:s,leaked:e-t-n,poolSize:this.pool.length}}reset(){this.pool.length=0,E&&this.stats&&(this.stats.acquired=0,this.stats.released=0,this.stats.rejected={frozen:0,tooLarge:0,poolFull:0})}}const y=new j,m=new j,S=new j;function q(i,e,t,s){if(e!==_&&t!==p)for(let r=0;r<e.length;r++){const c=e[r];c&&(c._tempUnsub=t[r])}const n=m.acquire();n.length=i.length;for(let r=0;r<i.length;r++){const c=i[r];c&&(c._tempUnsub?(n[r]=c._tempUnsub,c._tempUnsub=void 0):(b.checkCircular(c,s),n[r]=c.subscribe(s)))}if(e!==_)for(let r=0;r<e.length;r++){const c=e[r];c?._tempUnsub&&(c._tempUnsub(),c._tempUnsub=void 0)}return t!==p&&m.release(t),n}class ee extends W{constructor(e,t={}){if(typeof e!="function")throw new I(l.COMPUTED_MUST_BE_FUNCTION);if(super(),this._value=void 0,this.flags=u.DIRTY|u.IDLE,this._error=null,this._promiseId=0,this._equal=t.equal??Object.is,this._fn=e,this._defaultValue="defaultValue"in t?t.defaultValue:G,this._hasDefaultValue=this._defaultValue!==G,this._onError=t.onError??null,this.MAX_PROMISE_ID=Number.MAX_SAFE_INTEGER-1,this._functionSubscribersStore=new M,this._objectSubscribersStore=new M,this._dependencies=_,this._dependencyVersions=f,this._unsubscribes=p,this._notifyJob=()=>{this._functionSubscribersStore.forEachSafe(s=>s(),s=>console.error(s)),this._objectSubscribersStore.forEachSafe(s=>s.execute(),s=>console.error(s))},this._trackable=Object.assign(()=>this._markDirty(),{addDependency:s=>{}}),b.attachDebugInfo(this,"computed",this.id),b.enabled){const s=this;s.subscriberCount=()=>this._functionSubscribersStore.size+this._objectSubscribersStore.size,s.isDirty=()=>this._isDirty(),s.dependencies=this._dependencies,s.stateFlags=this._getFlagsAsString()}if(t.lazy===!1)try{this._recompute()}catch{}}get _functionSubscribers(){return this._functionSubscribersStore}get _objectSubscribers(){return this._objectSubscribersStore}get value(){const e=this._computeValue();return this._registerTracking(),e}peek(){return this._value}get state(){return this._getAsyncState()}get hasError(){return this._isRejected()}get lastError(){return this._error}get isPending(){return this._isPending()}get isResolved(){return this._isResolved()}invalidate(){this._markDirty(),this._dependencyVersions!==f&&(S.release(this._dependencyVersions),this._dependencyVersions=f)}dispose(){if(this._unsubscribes!==p){for(let e=0;e<this._unsubscribes.length;e++){const t=this._unsubscribes[e];t&&t()}m.release(this._unsubscribes),this._unsubscribes=p}this._dependencies!==_&&(y.release(this._dependencies),this._dependencies=_),this._dependencyVersions!==f&&(S.release(this._dependencyVersions),this._dependencyVersions=f),this._functionSubscribersStore.clear(),this._objectSubscribersStore.clear(),this.flags=u.DIRTY|u.IDLE,this._error=null,this._value=void 0,this._promiseId=(this._promiseId+1)%this.MAX_PROMISE_ID}_isDirty(){return(this.flags&u.DIRTY)!==0}_setDirty(){this.flags|=u.DIRTY}_clearDirty(){this.flags&=-2}_isIdle(){return(this.flags&u.IDLE)!==0}_setIdle(){this.flags|=u.IDLE,this.flags&=-29}_isPending(){return(this.flags&u.PENDING)!==0}_setPending(){this.flags|=u.PENDING,this.flags&=-27}_isResolved(){return(this.flags&u.RESOLVED)!==0}_setResolved(){this.flags|=u.RESOLVED,this.flags&=-87}_isRejected(){return(this.flags&u.REJECTED)!==0}_setRejected(){this.flags|=u.REJECTED|u.HAS_ERROR,this.flags&=-15}_isRecomputing(){return(this.flags&u.RECOMPUTING)!==0}_setRecomputing(e){const t=u.RECOMPUTING;this.flags=this.flags&~t|-Number(e)&t}_getAsyncState(){return this._isPending()?U.PENDING:this._isResolved()?U.RESOLVED:this._isRejected()?U.REJECTED:U.IDLE}_getFlagsAsString(){const e=[];return this._isDirty()&&e.push("DIRTY"),this._isIdle()&&e.push("IDLE"),this._isPending()&&e.push("PENDING"),this._isResolved()&&e.push("RESOLVED"),this._isRejected()&&e.push("REJECTED"),this._isRecomputing()&&e.push("RECOMPUTING"),e.join(" | ")}_computeValue(){return this._isRecomputing()?this._value:((this._isDirty()||this._isIdle())&&this._recompute(),this._isPending()?this._handlePending():this._isRejected()?this._handleRejected():this._value)}_recompute(){if(this._isRecomputing())return;this._setRecomputing(!0);const e=this._dependencies,t=this._dependencyVersions,s=y.acquire(),n=S.acquire(),r=K();let c=0;const O=h=>{h._lastSeenEpoch!==r&&(h._lastSeenEpoch=r,c<s.length?(s[c]=h,n[c]=h.version):(s.push(h),n.push(h.version)),c++)},D=this._trackable.addDependency;this._trackable.addDependency=O;let C=!1;try{const h=R.run(this._trackable,this._fn);if(s.length=c,n.length=c,Q(h)){this._unsubscribes=q(s,e,this._unsubscribes,this),this._dependencies=s,this._dependencyVersions=n,C=!0,this._handleAsyncComputation(h),this._setRecomputing(!1);return}this._unsubscribes=q(s,e,this._unsubscribes,this),this._dependencies=s,this._dependencyVersions=n,C=!0,this._handleSyncResult(h)}catch(h){s.length=c,n.length=c,this._unsubscribes=q(s,e,this._unsubscribes,this),this._dependencies=s,this._dependencyVersions=n,C=!0,this._handleComputationError(h)}finally{this._trackable.addDependency=D,C?(e!==_&&y.release(e),t!==f&&S.release(t)):(y.release(s),S.release(n))}}_handleSyncResult(e){(!this._isResolved()||!this._equal(this._value,e))&&(this.version=this.version+1&A),this._value=e,this._clearDirty(),this._setResolved(),this._error=null,this._setRecomputing(!1)}_handleAsyncComputation(e){this._setPending(),this._clearDirty(),this._promiseId=this._promiseId>=this.MAX_PROMISE_ID?1:this._promiseId+1;const t=this._promiseId;e.then(s=>{t===this._promiseId&&this._handleAsyncResolution(s)}).catch(s=>{t===this._promiseId&&this._handleAsyncRejection(s)})}_handleAsyncResolution(e){(!this._isResolved()||!this._equal(this._value,e))&&(this.version=this.version+1&A),this._value=e,this._clearDirty(),this._setResolved(),this._error=null,this._setRecomputing(!1)}_handleAsyncRejection(e){const t=T(e,I,l.COMPUTED_ASYNC_COMPUTATION_FAILED);if(this._error=t,this._setRejected(),this._clearDirty(),this._setRecomputing(!1),this._onError&&typeof this._onError=="function")try{this._onError(t)}catch(s){console.error(l.CALLBACK_ERROR_IN_ERROR_HANDLER,s)}this._notifySubscribers(void 0,void 0)}_handleComputationError(e){const t=T(e,I,l.COMPUTED_COMPUTATION_FAILED);if(this._error=t,this._setRejected(),this._clearDirty(),this._setRecomputing(!1),this._onError&&typeof this._onError=="function")try{this._onError(t)}catch(s){console.error(l.CALLBACK_ERROR_IN_ERROR_HANDLER,s)}throw t}_handlePending(){if(this._hasDefaultValue)return this._defaultValue;throw new I(l.COMPUTED_ASYNC_PENDING_NO_DEFAULT)}_handleRejected(){if(this._error?.recoverable&&this._hasDefaultValue)return this._defaultValue;throw this._error}execute(){this._markDirty()}_markDirty(){this._isRecomputing()||this._isDirty()||(this._setDirty(),this._notifyJob())}_registerTracking(){const e=R.getCurrent();if(e)if(typeof e=="object"&&e!==null&&e.addDependency)e.addDependency(this);else if(typeof e=="function"){const t=e;t.addDependency?t.addDependency(this):this._functionSubscribersStore.add(e)}else e.execute&&this._objectSubscribersStore.add(e)}}Object.freeze(ee.prototype);function _e(i,e={}){return new ee(i,e)}class fe extends J{constructor(e,t={}){super(),this.run=()=>{if(this.isDisposed)throw new g(l.EFFECT_MUST_BE_FUNCTION);this._dependencyVersions!==f&&(S.release(this._dependencyVersions),this._dependencyVersions=f),this.execute()},this.dispose=()=>{if(!this.isDisposed){if(this._setDisposed(),this._safeCleanup(),this._unsubscribes!==p){for(let s=0;s<this._unsubscribes.length;s++){const n=this._unsubscribes[s];n&&n()}m.release(this._unsubscribes),this._unsubscribes=p}this._dependencies!==_&&(y.release(this._dependencies),this._dependencies=_),this._dependencyVersions!==f&&(S.release(this._dependencyVersions),this._dependencyVersions=f)}},this.addDependency=s=>{if(this.isExecuting&&this._nextDeps&&this._nextUnsubs&&this._nextVersions){const n=s,r=this._currentEpoch;if(n._lastSeenEpoch===r)return;n._lastSeenEpoch=r,this._nextDeps.push(n),this._nextVersions.push(n.version),n._tempUnsub?(this._nextUnsubs.push(n._tempUnsub),n._tempUnsub=void 0):this._subscribeTo(n)}},this.execute=()=>{if(this.isDisposed||this.isExecuting||!this._shouldExecute())return;this._checkInfiniteLoop(),this._setExecuting(!0),this._safeCleanup();const s=this._dependencies,n=this._dependencyVersions,r=this._unsubscribes,c=y.acquire(),O=S.acquire(),D=m.acquire(),C=K();if(s!==_&&r!==p)for(let o=0;o<s.length;o++){const a=s[o];a&&(a._tempUnsub=r[o])}this._nextDeps=c,this._nextVersions=O,this._nextUnsubs=D,this._currentEpoch=C;let h=!1;try{const o=R.run(this,this._fn);this._dependencies=c,this._dependencyVersions=O,this._unsubscribes=D,h=!0,this._checkLoopWarnings(),Q(o)?o.then(a=>{!this.isDisposed&&typeof a=="function"&&(this._cleanup=a)}).catch(a=>{console.error(T(a,g,l.EFFECT_EXECUTION_FAILED))}):this._cleanup=typeof o=="function"?o:null}catch(o){h=!0,console.error(T(o,g,l.EFFECT_EXECUTION_FAILED)),this._cleanup=null}finally{if(this._setExecuting(!1),this._nextDeps=null,this._nextVersions=null,this._nextUnsubs=null,h){if(s!==_){for(let o=0;o<s.length;o++){const a=s[o];a?._tempUnsub&&(a._tempUnsub(),a._tempUnsub=void 0)}y.release(s)}r!==p&&m.release(r),n!==f&&S.release(n)}else{y.release(c),S.release(O);for(let o=0;o<D.length;o++)D[o]?.();if(m.release(D),s!==_)for(let o=0;o<s.length;o++){const a=s[o];a&&(a._tempUnsub=void 0)}}}},this._currentEpoch=-1,this._lastFlushEpoch=-1,this._executionsInEpoch=0,this._fn=e,this._sync=t.sync??!1,this._maxExecutions=t.maxExecutionsPerSecond??F.MAX_EXECUTIONS_PER_SECOND,this._maxExecutionsPerFlush=t.maxExecutionsPerFlush??F.MAX_EXECUTIONS_PER_EFFECT,this._trackModifications=t.trackModifications??!1,this._cleanup=null,this._dependencies=_,this._dependencyVersions=f,this._unsubscribes=p,this._nextDeps=null,this._nextVersions=null,this._nextUnsubs=null,this._history=E?[]:null,this._executionCount=0,b.attachDebugInfo(this,"effect",this.id)}_subscribeTo(e){try{const t=e.subscribe(()=>{this._trackModifications&&this.isExecuting&&(e._modifiedAtEpoch=this._currentEpoch),this._sync?this.execute():x.schedule(this.execute)});this._nextUnsubs&&this._nextUnsubs.push(t)}catch(t){console.error(T(t,g,l.EFFECT_EXECUTION_FAILED)),this._nextUnsubs&&this._nextUnsubs.push(()=>{})}}get isDisposed(){return(this.flags&P.DISPOSED)!==0}get executionCount(){return this._executionCount}get isExecuting(){return(this.flags&P.EXECUTING)!==0}_setDisposed(){this.flags|=P.DISPOSED}_setExecuting(e){const t=P.EXECUTING;this.flags=this.flags&~t|-Number(e)&t}_safeCleanup(){if(this._cleanup&&typeof this._cleanup=="function"){try{this._cleanup()}catch(e){console.error(T(e,g,l.EFFECT_CLEANUP_FAILED))}this._cleanup=null}}_checkInfiniteLoop(){if(this._lastFlushEpoch!==v&&(this._lastFlushEpoch=v,this._executionsInEpoch=0),this._executionsInEpoch++,this._executionsInEpoch>this._maxExecutionsPerFlush&&this._throwInfiniteLoopError("per-effect"),oe()>F.MAX_EXECUTIONS_PER_FLUSH&&this._throwInfiniteLoopError("global"),this._executionCount++,this._history){const e=Date.now();this._history.push(e),this._history.length>F.MAX_EXECUTIONS_PER_SECOND+10&&this._history.shift(),this._checkTimestampLoop(e)}}_checkTimestampLoop(e){const t=this._history;if(!t||this._maxExecutions<=0)return;const s=e-1e3;let n=0;for(let r=t.length-1;r>=0&&!(t[r]<s);r--)n++;if(n>this._maxExecutions){const r=new g(`Effect executed ${n} times within 1 second. Infinite loop suspected`);if(this.dispose(),console.error(r),E)throw r}}_throwInfiniteLoopError(e){const t=new g(`Infinite loop detected (${e}): effect executed ${this._executionsInEpoch} times in current flush. Total executions in flush: ${z}`);throw this.dispose(),console.error(t),t}_shouldExecute(){if(this._dependencies===_||this._dependencyVersions===f)return!0;for(let e=0;e<this._dependencies.length;e++){const t=this._dependencies[e];if(t){if("value"in t)try{Z(()=>t.value)}catch{return!0}if(t.version!==this._dependencyVersions[e])return!0}}return!1}_checkLoopWarnings(){if(this._trackModifications&&b.enabled){const e=this._dependencies;for(let t=0;t<e.length;t++){const s=e[t];s&&s._modifiedAtEpoch===this._currentEpoch&&b.warn(!0,`Effect is reading a dependency (${b.getDebugName(s)||"unknown"}) that it just modified. Infinite loop may occur`)}}}}function de(i,e={}){if(typeof i!="function")throw new g(l.EFFECT_MUST_BE_FUNCTION);const t=new fe(i,e);return t.execute(),t}function te(i){return i!==null&&typeof i=="object"&&"value"in i&&"subscribe"in i&&typeof i.subscribe=="function"}function Ee(i){if(b.enabled){const e=b.getDebugType(i);if(e)return e==="computed"}return te(i)&&"invalidate"in i&&typeof i.invalidate=="function"}function be(i){return i!==null&&typeof i=="object"&&"dispose"in i&&"run"in i&&typeof i.dispose=="function"&&typeof i.run=="function"}exports.AsyncState=U;exports.AtomError=d;exports.ComputedError=I;exports.DEBUG_CONFIG=k;exports.DEBUG_RUNTIME=b;exports.EffectError=g;exports.POOL_CONFIG=se;exports.SCHEDULER_CONFIG=F;exports.SchedulerError=N;exports.atom=ae;exports.batch=he;exports.computed=_e;exports.effect=de;exports.isAtom=te;exports.isComputed=Ee;exports.isEffect=be;exports.scheduler=x;exports.untracked=Z;
2
2
  //# sourceMappingURL=index.cjs.map