@but212/atom-effect 0.15.4 → 0.16.1

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
@@ -15,9 +15,9 @@ npm i @but212/atom-effect
15
15
  ### CDN
16
16
 
17
17
  ```html
18
- <script src="https://cdn.jsdelivr.net/npm/@but212/atom-effect@latest"></script>
18
+ <script src="https://cdn.jsdelivr.net/npm/@but212/atom-effect@0.16.1"></script>
19
19
  <!-- or -->
20
- <script src="https://unpkg.com/@but212/atom-effect@latest"></script>
20
+ <script src="https://unpkg.com/@but212/atom-effect@0.16.1"></script>
21
21
  ```
22
22
 
23
23
  ## Core API
@@ -143,14 +143,14 @@ pnpm build # Build production bundle
143
143
 
144
144
  | Operation | Performance |
145
145
  | --- | --- |
146
- | Atom creation (x1000) | ~13.3K ops/sec |
147
- | Atom read (x1000) | ~36.9K ops/sec |
148
- | Atom write (x1000) | ~343K ops/sec |
149
- | Computed creation | ~2.17M ops/sec |
150
- | Computed recomputation | ~584K ops/sec |
151
- | Effect execution | ~2.56M ops/sec |
152
- | Batched updates (x2) | ~3.25M ops/sec |
153
- | Deep chain (100 levels) | ~9.32K ops/sec |
146
+ | Atom creation (x1000) | ~13.8K ops/sec |
147
+ | Atom read (x1000) | ~38.4K ops/sec |
148
+ | Atom write (x1000) | ~556K ops/sec |
149
+ | Computed creation (x1000) | ~3.77K ops/sec |
150
+ | Computed recomputation | ~863K ops/sec |
151
+ | Effect execution (x1000) | ~14.3K ops/sec |
152
+ | Batched updates (x2) (x1000) | ~4.73K ops/sec |
153
+ | Deep chain (100 levels) | ~17.5K ops/sec |
154
154
 
155
155
  ## Contributing
156
156
 
@@ -1,2 +1,2 @@
1
- (function(l,P){typeof exports=="object"&&typeof module<"u"?P(exports):typeof define=="function"&&define.amd?define(["exports"],P):(l=typeof globalThis<"u"?globalThis:l||self,P(l.AtomEffect={}))})(this,(function(l){"use strict";const P={ONE_SECOND_MS:1e3},v={IDLE:"idle",PENDING:"pending",RESOLVED:"resolved",REJECTED:"rejected"},g={DISPOSED:1,HAS_FN_SUBS:2,HAS_OBJ_SUBS:4},b={...g,EXECUTING:8},u={...g,DIRTY:8,IDLE:16,PENDING:32,RESOLVED:64,REJECTED:128,RECOMPUTING:256,HAS_ERROR:512},D={...g,SYNC:8,NOTIFICATION_SCHEDULED:16},he={MAX_SIZE:1e3,WARMUP_SIZE:100},O={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,BATCH_QUEUE_SHRINK_THRESHOLD:1e3},k={MAX_DEPENDENCIES:1e3,WARN_INFINITE_LOOP:!0},R=1073741823,E=typeof process<"u"&&process.env&&process.env.NODE_ENV!=="production",ue=Object.freeze([]);class C extends Error{constructor(e,t=null,s=!0){super(e),this.name="AtomError",this.cause=t,this.recoverable=s,this.timestamp=new Date}}class N extends C{constructor(e,t=null){super(e,t,!0),this.name="ComputedError"}}class y extends C{constructor(e,t=null){super(e,t,!1),this.name="EffectError"}}class L extends C{constructor(e,t=null){super(e,t,!1),this.name="SchedulerError"}}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_CIRCULAR_DEPENDENCY:"Circular dependency detected during computation",COMPUTED_DEPENDENCY_SUBSCRIPTION_FAILED:"Failed to subscribe to dependency",COMPUTED_DISPOSED:"Cannot access a disposed computed",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",EFFECT_DISPOSED:"Cannot run a disposed effect",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"},H=Symbol("debugName"),_e=Symbol("id"),j=Symbol("type"),q=Symbol("noDefaultValue");function le(i){return"dependencies"in i&&Array.isArray(i.dependencies)}let Q=0;function J(i,e,t){if(i._visitedEpoch!==t){if(i._visitedEpoch=t,i===e)throw new N("Indirect circular dependency detected");if(le(i)){const s=i.dependencies;for(let n=0;n<s.length;n++){const r=s[n];r&&J(r,e,t)}}}}const I={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 N("Direct circular dependency detected");this.enabled&&(Q++,J(i,e,Q))},attachDebugInfo(i,e,t){if(!this.enabled)return;const s=i;s[H]=`${e}_${t}`,s[_e]=t,s[j]=e},getDebugName(i){if(i!=null&&H in i)return i[H]},getDebugType(i){if(i!=null&&j in i)return i[j]}};let ae=1;const fe=()=>ae++;class ${constructor(){this.flags=0,this.version=0,this._lastSeenEpoch=-1,this._modifiedAtEpoch=-1,this._visitedEpoch=-1,this.id=fe()&R,this._tempUnsub=void 0}getShift(e){return this.version-e&R}}class K extends ${subscribe(e){if(typeof e=="function")return this._addSubscriber(this._fnSubs,e,g.HAS_FN_SUBS);if(e!==null&&typeof e=="object"&&"execute"in e)return this._addSubscriber(this._objSubs,e,g.HAS_OBJ_SUBS);throw new C(a.ATOM_SUBSCRIBER_MUST_BE_FUNCTION)}subscriberCount(){return this._fnSubs.length+this._objSubs.length}_addSubscriber(e,t,s){if(e.indexOf(t)!==-1)return E&&console.warn("Attempted to subscribe the same listener twice. Ignoring duplicate subscription."),()=>{};e.push(t),this.flags|=s;let r=!1;return()=>{if(r)return;r=!0;const o=e.indexOf(t);if(o!==-1){const c=e.pop();o<e.length&&(e[o]=c),this.flags&=~(e.length===0?s:0)}}}_notifySubscribers(e,t){const s=this.flags,n=g.HAS_FN_SUBS|g.HAS_OBJ_SUBS;if(s&n){if(s&g.HAS_FN_SUBS){const r=this._fnSubs;for(let o=0,c=r.length;o<c;o++){const h=r[o];if(h)try{h(e,t)}catch(_){console.error(new C(a.ATOM_INDIVIDUAL_SUBSCRIBER_FAILED,_))}}}if(s&g.HAS_OBJ_SUBS){const r=this._objSubs;for(let o=0,c=r.length;o<c;o++){const h=r[o];if(h)try{h.execute()}catch(_){console.error(new C(a.ATOM_INDIVIDUAL_SUBSCRIBER_FAILED,_))}}}}}}class Ee{constructor(){this.acquired=0,this.released=0,this.rejected=new de}}class de{constructor(){this.frozen=0,this.tooLarge=0,this.poolFull=0}}class G{constructor(){this.pool=[],this.maxPoolSize=50,this.maxReusableCapacity=256,this.stats=E?new Ee:null}acquire(){const e=this.stats;return E&&e&&e.acquired++,this.pool.pop()??[]}release(e,t){if(t&&e===t||Object.isFrozen(e)){const c=this.stats;E&&c&&e!==t&&c.rejected.frozen++;return}const s=e.length,n=this.pool,r=n.length;if(s>this.maxReusableCapacity||r>=this.maxPoolSize){const c=this.stats;E&&c&&(s>this.maxReusableCapacity?c.rejected.tooLarge++:c.rejected.poolFull++);return}e.length=0,n.push(e);const o=this.stats;E&&o&&o.released++}getStats(){const e=this.stats;if(!E||!e)return null;const{acquired:t,released:s,rejected:n}=e,r=n.frozen+n.tooLarge+n.poolFull;return{acquired:t,released:s,rejected:{frozen:n.frozen,tooLarge:n.tooLarge,poolFull:n.poolFull},leaked:t-s-r,poolSize:this.pool.length}}reset(){this.pool.length=0;const e=this.stats;E&&e&&(e.acquired=0,e.released=0,e.rejected.frozen=0,e.rejected.tooLarge=0,e.rejected.poolFull=0)}}const d=Object.freeze([]),A=Object.freeze([]),S=Object.freeze([]),m=new G,x=new G,T=new G;function U(i,e,t,s){if(e!=null){if((typeof e=="object"||typeof e=="function")&&typeof e.addDependency=="function"){e.addDependency(i);return}if(typeof e=="function"){const n=e;t.indexOf(n)===-1&&(t.push(n),i.flags|=g.HAS_FN_SUBS);return}typeof e=="object"&&typeof e.execute=="function"&&s.indexOf(e)===-1&&(s.push(e),i.flags|=g.HAS_OBJ_SUBS)}}function W(i,e,t,s){const n=i.length,r=e.length,o=e!==d&&r>0;if(o)for(let h=0;h<r;h++){const _=e[h];_&&(_._tempUnsub=t[h])}const c=x.acquire();c.length=n;for(let h=0;h<n;h++){const _=i[h];if(!_)continue;const f=_._tempUnsub;f?(c[h]=f,_._tempUnsub=void 0):(I.checkCircular(_,s),c[h]=_.subscribe(s))}if(o)for(let h=0;h<r;h++){const _=e[h];if(_){const f=_._tempUnsub;f&&(f(),_._tempUnsub=void 0)}}return t!==A&&x.release(t),c}let B=0;function Z(){return B=B+1&R||1,B}function pe(){return B}let z=0,X=0,V=!1;function ee(){return V?(E&&console.warn("Warning: startFlush() called during flush - ignored to prevent infinite loop detection bypass"),!1):(V=!0,z=z+1&R||1,X=0,!0)}function te(){V=!1}function Se(){return V?++X:0}class ge{constructor(){this._queueBuffer=[[],[]],this._bufferIndex=0,this._size=0,this._epoch=0,this.isProcessing=!1,this._isBatching=!1,this.batchDepth=0,this.batchQueue=[],this.batchQueueSize=0,this.isFlushingSync=!1,this.maxFlushIterations=O.MAX_FLUSH_ITERATIONS}get phase(){return this.isProcessing||this.isFlushingSync?2:this._isBatching?1:0}get queueSize(){return this._size}get isBatching(){return this._isBatching}schedule(e){if(E&&typeof e!="function")throw new L("Scheduler callback must be a function");const t=this._epoch;if(e._nextEpoch!==t){if(e._nextEpoch=t,this._isBatching||this.isFlushingSync){this.batchQueue[this.batchQueueSize++]=e;return}this._queueBuffer[this._bufferIndex][this._size++]=e,this.isProcessing||this.flush()}}flush(){this.isProcessing||this._size===0||(this.isProcessing=!0,queueMicrotask(()=>{try{if(this._size===0)return;const e=ee();this._drainQueue(),e&&te()}finally{this.isProcessing=!1,this._size>0&&!this._isBatching&&this.flush()}}))}flushSync(){this.isFlushingSync=!0;const e=ee();try{this._mergeBatchQueue(),this._drainQueue()}finally{this.isFlushingSync=!1,e&&te()}}_mergeBatchQueue(){const e=this.batchQueueSize;if(e===0)return;const t=++this._epoch,s=this.batchQueue,n=this._queueBuffer[this._bufferIndex];let r=this._size;for(let o=0;o<e;o++){const c=s[o];c._nextEpoch!==t&&(c._nextEpoch=t,n[r++]=c)}this._size=r,this.batchQueueSize=0,s.length>O.BATCH_QUEUE_SHRINK_THRESHOLD&&(s.length=0)}_drainQueue(){let e=0;const t=this.maxFlushIterations;for(;this._size>0;){if(++e>t){this._handleFlushOverflow();return}this._processQueue(),this._mergeBatchQueue()}}_processQueue(){const e=this._bufferIndex,t=this._queueBuffer[e],s=this._size,n=e^1;this._bufferIndex=n,this._size=0,this._epoch++,this._processJobs(t,s)}_handleFlushOverflow(){console.error(new L(`Maximum flush iterations (${this.maxFlushIterations}) exceeded. Possible infinite loop.`)),this._size=0,this._queueBuffer[this._bufferIndex].length=0,this.batchQueueSize=0}_processJobs(e,t){for(let s=0;s<t;s++)try{e[s]()}catch(n){console.error(new L("Error occurred during scheduler execution",n))}e.length=0}startBatch(){this.batchDepth++,this._isBatching=!0}endBatch(){if(this.batchDepth===0){E&&console.warn("endBatch() called without matching startBatch(). Ignoring.");return}this.batchDepth--,this.batchDepth===0&&(this.flushSync(),this._isBatching=!1)}setMaxFlushIterations(e){if(e<O.MIN_FLUSH_ITERATIONS)throw new L(`Max flush iterations must be at least ${O.MIN_FLUSH_ITERATIONS}`);this.maxFlushIterations=e}}const F=new ge;class be{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 p=new be;function se(i){if(typeof i!="function")throw new C("Untracked callback must be a function");const e=p.current;p.current=null;try{return i()}finally{p.current=e}}class Ie extends K{constructor(e,t){super(),this._value=e,this._pendingOldValue=void 0,this._notifyTask=void 0,this._fnSubs=[],this._objSubs=[],t&&(this.flags|=D.SYNC),I.attachDebugInfo(this,"atom",this.id)}get value(){const e=p.current;return e&&U(this,e,this._fnSubs,this._objSubs),this._value}set value(e){const t=this._value;if(Object.is(t,e))return;this._value=e,this.version=this.version+1&R;const s=this.flags,n=D.HAS_FN_SUBS|D.HAS_OBJ_SUBS;s&n&&this._scheduleNotification(t)}_scheduleNotification(e){let t=this.flags;if(t&D.NOTIFICATION_SCHEDULED||(this._pendingOldValue=e,this.flags=t|=D.NOTIFICATION_SCHEDULED),t&D.SYNC&&!F.isBatching){this._flushNotifications();return}let s=this._notifyTask;s||(s=this._notifyTask=()=>this._flushNotifications()),F.schedule(s)}_flushNotifications(){const e=this.flags;if(!(e&D.NOTIFICATION_SCHEDULED)||e&D.DISPOSED)return;const t=this._pendingOldValue,s=this._value;this._pendingOldValue=void 0,this.flags&=-17,this._notifySubscribers(s,t)}peek(){return this._value}dispose(){this.flags&D.DISPOSED||(this._fnSubs=[],this._objSubs=[],this.flags|=D.DISPOSED,this._value=void 0,this._pendingOldValue=void 0,this._notifyTask=void 0)}}function De(i,e={}){return new Ie(i,e.sync??!1)}function M(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 C)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 ie(i){return i!==null&&typeof i=="object"&&"value"in i&&"subscribe"in i&&typeof i.subscribe=="function"}function Ce(i){if(I.enabled&&i!=null&&typeof i=="object"){const e=I.getDebugType(i);if(e)return e==="computed"}return ie(i)&&"invalidate"in i&&typeof i.invalidate=="function"}function Ne(i){return i!==null&&typeof i=="object"&&"dispose"in i&&"run"in i&&typeof i.dispose=="function"&&typeof i.run=="function"}function ne(i){return i!=null&&typeof i.then=="function"}const re=u.RESOLVED|u.PENDING|u.REJECTED,w=Array(re+1).fill(v.IDLE);w[u.RESOLVED]=v.RESOLVED,w[u.PENDING]=v.PENDING,w[u.REJECTED]=v.REJECTED;class Oe{constructor(e){this._owner=e,this._epoch=-1,this._nextDeps=d,this._nextVersions=S,this._depCount=0}execute(){this._owner._markDirty()}addDependency(e){if(e._lastSeenEpoch===this._epoch)return;e._lastSeenEpoch=this._epoch;const t=this._depCount,s=this._nextDeps,n=this._nextVersions;t<s.length?(s[t]=e,n[t]=e.version):(s.push(e),n.push(e.version)),this._depCount=t+1}reset(){this._epoch=-1,this._nextDeps=d,this._nextVersions=S,this._depCount=0}}class oe extends K{constructor(e,t={}){if(typeof e!="function")throw new N(a.COMPUTED_MUST_BE_FUNCTION);if(super(),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._fnSubs=[],this._objSubs=[],this._dependencies=d,this._dependencyVersions=S,this._unsubscribes=A,this._cachedErrors=null,this._errorCacheEpoch=-1,this._asyncStartAggregateVersion=0,this._asyncRetryCount=0,this._trackable=new Oe(this),I.attachDebugInfo(this,"computed",this.id),I.enabled){const s=this;s.subscriberCount=this.subscriberCount.bind(this),s.isDirty=()=>(this.flags&u.DIRTY)!==0,s.dependencies=this._dependencies,s.stateFlags=""}if(t.lazy===!1)try{this._recompute()}catch{}}get value(){const e=p.current;e&&U(this,e,this._fnSubs,this._objSubs);const t=this.flags;if(t&u.DISPOSED)throw new N(a.COMPUTED_DISPOSED);if(t&u.RECOMPUTING){if(this._hasDefaultValue)return this._defaultValue;throw new N(a.COMPUTED_CIRCULAR_DEPENDENCY)}t&(u.DIRTY|u.IDLE)&&this._recompute();const s=this.flags;return s&u.PENDING?this._handlePending():s&u.REJECTED?this._handleRejected():this._value}peek(){return this._value}get state(){const e=p.current;return e&&U(this,e,this._fnSubs,this._objSubs),w[this.flags&re]}get hasError(){const e=p.current;if(e&&U(this,e,this._fnSubs,this._objSubs),this.flags&(u.REJECTED|u.HAS_ERROR))return!0;const s=this._dependencies;for(let n=0,r=s.length;n<r;n++){const o=s[n];if(o&&o.flags&u.HAS_ERROR)return!0}return!1}get isValid(){return!this.hasError}get errors(){const e=p.current;if(e&&U(this,e,this._fnSubs,this._objSubs),!this.hasError)return ue;const t=pe();if(this._errorCacheEpoch===t&&this._cachedErrors!==null)return this._cachedErrors;const s=new Set;this._error&&s.add(this._error);const n=this._dependencies;for(let o=0,c=n.length;o<c;o++){const h=n[o];if(h&&"errors"in h){const _=h.errors;for(let f=0,Y=_.length;f<Y;f++){const ce=_[f];ce&&s.add(ce)}}}const r=Object.freeze([...s]);return this._cachedErrors=r,this._errorCacheEpoch=t,r}get lastError(){const e=p.current;return e&&U(this,e,this._fnSubs,this._objSubs),this._error}get isPending(){const e=p.current;return e&&U(this,e,this._fnSubs,this._objSubs),(this.flags&u.PENDING)!==0}get isResolved(){const e=p.current;return e&&U(this,e,this._fnSubs,this._objSubs),(this.flags&u.RESOLVED)!==0}invalidate(){this._markDirty();const e=this._dependencyVersions;e!==S&&(T.release(e),this._dependencyVersions=S),this._errorCacheEpoch=-1,this._cachedErrors=null}dispose(){const e=this._unsubscribes;if(e!==A){for(let n=0,r=e.length;n<r;n++){const o=e[n];o&&o()}x.release(e),this._unsubscribes=A}const t=this._dependencies;t!==d&&(m.release(t),this._dependencies=d);const s=this._dependencyVersions;s!==S&&(T.release(s),this._dependencyVersions=S),this._fnSubs=[],this._objSubs=[],this.flags=u.DISPOSED|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}_clearDirty(){this.flags&=-9}_setPending(){this.flags=(this.flags|u.PENDING)&-209}_isResolved(){return(this.flags&u.RESOLVED)!==0}_setResolved(){this.flags=(this.flags|u.RESOLVED)&-689}_isRejected(){return(this.flags&u.REJECTED)!==0}_setRejected(){this.flags=this.flags&-113|(u.REJECTED|u.HAS_ERROR)}_setRecomputing(e){const t=u.RECOMPUTING;this.flags=this.flags&~t|(e?-1:0)&t}_recompute(){if(this.flags&u.RECOMPUTING)return;this._setRecomputing(!0);const e=this._trackable,t=this._dependencies,s=this._dependencyVersions;e._epoch=Z(),e._nextDeps=m.acquire(),e._nextVersions=T.acquire(),e._depCount=0;let n=!1;try{const r=p.run(e,this._fn),o=e._nextDeps,c=e._nextVersions,h=e._depCount;o.length=h,c.length=h,this._unsubscribes=W(o,t,this._unsubscribes,this),this._dependencies=o,this._dependencyVersions=c,n=!0,ne(r)?this._handleAsyncComputation(r):this._finalizeResolution(r)}catch(r){let o=r;if(!n)try{const c=e._nextDeps,h=e._nextVersions,_=e._depCount;c.length=_,h.length=_,this._unsubscribes=W(c,t,this._unsubscribes,this),this._dependencies=c,this._dependencyVersions=h,n=!0}catch(c){o=c}this._handleComputationError(o)}finally{n?(t!==d&&m.release(t),s!==S&&T.release(s)):(m.release(e._nextDeps),T.release(e._nextVersions)),e.reset(),this._setRecomputing(!1)}}_handleAsyncComputation(e){this._setPending(),this._clearDirty(),this._notifySubscribers(void 0,void 0),this._asyncStartAggregateVersion=this._captureVersionSnapshot(),this._asyncRetryCount=0,this._promiseId=(this._promiseId+1)%this.MAX_PROMISE_ID;const t=this._promiseId;e.then(s=>{if(t!==this._promiseId)return;if(this._captureVersionSnapshot()!==this._asyncStartAggregateVersion){if(this._asyncRetryCount<this.MAX_ASYNC_RETRIES){this._asyncRetryCount++,this._markDirty();return}const o=new N(`Async drift exceeded threshold after ${this.MAX_ASYNC_RETRIES} retries.`);this._handleAsyncRejection(o);return}this._finalizeResolution(s),this._notifySubscribers(s,void 0)}).catch(s=>{t===this._promiseId&&this._handleAsyncRejection(s)})}_captureVersionSnapshot(){let e=0;const t=this._dependencies;for(let s=0,n=t.length;s<n;s++){const r=t[s];if(r){const o=r.version;e=((e<<5)-e|0)+o&R}}return e}_handleAsyncRejection(e){const t=M(e,N,a.COMPUTED_ASYNC_COMPUTATION_FAILED);this.flags&u.REJECTED||(this.version=this.version+1&R),this._error=t,this._setRejected(),this._clearDirty();const s=this._onError;if(s)try{s(t)}catch(n){console.error(a.CALLBACK_ERROR_IN_ERROR_HANDLER,n)}this._notifySubscribers(void 0,void 0)}_finalizeResolution(e){(!(this.flags&u.RESOLVED)||!this._equal(this._value,e))&&(this.version=this.version+1&R),this._value=e,this._clearDirty(),this._setResolved(),this._error=null,this._setRecomputing(!1),this._cachedErrors=null,this._errorCacheEpoch=-1}_handleComputationError(e){const t=M(e,N,a.COMPUTED_COMPUTATION_FAILED);this._error=t,this._setRejected(),this._clearDirty(),this._setRecomputing(!1);const s=this._onError;if(s)try{s(t)}catch(n){console.error(a.CALLBACK_ERROR_IN_ERROR_HANDLER,n)}throw t}_handlePending(){if(this._hasDefaultValue)return this._defaultValue;throw new N(a.COMPUTED_ASYNC_PENDING_NO_DEFAULT)}_handleRejected(){const e=this._error;if(e?.recoverable&&this._hasDefaultValue)return this._defaultValue;throw e}execute(){this._markDirty()}_markDirty(){const e=this.flags;e&(u.RECOMPUTING|u.DIRTY)||(this.flags=e|u.DIRTY,this._notifySubscribers(void 0,void 0))}}Object.freeze(oe.prototype);function Te(i,e={}){return new oe(i,e)}class Re extends ${constructor(e,t={}){super(),this._cleanup=null,this._dependencies=d,this._dependencyVersions=S,this._unsubscribes=A,this._nextDeps=null,this._nextVersions=null,this._nextUnsubs=null,this._executeTask=void 0,this._onError=t.onError??null,this._currentEpoch=-1,this._lastFlushEpoch=-1,this._executionsInEpoch=0,this._fn=e,this._sync=t.sync??!1,this._maxExecutions=t.maxExecutionsPerSecond??O.MAX_EXECUTIONS_PER_SECOND,this._maxExecutionsPerFlush=t.maxExecutionsPerFlush??O.MAX_EXECUTIONS_PER_EFFECT,this._trackModifications=t.trackModifications??!1,this._executionCount=0,this._historyPtr=0;const s=Number.isFinite(this._maxExecutions),n=s?Math.min(this._maxExecutions+1,O.MAX_EXECUTIONS_PER_SECOND+1):0;this._historyCapacity=n,this._history=E&&s&&n>0?new Array(n).fill(0):null,this._execId=0,I.attachDebugInfo(this,"effect",this.id)}run(){if(this.flags&b.DISPOSED)throw new y(a.EFFECT_DISPOSED);this.execute(!0)}dispose(){const e=this.flags;if(e&b.DISPOSED)return;this.flags=e|b.DISPOSED,this._safeCleanup();const t=this._unsubscribes;if(t!==A){for(let r=0,o=t.length;r<o;r++){const c=t[r];c&&c()}x.release(t),this._unsubscribes=A}const s=this._dependencies;s!==d&&(m.release(s),this._dependencies=d);const n=this._dependencyVersions;n!==S&&(T.release(n),this._dependencyVersions=S),this._executeTask=void 0}addDependency(e){if(!(this.flags&b.EXECUTING))return;const s=this._currentEpoch;if(e._lastSeenEpoch===s)return;e._lastSeenEpoch=s;const n=this._nextDeps,r=this._nextVersions,o=this._nextUnsubs;if(!n||!r||!o)return;n.push(e),r.push(e.version);const c=e._tempUnsub;c?(o.push(c),e._tempUnsub=void 0):this._subscribeTo(e)}execute(e=!1){if(this.flags&(b.DISPOSED|b.EXECUTING)||!e&&!this._shouldExecute())return;this._checkInfiniteLoop(),this._setExecuting(!0),this._safeCleanup();const s=this._prepareEffectExecutionContext();let n=!1;try{const r=p.run(this,this._fn),o=s.nextDeps.length;s.nextDeps.length=o,s.nextVersions.length=o,this._dependencies=s.nextDeps,this._dependencyVersions=s.nextVersions,this._unsubscribes=s.nextUnsubs,n=!0,this._checkLoopWarnings();const c=++this._execId;ne(r)?r.then(h=>{const _=c!==this._execId,f=this.flags&b.DISPOSED;if(_||f){if(typeof h=="function")try{h()}catch(Y){this._handleExecutionError(Y,a.EFFECT_CLEANUP_FAILED)}return}typeof h=="function"&&(this._cleanup=h)}).catch(h=>{c===this._execId&&this._handleExecutionError(h)}):this._cleanup=typeof r=="function"?r:null}catch(r){n=!0,this._handleExecutionError(r),this._cleanup=null}finally{this._cleanupEffect(s,n),this._setExecuting(!1)}}_prepareEffectExecutionContext(){const e=this._dependencies,t=this._dependencyVersions,s=this._unsubscribes,n=m.acquire(),r=T.acquire(),o=x.acquire(),c=Z();if(e!==d)for(let h=0,_=e.length;h<_;h++){const f=e[h];f&&(f._tempUnsub=s[h])}return this._nextDeps=n,this._nextVersions=r,this._nextUnsubs=o,this._currentEpoch=c,{prevDeps:e,prevVersions:t,prevUnsubs:s,nextDeps:n,nextVersions:r,nextUnsubs:o}}_cleanupEffect(e,t){this._nextDeps=null,this._nextVersions=null,this._nextUnsubs=null;const s=e.prevDeps;if(t){if(s!==d){for(let n=0,r=s.length;n<r;n++){const o=s[n],c=o?o._tempUnsub:void 0;c&&(c(),o&&(o._tempUnsub=void 0))}m.release(s)}e.prevUnsubs!==A&&x.release(e.prevUnsubs),e.prevVersions!==S&&T.release(e.prevVersions)}else{m.release(e.nextDeps),T.release(e.nextVersions);const n=e.nextUnsubs;for(let r=0,o=n.length;r<o;r++)n[r]?.();if(x.release(n),s!==d)for(let r=0,o=s.length;r<o;r++){const c=s[r];c&&(c._tempUnsub=void 0)}}}_subscribeTo(e){try{const t=e.subscribe(()=>{if(this._trackModifications&&this.flags&b.EXECUTING&&(e._modifiedAtEpoch=this._currentEpoch),this._sync){this.execute();return}let n=this._executeTask;n||(n=this._executeTask=()=>this.execute()),F.schedule(n)}),s=this._nextUnsubs;s&&s.push(t)}catch(t){console.error(M(t,y,a.EFFECT_EXECUTION_FAILED));const s=this._nextUnsubs;s&&s.push(()=>{})}}get isDisposed(){return(this.flags&b.DISPOSED)!==0}get executionCount(){return this._executionCount}get isExecuting(){return(this.flags&b.EXECUTING)!==0}_setExecuting(e){const t=b.EXECUTING;this.flags=this.flags&~t|(e?-1:0)&t}_safeCleanup(){const e=this._cleanup;if(e){try{e()}catch(t){this._handleExecutionError(t,a.EFFECT_CLEANUP_FAILED)}this._cleanup=null}}_checkInfiniteLoop(){const e=z;this._lastFlushEpoch!==e&&(this._lastFlushEpoch=e,this._executionsInEpoch=0),++this._executionsInEpoch>this._maxExecutionsPerFlush&&this._throwInfiniteLoopError("per-effect"),Se()>O.MAX_EXECUTIONS_PER_FLUSH&&this._throwInfiniteLoopError("global"),this._executionCount++;const s=this._history;if(s){const n=Date.now(),r=this._historyPtr,o=this._historyCapacity;s[r]=n;const c=(r+1)%o;this._historyPtr=c;const h=s[c]??0;if(h>0&&n-h<P.ONE_SECOND_MS){const _=new y(`Effect executed ${o} times within 1 second. Infinite loop suspected`);if(this.dispose(),console.error(_),this._onError&&this._onError(_),E)throw _;return}}}_throwInfiniteLoopError(e){const t=new y(`Infinite loop detected (${e}): effect executed ${this._executionsInEpoch} times in current flush. Total executions in flush: ${X}`);throw this.dispose(),console.error(t),t}_shouldExecute(){const e=this._dependencies;if(e.length===0)return!0;const t=this._dependencyVersions;for(let s=0,n=e.length;s<n;s++){const r=e[s];if(r){if(r.version!==t[s])return!0;if("value"in r)try{if(se(()=>r.value),r.version!==t[s])return!0}catch{return!0}}}return!1}_handleExecutionError(e,t=a.EFFECT_EXECUTION_FAILED){const s=M(e,y,t);console.error(s);const n=this._onError;if(n)try{n(s)}catch(r){console.error(M(r,y,a.CALLBACK_ERROR_IN_ERROR_HANDLER))}}_checkLoopWarnings(){if(this._trackModifications&&I.enabled){const e=this._dependencies,t=this._currentEpoch;for(let s=0,n=e.length;s<n;s++){const r=e[s];r&&r._modifiedAtEpoch===t&&I.warn(!0,`Effect is reading a dependency (${I.getDebugName(r)||"unknown"}) that it just modified. Infinite loop may occur`)}}}}function ye(i,e={}){if(typeof i!="function")throw new y(a.EFFECT_MUST_BE_FUNCTION);const t=new Re(i,e);return t.execute(),t}function Ae(i){if(typeof i!="function")throw new C("Batch callback must be a function");F.startBatch();try{return i()}finally{F.endBatch()}}l.AsyncState=v,l.AtomError=C,l.ComputedError=N,l.DEBUG_CONFIG=k,l.DEBUG_RUNTIME=I,l.EffectError=y,l.POOL_CONFIG=he,l.SCHEDULER_CONFIG=O,l.SchedulerError=L,l.atom=De,l.batch=Ae,l.computed=Te,l.effect=ye,l.isAtom=ie,l.isComputed=Ce,l.isEffect=Ne,l.scheduler=F,l.untracked=se,Object.defineProperty(l,Symbol.toStringTag,{value:"Module"})}));
1
+ (function(f,k){typeof exports=="object"&&typeof module<"u"?k(exports):typeof define=="function"&&define.amd?define(["exports"],k):(f=typeof globalThis<"u"?globalThis:f||self,k(f.AtomEffect={}))})(this,(function(f){"use strict";const k={ONE_SECOND_MS:1e3},F={IDLE:"idle",PENDING:"pending",RESOLVED:"resolved",REJECTED:"rejected"},b={DISPOSED:1,HAS_FN_SUBS:2,HAS_OBJ_SUBS:4},g={...b,EXECUTING:8},h={...b,DIRTY:8,IDLE:16,PENDING:32,RESOLVED:64,REJECTED:128,RECOMPUTING:256,HAS_ERROR:512},D={...b,SYNC:8,NOTIFICATION_SCHEDULED:16},ot={MAX_SIZE:1e3,WARMUP_SIZE:100},O={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,BATCH_QUEUE_SHRINK_THRESHOLD:1e3},H={MAX_DEPENDENCIES:1e3,WARN_INFINITE_LOOP:!0},U=1073741823,T=typeof process<"u"&&process.env&&process.env.NODE_ENV!=="production",ct=Object.freeze([]);class N extends Error{constructor(t,e=null,s=!0){super(t),this.name="AtomError",this.cause=e,this.recoverable=s,this.timestamp=new Date}}class C extends N{constructor(t,e=null){super(t,e,!0),this.name="ComputedError"}}class A extends N{constructor(t,e=null){super(t,e,!1),this.name="EffectError"}}class P extends N{constructor(t,e=null){super(t,e,!1),this.name="SchedulerError"}}const G=Symbol("debugName"),ht=Symbol("id"),z=Symbol("type"),V=Symbol("noDefaultValue");function ut(i){return"dependencies"in i&&Array.isArray(i.dependencies)}function Q(i,t,e){if(!e.has(i.id)){if(e.add(i.id),i===t)throw new C("Indirect circular dependency detected");if(ut(i)){const s=i.dependencies;for(let n=0;n<s.length;n++){const r=s[n];r&&Q(r,t,e)}}}}const I={enabled:typeof process<"u"&&process.env?.NODE_ENV==="development",maxDependencies:H.MAX_DEPENDENCIES,warnInfiniteLoop:H.WARN_INFINITE_LOOP,warn(i,t){this.enabled&&i&&console.warn(`[Atom Effect] ${t}`)},checkCircular(i,t){if(i===t)throw new C("Direct circular dependency detected");this.enabled&&Q(i,t,new Set)},attachDebugInfo(i,t,e){if(!this.enabled)return;const s=i;s[G]=`${t}_${e}`,s[ht]=e,s[z]=t},getDebugName(i){if(i!=null&&G in i)return i[G]},getDebugType(i){if(i!=null&&z in i)return i[z]}};let lt=1;const at=()=>lt++;function R(i,t,e){if(t==null)return;const s=t;if(typeof s.addDependency=="function"){s.addDependency(i);return}if(typeof t=="function"){const r=t,o=e.length;for(let l=0;l<o;l++)if(e[l].fn===r)return;e.push(new v(r)),i.flags|=b.HAS_FN_SUBS;return}const n=t;if(typeof n.execute=="function"){const r=e.length;for(let o=0;o<r;o++)if(e[o].sub===n)return;e.push(new v(void 0,n)),i.flags|=b.HAS_OBJ_SUBS}}function ft(i,t,e){const s=t.length,n=i.length;if(s>0)for(let r=0;r<s;r++){const o=t[r];o&&(o.node._tempUnsub=o.unsub)}for(let r=0;r<n;r++){const o=i[r];if(!o)continue;const l=o.node,c=l._tempUnsub;c!==void 0?(o.unsub=c,l._tempUnsub=void 0):(I.checkCircular(l,e),o.unsub=l.subscribe(e))}if(s>0)for(let r=0;r<s;r++){const o=t[r];if(o){const l=o.node,c=l._tempUnsub;c!==void 0&&(c(),l._tempUnsub=void 0),o.unsub=void 0}}}class X{constructor(t,e,s=void 0){this.node=t,this.version=e,this.unsub=s}}class v{constructor(t,e){this.fn=t,this.sub=e}}const E={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",COMPUTED_CIRCULAR_DEPENDENCY:"Circular dependency detected during computation",COMPUTED_DISPOSED:"Cannot access a disposed computed",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",EFFECT_DISPOSED:"Cannot run a disposed effect",LARGE_DEPENDENCY_GRAPH:i=>`Large dependency graph detected: ${i} dependencies`,CALLBACK_ERROR_IN_ERROR_HANDLER:"Error occurred during onError callback execution"};class q{constructor(){this.flags=0,this.version=0,this._lastSeenEpoch=-1,this._modifiedAtEpoch=-1,this.id=at()&U,this._tempUnsub=void 0}}class J extends q{subscribe(t){const e=this._subscribers,s=typeof t=="function";if(!s&&(t===null||typeof t!="object"||typeof t.execute!="function"))throw new N(E.ATOM_SUBSCRIBER_MUST_BE_FUNCTION);const n=e.length;if(s){for(let o=0;o<n;o++)if(e[o].fn===t)return T&&console.warn("Attempted to subscribe the same listener twice. Ignoring duplicate subscription."),()=>{}}else for(let o=0;o<n;o++)if(e[o].sub===t)return T&&console.warn("Attempted to subscribe the same listener twice. Ignoring duplicate subscription."),()=>{};const r=s?new v(t):new v(void 0,t);return e.push(r),this.flags|=s?b.HAS_FN_SUBS:b.HAS_OBJ_SUBS,()=>{const o=e.indexOf(r);if(o===-1)return;const l=e.pop();o<e.length&&(e[o]=l);const c=e.length;if(c===0)this.flags&=-7;else{let a=!1,u=!1;for(let S=0;S<c&&(e[S].fn?a=!0:u=!0,!(a&&u));S++);let _=this.flags;a||(_&=-3),u||(_&=-5),this.flags=_}}}subscriberCount(){return this._subscribers.length}_notifySubscribers(t,e){if(!(this.flags&(b.HAS_FN_SUBS|b.HAS_OBJ_SUBS)))return;const n=this._subscribers,r=n.length;for(let o=0;o<r;o++){const l=n[o];try{l.fn?l.fn(t,e):l.sub&&l.sub.execute()}catch(c){this._handleNotifyError(c)}}}_handleNotifyError(t){console.error(new N(E.ATOM_INDIVIDUAL_SUBSCRIBER_FAILED,t))}}let w=0;function $(){return w=w+1&U||1,w}function _t(){return w}let Y=0,j=0,M=!1;function K(){return M?(T&&console.warn("Warning: startFlush() called during flush - ignored to prevent infinite loop detection bypass"),!1):(M=!0,Y=Y+1&U||1,j=0,!0)}function W(){M=!1}function Et(){return M?++j:0}class dt{constructor(){this._queueBuffer=[[],[]],this._bufferIndex=0,this._size=0,this._epoch=0,this._isProcessing=!1,this._isBatching=!1,this._batchDepth=0,this._batchQueue=[],this._batchQueueSize=0,this._isFlushingSync=!1,this._maxFlushIterations=O.MAX_FLUSH_ITERATIONS}get phase(){return this._isProcessing||this._isFlushingSync?2:this._isBatching?1:0}get queueSize(){return this._size}get isBatching(){return this._isBatching}schedule(t){if(T&&typeof t!="function")throw new P("Scheduler callback must be a function");const e=this._epoch;if(t._nextEpoch===e)return;if(t._nextEpoch=e,this._isBatching||this._isFlushingSync){this._batchQueue[this._batchQueueSize++]=t;return}const s=this._bufferIndex,n=this._size;this._queueBuffer[s][n]=t,this._size=n+1,this._isProcessing||this.flush()}flush(){this._isProcessing||this._size===0||(this._isProcessing=!0,queueMicrotask(()=>{try{if(this._size===0)return;const t=K();this._drainQueue(),t&&W()}finally{this._isProcessing=!1,this._size>0&&!this._isBatching&&this.flush()}}))}flushSync(){this._isFlushingSync=!0;const t=K();try{this._mergeBatchQueue(),this._drainQueue()}finally{this._isFlushingSync=!1,t&&W()}}_mergeBatchQueue(){const t=this._batchQueueSize;if(t===0)return;const e=++this._epoch,s=this._batchQueue,n=this._queueBuffer[this._bufferIndex];let r=this._size;for(let o=0;o<t;o++){const l=s[o];l._nextEpoch!==e&&(l._nextEpoch=e,n[r++]=l)}this._size=r,this._batchQueueSize=0,s.length>O.BATCH_QUEUE_SHRINK_THRESHOLD&&(s.length=0)}_drainQueue(){let t=0;const e=this._maxFlushIterations;for(;this._size>0;){if(++t>e){this._handleFlushOverflow();return}this._processQueue(),this._mergeBatchQueue()}}_processQueue(){const t=this._bufferIndex,e=this._queueBuffer[t],s=this._size;this._bufferIndex=t^1,this._size=0,this._epoch++,this._processJobs(e,s)}_handleFlushOverflow(){console.error(new P(`Maximum flush iterations (${this._maxFlushIterations}) exceeded. Possible infinite loop.`)),this._size=0,this._queueBuffer[this._bufferIndex].length=0,this._batchQueueSize=0}_processJobs(t,e){for(let s=0;s<e;s++)try{const n=t[s];n&&n()}catch(n){console.error(new P("Error occurred during scheduler execution",n))}t.length=0}startBatch(){this._batchDepth++,this._isBatching=!0}endBatch(){const t=this._batchDepth;if(t===0){T&&console.warn("endBatch() called without matching startBatch(). Ignoring.");return}const e=t-1;this._batchDepth=e,e===0&&(this.flushSync(),this._isBatching=!1)}setMaxFlushIterations(t){if(t<O.MIN_FLUSH_ITERATIONS)throw new P(`Max flush iterations must be at least ${O.MIN_FLUSH_ITERATIONS}`);this._maxFlushIterations=t}}const L=new dt;class pt{constructor(){this.current=null}run(t,e){const s=this.current;this.current=t;try{return e()}finally{this.current=s}}getCurrent(){return this.current}}const d=new pt;function Z(i){if(typeof i!="function")throw new N("Untracked callback must be a function");const t=d.current;d.current=null;try{return i()}finally{d.current=t}}class St extends J{constructor(t,e){super(),this._value=t,this._pendingOldValue=void 0,this._notifyTask=void 0,this._subscribers=[],e&&(this.flags|=D.SYNC),I.attachDebugInfo(this,"atom",this.id)}get value(){const t=d.current;return t&&R(this,t,this._subscribers),this._value}set value(t){const e=this._value;if(e===t||Object.is(e,t))return;this._value=t,this.version=this.version+1&U;let s=this.flags;if(s&(D.HAS_FN_SUBS|D.HAS_OBJ_SUBS)){if(s&D.NOTIFICATION_SCHEDULED)return;if(this._pendingOldValue=e,s|=D.NOTIFICATION_SCHEDULED,this.flags=s,s&D.SYNC&&!L.isBatching){this._flushNotifications();return}this._notifyTask||(this._notifyTask=()=>this._flushNotifications()),L.schedule(this._notifyTask)}}_flushNotifications(){const t=this.flags;if(!(t&D.NOTIFICATION_SCHEDULED)||t&D.DISPOSED)return;const e=this._pendingOldValue;this._pendingOldValue=void 0,this.flags=t&-17,this._notifySubscribers(this._value,e)}peek(){return this._value}dispose(){const t=this.flags;t&D.DISPOSED||(this._subscribers.length=0,this.flags=t|D.DISPOSED,this._value=void 0,this._pendingOldValue=void 0,this._notifyTask=void 0)}}function gt(i,t={}){return new St(i,t.sync??!1)}class It{constructor(){this.frozen=0,this.tooLarge=0,this.poolFull=0}}class Dt{constructor(){this.acquired=0,this.released=0,this.rejected=new It}}class Ct{constructor(){this.pool=[],this.maxPoolSize=50,this.maxReusableCapacity=256,this.stats=T?new Dt:null}acquire(){const t=this.stats;return t&&t.acquired++,this.pool.pop()??[]}release(t,e){const s=this.stats;if(e&&t===e)return;if(Object.isFrozen(t)){s&&s.rejected.frozen++;return}if(t.length>this.maxReusableCapacity){s&&s.rejected.tooLarge++;return}const n=this.pool;if(n.length>=this.maxPoolSize){s&&s.rejected.poolFull++;return}t.length=0,n.push(t),s&&s.released++}getStats(){const t=this.stats;if(!t)return null;const{acquired:e,released:s,rejected:n}=t,{frozen:r,tooLarge:o,poolFull:l}=n;return{acquired:e,released:s,rejected:{frozen:r,tooLarge:o,poolFull:l},leaked:e-s-(r+o+l),poolSize:this.pool.length}}reset(){this.pool.length=0;const t=this.stats;t&&(t.acquired=0,t.released=0,t.rejected.frozen=0,t.rejected.tooLarge=0,t.rejected.poolFull=0)}}const p=Object.freeze([]),m=new Ct;function x(i,t,e){if(i instanceof TypeError)return new t(`Type error (${e}): ${i.message}`,i);if(i instanceof ReferenceError)return new t(`Reference error (${e}): ${i.message}`,i);if(i instanceof N)return i;const s=i instanceof Error?i.message:String(i),n=i instanceof Error?i:null;return new t(`Unexpected error (${e}): ${s}`,n)}function tt(i){return i!==null&&typeof i=="object"&&"value"in i&&typeof i.subscribe=="function"}function bt(i){return I.enabled&&i!=null&&typeof i=="object"&&I.getDebugType(i)==="computed"?!0:tt(i)&&typeof i.invalidate=="function"}function Ot(i){return i!==null&&typeof i=="object"&&typeof i.dispose=="function"&&typeof i.run=="function"}function et(i){return i!=null&&typeof i.then=="function"}const st=h.RESOLVED|h.PENDING|h.REJECTED,B=Array(st+1).fill(F.IDLE);B[h.RESOLVED]=F.RESOLVED,B[h.PENDING]=F.PENDING,B[h.REJECTED]=F.REJECTED;const it=3,nt=Number.MAX_SAFE_INTEGER-1;class rt extends J{constructor(t,e={}){if(typeof t!="function")throw new C(E.COMPUTED_MUST_BE_FUNCTION);if(super(),this._value=void 0,this.flags=h.DIRTY|h.IDLE,this._error=null,this._promiseId=0,this._equal=e.equal??Object.is,this._fn=t,this._defaultValue="defaultValue"in e?e.defaultValue:V,this._onError=e.onError??null,this._subscribers=[],this._links=p,this._cachedErrors=null,this._errorCacheEpoch=-1,this._asyncStartAggregateVersion=0,this._asyncRetryCount=0,this._trackEpoch=-1,this._trackLinks=p,this._trackCount=0,I.attachDebugInfo(this,"computed",this.id),I.enabled){const s=this;s.subscriberCount=this.subscriberCount.bind(this),s.isDirty=()=>(this.flags&h.DIRTY)!==0,s.links=this._links}if(e.lazy===!1)try{this._recompute()}catch{}}get value(){const t=d.current;t&&R(this,t,this._subscribers);let e=this.flags;if((e&(h.RESOLVED|h.DIRTY|h.IDLE))===h.RESOLVED)return this._value;if(e&h.DISPOSED)throw new C(E.COMPUTED_DISPOSED);if(e&h.RECOMPUTING){const r=this._defaultValue;if(r!==V)return r;throw new C(E.COMPUTED_CIRCULAR_DEPENDENCY)}if(e&(h.DIRTY|h.IDLE)&&(this._recompute(),e=this.flags),e&h.RESOLVED)return this._value;const s=this._defaultValue,n=s!==V;if(e&h.PENDING){if(n)return s;throw new C(E.COMPUTED_ASYNC_PENDING_NO_DEFAULT)}if(e&h.REJECTED){const r=this._error;if(r?.recoverable&&n)return s;throw r}return this._value}peek(){return this._value}get state(){const t=d.current;return t&&R(this,t,this._subscribers),B[this.flags&st]}get hasError(){const t=d.current;if(t&&R(this,t,this._subscribers),this.flags&(h.REJECTED|h.HAS_ERROR))return!0;const s=this._links;for(let n=0,r=s.length;n<r;n++)if(s[n].node.flags&h.HAS_ERROR)return!0;return!1}get isValid(){return!this.hasError}get errors(){const t=d.current;if(t&&R(this,t,this._subscribers),!this.hasError)return ct;const e=_t();if(this._errorCacheEpoch===e&&this._cachedErrors!==null)return this._cachedErrors;const s=new Set,n=this._error;n&&s.add(n);const r=this._links;for(let l=0,c=r.length;l<c;l++){const a=r[l].node;if(a.flags&h.HAS_ERROR){const u=a.errors;if(u)for(let _=0,S=u.length;_<S;_++){const y=u[_];y&&s.add(y)}}}const o=Object.freeze(Array.from(s));return this._errorCacheEpoch=e,this._cachedErrors=o,o}get lastError(){const t=d.current;return t&&R(this,t,this._subscribers),this._error}get isPending(){const t=d.current;return t&&R(this,t,this._subscribers),(this.flags&h.PENDING)!==0}get isResolved(){const t=d.current;return t&&R(this,t,this._subscribers),(this.flags&h.RESOLVED)!==0}invalidate(){this._markDirty(),this._errorCacheEpoch=-1,this._cachedErrors=null}dispose(){if(this.flags&h.DISPOSED)return;const e=this._links;if(e!==p){for(let s=0,n=e.length;s<n;s++){const r=e[s];r?.unsub&&r.unsub()}m.release(e),this._links=p}this._subscribers.length=0,this.flags=h.DISPOSED|h.DIRTY|h.IDLE,this._error=null,this._value=void 0,this._promiseId=(this._promiseId+1)%nt,this._cachedErrors=null,this._errorCacheEpoch=-1}addDependency(t){const e=this._trackEpoch;if(t._lastSeenEpoch===e)return;t._lastSeenEpoch=e;const s=this._trackCount,n=this._trackLinks;if(s<n.length){const r=n[s];r.node=t,r.version=t.version}else n.push(new X(t,t.version));this._trackCount=s+1}_commitDeps(t){const e=this._trackLinks,s=this._trackCount;e.length=s,ft(e,t,this),this._links=e}_recompute(){if(this.flags&h.RECOMPUTING)return;this.flags|=h.RECOMPUTING;const t=this._links;this._trackEpoch=$(),this._trackLinks=m.acquire(),this._trackCount=0;let e=!1;try{const s=d.run(this,this._fn);this._commitDeps(t),e=!0,et(s)?this._handleAsyncComputation(s):this._finalizeResolution(s)}catch(s){let n=s;if(!e)try{this._commitDeps(t),e=!0}catch(r){n=r}this._handleComputationError(n)}finally{e?t!==p&&m.release(t):m.release(this._trackLinks),this._trackEpoch=-1,this._trackLinks=p,this._trackCount=0,this.flags&=-257}}_handleAsyncComputation(t){this.flags=(this.flags|h.PENDING)&-217,this._notifySubscribers(void 0,void 0),this._asyncStartAggregateVersion=this._captureVersionSnapshot(),this._asyncRetryCount=0,this._promiseId=(this._promiseId+1)%nt;const e=this._promiseId;t.then(s=>{if(e===this._promiseId){if(this._captureVersionSnapshot()!==this._asyncStartAggregateVersion){if(this._asyncRetryCount<it){this._asyncRetryCount++,this._markDirty();return}this._handleAsyncRejection(new C(`Async drift threshold exceeded after ${it} retries.`));return}this._finalizeResolution(s),this._notifySubscribers(s,void 0)}}).catch(s=>{e===this._promiseId&&this._handleAsyncRejection(s)})}_captureVersionSnapshot(){let t=0;const e=this._links;for(let s=0,n=e.length;s<n;s++){const r=e[s].node.version;t=((t<<5)-t|0)+r&U}return t}_handleAsyncRejection(t){const e=x(t,C,E.COMPUTED_ASYNC_COMPUTATION_FAILED);this.flags&h.REJECTED||(this.version=this.version+1&U),this._error=e,this.flags=this.flags&-121|(h.REJECTED|h.HAS_ERROR);const s=this._onError;if(s)try{s(e)}catch(n){console.error(E.CALLBACK_ERROR_IN_ERROR_HANDLER,n)}this._notifySubscribers(void 0,void 0)}_finalizeResolution(t){(!(this.flags&h.RESOLVED)||!this._equal(this._value,t))&&(this.version=this.version+1&U),this._value=t,this._error=null,this.flags=(this.flags|h.RESOLVED)&-697,this._cachedErrors=null,this._errorCacheEpoch=-1}_handleComputationError(t){const e=x(t,C,E.COMPUTED_COMPUTATION_FAILED);this._error=e,this.flags=this.flags&-121|(h.REJECTED|h.HAS_ERROR);const s=this._onError;if(s)try{s(e)}catch(n){console.error(E.CALLBACK_ERROR_IN_ERROR_HANDLER,n)}throw e}execute(){this._markDirty()}_markDirty(){const t=this.flags;t&(h.RECOMPUTING|h.DIRTY)||(this.flags=t|h.DIRTY,this._notifySubscribers(void 0,void 0))}}Object.freeze(rt.prototype);function Nt(i,t={}){return new rt(i,t)}class Tt extends q{constructor(t,e={}){super(),this._cleanup=null,this._links=p,this._nextLinks=null,this._executeTask=void 0,this._onError=e.onError??null,this._currentEpoch=-1,this._lastFlushEpoch=-1,this._executionsInEpoch=0,this._fn=t,this._sync=e.sync??!1,this._maxExecutions=e.maxExecutionsPerSecond??O.MAX_EXECUTIONS_PER_SECOND,this._maxExecutionsPerFlush=e.maxExecutionsPerFlush??O.MAX_EXECUTIONS_PER_EFFECT,this._trackModifications=e.trackModifications??!1,this._executionCount=0,this._historyPtr=0;const s=Number.isFinite(this._maxExecutions),n=s?Math.min(this._maxExecutions+1,O.MAX_EXECUTIONS_PER_SECOND+1):0;this._historyCapacity=n,this._history=T&&s&&n>0?new Array(n).fill(0):null,this._execId=0,I.attachDebugInfo(this,"effect",this.id)}run(){if(this.flags&g.DISPOSED)throw new A(E.EFFECT_DISPOSED);this.execute(!0)}dispose(){const t=this.flags;if(t&g.DISPOSED)return;if(this.flags=t|g.DISPOSED,this._cleanup){try{this._cleanup()}catch(s){this._handleExecutionError(s,E.EFFECT_CLEANUP_FAILED)}this._cleanup=null}const e=this._links;if(e!==p){for(let s=0,n=e.length;s<n;s++){const r=e[s];r?.unsub&&r.unsub()}m.release(e),this._links=p}this._executeTask=void 0}addDependency(t){if(!(this.flags&g.EXECUTING))return;const s=this._currentEpoch;if(t._lastSeenEpoch===s)return;t._lastSeenEpoch=s;const n=this._nextLinks,r=t._tempUnsub;if(r){n.push(new X(t,t.version,r)),t._tempUnsub=void 0;return}try{const o=this._sync,l=this._trackModifications,c=t.subscribe(()=>{if(l&&this.flags&g.EXECUTING&&(t._modifiedAtEpoch=this._currentEpoch),o){this.execute();return}this._executeTask||(this._executeTask=()=>this.execute());const a=this._executeTask;L.schedule(a)});n.push(new X(t,t.version,c))}catch(o){console.error(x(o,A,E.EFFECT_EXECUTION_FAILED))}}execute(t=!1){if(this.flags&(g.DISPOSED|g.EXECUTING))return;if(!t){const c=this._links,a=c.length;if(a>0){let u=!1;for(let _=0;_<a;_++){const S=c[_],y=S.node;if(y.version!==S.version){u=!0;break}if("value"in y)try{if(Z(()=>y.value),y.version!==S.version){u=!0;break}}catch{u=!0;break}}if(!u)return}}const s=Y;this._lastFlushEpoch!==s&&(this._lastFlushEpoch=s,this._executionsInEpoch=0),++this._executionsInEpoch>this._maxExecutionsPerFlush&&this._throwInfiniteLoopError("per-effect"),Et()>O.MAX_EXECUTIONS_PER_FLUSH&&this._throwInfiniteLoopError("global"),this._executionCount++;const n=this._history;if(n){const c=Date.now(),a=this._historyPtr;n[a]=c;const u=(a+1)%this._historyCapacity;this._historyPtr=u;const _=n[u]||0;if(_>0&&c-_<k.ONE_SECOND_MS){const S=new A("Effect executed too frequently within 1 second. Suspected infinite loop.");if(this.dispose(),this._handleExecutionError(S),T)throw S;return}}if(this.flags|=g.EXECUTING,this._cleanup){try{this._cleanup()}catch(c){this._handleExecutionError(c,E.EFFECT_CLEANUP_FAILED)}this._cleanup=null}const r=this._links;if(r!==p)for(let c=0,a=r.length;c<a;c++){const u=r[c];u&&(u.node._tempUnsub=u.unsub)}const o=m.acquire();this._nextLinks=o,this._currentEpoch=$();let l=!1;try{const c=d.run(this,this._fn);this._links=o,l=!0,this._checkLoopWarnings();const a=++this._execId;et(c)?c.then(u=>{if(a!==this._execId||this.flags&g.DISPOSED){if(typeof u=="function")try{u()}catch(_){this._handleExecutionError(_,E.EFFECT_CLEANUP_FAILED)}return}typeof u=="function"&&(this._cleanup=u)}).catch(u=>{a===this._execId&&this._handleExecutionError(u)}):this._cleanup=typeof c=="function"?c:null}catch(c){l=!0,this._handleExecutionError(c),this._cleanup=null}finally{if(this._nextLinks=null,l){if(r!==p){for(let c=0,a=r.length;c<a;c++){const u=r[c],_=u?u.node._tempUnsub:void 0;_&&(_(),u&&(u.node._tempUnsub=void 0))}m.release(r)}}else{for(let c=0,a=o.length;c<a;c++){const u=o[c];u?.unsub&&u.unsub()}if(m.release(o),r!==p)for(let c=0,a=r.length;c<a;c++){const u=r[c];u&&(u.node._tempUnsub=void 0)}}this.flags&=-9}}get isDisposed(){return(this.flags&g.DISPOSED)!==0}get executionCount(){return this._executionCount}get isExecuting(){return(this.flags&g.EXECUTING)!==0}_throwInfiniteLoopError(t){const e=new A(`Infinite loop detected (${t}): effect executed ${this._executionsInEpoch} times in current flush. Total executions in flush: ${j}`);throw this.dispose(),console.error(e),e}_handleExecutionError(t,e=E.EFFECT_EXECUTION_FAILED){const s=x(t,A,e);console.error(s);const n=this._onError;if(n)try{n(s)}catch(r){console.error(x(r,A,E.CALLBACK_ERROR_IN_ERROR_HANDLER))}}_checkLoopWarnings(){if(this._trackModifications&&I.enabled){const t=this._links,e=this._currentEpoch;for(let s=0,n=t.length;s<n;s++){const o=t[s].node;o&&o._modifiedAtEpoch===e&&I.warn(!0,`Effect is reading a dependency (${I.getDebugName(o)||"unknown"}) that it just modified. Infinite loop may occur`)}}}}function At(i,t={}){if(typeof i!="function")throw new A(E.EFFECT_MUST_BE_FUNCTION);const e=new Tt(i,t);return e.execute(),e}function Rt(i){if(typeof i!="function")throw new N("Batch callback must be a function");L.startBatch();try{return i()}finally{L.endBatch()}}f.AsyncState=F,f.AtomError=N,f.ComputedError=C,f.DEBUG_CONFIG=H,f.DEBUG_RUNTIME=I,f.EffectError=A,f.POOL_CONFIG=ot,f.SCHEDULER_CONFIG=O,f.SchedulerError=P,f.atom=gt,f.batch=Rt,f.computed=Nt,f.effect=At,f.isAtom=tt,f.isComputed=bt,f.isEffect=Ot,f.scheduler=L,f.untracked=Z,Object.defineProperty(f,Symbol.toStringTag,{value:"Module"})}));
2
2
  //# sourceMappingURL=atom-effect.min.js.map