@but212/atom-effect 0.10.1 → 0.11.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/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const se={ONE_SECOND_MS:1e3},U={IDLE:"idle",PENDING:"pending",RESOLVED:"resolved",REJECTED:"rejected"},x={DISPOSED:1,EXECUTING:2},c={DIRTY:1,IDLE:2,PENDING:4,RESOLVED:8,REJECTED:16,RECOMPUTING:32,HAS_ERROR:64},R={SYNC:1,NOTIFICATION_SCHEDULED:2},ie={MAX_SIZE:1e3,WARMUP_SIZE:100},g={MAX_EXECUTIONS_PER_SECOND:1e3,CLEANUP_THRESHOLD:1e3,MAX_EXECUTIONS_PER_EFFECT:100,MAX_EXECUTIONS_PER_FLUSH:1e4,MAX_FLUSH_ITERATIONS:1e3,MIN_FLUSH_ITERATIONS:10},k={MAX_DEPENDENCIES:1e3,WARN_INFINITE_LOOP:!0},m=1073741823,l=typeof process<"u"&&process.env&&process.env.NODE_ENV!=="production",re=Object.freeze([]);class p 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 p{constructor(e,t=null){super(e,t,!0),this.name="ComputedError"}}class S extends p{constructor(e,t=null){super(e,t,!1),this.name="EffectError"}}class O extends p{constructor(e,t=null){super(e,t,!1),this.name="SchedulerError"}}const h={COMPUTED_MUST_BE_FUNCTION:"Computed function must be a function",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",ATOM_SUBSCRIBER_MUST_BE_FUNCTION:"Subscription listener must be a function or Subscriber object",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",CALLBACK_ERROR_IN_ERROR_HANDLER:"Error occurred during onError callback execution"},V=Symbol("debugName"),ne=Symbol("id"),w=Symbol("type"),q=Symbol("noDefaultValue");function oe(i){return"dependencies"in i&&Array.isArray(i.dependencies)}let z=0;function Y(i,e,t){if(i._visitedEpoch!==t){if(i._visitedEpoch=t,i===e)throw new I("Indirect circular dependency detected");if(oe(i)){const s=i.dependencies;for(let r=0;r<s.length;r++){const n=s[r];n&&Y(n,e,t)}}}}const f={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){if(i===e)throw new I("Direct circular dependency detected");this.enabled&&(z++,Y(i,e,z))},attachDebugInfo(i,e,t){if(!this.enabled)return;const s=i;s[V]=`${e}_${t}`,s[ne]=t,s[w]=e},getDebugName(i){if(i!=null&&V in i)return i[V]},getDebugType(i){if(i!=null&&w in i)return i[w]}};let ce=1;const he=()=>ce++;class H{constructor(){this.id=he()&m,this.flags=0}}class Q extends H{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 p(h.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 p(h.ATOM_INDIVIDUAL_SUBSCRIBER_FAILED,s))),this._objectSubscribers.forEachSafe(s=>s.execute(),s=>console.error(new p(h.ATOM_INDIVIDUAL_SUBSCRIBER_FAILED,s)))}}let F=0;function $(){return F=F+1&m||1,F}function ue(){return F}let v=0,j=0,P=!1;function G(){return P?(l&&console.warn("Warning: startFlush() called during flush - ignored to prevent infinite loop detection bypass"),!1):(P=!0,v=v+1&m,j=0,!0)}function X(){P=!1}function ae(){return P?++j:0}class _e{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=g.MAX_FLUSH_ITERATIONS}get phase(){return this.isProcessing||this.isFlushingSync?2:this.isBatching?1:0}schedule(e){if(typeof e!="function")throw new O("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(){this.isProcessing||this.queueSize===0||(this.isProcessing=!0,queueMicrotask(()=>{try{if(this.queueSize===0)return;const e=G();this._drainQueue(),e&&X()}finally{this.isProcessing=!1,this.queueSize>0&&!this.isBatching&&this.flush()}}))}flushSync(){this.isFlushingSync=!0;const e=G();try{this._mergeBatchQueue(),this._drainQueue()}finally{this.isFlushingSync=!1,e&&X()}}_mergeBatchQueue(){if(this._epoch++,this.batchQueueSize>0){for(let e=0;e<this.batchQueueSize;e++){const t=this.batchQueue[e];t&&t._nextEpoch!==this._epoch&&(t._nextEpoch=this._epoch,this.queue[this.queueSize++]=t)}this.batchQueueSize=0}}_drainQueue(){let e=0;for(;this.queueSize>0;){if(++e>this.maxFlushIterations){this._handleFlushOverflow();break}this._processCurrentQueue(),this._mergeBatchQueue()}}_processCurrentQueue(){const e=this.queue,t=this.queueSize;this.queue=this.queue===this.queueA?this.queueB:this.queueA,this.queueSize=0,this._epoch++,this._processJobs(e,t)}_handleFlushOverflow(){console.error(new O(`Maximum flush iterations (${this.maxFlushIterations}) exceeded. Possible infinite loop.`)),this.queueSize=0,this.queue.length=0,this.batchQueueSize=0}_processJobs(e,t){for(let s=0;s<t;s++)try{e[s]?.()}catch(r){console.error(new O("Error occurred during scheduler execution",r))}e.length=0}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<g.MIN_FLUSH_ITERATIONS)throw new O(`Max flush iterations must be at least ${g.MIN_FLUSH_ITERATIONS}`);this.maxFlushIterations=e}}const T=new _e;function le(i){if(typeof i!="function")throw new p("Batch callback must be a function");T.startBatch();try{return i()}finally{T.endBatch()}}class fe{constructor(){this.current=null}run(e,t){const s=this.current;this.current=e;try{return t()}finally{this.current=s}}getCurrent(){return this.current}}const C=new fe;function J(i){if(typeof i!="function")throw new p("Untracked callback must be a function");const e=C.current;C.current=null;try{return i()}finally{C.current=e}}class L{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(r){t?t(r):console.error("[SubscriberManager] Error in subscriber callback:",r)}}get size(){return this.subscribers?.length??0}get hasSubscribers(){return this.subscribers!==null&&this.subscribers.length>0}clear(){this.subscribers=null}toArray(){return this.subscribers?[...this.subscribers]:[]}}class B{constructor(){this.pool=[],this.maxPoolSize=50,this.maxReusableCapacity=256,this.stats=l?{acquired:0,released:0,rejected:{frozen:0,tooLarge:0,poolFull:0}}:null}acquire(){return l&&this.stats&&this.stats.acquired++,this.pool.pop()??[]}release(e,t){if(!(t&&e===t)){if(Object.isFrozen(e)){l&&this.stats&&this.stats.rejected.frozen++;return}if(e.length>this.maxReusableCapacity){l&&this.stats&&this.stats.rejected.tooLarge++;return}if(this.pool.length>=this.maxPoolSize){l&&this.stats&&this.stats.rejected.poolFull++;return}e.length=0,this.pool.push(e),l&&this.stats&&this.stats.released++}}getStats(){if(!l||!this.stats)return null;const{acquired:e,released:t,rejected:s}=this.stats,r=s.frozen+s.tooLarge+s.poolFull;return{acquired:e,released:t,rejected:s,leaked:e-t-r,poolSize:this.pool.length}}reset(){this.pool.length=0,l&&this.stats&&(this.stats.acquired=0,this.stats.released=0,this.stats.rejected={frozen:0,tooLarge:0,poolFull:0})}}const u=Object.freeze([]),d=Object.freeze([]),a=Object.freeze([]),D=new B,y=new B,E=new B;function W(i){return i!==null&&typeof i=="object"&&"value"in i&&"subscribe"in i&&typeof i.subscribe=="function"}function de(i){if(f.enabled&&(i==null||typeof i=="object")){const e=f.getDebugType(i);if(e)return e==="computed"}return W(i)&&"invalidate"in i&&typeof i.invalidate=="function"}function Ee(i){return i!==null&&typeof i=="object"&&"dispose"in i&&"run"in i&&typeof i.dispose=="function"&&typeof i.run=="function"}function K(i){return i!=null&&typeof i.then=="function"}function pe(i){return typeof i=="object"&&i!==null}function be(i){return(typeof i=="object"||typeof i=="function")&&i!==null&&typeof i.addDependency=="function"}function Se(i){return typeof i=="function"&&typeof i.addDependency!="function"}function ge(i){return pe(i)&&typeof i.execute=="function"}function Z(i,e,t,s){if(e){if(be(e)){e.addDependency(i);return}if(Se(e)){t.add(e);return}ge(e)&&s.add(e)}}function De(i,e,t,s){if(e!==u&&t!==d)for(let n=0;n<e.length;n++){const o=e[n];o&&(o._tempUnsub=t[n])}const r=y.acquire();r.length=i.length;for(let n=0;n<i.length;n++){const o=i[n];o&&(o._tempUnsub?(r[n]=o._tempUnsub,o._tempUnsub=void 0):(f.checkCircular(o,s),r[n]=o.subscribe(s)))}if(e!==u)for(let n=0;n<e.length;n++){const o=e[n];o?._tempUnsub&&(o._tempUnsub(),o._tempUnsub=void 0)}return t!==d&&y.release(t),r}class Ie extends Q{constructor(e,t){super(),this._functionSubscribersStore=null,this._objectSubscribersStore=null,this._value=e,t&&(this.flags|=R.SYNC),f.attachDebugInfo(this,"atom",this.id)}get _functionSubscribers(){return this._functionSubscribersStore||(this._functionSubscribersStore=new L),this._functionSubscribersStore}get _objectSubscribers(){return this._objectSubscribersStore||(this._objectSubscribersStore=new L),this._objectSubscribersStore}get value(){const e=C.current;return e&&Z(this,e,this._functionSubscribers,this._objectSubscribers),this._value}set value(e){if(Object.is(this._value,e))return;const t=this._value;this._value=e,this.version=this.version+1&m;const s=this._functionSubscribersStore?.hasSubscribers,r=this._objectSubscribersStore?.hasSubscribers;(s||r)&&this._scheduleNotification(t)}_scheduleNotification(e){if(this.flags&R.NOTIFICATION_SCHEDULED||(this._pendingOldValue=e,this.flags|=R.NOTIFICATION_SCHEDULED),this.flags&R.SYNC&&!T.isBatching){this._flushNotifications();return}this._notifyTask||(this._notifyTask=()=>this._flushNotifications()),T.schedule(this._notifyTask)}_flushNotifications(){if(!(this.flags&R.NOTIFICATION_SCHEDULED))return;const e=this._pendingOldValue,t=this._value;this._pendingOldValue=void 0,this.flags&=-3,this._notifySubscribers(t,e)}_notifySubscribers(e,t){this._functionSubscribersStore&&this._functionSubscribersStore.forEachSafe(s=>s(e,t)),this._objectSubscribersStore&&this._objectSubscribersStore.forEachSafe(s=>s.execute())}peek(){return this._value}dispose(){this._functionSubscribersStore?.clear(),this._objectSubscribersStore?.clear(),this._value=void 0,this._notifyTask=void 0}}function ye(i,e={}){return new Ie(i,e.sync??!1)}function A(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 p)return i;const s=i instanceof Error?i.message:String(i),r=i instanceof Error?i:null;return new e(`Unexpected error (${t}): ${s}`,r)}const ee=c.RESOLVED|c.PENDING|c.REJECTED,M=Array(ee+1).fill(U.IDLE);M[c.RESOLVED]=U.RESOLVED;M[c.PENDING]=U.PENDING;M[c.REJECTED]=U.REJECTED;class te extends Q{constructor(e,t={}){if(typeof e!="function")throw new I(h.COMPUTED_MUST_BE_FUNCTION);if(super(),this._cachedErrors=null,this._errorCacheEpoch=-1,this._value=void 0,this.flags=c.DIRTY|c.IDLE,this._error=null,this._promiseId=0,this._equal=t.equal??Object.is,this._fn=e,this._defaultValue="defaultValue"in t?t.defaultValue:q,this._hasDefaultValue=this._defaultValue!==q,this._onError=t.onError??null,this.MAX_PROMISE_ID=Number.MAX_SAFE_INTEGER-1,this._functionSubscribersStore=new L,this._objectSubscribersStore=new L,this._dependencies=u,this._dependencyVersions=a,this._unsubscribes=d,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=>{}}),f.attachDebugInfo(this,"computed",this.id),f.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(){return this._registerTracking(),this._computeValue()}peek(){return this._value}get state(){return this._registerTracking(),this._getAsyncState()}get hasError(){if(this._registerTracking(),this._isRejected())return!0;for(let e=0;e<this._dependencies.length;e++){const t=this._dependencies[e];if(t&&"hasError"in t&&t.hasError)return!0}return!1}get isValid(){return!this.hasError}get errors(){if(this._registerTracking(),!this.hasError)return re;const e=ue();if(this._errorCacheEpoch===e&&this._cachedErrors!==null)return this._cachedErrors;const t=new Set;this._error&&t.add(this._error);for(let s=0;s<this._dependencies.length;s++){const r=this._dependencies[s];if(r&&"errors"in r){const n=r.errors;for(let o=0;o<n.length;o++){const _=n[o];_&&t.add(_)}}}return this._cachedErrors=Object.freeze([...t]),this._errorCacheEpoch=e,this._cachedErrors}get lastError(){return this._registerTracking(),this._error}get isPending(){return this._registerTracking(),this._isPending()}get isResolved(){return this._registerTracking(),this._isResolved()}invalidate(){this._markDirty(),this._dependencyVersions!==a&&(E.release(this._dependencyVersions),this._dependencyVersions=a),this._errorCacheEpoch=-1,this._cachedErrors=null}dispose(){if(this._unsubscribes!==d){for(let e=0;e<this._unsubscribes.length;e++){const t=this._unsubscribes[e];t&&t()}y.release(this._unsubscribes),this._unsubscribes=d}this._dependencies!==u&&(D.release(this._dependencies),this._dependencies=u),this._dependencyVersions!==a&&(E.release(this._dependencyVersions),this._dependencyVersions=a),this._functionSubscribersStore.clear(),this._objectSubscribersStore.clear(),this.flags=c.DIRTY|c.IDLE,this._error=null,this._value=void 0,this._promiseId=(this._promiseId+1)%this.MAX_PROMISE_ID,this._cachedErrors=null,this._errorCacheEpoch=-1}_isDirty(){return(this.flags&c.DIRTY)!==0}_setDirty(){this.flags|=c.DIRTY}_clearDirty(){this.flags&=-2}_isIdle(){return(this.flags&c.IDLE)!==0}_setIdle(){this.flags|=c.IDLE,this.flags&=-29}_isPending(){return(this.flags&c.PENDING)!==0}_setPending(){this.flags|=c.PENDING,this.flags&=-27}_isResolved(){return(this.flags&c.RESOLVED)!==0}_setResolved(){this.flags|=c.RESOLVED,this.flags&=-87}_isRejected(){return(this.flags&c.REJECTED)!==0}_setRejected(){this.flags|=c.REJECTED|c.HAS_ERROR,this.flags&=-15}_isRecomputing(){return(this.flags&c.RECOMPUTING)!==0}_setRecomputing(e){const t=c.RECOMPUTING;this.flags=this.flags&~t|-Number(e)&t}_getAsyncState(){return M[this.flags&ee]}_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._prepareComputationContext();let t=!1;try{const s=C.run(this._trackable,this._fn);this._commitDependencies(e),t=!0,K(s)?this._handleAsyncComputation(s):this._handleSyncResult(s)}catch(s){if(!t)try{this._commitDependencies(e),t=!0}catch(r){this._handleComputationError(r)}this._handleComputationError(s)}finally{this._cleanupContext(e,t),this._setRecomputing(!1)}}_prepareComputationContext(){const e=this._dependencies,t=this._dependencyVersions,s=D.acquire(),r=E.acquire(),n=$(),o={depCount:0},_=b=>{b._lastSeenEpoch!==n&&(b._lastSeenEpoch=n,o.depCount<s.length?(s[o.depCount]=b,r[o.depCount]=b.version):(s.push(b),r.push(b.version)),o.depCount++)},N=this._trackable.addDependency;return this._trackable.addDependency=_,{prevDeps:e,prevVersions:t,nextDeps:s,nextVersions:r,originalAdd:N,state:o}}_commitDependencies(e){const{nextDeps:t,nextVersions:s,state:r,prevDeps:n}=e;t.length=r.depCount,s.length=r.depCount,this._unsubscribes=De(t,n,this._unsubscribes,this),this._dependencies=t,this._dependencyVersions=s}_cleanupContext(e,t){this._trackable.addDependency=e.originalAdd,t?(e.prevDeps!==u&&D.release(e.prevDeps),e.prevVersions!==a&&E.release(e.prevVersions)):(D.release(e.nextDeps),E.release(e.nextVersions))}_handleSyncResult(e){const t=!this._isResolved()||!this._equal(this._value,e);this.version=this.version+Number(t)&m,this._value=e,this._clearDirty(),this._setResolved(),this._error=null,this._setRecomputing(!1),this._cachedErrors=null,this._errorCacheEpoch=-1}_handleAsyncComputation(e){this._setPending(),this._clearDirty(),this._notifyJob(),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.version=this.version+Number(t)&m,this._value=e,this._clearDirty(),this._setResolved(),this._error=null,this._setRecomputing(!1),this._cachedErrors=null,this._errorCacheEpoch=-1,this._notifyJob()}_handleAsyncRejection(e){const t=A(e,I,h.COMPUTED_ASYNC_COMPUTATION_FAILED),s=!this._isRejected();if(this.version=this.version+Number(s)&m,this._error=t,this._setRejected(),this._clearDirty(),this._setRecomputing(!1),this._onError)try{this._onError(t)}catch(r){console.error(h.CALLBACK_ERROR_IN_ERROR_HANDLER,r)}this._notifyJob()}_handleComputationError(e){const t=A(e,I,h.COMPUTED_COMPUTATION_FAILED);if(this._error=t,this._setRejected(),this._clearDirty(),this._setRecomputing(!1),this._onError)try{this._onError(t)}catch(s){console.error(h.CALLBACK_ERROR_IN_ERROR_HANDLER,s)}throw t}_handlePending(){if(this._hasDefaultValue)return this._defaultValue;throw new I(h.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(){Z(this,C.getCurrent(),this._functionSubscribersStore,this._objectSubscribersStore)}}Object.freeze(te.prototype);function me(i,e={}){return new te(i,e)}class Ce extends H{constructor(e,t={}){super(),this.run=()=>{if(this.isDisposed)throw new S(h.EFFECT_MUST_BE_FUNCTION);this._dependencyVersions!==a&&(E.release(this._dependencyVersions),this._dependencyVersions=a),this.execute()},this.dispose=()=>{if(!this.isDisposed){if(this._setDisposed(),this._safeCleanup(),this._unsubscribes!==d){for(let r=0;r<this._unsubscribes.length;r++){const n=this._unsubscribes[r];n&&n()}y.release(this._unsubscribes),this._unsubscribes=d}this._dependencies!==u&&(D.release(this._dependencies),this._dependencies=u),this._dependencyVersions!==a&&(E.release(this._dependencyVersions),this._dependencyVersions=a)}},this.addDependency=r=>{if(this.isExecuting&&this._nextDeps&&this._nextUnsubs&&this._nextVersions){const n=this._currentEpoch;if(r._lastSeenEpoch===n)return;r._lastSeenEpoch=n,this._nextDeps.push(r),this._nextVersions.push(r.version),r._tempUnsub?(this._nextUnsubs.push(r._tempUnsub),r._tempUnsub=void 0):this._subscribeTo(r)}},this.execute=()=>{if(this.isDisposed||this.isExecuting||!this._shouldExecute())return;this._checkInfiniteLoop(),this._setExecuting(!0),this._safeCleanup();const r=this._prepareEffectContext();let n=!1;try{const o=C.run(this,this._fn);this._commitEffect(r),n=!0,this._checkLoopWarnings(),K(o)?o.then(_=>{!this.isDisposed&&typeof _=="function"&&(this._cleanup=_)}).catch(_=>{this._handleExecutionError(_)}):this._cleanup=typeof o=="function"?o:null}catch(o){n=!0,this._handleExecutionError(o),this._cleanup=null}finally{this._cleanupEffect(r,n),this._setExecuting(!1)}},this._currentEpoch=-1,this._lastFlushEpoch=-1,this._executionsInEpoch=0,this._fn=e,this._sync=t.sync??!1,this._maxExecutions=t.maxExecutionsPerSecond??g.MAX_EXECUTIONS_PER_SECOND,this._maxExecutionsPerFlush=t.maxExecutionsPerFlush??g.MAX_EXECUTIONS_PER_EFFECT,this._trackModifications=t.trackModifications??!1,this._cleanup=null,this._dependencies=u,this._dependencyVersions=a,this._unsubscribes=d,this._nextDeps=null,this._nextVersions=null,this._nextUnsubs=null,this._onError=t.onError??null,this._historyPtr=0;const s=Number.isFinite(this._maxExecutions);this._historyCapacity=s?Math.min(this._maxExecutions+1,g.MAX_EXECUTIONS_PER_SECOND+1):0,this._history=l&&s&&this._historyCapacity>0?new Array(this._historyCapacity).fill(0):null,this._executionCount=0,f.attachDebugInfo(this,"effect",this.id)}_prepareEffectContext(){const e=this._dependencies,t=this._dependencyVersions,s=this._unsubscribes,r=D.acquire(),n=E.acquire(),o=y.acquire(),_=$();if(e!==u&&s!==d)for(let N=0;N<e.length;N++){const b=e[N];b&&(b._tempUnsub=s[N])}return this._nextDeps=r,this._nextVersions=n,this._nextUnsubs=o,this._currentEpoch=_,{prevDeps:e,prevVersions:t,prevUnsubs:s,nextDeps:r,nextVersions:n,nextUnsubs:o}}_commitEffect(e){const t=e.nextDeps.length;e.nextDeps.length=t,e.nextVersions.length=t,this._dependencies=e.nextDeps,this._dependencyVersions=e.nextVersions,this._unsubscribes=e.nextUnsubs}_cleanupEffect(e,t){if(this._nextDeps=null,this._nextVersions=null,this._nextUnsubs=null,t){if(e.prevDeps!==u){for(let s=0;s<e.prevDeps.length;s++){const r=e.prevDeps[s];r?._tempUnsub&&(r._tempUnsub(),r._tempUnsub=void 0)}D.release(e.prevDeps)}e.prevUnsubs!==d&&y.release(e.prevUnsubs),e.prevVersions!==a&&E.release(e.prevVersions)}else{D.release(e.nextDeps),E.release(e.nextVersions);for(let s=0;s<e.nextUnsubs.length;s++)e.nextUnsubs[s]?.();if(y.release(e.nextUnsubs),e.prevDeps!==u)for(let s=0;s<e.prevDeps.length;s++){const r=e.prevDeps[s];r&&(r._tempUnsub=void 0)}}}_subscribeTo(e){try{const t=e.subscribe(()=>{this._trackModifications&&this.isExecuting&&(e._modifiedAtEpoch=this._currentEpoch),this._sync?this.execute():T.schedule(this.execute)});this._nextUnsubs&&this._nextUnsubs.push(t)}catch(t){console.error(A(t,S,h.EFFECT_EXECUTION_FAILED)),this._nextUnsubs&&this._nextUnsubs.push(()=>{})}}get isDisposed(){return(this.flags&x.DISPOSED)!==0}get executionCount(){return this._executionCount}get isExecuting(){return(this.flags&x.EXECUTING)!==0}_setDisposed(){this.flags|=x.DISPOSED}_setExecuting(e){const t=x.EXECUTING;this.flags=this.flags&~t|-Number(e)&t}_safeCleanup(){if(this._cleanup){try{this._cleanup()}catch(e){console.error(A(e,S,h.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"),ae()>g.MAX_EXECUTIONS_PER_FLUSH&&this._throwInfiniteLoopError("global"),this._executionCount++,this._history&&this._maxExecutions>0){const e=Date.now(),t=this._historyPtr,s=this._historyCapacity;this._history[t]=e;const r=(t+1)%s,n=this._history[r]??0;if(this._historyPtr=r,n>0&&e-n<se.ONE_SECOND_MS){const o=new S(`Effect executed ${s} times within 1 second. Infinite loop suspected`);if(this.dispose(),console.error(o),this._onError&&this._onError(o),l)throw o}}}_throwInfiniteLoopError(e){const t=new S(`Infinite loop detected (${e}): effect executed ${this._executionsInEpoch} times in current flush. Total executions in flush: ${j}`);throw this.dispose(),console.error(t),t}_shouldExecute(){if(this._dependencies===u||this._dependencyVersions===a)return!0;for(let e=0;e<this._dependencies.length;e++){const t=this._dependencies[e];if(t){if("value"in t)try{J(()=>t.value)}catch{return!0}if(t.version!==this._dependencyVersions[e])return!0}}return!1}_handleExecutionError(e){const t=A(e,S,h.EFFECT_EXECUTION_FAILED);console.error(t),this._onError&&this._onError(t)}_checkLoopWarnings(){if(this._trackModifications&&f.enabled){const e=this._dependencies;for(let t=0;t<e.length;t++){const s=e[t];s&&s._modifiedAtEpoch===this._currentEpoch&&f.warn(!0,`Effect is reading a dependency (${f.getDebugName(s)||"unknown"}) that it just modified. Infinite loop may occur`)}}}}function Ne(i,e={}){if(typeof i!="function")throw new S(h.EFFECT_MUST_BE_FUNCTION);const t=new Ce(i,e);return t.execute(),t}exports.AsyncState=U;exports.AtomError=p;exports.ComputedError=I;exports.DEBUG_CONFIG=k;exports.DEBUG_RUNTIME=f;exports.EffectError=S;exports.POOL_CONFIG=ie;exports.SCHEDULER_CONFIG=g;exports.SchedulerError=O;exports.atom=ye;exports.batch=le;exports.computed=me;exports.effect=Ne;exports.isAtom=W;exports.isComputed=de;exports.isEffect=Ee;exports.scheduler=T;exports.untracked=J;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const ie={ONE_SECOND_MS:1e3},U={IDLE:"idle",PENDING:"pending",RESOLVED:"resolved",REJECTED:"rejected"},x={DISPOSED:1,EXECUTING:2},u={DIRTY:1,IDLE:2,PENDING:4,RESOLVED:8,REJECTED:16,RECOMPUTING:32,HAS_ERROR:64},T={SYNC:1,NOTIFICATION_SCHEDULED:2},re={MAX_SIZE:1e3,WARMUP_SIZE:100},y={MAX_EXECUTIONS_PER_SECOND:1e3,CLEANUP_THRESHOLD:1e3,MAX_EXECUTIONS_PER_EFFECT:100,MAX_EXECUTIONS_PER_FLUSH:1e4,MAX_FLUSH_ITERATIONS:1e3,MIN_FLUSH_ITERATIONS:10},z={MAX_DEPENDENCIES:1e3,WARN_INFINITE_LOOP:!0},I=1073741823,j=1<<19,l=typeof process<"u"&&process.env&&process.env.NODE_ENV!=="production",ne=Object.freeze([]);class p extends Error{constructor(e,t=null,s=!0){super(e),this.name="AtomError",this.cause=t,this.recoverable=s,this.timestamp=new Date}}class S extends p{constructor(e,t=null){super(e,t,!0),this.name="ComputedError"}}class g extends p{constructor(e,t=null){super(e,t,!1),this.name="EffectError"}}class N extends p{constructor(e,t=null){super(e,t,!1),this.name="SchedulerError"}}const h={COMPUTED_MUST_BE_FUNCTION:"Computed function must be a function",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",ATOM_SUBSCRIBER_MUST_BE_FUNCTION:"Subscription listener must be a function or Subscriber object",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",CALLBACK_ERROR_IN_ERROR_HANDLER:"Error occurred during onError callback execution"},V=Symbol("debugName"),oe=Symbol("id"),w=Symbol("type"),Q=Symbol("noDefaultValue");function ue(i){return"dependencies"in i&&Array.isArray(i.dependencies)}let q=0;function Y(i,e,t){if(i._visitedEpoch!==t){if(i._visitedEpoch=t,i===e)throw new S("Indirect circular dependency detected");if(ue(i)){const s=i.dependencies;for(let r=0;r<s.length;r++){const n=s[r];n&&Y(n,e,t)}}}}const f={enabled:typeof process<"u"&&process.env?.NODE_ENV==="development",maxDependencies:z.MAX_DEPENDENCIES,warnInfiniteLoop:z.WARN_INFINITE_LOOP,warn(i,e){this.enabled&&i&&console.warn(`[Atom Effect] ${e}`)},checkCircular(i,e){if(i===e)throw new S("Direct circular dependency detected");this.enabled&&(q++,Y(i,e,q))},attachDebugInfo(i,e,t){if(!this.enabled)return;const s=i;s[V]=`${e}_${t}`,s[oe]=t,s[w]=e},getDebugName(i){if(i!=null&&V in i)return i[V]},getDebugType(i){if(i!=null&&w in i)return i[w]}};let he=1;const ce=()=>he++;class H{constructor(){this.id=ce()&I,this.flags=0,this.version=0}rotatePhase(){return this.version=this.version+1&I,this.version}getShift(e){return this.version-e&I}}class $ extends H{constructor(){super(),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 p(h.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 p(h.ATOM_INDIVIDUAL_SUBSCRIBER_FAILED,s))),this._objectSubscribers.forEachSafe(s=>s.execute(),s=>console.error(new p(h.ATOM_INDIVIDUAL_SUBSCRIBER_FAILED,s)))}}let F=0;function J(){return F=F+1&I||1,F}function ae(){return F}let P=0,k=0,v=!1;function G(){return v?(l&&console.warn("Warning: startFlush() called during flush - ignored to prevent infinite loop detection bypass"),!1):(v=!0,P=P+1&I,k=0,!0)}function X(){v=!1}function _e(){return v?++k:0}class le{constructor(){this.queueA=[],this.queueB=[],this.queue=this.queueA,this.queueSize=0,this.urgentQueueA=[],this.urgentQueueB=[],this.urgentQueue=this.urgentQueueA,this.urgentQueueSize=0,this._epoch=0,this.isProcessing=!1,this.isBatching=!1,this.batchDepth=0,this.batchQueue=[],this.batchQueueSize=0,this.isFlushingSync=!1,this.maxFlushIterations=y.MAX_FLUSH_ITERATIONS}get phase(){return this.isProcessing||this.isFlushingSync?2:this.isBatching?1:0}schedule(e,t){if(typeof e!="function")throw new N("Scheduler callback must be a function");if(e._nextEpoch!==this._epoch)if(e._nextEpoch=this._epoch,this.isBatching||this.isFlushingSync)this.batchQueue[this.batchQueueSize++]=e;else{const s=this._calculateUrgency(e,t);this.urgentQueue[this.urgentQueueSize]=e,this.queue[this.queueSize]=e,this.urgentQueueSize+=s,this.queueSize+=s^1,this.isProcessing||this.flush()}}_calculateUrgency(e,t){if(!t||e._cachedVersion===void 0)return 0;const s=t.getShift(e._cachedVersion);return j-1-s>>>31&1}flush(){this.isProcessing||this.queueSize===0&&this.urgentQueueSize===0||(this.isProcessing=!0,queueMicrotask(()=>{try{if(this.queueSize===0&&this.urgentQueueSize===0)return;const e=G();this._drainQueue(),e&&X()}finally{this.isProcessing=!1,(this.queueSize>0||this.urgentQueueSize>0)&&!this.isBatching&&this.flush()}}))}flushSync(){this.isFlushingSync=!0;const e=G();try{this._mergeBatchQueue(),this._drainQueue()}finally{this.isFlushingSync=!1,e&&X()}}_mergeBatchQueue(){if(this._epoch++,this.batchQueueSize>0){for(let e=0;e<this.batchQueueSize;e++){const t=this.batchQueue[e];t&&t._nextEpoch!==this._epoch&&(t._nextEpoch=this._epoch,this.queue[this.queueSize++]=t)}this.batchQueueSize=0}}_drainQueue(){let e=0;for(;this.urgentQueueSize>0||this.queueSize>0;){if(++e>this.maxFlushIterations){this._handleFlushOverflow();break}this.urgentQueueSize>0&&this._processUrgentQueue(),this.queueSize>0&&this._processCurrentQueue(),this._mergeBatchQueue()}}_processUrgentQueue(){const e=this.urgentQueue,t=this.urgentQueueSize;this.urgentQueue=this.urgentQueue===this.urgentQueueA?this.urgentQueueB:this.urgentQueueA,this.urgentQueueSize=0,this._epoch++,this._processJobs(e,t)}_processCurrentQueue(){const e=this.queue,t=this.queueSize;this.queue=this.queue===this.queueA?this.queueB:this.queueA,this.queueSize=0,this._epoch++,this._processJobs(e,t)}_handleFlushOverflow(){console.error(new N(`Maximum flush iterations (${this.maxFlushIterations}) exceeded. Possible infinite loop.`)),this.queueSize=0,this.queue.length=0,this.urgentQueueSize=0,this.urgentQueue.length=0,this.batchQueueSize=0}_processJobs(e,t){for(let s=0;s<t;s++)try{e[s]?.()}catch(r){console.error(new N("Error occurred during scheduler execution",r))}e.length=0}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<y.MIN_FLUSH_ITERATIONS)throw new N(`Max flush iterations must be at least ${y.MIN_FLUSH_ITERATIONS}`);this.maxFlushIterations=e}}const R=new le;function fe(i){if(typeof i!="function")throw new p("Batch callback must be a function");R.startBatch();try{return i()}finally{R.endBatch()}}class de{constructor(){this.current=null}run(e,t){const s=this.current;this.current=e;try{return t()}finally{this.current=s}}getCurrent(){return this.current}}const m=new de;function W(i){if(typeof i!="function")throw new p("Untracked callback must be a function");const e=m.current;m.current=null;try{return i()}finally{m.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(r){t?t(r):console.error("[SubscriberManager] Error in subscriber callback:",r)}}get size(){return this.subscribers?.length??0}get hasSubscribers(){return this.subscribers!==null&&this.subscribers.length>0}clear(){this.subscribers=null}toArray(){return this.subscribers?[...this.subscribers]:[]}}class B{constructor(){this.pool=[],this.maxPoolSize=50,this.maxReusableCapacity=256,this.stats=l?{acquired:0,released:0,rejected:{frozen:0,tooLarge:0,poolFull:0}}:null}acquire(){return l&&this.stats&&this.stats.acquired++,this.pool.pop()??[]}release(e,t){if(!(t&&e===t)){if(Object.isFrozen(e)){l&&this.stats&&this.stats.rejected.frozen++;return}if(e.length>this.maxReusableCapacity){l&&this.stats&&this.stats.rejected.tooLarge++;return}if(this.pool.length>=this.maxPoolSize){l&&this.stats&&this.stats.rejected.poolFull++;return}e.length=0,this.pool.push(e),l&&this.stats&&this.stats.released++}}getStats(){if(!l||!this.stats)return null;const{acquired:e,released:t,rejected:s}=this.stats,r=s.frozen+s.tooLarge+s.poolFull;return{acquired:e,released:t,rejected:s,leaked:e-t-r,poolSize:this.pool.length}}reset(){this.pool.length=0,l&&this.stats&&(this.stats.acquired=0,this.stats.released=0,this.stats.rejected={frozen:0,tooLarge:0,poolFull:0})}}const a=Object.freeze([]),d=Object.freeze([]),_=Object.freeze([]),D=new B,C=new B,E=new B;function K(i){return i!==null&&typeof i=="object"&&"value"in i&&"subscribe"in i&&typeof i.subscribe=="function"}function Ee(i){if(f.enabled&&(i==null||typeof i=="object")){const e=f.getDebugType(i);if(e)return e==="computed"}return K(i)&&"invalidate"in i&&typeof i.invalidate=="function"}function pe(i){return i!==null&&typeof i=="object"&&"dispose"in i&&"run"in i&&typeof i.dispose=="function"&&typeof i.run=="function"}function Z(i){return i!=null&&typeof i.then=="function"}function be(i){return typeof i=="object"&&i!==null}function ge(i){return(typeof i=="object"||typeof i=="function")&&i!==null&&typeof i.addDependency=="function"}function Se(i){return typeof i=="function"&&typeof i.addDependency!="function"}function ye(i){return be(i)&&typeof i.execute=="function"}function ee(i,e,t,s){if(e){if(ge(e)){e.addDependency(i);return}if(Se(e)){t.add(e);return}ye(e)&&s.add(e)}}function De(i,e,t,s){if(e!==a&&t!==d)for(let n=0;n<e.length;n++){const o=e[n];o&&(o._tempUnsub=t[n])}const r=C.acquire();r.length=i.length;for(let n=0;n<i.length;n++){const o=i[n];o&&(o._tempUnsub?(r[n]=o._tempUnsub,o._tempUnsub=void 0):(f.checkCircular(o,s),r[n]=o.subscribe(s)))}if(e!==a)for(let n=0;n<e.length;n++){const o=e[n];o?._tempUnsub&&(o._tempUnsub(),o._tempUnsub=void 0)}return t!==d&&C.release(t),r}class Ie extends ${constructor(e,t){super(),this._functionSubscribersStore=null,this._objectSubscribersStore=null,this._value=e,t&&(this.flags|=T.SYNC),f.attachDebugInfo(this,"atom",this.id)}get _functionSubscribers(){return this._functionSubscribersStore||(this._functionSubscribersStore=new M),this._functionSubscribersStore}get _objectSubscribers(){return this._objectSubscribersStore||(this._objectSubscribersStore=new M),this._objectSubscribersStore}get value(){const e=m.current;return e&&ee(this,e,this._functionSubscribers,this._objectSubscribers),this._value}set value(e){if(Object.is(this._value,e))return;const t=this._value;this._value=e,this.rotatePhase();const s=this._functionSubscribersStore?.hasSubscribers,r=this._objectSubscribersStore?.hasSubscribers;(s||r)&&this._scheduleNotification(t)}_scheduleNotification(e){if(this.flags&T.NOTIFICATION_SCHEDULED||(this._pendingOldValue=e,this.flags|=T.NOTIFICATION_SCHEDULED),this.flags&T.SYNC&&!R.isBatching){this._flushNotifications();return}this._notifyTask||(this._notifyTask=()=>this._flushNotifications()),R.schedule(this._notifyTask)}_flushNotifications(){if(!(this.flags&T.NOTIFICATION_SCHEDULED))return;const e=this._pendingOldValue,t=this._value;this._pendingOldValue=void 0,this.flags&=-3,this._notifySubscribers(t,e)}_notifySubscribers(e,t){this._functionSubscribersStore&&this._functionSubscribersStore.forEachSafe(s=>s(e,t)),this._objectSubscribersStore&&this._objectSubscribersStore.forEachSafe(s=>s.execute())}peek(){return this._value}dispose(){this._functionSubscribersStore?.clear(),this._objectSubscribersStore?.clear(),this._value=void 0,this._notifyTask=void 0}}function Ce(i,e={}){return new Ie(i,e.sync??!1)}function O(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 p)return i;const s=i instanceof Error?i.message:String(i),r=i instanceof Error?i:null;return new e(`Unexpected error (${t}): ${s}`,r)}const te=u.RESOLVED|u.PENDING|u.REJECTED,L=Array(te+1).fill(U.IDLE);L[u.RESOLVED]=U.RESOLVED;L[u.PENDING]=U.PENDING;L[u.REJECTED]=U.REJECTED;class se extends ${constructor(e,t={}){if(typeof e!="function")throw new S(h.COMPUTED_MUST_BE_FUNCTION);if(super(),this._cachedErrors=null,this._errorCacheEpoch=-1,this._asyncStartAggregateVersion=0,this._asyncRetryCount=0,this.MAX_ASYNC_RETRIES=3,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:Q,this._hasDefaultValue=this._defaultValue!==Q,this._onError=t.onError??null,this.MAX_PROMISE_ID=Number.MAX_SAFE_INTEGER-1,this._functionSubscribersStore=new M,this._objectSubscribersStore=new M,this._dependencies=a,this._dependencyVersions=_,this._unsubscribes=d,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=>{}}),f.attachDebugInfo(this,"computed",this.id),f.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(){return this._registerTracking(),this._computeValue()}peek(){return this._value}get state(){return this._registerTracking(),this._getAsyncState()}get hasError(){if(this._registerTracking(),this._isRejected())return!0;for(let e=0;e<this._dependencies.length;e++){const t=this._dependencies[e];if(t&&"hasError"in t&&t.hasError)return!0}return!1}get isValid(){return!this.hasError}get errors(){if(this._registerTracking(),!this.hasError)return ne;const e=ae();if(this._errorCacheEpoch===e&&this._cachedErrors!==null)return this._cachedErrors;const t=new Set;this._error&&t.add(this._error);for(let s=0;s<this._dependencies.length;s++){const r=this._dependencies[s];if(r&&"errors"in r){const n=r.errors;for(let o=0;o<n.length;o++){const c=n[o];c&&t.add(c)}}}return this._cachedErrors=Object.freeze([...t]),this._errorCacheEpoch=e,this._cachedErrors}get lastError(){return this._registerTracking(),this._error}get isPending(){return this._registerTracking(),this._isPending()}get isResolved(){return this._registerTracking(),this._isResolved()}invalidate(){this._markDirty(),this._dependencyVersions!==_&&(E.release(this._dependencyVersions),this._dependencyVersions=_),this._errorCacheEpoch=-1,this._cachedErrors=null}dispose(){if(this._unsubscribes!==d){for(let e=0;e<this._unsubscribes.length;e++){const t=this._unsubscribes[e];t&&t()}C.release(this._unsubscribes),this._unsubscribes=d}this._dependencies!==a&&(D.release(this._dependencies),this._dependencies=a),this._dependencyVersions!==_&&(E.release(this._dependencyVersions),this._dependencyVersions=_),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,this._cachedErrors=null,this._errorCacheEpoch=-1}_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 L[this.flags&te]}_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._prepareComputationContext();let t=!1;try{const s=m.run(this._trackable,this._fn);this._commitDependencies(e),t=!0,Z(s)?this._handleAsyncComputation(s):this._handleSyncResult(s)}catch(s){if(!t)try{this._commitDependencies(e),t=!0}catch(r){this._handleComputationError(r)}this._handleComputationError(s)}finally{this._cleanupContext(e,t),this._setRecomputing(!1)}}_prepareComputationContext(){const e=this._dependencies,t=this._dependencyVersions,s=D.acquire(),r=E.acquire(),n=J(),o={depCount:0},c=b=>{b._lastSeenEpoch!==n&&(b._lastSeenEpoch=n,o.depCount<s.length?(s[o.depCount]=b,r[o.depCount]=b.version):(s.push(b),r.push(b.version)),o.depCount++)},A=this._trackable.addDependency;return this._trackable.addDependency=c,{prevDeps:e,prevVersions:t,nextDeps:s,nextVersions:r,originalAdd:A,state:o}}_commitDependencies(e){const{nextDeps:t,nextVersions:s,state:r,prevDeps:n}=e;t.length=r.depCount,s.length=r.depCount,this._unsubscribes=De(t,n,this._unsubscribes,this),this._dependencies=t,this._dependencyVersions=s}_cleanupContext(e,t){this._trackable.addDependency=e.originalAdd,t?(e.prevDeps!==a&&D.release(e.prevDeps),e.prevVersions!==_&&E.release(e.prevVersions)):(D.release(e.nextDeps),E.release(e.nextVersions))}_getAggregateShift(){let e=0;const t=this._dependencies,s=this._dependencyVersions;for(let r=0;r<t.length;r++){const n=t[r],o=s[r];n&&o!==void 0&&(e=e+n.getShift(o)&I)}return e}isUrgent(){return this._getAggregateShift()>=j}_handleSyncResult(e){(!this._isResolved()||!this._equal(this._value,e))&&this.rotatePhase(),this._value=e,this._clearDirty(),this._setResolved(),this._error=null,this._setRecomputing(!1),this._cachedErrors=null,this._errorCacheEpoch=-1}_handleAsyncComputation(e){this._setPending(),this._clearDirty(),this._notifyJob(),this._asyncStartAggregateVersion=this._captureVersionSnapshot(),this._asyncRetryCount=0,this._promiseId=this._promiseId>=this.MAX_PROMISE_ID?1:this._promiseId+1;const t=this._promiseId;e.then(s=>{if(t!==this._promiseId)return;const n=this._captureVersionSnapshot()-this._asyncStartAggregateVersion&I;if(j-1-n>>>31&1){if(this._asyncRetryCount<this.MAX_ASYNC_RETRIES){this._asyncRetryCount++,this._markDirty();return}const c=new S(`Async drift exceeded threshold after ${this.MAX_ASYNC_RETRIES} retries. Dependencies changed too rapidly for stable computation.`);this._handleAsyncRejection(c);return}this._handleAsyncResolution(s)}).catch(s=>{t===this._promiseId&&this._handleAsyncRejection(s)})}_captureVersionSnapshot(){let e=0;const t=this._dependencies;for(let s=0;s<t.length;s++){const r=t[s];r&&(e=e+r.version&I)}return e}_handleAsyncResolution(e){(!this._isResolved()||!this._equal(this._value,e))&&this.rotatePhase(),this._value=e,this._clearDirty(),this._setResolved(),this._error=null,this._setRecomputing(!1),this._cachedErrors=null,this._errorCacheEpoch=-1,this._notifyJob()}_handleAsyncRejection(e){const t=O(e,S,h.COMPUTED_ASYNC_COMPUTATION_FAILED);if(!this._isRejected()&&this.rotatePhase(),this._error=t,this._setRejected(),this._clearDirty(),this._setRecomputing(!1),this._onError)try{this._onError(t)}catch(r){console.error(h.CALLBACK_ERROR_IN_ERROR_HANDLER,r)}this._notifyJob()}_handleComputationError(e){const t=O(e,S,h.COMPUTED_COMPUTATION_FAILED);if(this._error=t,this._setRejected(),this._clearDirty(),this._setRecomputing(!1),this._onError)try{this._onError(t)}catch(s){console.error(h.CALLBACK_ERROR_IN_ERROR_HANDLER,s)}throw t}_handlePending(){if(this._hasDefaultValue)return this._defaultValue;throw new S(h.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(){ee(this,m.getCurrent(),this._functionSubscribersStore,this._objectSubscribersStore)}}Object.freeze(se.prototype);function me(i,e={}){return new se(i,e)}class Ae extends H{constructor(e,t={}){super(),this.run=()=>{if(this.isDisposed)throw new g(h.EFFECT_MUST_BE_FUNCTION);this._dependencyVersions!==_&&(E.release(this._dependencyVersions),this._dependencyVersions=_),this.execute()},this.dispose=()=>{if(!this.isDisposed){if(this._setDisposed(),this._safeCleanup(),this._unsubscribes!==d){for(let r=0;r<this._unsubscribes.length;r++){const n=this._unsubscribes[r];n&&n()}C.release(this._unsubscribes),this._unsubscribes=d}this._dependencies!==a&&(D.release(this._dependencies),this._dependencies=a),this._dependencyVersions!==_&&(E.release(this._dependencyVersions),this._dependencyVersions=_)}},this.addDependency=r=>{if(this.isExecuting&&this._nextDeps&&this._nextUnsubs&&this._nextVersions){const n=this._currentEpoch;if(r._lastSeenEpoch===n)return;r._lastSeenEpoch=n,this._nextDeps.push(r),this._nextVersions.push(r.version),r._tempUnsub?(this._nextUnsubs.push(r._tempUnsub),r._tempUnsub=void 0):this._subscribeTo(r)}},this.execute=()=>{if(this.isDisposed||this.isExecuting||!this._shouldExecute())return;this._checkInfiniteLoop(),this._setExecuting(!0),this._safeCleanup();const r=this._prepareEffectContext();let n=!1;try{const o=m.run(this,this._fn);this._commitEffect(r),n=!0,this._checkLoopWarnings(),Z(o)?o.then(c=>{!this.isDisposed&&typeof c=="function"&&(this._cleanup=c)}).catch(c=>{this._handleExecutionError(c)}):this._cleanup=typeof o=="function"?o:null}catch(o){n=!0,this._handleExecutionError(o),this._cleanup=null}finally{this._cleanupEffect(r,n),this._setExecuting(!1)}},this._currentEpoch=-1,this._lastFlushEpoch=-1,this._executionsInEpoch=0,this._fn=e,this._sync=t.sync??!1,this._maxExecutions=t.maxExecutionsPerSecond??y.MAX_EXECUTIONS_PER_SECOND,this._maxExecutionsPerFlush=t.maxExecutionsPerFlush??y.MAX_EXECUTIONS_PER_EFFECT,this._trackModifications=t.trackModifications??!1,this._cleanup=null,this._dependencies=a,this._dependencyVersions=_,this._unsubscribes=d,this._nextDeps=null,this._nextVersions=null,this._nextUnsubs=null,this._onError=t.onError??null,this._historyPtr=0;const s=Number.isFinite(this._maxExecutions);this._historyCapacity=s?Math.min(this._maxExecutions+1,y.MAX_EXECUTIONS_PER_SECOND+1):0,this._history=l&&s&&this._historyCapacity>0?new Array(this._historyCapacity).fill(0):null,this._executionCount=0,f.attachDebugInfo(this,"effect",this.id)}_prepareEffectContext(){const e=this._dependencies,t=this._dependencyVersions,s=this._unsubscribes,r=D.acquire(),n=E.acquire(),o=C.acquire(),c=J();if(e!==a&&s!==d)for(let A=0;A<e.length;A++){const b=e[A];b&&(b._tempUnsub=s[A])}return this._nextDeps=r,this._nextVersions=n,this._nextUnsubs=o,this._currentEpoch=c,{prevDeps:e,prevVersions:t,prevUnsubs:s,nextDeps:r,nextVersions:n,nextUnsubs:o}}_commitEffect(e){const t=e.nextDeps.length;e.nextDeps.length=t,e.nextVersions.length=t,this._dependencies=e.nextDeps,this._dependencyVersions=e.nextVersions,this._unsubscribes=e.nextUnsubs}_cleanupEffect(e,t){if(this._nextDeps=null,this._nextVersions=null,this._nextUnsubs=null,t){if(e.prevDeps!==a){for(let s=0;s<e.prevDeps.length;s++){const r=e.prevDeps[s];r?._tempUnsub&&(r._tempUnsub(),r._tempUnsub=void 0)}D.release(e.prevDeps)}e.prevUnsubs!==d&&C.release(e.prevUnsubs),e.prevVersions!==_&&E.release(e.prevVersions)}else{D.release(e.nextDeps),E.release(e.nextVersions);for(let s=0;s<e.nextUnsubs.length;s++)e.nextUnsubs[s]?.();if(C.release(e.nextUnsubs),e.prevDeps!==a)for(let s=0;s<e.prevDeps.length;s++){const r=e.prevDeps[s];r&&(r._tempUnsub=void 0)}}}_subscribeTo(e){try{const t=e.subscribe(()=>{this._trackModifications&&this.isExecuting&&(e._modifiedAtEpoch=this._currentEpoch),this._sync?this.execute():R.schedule(this.execute)});this._nextUnsubs&&this._nextUnsubs.push(t)}catch(t){console.error(O(t,g,h.EFFECT_EXECUTION_FAILED)),this._nextUnsubs&&this._nextUnsubs.push(()=>{})}}get isDisposed(){return(this.flags&x.DISPOSED)!==0}get executionCount(){return this._executionCount}get isExecuting(){return(this.flags&x.EXECUTING)!==0}_setDisposed(){this.flags|=x.DISPOSED}_setExecuting(e){const t=x.EXECUTING;this.flags=this.flags&~t|-Number(e)&t}_safeCleanup(){if(this._cleanup){try{this._cleanup()}catch(e){console.error(O(e,g,h.EFFECT_CLEANUP_FAILED))}this._cleanup=null}}_checkInfiniteLoop(){if(this._lastFlushEpoch!==P&&(this._lastFlushEpoch=P,this._executionsInEpoch=0),this._executionsInEpoch++,this._executionsInEpoch>this._maxExecutionsPerFlush&&this._throwInfiniteLoopError("per-effect"),_e()>y.MAX_EXECUTIONS_PER_FLUSH&&this._throwInfiniteLoopError("global"),this._executionCount++,this._history&&this._maxExecutions>0){const e=Date.now(),t=this._historyPtr,s=this._historyCapacity;this._history[t]=e;const r=(t+1)%s,n=this._history[r]??0;if(this._historyPtr=r,n>0&&e-n<ie.ONE_SECOND_MS){const o=new g(`Effect executed ${s} times within 1 second. Infinite loop suspected`);if(this.dispose(),console.error(o),this._onError&&this._onError(o),l)throw o}}}_throwInfiniteLoopError(e){const t=new g(`Infinite loop detected (${e}): effect executed ${this._executionsInEpoch} times in current flush. Total executions in flush: ${k}`);throw this.dispose(),console.error(t),t}_shouldExecute(){if(this._dependencies===a||this._dependencyVersions===_)return!0;for(let e=0;e<this._dependencies.length;e++){const t=this._dependencies[e];if(t){if("value"in t)try{W(()=>t.value)}catch{return!0}if(t.version!==this._dependencyVersions[e])return!0}}return!1}_handleExecutionError(e){const t=O(e,g,h.EFFECT_EXECUTION_FAILED);console.error(t),this._onError&&this._onError(t)}_checkLoopWarnings(){if(this._trackModifications&&f.enabled){const e=this._dependencies;for(let t=0;t<e.length;t++){const s=e[t];s&&s._modifiedAtEpoch===this._currentEpoch&&f.warn(!0,`Effect is reading a dependency (${f.getDebugName(s)||"unknown"}) that it just modified. Infinite loop may occur`)}}}}function Re(i,e={}){if(typeof i!="function")throw new g(h.EFFECT_MUST_BE_FUNCTION);const t=new Ae(i,e);return t.execute(),t}exports.AsyncState=U;exports.AtomError=p;exports.ComputedError=S;exports.DEBUG_CONFIG=z;exports.DEBUG_RUNTIME=f;exports.EffectError=g;exports.POOL_CONFIG=re;exports.SCHEDULER_CONFIG=y;exports.SchedulerError=N;exports.atom=Ce;exports.batch=fe;exports.computed=me;exports.effect=Re;exports.isAtom=K;exports.isComputed=Ee;exports.isEffect=pe;exports.scheduler=R;exports.untracked=W;
2
2
  //# sourceMappingURL=index.cjs.map