@but212/atom-effect 0.16.0 → 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) | ~10.7K ops/sec |
147
- | Atom read (x1000) | ~32.8K ops/sec |
148
- | Atom write (x1000) | ~552K ops/sec |
149
- | Computed creation (x1000) | ~3.22K ops/sec |
150
- | Computed recomputation | ~600K ops/sec |
151
- | Effect execution (x1000) | ~9.39K ops/sec |
152
- | Batched updates (x2) (x1000) | ~4.89K ops/sec |
153
- | Deep chain (100 levels) | ~10.0K 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(a,V){typeof exports=="object"&&typeof module<"u"?V(exports):typeof define=="function"&&define.amd?define(["exports"],V):(a=typeof globalThis<"u"?globalThis:a||self,V(a.AtomEffect={}))})(this,(function(a){"use strict";const V={ONE_SECOND_MS:1e3},k={IDLE:"idle",PENDING:"pending",RESOLVED:"resolved",REJECTED:"rejected"},I={DISPOSED:1,HAS_FN_SUBS:2,HAS_OBJ_SUBS:4},b={...I,EXECUTING:8},o={...I,DIRTY:8,IDLE:16,PENDING:32,RESOLVED:64,REJECTED:128,RECOMPUTING:256,HAS_ERROR:512},N={...I,SYNC:8,NOTIFICATION_SCHEDULED:16},fe={MAX_SIZE:1e3,WARMUP_SIZE:100},T={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},q={MAX_DEPENDENCIES:1e3,WARN_INFINITE_LOOP:!0},v=1073741823,M=typeof process<"u"&&process.env&&process.env.NODE_ENV!=="production",Ee=Object.freeze([]);class A extends Error{constructor(e,t=null,s=!0){super(e),this.name="AtomError",this.cause=t,this.recoverable=s,this.timestamp=new Date}}class y extends A{constructor(e,t=null){super(e,t,!0),this.name="ComputedError"}}class U extends A{constructor(e,t=null){super(e,t,!1),this.name="EffectError"}}class H extends A{constructor(e,t=null){super(e,t,!1),this.name="SchedulerError"}}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"},Q=Symbol("debugName"),de=Symbol("id"),J=Symbol("type"),$=Symbol("noDefaultValue");function pe(i){return"dependencies"in i&&Array.isArray(i.dependencies)}function ee(i,e,t){if(!t.has(i.id)){if(t.add(i.id),i===e)throw new y("Indirect circular dependency detected");if(pe(i)){const s=i.dependencies;for(let n=0;n<s.length;n++){const r=s[n];r&&ee(r,e,t)}}}}const C={enabled:typeof process<"u"&&process.env?.NODE_ENV==="development",maxDependencies:q.MAX_DEPENDENCIES,warnInfiniteLoop:q.WARN_INFINITE_LOOP,warn(i,e){this.enabled&&i&&console.warn(`[Atom Effect] ${e}`)},checkCircular(i,e){if(i===e)throw new y("Direct circular dependency detected");this.enabled&&ee(i,e,new Set)},attachDebugInfo(i,e,t){if(!this.enabled)return;const s=i;s[Q]=`${e}_${t}`,s[de]=t,s[J]=e},getDebugName(i){if(i!=null&&Q in i)return i[Q]},getDebugType(i){if(i!=null&&J in i)return i[J]}};let Se=1;const ge=()=>Se++;class te{constructor(){this.flags=0,this.version=0,this._lastSeenEpoch=-1,this._modifiedAtEpoch=-1,this.id=ge()&v,this._tempUnsub=void 0}}class se extends te{subscribe(e){if(typeof e=="function")return this._addSubscriber(this._fnSubs,e,I.HAS_FN_SUBS);if(e!==null&&typeof e=="object"&&"execute"in e)return this._addSubscriber(this._objSubs,e,I.HAS_OBJ_SUBS);throw new A(E.ATOM_SUBSCRIBER_MUST_BE_FUNCTION)}_addSubscriber(e,t,s){return e.indexOf(t)!==-1?(M&&console.warn("Attempted to subscribe the same listener twice. Ignoring duplicate subscription."),()=>{}):(e.push(t),this.flags|=s,()=>{const n=e.indexOf(t);if(n===-1)return;const r=e.pop();n<e.length&&(e[n]=r),e.length===0&&(this.flags&=~s)})}subscriberCount(){return this._fnSubs.length+this._objSubs.length}_notifySubscribers(e,t){const s=this.flags;if(s&(I.HAS_FN_SUBS|I.HAS_OBJ_SUBS)){if(s&I.HAS_FN_SUBS){const n=this._fnSubs;for(let r=0;r<n.length;r++)try{n[r](e,t)}catch(h){this._handleNotifyError(h)}}if(s&I.HAS_OBJ_SUBS){const n=this._objSubs;for(let r=0;r<n.length;r++)try{n[r].execute()}catch(h){this._handleNotifyError(h)}}}}_handleNotifyError(e){console.error(new A(E.ATOM_INDIVIDUAL_SUBSCRIBER_FAILED,e))}}class De{constructor(){this.frozen=0,this.tooLarge=0,this.poolFull=0}}class Ie{constructor(){this.acquired=0,this.released=0,this.rejected=new De}}class K{constructor(){this.pool=[],this.maxPoolSize=50,this.maxReusableCapacity=256,this.stats=M?new Ie:null}acquire(){const e=this.stats;return e&&e.acquired++,this.pool.pop()??[]}release(e,t){const s=this.stats;if(t&&e===t)return;if(Object.isFrozen(e)){s&&s.rejected.frozen++;return}if(e.length>this.maxReusableCapacity){s&&s.rejected.tooLarge++;return}const n=this.pool;if(n.length>=this.maxPoolSize){s&&s.rejected.poolFull++;return}e.length=0,n.push(e),s&&s.released++}getStats(){const e=this.stats;if(!e)return null;const{acquired:t,released:s,rejected:n}=e,{frozen:r,tooLarge:h,poolFull:c}=n;return{acquired:t,released:s,rejected:{frozen:r,tooLarge:h,poolFull:c},leaked:t-s-(r+h+c),poolSize:this.pool.length}}reset(){this.pool.length=0;const e=this.stats;e&&(e.acquired=0,e.released=0,e.rejected.frozen=0,e.rejected.tooLarge=0,e.rejected.poolFull=0)}}const S=Object.freeze([]),x=Object.freeze([]),g=Object.freeze([]),F=new K,w=new K,R=new K;function P(i,e,t,s){if(e!=null){if(typeof e.addDependency=="function"){e.addDependency(i);return}if(typeof e=="function"){const n=e;t.indexOf(n)===-1&&(t.push(n),i.flags|=I.HAS_FN_SUBS);return}if(typeof e.execute=="function"){const n=e;s.indexOf(n)===-1&&(s.push(n),i.flags|=I.HAS_OBJ_SUBS)}}}function be(i,e,t,s){const n=e.length;if(n>0)for(let c=0;c<n;c++){const l=e[c];l&&(l._tempUnsub=t[c])}const r=i.length,h=w.acquire();h.length=r;for(let c=0;c<r;c++){const l=i[c];if(!l)continue;const d=l._tempUnsub;d?(h[c]=d,l._tempUnsub=void 0):(C.checkCircular(l,s),h[c]=l.subscribe(s))}if(n>0)for(let c=0;c<n;c++){const l=e[c];if(l){const d=l._tempUnsub;d&&(d(),l._tempUnsub=void 0)}}return t!==x&&w.release(t),h}let z=0;function ie(){return z=z+1&v||1,z}function Ce(){return z}let W=0,Z=0,j=!1;function ne(){return j?(M&&console.warn("Warning: startFlush() called during flush - ignored to prevent infinite loop detection bypass"),!1):(j=!0,W=W+1&v||1,Z=0,!0)}function re(){j=!1}function Oe(){return j?++Z:0}class Ne{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=T.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(M&&typeof e!="function")throw new H("Scheduler callback must be a function");const t=this._epoch;if(e._nextEpoch===t)return;if(e._nextEpoch=t,this._isBatching||this._isFlushingSync){this._batchQueue[this._batchQueueSize++]=e;return}const s=this._bufferIndex,n=this._size;this._queueBuffer[s][n]=e,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 e=ne();this._drainQueue(),e&&re()}finally{this._isProcessing=!1,this._size>0&&!this._isBatching&&this.flush()}}))}flushSync(){this._isFlushingSync=!0;const e=ne();try{this._mergeBatchQueue(),this._drainQueue()}finally{this._isFlushingSync=!1,e&&re()}}_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 h=0;h<e;h++){const c=s[h];c._nextEpoch!==t&&(c._nextEpoch=t,n[r++]=c)}this._size=r,this._batchQueueSize=0,s.length>T.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;this._bufferIndex=e^1,this._size=0,this._epoch++,this._processJobs(t,s)}_handleFlushOverflow(){console.error(new H(`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{const n=e[s];n&&n()}catch(n){console.error(new H("Error occurred during scheduler execution",n))}e.length=0}startBatch(){this._batchDepth++,this._isBatching=!0}endBatch(){const e=this._batchDepth;if(e===0){M&&console.warn("endBatch() called without matching startBatch(). Ignoring.");return}const t=e-1;this._batchDepth=t,t===0&&(this.flushSync(),this._isBatching=!1)}setMaxFlushIterations(e){if(e<T.MIN_FLUSH_ITERATIONS)throw new H(`Max flush iterations must be at least ${T.MIN_FLUSH_ITERATIONS}`);this._maxFlushIterations=e}}const B=new Ne;class ye{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 ye;function oe(i){if(typeof i!="function")throw new A("Untracked callback must be a function");const e=p.current;p.current=null;try{return i()}finally{p.current=e}}class Te extends se{constructor(e,t){super(),this._value=e,this._pendingOldValue=void 0,this._notifyTask=void 0,this._fnSubs=[],this._objSubs=[],t&&(this.flags|=N.SYNC),C.attachDebugInfo(this,"atom",this.id)}get value(){const e=p.current;return e&&P(this,e,this._fnSubs,this._objSubs),this._value}set value(e){const t=this._value;if(t===e||Object.is(t,e))return;this._value=e,this.version=this.version+1&v,this.flags&(N.HAS_FN_SUBS|N.HAS_OBJ_SUBS)&&this._scheduleNotification(t)}_scheduleNotification(e){let t=this.flags;if(t&N.NOTIFICATION_SCHEDULED||(this._pendingOldValue=e,t|=N.NOTIFICATION_SCHEDULED,this.flags=t),t&N.SYNC&&!B.isBatching){this._flushNotifications();return}this._notifyTask||(this._notifyTask=()=>this._flushNotifications());const s=this._notifyTask;B.schedule(s)}_flushNotifications(){const e=this.flags;if(!(e&N.NOTIFICATION_SCHEDULED)||e&N.DISPOSED)return;const t=this._pendingOldValue;this._pendingOldValue=void 0,this.flags=e&-17,this._notifySubscribers(this._value,t)}peek(){return this._value}dispose(){const e=this.flags;e&N.DISPOSED||(this._fnSubs.length=0,this._objSubs.length=0,this.flags=e|N.DISPOSED,this._value=void 0,this._pendingOldValue=void 0,this._notifyTask=void 0)}}function Ae(i,e={}){return new Te(i,e.sync??!1)}function G(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 A)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 ce(i){return i!==null&&typeof i=="object"&&"value"in i&&typeof i.subscribe=="function"}function Re(i){return C.enabled&&i!=null&&typeof i=="object"&&C.getDebugType(i)==="computed"?!0:ce(i)&&typeof i.invalidate=="function"}function me(i){return i!==null&&typeof i=="object"&&typeof i.dispose=="function"&&typeof i.run=="function"}function he(i){return i!=null&&typeof i.then=="function"}const ue=o.RESOLVED|o.PENDING|o.REJECTED,X=Array(ue+1).fill(k.IDLE);X[o.RESOLVED]=k.RESOLVED,X[o.PENDING]=k.PENDING,X[o.REJECTED]=k.REJECTED;const _e=3,ae=Number.MAX_SAFE_INTEGER-1;class le extends se{constructor(e,t={}){if(typeof e!="function")throw new y(E.COMPUTED_MUST_BE_FUNCTION);if(super(),this._value=void 0,this.flags=o.DIRTY|o.IDLE,this._error=null,this._promiseId=0,this._equal=t.equal??Object.is,this._fn=e,this._defaultValue="defaultValue"in t?t.defaultValue:$,this._onError=t.onError??null,this._fnSubs=[],this._objSubs=[],this._dependencies=S,this._dependencyVersions=g,this._unsubscribes=x,this._cachedErrors=null,this._errorCacheEpoch=-1,this._asyncStartAggregateVersion=0,this._asyncRetryCount=0,this._trackEpoch=-1,this._trackDeps=S,this._trackVersions=g,this._trackCount=0,C.attachDebugInfo(this,"computed",this.id),C.enabled){const s=this;s.subscriberCount=this.subscriberCount.bind(this),s.isDirty=()=>(this.flags&o.DIRTY)!==0,s.dependencies=this._dependencies}if(t.lazy===!1)try{this._recompute()}catch{}}get value(){const e=p.current;e&&P(this,e,this._fnSubs,this._objSubs);let t=this.flags;if((t&(o.RESOLVED|o.DIRTY|o.IDLE))===o.RESOLVED)return this._value;if(t&o.DISPOSED)throw new y(E.COMPUTED_DISPOSED);if(t&o.RECOMPUTING){const r=this._defaultValue;if(r!==$)return r;throw new y(E.COMPUTED_CIRCULAR_DEPENDENCY)}if(t&(o.DIRTY|o.IDLE)&&(this._recompute(),t=this.flags),t&o.RESOLVED)return this._value;const s=this._defaultValue,n=s!==$;if(t&o.PENDING){if(n)return s;throw new y(E.COMPUTED_ASYNC_PENDING_NO_DEFAULT)}if(t&o.REJECTED){const r=this._error;if(r?.recoverable&&n)return s;throw r}return this._value}peek(){return this._value}get state(){const e=p.current;return e&&P(this,e,this._fnSubs,this._objSubs),X[this.flags&ue]}get hasError(){const e=p.current;if(e&&P(this,e,this._fnSubs,this._objSubs),this.flags&(o.REJECTED|o.HAS_ERROR))return!0;const s=this._dependencies;for(let n=0,r=s.length;n<r;n++)if(s[n].flags&o.HAS_ERROR)return!0;return!1}get isValid(){return!this.hasError}get errors(){const e=p.current;if(e&&P(this,e,this._fnSubs,this._objSubs),!this.hasError)return Ee;const t=Ce();if(this._errorCacheEpoch===t&&this._cachedErrors!==null)return this._cachedErrors;const s=new Set,n=this._error;n&&s.add(n);const r=this._dependencies;for(let c=0,l=r.length;c<l;c++){const d=r[c];if(d.flags&o.HAS_ERROR){const O=d.errors;if(O)for(let m=0,u=O.length;m<u;m++){const f=O[m];f&&s.add(f)}}}const h=Object.freeze(Array.from(s));return this._errorCacheEpoch=t,this._cachedErrors=h,h}get lastError(){const e=p.current;return e&&P(this,e,this._fnSubs,this._objSubs),this._error}get isPending(){const e=p.current;return e&&P(this,e,this._fnSubs,this._objSubs),(this.flags&o.PENDING)!==0}get isResolved(){const e=p.current;return e&&P(this,e,this._fnSubs,this._objSubs),(this.flags&o.RESOLVED)!==0}invalidate(){this._markDirty();const e=this._dependencyVersions;e!==g&&(R.release(e),this._dependencyVersions=g),this._errorCacheEpoch=-1,this._cachedErrors=null}dispose(){if(this.flags&o.DISPOSED)return;const t=this._unsubscribes;if(t!==x){for(let r=0,h=t.length;r<h;r++){const c=t[r];c&&c()}w.release(t),this._unsubscribes=x}const s=this._dependencies;s!==S&&(F.release(s),this._dependencies=S);const n=this._dependencyVersions;n!==g&&(R.release(n),this._dependencyVersions=g),this._fnSubs.length=0,this._objSubs.length=0,this.flags=o.DISPOSED|o.DIRTY|o.IDLE,this._error=null,this._value=void 0,this._promiseId=(this._promiseId+1)%ae,this._cachedErrors=null,this._errorCacheEpoch=-1}addDependency(e){if(e._lastSeenEpoch===this._trackEpoch)return;e._lastSeenEpoch=this._trackEpoch;const t=this._trackCount,s=this._trackDeps,n=this._trackVersions;t<s.length?(s[t]=e,n[t]=e.version):(s.push(e),n.push(e.version)),this._trackCount=t+1}_commitDeps(e){const t=this._trackDeps,s=this._trackVersions,n=this._trackCount;t.length=n,s.length=n,this._unsubscribes=be(t,e,this._unsubscribes,this),this._dependencies=t,this._dependencyVersions=s}_recompute(){if(this.flags&o.RECOMPUTING)return;this.flags|=o.RECOMPUTING;const e=this._dependencies,t=this._dependencyVersions;this._trackEpoch=ie(),this._trackDeps=F.acquire(),this._trackVersions=R.acquire(),this._trackCount=0;let s=!1;try{const n=p.run(this,this._fn);this._commitDeps(e),s=!0,he(n)?this._handleAsyncComputation(n):this._finalizeResolution(n)}catch(n){let r=n;if(!s)try{this._commitDeps(e),s=!0}catch(h){r=h}this._handleComputationError(r)}finally{s?(e!==S&&F.release(e),t!==g&&R.release(t)):(F.release(this._trackDeps),R.release(this._trackVersions)),this._trackEpoch=-1,this._trackDeps=S,this._trackVersions=g,this._trackCount=0,this.flags&=-257}}_handleAsyncComputation(e){this.flags=(this.flags|o.PENDING)&-217,this._notifySubscribers(void 0,void 0),this._asyncStartAggregateVersion=this._captureVersionSnapshot(),this._asyncRetryCount=0,this._promiseId=(this._promiseId+1)%ae;const t=this._promiseId;e.then(s=>{if(t===this._promiseId){if(this._captureVersionSnapshot()!==this._asyncStartAggregateVersion){if(this._asyncRetryCount<_e){this._asyncRetryCount++,this._markDirty();return}this._handleAsyncRejection(new y(`Async drift threshold exceeded after ${_e} retries.`));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 h=r.version;e=((e<<5)-e|0)+h&v}}return e}_handleAsyncRejection(e){const t=G(e,y,E.COMPUTED_ASYNC_COMPUTATION_FAILED);this.flags&o.REJECTED||(this.version=this.version+1&v),this._error=t,this.flags=this.flags&-121|(o.REJECTED|o.HAS_ERROR);const s=this._onError;if(s)try{s(t)}catch(n){console.error(E.CALLBACK_ERROR_IN_ERROR_HANDLER,n)}this._notifySubscribers(void 0,void 0)}_finalizeResolution(e){(!(this.flags&o.RESOLVED)||!this._equal(this._value,e))&&(this.version=this.version+1&v),this._value=e,this._error=null,this.flags=(this.flags|o.RESOLVED)&-697,this._cachedErrors=null,this._errorCacheEpoch=-1}_handleComputationError(e){const t=G(e,y,E.COMPUTED_COMPUTATION_FAILED);this._error=t,this.flags=this.flags&-121|(o.REJECTED|o.HAS_ERROR);const s=this._onError;if(s)try{s(t)}catch(n){console.error(E.CALLBACK_ERROR_IN_ERROR_HANDLER,n)}throw t}execute(){this._markDirty()}_markDirty(){const e=this.flags;e&(o.RECOMPUTING|o.DIRTY)||(this.flags=e|o.DIRTY,this._notifySubscribers(void 0,void 0))}}Object.freeze(le.prototype);function Ue(i,e={}){return new le(i,e)}class xe extends te{constructor(e,t={}){super(),this._cleanup=null,this._dependencies=S,this._dependencyVersions=g,this._unsubscribes=x,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??T.MAX_EXECUTIONS_PER_SECOND,this._maxExecutionsPerFlush=t.maxExecutionsPerFlush??T.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,T.MAX_EXECUTIONS_PER_SECOND+1):0;this._historyCapacity=n,this._history=M&&s&&n>0?new Array(n).fill(0):null,this._execId=0,C.attachDebugInfo(this,"effect",this.id)}run(){if(this.flags&b.DISPOSED)throw new U(E.EFFECT_DISPOSED);this.execute(!0)}dispose(){const e=this.flags;if(e&b.DISPOSED)return;if(this.flags=e|b.DISPOSED,this._cleanup){try{this._cleanup()}catch(r){this._handleExecutionError(r,E.EFFECT_CLEANUP_FAILED)}this._cleanup=null}const t=this._unsubscribes;if(t!==x){for(let r=0,h=t.length;r<h;r++){const c=t[r];c&&c()}w.release(t),this._unsubscribes=x}const s=this._dependencies;s!==S&&(F.release(s),this._dependencies=S);const n=this._dependencyVersions;n!==g&&(R.release(n),this._dependencyVersions=g),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,h=this._nextUnsubs;n.push(e),r.push(e.version);const c=e._tempUnsub;if(c){h.push(c),e._tempUnsub=void 0;return}try{const l=this._sync,d=this._trackModifications,O=e.subscribe(()=>{if(d&&this.flags&b.EXECUTING&&(e._modifiedAtEpoch=this._currentEpoch),l){this.execute();return}this._executeTask||(this._executeTask=()=>this.execute());const m=this._executeTask;B.schedule(m)});h.push(O)}catch(l){console.error(G(l,U,E.EFFECT_EXECUTION_FAILED)),h.push(()=>{})}}execute(e=!1){if(this.flags&(b.DISPOSED|b.EXECUTING))return;if(!e){const u=this._dependencies,f=u.length;if(f>0){const _=this._dependencyVersions;let D=!1;for(let L=0;L<f;L++){const Y=u[L];if(Y.version!==_[L]){D=!0;break}if("value"in Y)try{if(oe(()=>Y.value),Y.version!==_[L]){D=!0;break}}catch{D=!0;break}}if(!D)return}}const s=W;this._lastFlushEpoch!==s&&(this._lastFlushEpoch=s,this._executionsInEpoch=0),++this._executionsInEpoch>this._maxExecutionsPerFlush&&this._throwInfiniteLoopError("per-effect"),Oe()>T.MAX_EXECUTIONS_PER_FLUSH&&this._throwInfiniteLoopError("global"),this._executionCount++;const n=this._history;if(n){const u=Date.now(),f=this._historyPtr;n[f]=u;const _=(f+1)%this._historyCapacity;this._historyPtr=_;const D=n[_]||0;if(D>0&&u-D<V.ONE_SECOND_MS){const L=new U("Effect executed too frequently within 1 second. Suspected infinite loop.");if(this.dispose(),this._handleExecutionError(L),M)throw L;return}}if(this.flags|=b.EXECUTING,this._cleanup){try{this._cleanup()}catch(u){this._handleExecutionError(u,E.EFFECT_CLEANUP_FAILED)}this._cleanup=null}const r=this._dependencies,h=this._dependencyVersions,c=this._unsubscribes;if(r!==S)for(let u=0,f=r.length;u<f;u++){const _=r[u];_&&(_._tempUnsub=c[u])}const l=F.acquire(),d=R.acquire(),O=w.acquire();this._nextDeps=l,this._nextVersions=d,this._nextUnsubs=O,this._currentEpoch=ie();let m=!1;try{const u=p.run(this,this._fn);this._dependencies=l,this._dependencyVersions=d,this._unsubscribes=O,m=!0,this._checkLoopWarnings();const f=++this._execId;he(u)?u.then(_=>{if(f!==this._execId||this.flags&b.DISPOSED){if(typeof _=="function")try{_()}catch(D){this._handleExecutionError(D,E.EFFECT_CLEANUP_FAILED)}return}typeof _=="function"&&(this._cleanup=_)}).catch(_=>{f===this._execId&&this._handleExecutionError(_)}):this._cleanup=typeof u=="function"?u:null}catch(u){m=!0,this._handleExecutionError(u),this._cleanup=null}finally{if(this._nextDeps=null,this._nextVersions=null,this._nextUnsubs=null,m){if(r!==S){for(let u=0,f=r.length;u<f;u++){const _=r[u],D=_?_._tempUnsub:void 0;D&&(D(),_&&(_._tempUnsub=void 0))}F.release(r)}h!==g&&R.release(h),c!==x&&w.release(c)}else{F.release(l),R.release(d);for(let u=0,f=O.length;u<f;u++){const _=O[u];_&&_()}if(w.release(O),r!==S)for(let u=0,f=r.length;u<f;u++){const _=r[u];_&&(_._tempUnsub=void 0)}}this.flags&=-9}}get isDisposed(){return(this.flags&b.DISPOSED)!==0}get executionCount(){return this._executionCount}get isExecuting(){return(this.flags&b.EXECUTING)!==0}_throwInfiniteLoopError(e){const t=new U(`Infinite loop detected (${e}): effect executed ${this._executionsInEpoch} times in current flush. Total executions in flush: ${Z}`);throw this.dispose(),console.error(t),t}_handleExecutionError(e,t=E.EFFECT_EXECUTION_FAILED){const s=G(e,U,t);console.error(s);const n=this._onError;if(n)try{n(s)}catch(r){console.error(G(r,U,E.CALLBACK_ERROR_IN_ERROR_HANDLER))}}_checkLoopWarnings(){if(this._trackModifications&&C.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&&C.warn(!0,`Effect is reading a dependency (${C.getDebugName(r)||"unknown"}) that it just modified. Infinite loop may occur`)}}}}function Fe(i,e={}){if(typeof i!="function")throw new U(E.EFFECT_MUST_BE_FUNCTION);const t=new xe(i,e);return t.execute(),t}function Pe(i){if(typeof i!="function")throw new A("Batch callback must be a function");B.startBatch();try{return i()}finally{B.endBatch()}}a.AsyncState=k,a.AtomError=A,a.ComputedError=y,a.DEBUG_CONFIG=q,a.DEBUG_RUNTIME=C,a.EffectError=U,a.POOL_CONFIG=fe,a.SCHEDULER_CONFIG=T,a.SchedulerError=H,a.atom=Ae,a.batch=Pe,a.computed=Ue,a.effect=Fe,a.isAtom=ce,a.isComputed=Re,a.isEffect=me,a.scheduler=B,a.untracked=oe,Object.defineProperty(a,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