@but212/atom-effect 0.28.0 → 0.29.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,3 +1,3 @@
1
- (function(c,p){typeof exports=="object"&&typeof module<"u"?p(exports):typeof define=="function"&&define.amd?define(["exports"],p):(c=typeof globalThis<"u"?globalThis:c||self,p(c.AtomEffect={}))})(this,function(c){Object.defineProperty(c,Symbol.toStringTag,{value:"Module"});var p={IDLE:"idle",PENDING:"pending",RESOLVED:"resolved",REJECTED:"rejected"},S={DISPOSED:1,EXECUTING:8},B={DISPOSED:1,IS_COMPUTED:2,DIRTY:8,IDLE:16,PENDING:32,RESOLVED:64,REJECTED:128,RECOMPUTING:256,HAS_ERROR:512,FORCE_COMPUTE:1024},E={DISPOSED:1,SYNC:8,NOTIFICATION_SCHEDULED:16},C={MAX_EXECUTIONS_PER_SECOND: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={WARN_INFINITE_LOOP:!0,EFFECT_FREQUENCY_WINDOW:1e3},Z={MAX_ASYNC_RETRIES:3,MAX_PROMISE_ID:Number.MAX_SAFE_INTEGER-1},y={UNINITIALIZED:-1,MIN:1},F=1073741823,at={VERSION_BITS:16},zt=(typeof process<"u"&&process.env,!1),J=Object.freeze([]),x=class{constructor(t,s,e=void 0){this.node=t,this.version=s,this.unsub=e}},Et=class{constructor(t,s){this.fn=t,this.sub=s}notify(t,s){const e=this.fn;if(e!==void 0){e(t,s);return}const i=this.sub;i!==void 0&&i.execute()}},m=class extends Error{constructor(t,s=null,e=!0){super(t),this.cause=s,this.recoverable=e,this.name="AtomError"}},g=class extends m{constructor(t,s=null){super(t,s,!0),this.name="ComputedError"}},D=class extends m{constructor(t,s=null){super(t,s,!1),this.name="EffectError"}},w=class extends m{constructor(t,s=null){super(t,s,!1),this.name="SchedulerError"}},_={COMPUTED_MUST_BE_FUNCTION:"Computed target must be a function",COMPUTED_ASYNC_PENDING_NO_DEFAULT:"Async computation pending with no default value",COMPUTED_COMPUTATION_FAILED:"Computation execution failed",COMPUTED_ASYNC_COMPUTATION_FAILED:"Async computation execution failed",COMPUTED_CIRCULAR_DEPENDENCY:"Circular dependency detected",COMPUTED_DISPOSED:"Attempted to access disposed computed",ATOM_SUBSCRIBER_MUST_BE_FUNCTION:"Subscriber must be a function or Subscriber object",ATOM_INDIVIDUAL_SUBSCRIBER_FAILED:"Subscriber execution failed",EFFECT_MUST_BE_FUNCTION:"Effect target must be a function",EFFECT_EXECUTION_FAILED:"Effect execution failed",EFFECT_CLEANUP_FAILED:"Effect cleanup failed",EFFECT_DISPOSED:"Attempted to run disposed effect",SCHEDULER_FLUSH_OVERFLOW:(t,s)=>`Maximum flush iterations (${t}) exceeded. ${s} jobs dropped. Possible infinite loop.`,CALLBACK_ERROR_IN_ERROR_HANDLER:"Exception encountered in onError handler",EFFECT_FREQUENCY_LIMIT_EXCEEDED:"Effect executed too frequently within 1 second. Suspected infinite loop.",SCHEDULER_CALLBACK_MUST_BE_FUNCTION:"Scheduler callback must be a function",SCHEDULER_END_BATCH_WITHOUT_START:"endBatch() called without matching startBatch(). Ignoring.",BATCH_CALLBACK_MUST_BE_FUNCTION:"Batch callback must be a function"},tt=class{constructor(){this._s0=null,this._s1=null,this._s2=null,this._s3=null,this._count=0,this._overflow=null,this._freeIndices=null}get size(){return this._count}getAt(t){if(t<4)switch(t){case 0:return this._s0;case 1:return this._s1;case 2:return this._s2;case 3:return this._s3}const s=this._overflow;if(s!==null){const e=s[t-4];return e===void 0?null:e}return null}setAt(t,s){switch(t){case 0:this._s0=s;break;case 1:this._s1=s;break;case 2:this._s2=s;break;case 3:this._s3=s;break;default:this._overflow??=[],this._overflow[t-4]=s}t>=this._count&&(this._count=t+1)}truncateFrom(t){const s=this._count;if(t>=s)return;if(t<=3){if(t<=0){const i=this._s0;i!=null&&(this._onItemRemoved(i),this._s0=null)}if(t<=1){const i=this._s1;i!=null&&(this._onItemRemoved(i),this._s1=null)}if(t<=2){const i=this._s2;i!=null&&(this._onItemRemoved(i),this._s2=null)}if(t<=3){const i=this._s3;i!=null&&(this._onItemRemoved(i),this._s3=null)}}const e=this._overflow;if(e!==null&&s>4){const i=t>4?t-4:0,r=e.length;for(let n=i;n<r;n++){const o=e[n];o!=null&&(this._onItemRemoved(o),e[n]=null)}t<=4?(e.length=0,this._overflow=null):e.length=t-4}this._freeIndices!==null&&(this._freeIndices=null),this._count=t}_onItemRemoved(t){}add(t){if(this._s0===null){this._s0=t,this._count++;return}if(this._s1===null){this._s1=t,this._count++;return}if(this._s2===null){this._s2=t,this._count++;return}if(this._s3===null){this._s3=t,this._count++;return}this._addToOverflow(t)}_addToOverflow(t){const s=this._overflow;if(s===null)this._overflow=[t];else{const e=this._freeIndices;e!==null&&e.length>0?s[e.pop()]=t:s.push(t)}this._count++}remove(t){if(this._s0===t)return this._s0=null,this._count--,!0;if(this._s1===t)return this._s1=null,this._count--,!0;if(this._s2===t)return this._s2=null,this._count--,!0;if(this._s3===t)return this._s3=null,this._count--,!0;const s=this._overflow;if(s==null)return!1;for(let e=0,i=s.length;e<i;e++)if(s[e]===t){s[e]=null,this._count--;let r=this._freeIndices;return r===null&&(r=this._freeIndices=[]),r.push(e),!0}return!1}has(t){if(this._count===0)return!1;if(this._s0===t||this._s1===t||this._s2===t||this._s3===t)return!0;const s=this._overflow;if(s!=null){for(let e=0,i=s.length;e<i;e++)if(s[e]===t)return!0}return!1}forEach(t){const s=this._count;if(s===0)return;let e=0;const i=this._s0;if(i!=null&&(t(i),++e===s))return;const r=this._s1;if(r!=null&&(t(r),++e===s))return;const n=this._s2;if(n!=null&&(t(n),++e===s))return;const o=this._s3;if(o!=null&&(t(o),++e===s))return;const u=this._overflow;if(u!=null)for(let l=0,h=u.length;l<h;l++){const f=u[l];if(f!=null&&(t(f),++e===s))return}}forEachIndexed(t){const s=this._count;if(s===0)return 0;let e=0;const i=this._s0;if(i!=null&&(t(i),++e===s))return e;const r=this._s1;if(r!=null&&(t(r),++e===s))return e;const n=this._s2;if(n!=null&&(t(n),++e===s))return e;const o=this._s3;if(o!=null&&(t(o),++e===s))return e;const u=this._overflow;if(u!=null)for(let l=0,h=u.length;l<h;l++){const f=u[l];if(f!=null&&(t(f),++e===s))return e}return e}compact(){const t=this._overflow;if(t===null)return;let s=t.length;if(s===0)return;let e=0;for(;e<s;)if(t[e]===null){for(;s>e&&t[s-1]===null;)t.pop(),s--;s>e&&(t[e]=t.pop(),s--,e++)}else e++;this._freeIndices=null,s===0&&(this._overflow=null)}clear(){this._s0=null,this._s1=null,this._s2=null,this._s3=null,this._count=0,this._overflow!==null&&(this._overflow.length=0,this._overflow=null),this._freeIndices=null}dispose(){this.clear()}},st=Symbol("AtomEffect.DebugName"),dt=Symbol("AtomEffect.Id"),et=Symbol("AtomEffect.Type"),z=Symbol("AtomEffect.NoDefaultValue"),pt=class{constructor(){this.enabled=!1,this.warnInfiniteLoop=H.WARN_INFINITE_LOOP}warn(t,s){}attachDebugInfo(t,s,e){}getDebugName(t){if(t!=null)return t[st]}getDebugType(t){if(t!=null)return t[et]}},U=new pt,Ct=1,It=()=>Ct++|0;function N(t,s,e){return t instanceof m?t:t instanceof Error?new s(`${t.name||t.constructor.name||"Error"} (${e}): ${t.message}`,t):new s(`Unexpected error (${e}): ${String(t)}`)}var X=class{constructor(){this.flags=0,this.version=0,this._lastSeenEpoch=y.UNINITIALIZED,this._notifying=0,this._hotIndex=-1,this._slots=null,this._deps=null,this.id=It()&F}get isDisposed(){return(this.flags&B.DISPOSED)!==0}get isComputed(){return(this.flags&B.IS_COMPUTED)!==0}get hasError(){return!1}subscribe(t){const s=typeof t=="function";if(!s&&(!t||typeof t.execute!="function"))throw N(new TypeError("Invalid subscriber"),m,_.ATOM_SUBSCRIBER_MUST_BE_FUNCTION);let e=this._slots;e||(e=new tt,this._slots=e);let i=!1;if(e._s0!=null&&(s?e._s0.fn===t:e._s0.sub===t))i=!0;else if(e._s1!=null&&(s?e._s1.fn===t:e._s1.sub===t))i=!0;else if(e._s2!=null&&(s?e._s2.fn===t:e._s2.sub===t))i=!0;else if(e._s3!=null&&(s?e._s3.fn===t:e._s3.sub===t))i=!0;else{const n=e._overflow;if(n!=null)for(let o=0,u=n.length;o<u;o++){const l=n[o];if(l!=null&&(s?l.fn===t:l.sub===t)){i=!0;break}}}if(i)return()=>{};const r=new Et(s?t:void 0,s?void 0:t);return e.add(r),()=>this._unsubscribe(r)}_unsubscribe(t){const s=this._slots;s&&(s.remove(t),this._notifying===0&&s.compact())}subscriberCount(){const t=this._slots;return t===null?0:t.size}_notifySubscribers(t,s){const e=this._slots;if(!(e===null||e.size===0)){this._notifying++;try{let i=e._s0;if(i!=null)try{i.notify(t,s)}catch(n){this._logNotifyError(n)}if(i=e._s1,i!=null)try{i.notify(t,s)}catch(n){this._logNotifyError(n)}if(i=e._s2,i!=null)try{i.notify(t,s)}catch(n){this._logNotifyError(n)}if(i=e._s3,i!=null)try{i.notify(t,s)}catch(n){this._logNotifyError(n)}const r=e._overflow;if(r!=null)for(let n=0,o=r.length;n<o;n++){const u=r[n];if(u!=null)try{u.notify(t,s)}catch(l){this._logNotifyError(l)}}}finally{--this._notifying===0&&e.compact()}}}_logNotifyError(t){console.error(N(t,m,_.ATOM_INDIVIDUAL_SUBSCRIBER_FAILED))}_isDirty(){const t=this._deps;if(t===null||t.size===0)return!1;const s=this._hotIndex;if(s!==-1){const e=t.getAt(s);if(e!=null&&e.node.version!==e.version)return!0}return!t.hasComputeds&&!t.isDirtyFast()?!1:this._deepDirtyCheck()}},G=0;function Q(){const t=G+1&F;return G=t===0?1:t,G}function V(t){const s=t+1&F;return s===0?1:s}var k=0,L=!1,it=0;function nt(){return it}function rt(){return L?!1:(L=!0,it=Q(),k=0,!0)}function ot(){L=!1}function Dt(){if(!L)return 0;const t=++k;if(t<=C.MAX_EXECUTIONS_PER_FLUSH)return t;throw new Error(`[atom-effect] Infinite loop detected: flush execution count exceeded ${C.MAX_EXECUTIONS_PER_FLUSH}`)}var vt=class{constructor(){this._queueBuffer=[[],[]],this._bufferIndex=0,this._size=0,this._epoch=0,this._isProcessing=!1,this._isFlushingSync=!1,this._batchDepth=0,this._batchQueue=[],this._batchQueueSize=0,this._maxFlushIterations=C.MAX_FLUSH_ITERATIONS,this.onOverflow=null,this._boundRunLoop=this._runLoop.bind(this)}get queueSize(){return this._size}get isBatching(){return this._batchDepth>0}schedule(t){const s=this._epoch;if(t._nextEpoch===s)return;if(t._nextEpoch=s,this._batchDepth>0||this._isFlushingSync){this._batchQueue[this._batchQueueSize++]=t;return}const e=this._bufferIndex,i=this._queueBuffer[e];i[this._size++]=t,this._isProcessing||this._flush()}_flush(){this._isProcessing||this._size===0||(this._isProcessing=!0,queueMicrotask(this._boundRunLoop))}_runLoop(){try{if(this._size===0)return;const t=rt();this._drainQueue(),t&&ot()}finally{this._isProcessing=!1,this._size>0&&this._batchDepth===0&&this._flush()}}_flushSync(){this._isFlushingSync=!0;const t=rt();try{this._mergeBatchQueue(),this._drainQueue()}finally{this._isFlushingSync=!1,t&&ot()}}_mergeBatchQueue(){const t=this._batchQueueSize;if(t===0)return;const s=++this._epoch,e=this._batchQueue,i=this._bufferIndex,r=this._queueBuffer[i];let n=this._size;for(let o=0;o<t;o++){const u=e[o];u._nextEpoch!==s&&(u._nextEpoch=s,r[n++]=u)}this._size=n,this._batchQueueSize=0,e.length=0}_drainQueue(){let t=0;for(;this._size>0;){if(++t>this._maxFlushIterations){this._handleFlushOverflow();return}this._processQueue(),this._mergeBatchQueue()}}_processQueue(){const t=this._bufferIndex,s=this._queueBuffer[t],e=this._size;this._bufferIndex=t^1,this._size=0,this._epoch=this._epoch+1|0;for(let i=0;i<e;i++){const r=s[i];try{typeof r=="function"?r():r.execute()}catch(n){console.error(new w("Error occurred during scheduler execution",n))}}s.length=0}_handleFlushOverflow(){const t=this._size+this._batchQueueSize,s=this._maxFlushIterations;console.error(new w(_.SCHEDULER_FLUSH_OVERFLOW(s,t))),this._size=0;const e=this._bufferIndex;this._queueBuffer[e].length=0,this._batchQueueSize=0;const i=this.onOverflow;if(i)try{i(t)}catch{}}startBatch(){this._batchDepth++}endBatch(){this._batchDepth!==0&&--this._batchDepth===0&&this._flushSync()}setMaxFlushIterations(t){if(t<C.MIN_FLUSH_ITERATIONS)throw new w(`Max flush iterations must be at least ${C.MIN_FLUSH_ITERATIONS}`);this._maxFlushIterations=t}},b=new vt,Y=Symbol.for("atom-effect/atom"),ut=Symbol.for("atom-effect/computed"),lt=Symbol.for("atom-effect/effect"),St=Symbol.for("atom-effect/writable"),mt=class{constructor(){this.current=null}run(t,s){if(this.current===t)return s();const e=this.current;this.current=t;try{return s()}finally{this.current=e}}},a=new mt;function gt(t){const s=a,e=s.current;if(e===null)return t();s.current=null;try{return t()}finally{s.current=e}}var Tt=class extends X{constructor(t,s){super(),this[Y]=!0,this[St]=!0,this._value=t,s&&(this.flags|=E.SYNC),U.attachDebugInfo(this,"atom",this.id)}get isNotificationScheduled(){return(this.flags&E.NOTIFICATION_SCHEDULED)!==0}get isSync(){return(this.flags&E.SYNC)!==0}get value(){const t=a.current;return t?.addDependency(this),this._value}set value(t){const s=this._value;if(Object.is(s,t))return;this._value=t,this.version=V(this.version);const e=this.flags;if((e&E.NOTIFICATION_SCHEDULED)!==0)return;const i=this._slots;i==null||i.size===0||(this._pendingOldValue=s,this.flags=e|E.NOTIFICATION_SCHEDULED,(e&E.SYNC)!==0&&!b.isBatching?this._flushNotifications():b.schedule(this))}execute(){this._flushNotifications()}_flushNotifications(){const t=this.flags;if((t&(E.NOTIFICATION_SCHEDULED|E.DISPOSED))!==E.NOTIFICATION_SCHEDULED)return;const s=this._pendingOldValue;this._pendingOldValue=void 0,this.flags=t&~E.NOTIFICATION_SCHEDULED,this._notifySubscribers(this._value,s)}peek(){return this._value}dispose(){const t=this.flags;(t&E.DISPOSED)===0&&(this._slots?.clear(),this.flags=t|E.DISPOSED,this._value=void 0,this._pendingOldValue=void 0)}_deepDirtyCheck(){return!1}[Symbol.dispose](){this.dispose()}};function yt(t,s={}){return new Tt(t,s.sync??!1)}var ht=class extends tt{constructor(...t){super(...t),this._map=null,this._SCAN_THRESHOLD=32,this.hasComputeds=!1,this._depsHash=0}prepareTracking(){this.hasComputeds=!1}_onItemRemoved(t){const s=t.unsub;s&&s()}claimExisting(t,s){const e=this._count;if(s>=e)return!1;const i=e-s;if(this._map!==null||i>this._SCAN_THRESHOLD)return this._claimViaMap(t,s);if(s<4)switch(s){case 0:{const n=this._s0;if(n&&n.node===t&&n.unsub)return n.version=t.version,!0}case 1:if(e>1){const n=this._s1;if(n&&n.node===t&&n.unsub)return n.version=t.version,s!==1&&(this._s1=this._s0,this._s0=n),!0}case 2:if(e>2){const n=this._s2;if(n&&n.node===t&&n.unsub){if(n.version=t.version,s!==2){const o=s===0?this._s0:this._s1;s===0?this._s0=n:this._s1=n,this._s2=o}return!0}}case 3:if(e>3){const n=this._s3;if(n&&n.node===t&&n.unsub){if(n.version=t.version,s!==3){let o;s===0?(o=this._s0,this._s0=n):s===1?(o=this._s1,this._s1=n):(o=this._s2,this._s2=n),this._s3=o}return!0}}}const r=this._overflow;if(r){const n=t.version,o=s>4?s:4,u=r.length;for(let l=o-4;l<u;l++){const h=r[l];if(h&&h.node===t&&h.unsub)return h.version=n,this._swapGeneral(l+4,s,h),!0}}return!1}_claimViaMap(t,s){let e=this._map;if(e===null){e=this._map=new Map;const n=this._count;if(s<4){const u=this._s0;s<=0&&u?.unsub&&e.set(u.node,0);const l=this._s1;s<=1&&l?.unsub&&e.set(l.node,1);const h=this._s2;s<=2&&h?.unsub&&e.set(h.node,2);const f=this._s3;s<=3&&f?.unsub&&e.set(f.node,3)}const o=this._overflow;if(o&&n>4){const u=s>4?s:4,l=o.length;for(let h=u-4;h<l;h++){const f=o[h];f?.unsub&&e.set(f.node,h+4)}}}const i=e.get(t);if(i===void 0||i<s)return!1;const r=this.getAt(i);if(r==null||!r.unsub)return!1;if(r.version=t.version,i!==s){let n;s===0?n=this._s0:s===1?n=this._s1:s===2?n=this._s2:s===3?n=this._s3:n=this._overflow[s-4]??null,this.setAt(s,r),this.setAt(i,n),n?.unsub&&e.set(n.node,i),e.set(t,s)}return!0}_swapGeneral(t,s,e){if(t===s)return;let i;if(s===0?i=this._s0:s===1?i=this._s1:s===2?i=this._s2:s===3?i=this._s3:i=this._overflow[s-4]??null,this.setAt(s,e),t===0)this._s0=i;else if(t===1)this._s1=i;else if(t===2)this._s2=i;else if(t===3)this._s3=i;else{const r=this._overflow;r[t-4]=i}}insertNew(t,s){const e=this._count;if(t<e){let i;t===0?i=this._s0:t===1?i=this._s1:t===2?i=this._s2:t===3?i=this._s3:i=this._overflow[t-4]??null,i!=null&&(this._addToOverflow(i),this._map!==null&&i.unsub&&this._map.set(i.node,this._count-1))}if(t===0)this._s0=s;else if(t===1)this._s1=s;else if(t===2)this._s2=s;else if(t===3)this._s3=s;else{let i=this._overflow;i||(i=[],this._overflow=i),i[t-4]=s}t>=e&&(this._count=t+1)}truncateFrom(t){t>=this._count||(super.truncateFrom(t),this._map!==null&&(this._map.clear(),this._map=null))}seal(){this._depsHash=this._calculateHash(!1)}isDirtyFast(){return this._calculateHash(!0)!==this._depsHash}_calculateHash(t){const s=this._count;if(s===0)return 0;const e=at.VERSION_BITS;let i=0;const r=this._s0;if(r!=null){const n=r.node,o=t?n.version:r.version;i=i+(o<<e)+n.id|0;const u=this._s1;if(s>1&&u!=null){const l=u.node,h=t?l.version:u.version;i=i+(h<<e)+l.id|0;const f=this._s2;if(s>2&&f!=null){const _t=f.node,Ht=t?_t.version:f.version;i=i+(Ht<<e)+_t.id|0;const K=this._s3;if(s>3&&K!=null){const ft=K.node,xt=t?ft.version:K.version;i=i+(xt<<e)+ft.id|0}}}}if(s>4){const n=this._overflow;for(let o=0,u=n.length;o<u;o++){const l=n[o],h=l.node,f=t?h.version:l.version;i=i+(f<<e)+h.id|0}}return i}disposeAll(){this._count>0&&this.truncateFrom(0),this.hasComputeds=!1}remove(t){throw new Error("remove() is strictly prohibited in DepSlotBuffer to preserve sequential cache paths.")}compact(){}};function Nt(t){return typeof t=="object"&&t!==null&&Y in t}function At(t){return typeof t=="object"&&t!==null&&ut in t}function bt(t){return typeof t=="object"&&t!==null&&lt in t}function ct(t){return typeof t=="object"&&t!==null&&typeof t.then=="function"}var{IDLE:v,DIRTY:d,PENDING:A,RESOLVED:I,REJECTED:T,HAS_ERROR:P,RECOMPUTING:O,DISPOSED:$,IS_COMPUTED:M,FORCE_COMPUTE:j}=B,Ot=class extends X{constructor(t,s={}){if(typeof t!="function")throw new g(_.COMPUTED_MUST_BE_FUNCTION);if(super(),this[Y]=!0,this[ut]=!0,this._error=null,this._promiseId=0,this._deps=new ht,this._asyncRetryCount=0,this._lastDriftEpoch=y.UNINITIALIZED,this._trackEpoch=y.UNINITIALIZED,this._trackCount=0,this._value=void 0,this.flags=M|d|v,this._equal=s.equal??Object.is,this._fn=t,this._defaultValue="defaultValue"in s?s.defaultValue:z,this._onError=s.onError??null,this._maxAsyncRetries=(s.maxAsyncRetries??Z.MAX_ASYNC_RETRIES)&F,U.attachDebugInfo(this,"computed",this.id),s.lazy===!1)try{this._recompute()}catch{}}get isDirty(){return(this.flags&d)!==0}get isRejected(){return(this.flags&T)!==0}get isRecomputing(){return(this.flags&O)!==0}get _hasErrorInternal(){return(this.flags&P)!==0}_track(){a.current?.addDependency(this)}get value(){const t=a.current;t?.addDependency(this);let s=this.flags;if((s&(I|d|v))===I)return this._value;if((s&$)!==0)throw new g(_.COMPUTED_DISPOSED);if((s&O)!==0){const r=this._defaultValue;if(r!==z)return r;throw new g(_.COMPUTED_CIRCULAR_DEPENDENCY)}if((s&(d|v))!==0){const r=this._deps;if((s&v)===0&&(s&j)===0&&r.size>0&&!this._isDirty()?s=this.flags&=~d:(this._recompute(),s=this.flags),(s&I)!==0)return this._value}const e=this._defaultValue,i=e!==z;if((s&A)!==0){if(i)return e;throw new g(_.COMPUTED_ASYNC_PENDING_NO_DEFAULT)}if((s&T)!==0){if(i)return e;throw this._error}return this._value}peek(){return this._value}get state(){const t=a.current;t?.addDependency(this);const s=this.flags;return(s&I)!==0?p.RESOLVED:(s&A)!==0?p.PENDING:(s&T)!==0?p.REJECTED:p.IDLE}get hasError(){const t=a.current;if(t?.addDependency(this),(this.flags&(T|P))!==0)return!0;const s=this._deps;if(!s.hasComputeds)return!1;const e=s.size;for(let i=0;i<e;i++)if(s.getAt(i)?.node.hasError)return!0;return!1}get isValid(){return!this.hasError}get errors(){const t=a.current;t?.addDependency(this);const s=this._error,e=this._deps;if(!e.hasComputeds)return s==null?J:Object.freeze([s]);const i=[];s!=null&&i.push(s);const r=e.size;for(let n=0;n<r;n++){const o=e.getAt(n);if(o==null)continue;const u=o.node;(u.flags&M)!==0&&u.hasError&&this._collectErrorsFromDep(u,i)}return i.length===0?J:Object.freeze(i)}_collectErrorsFromDep(t,s){const e=t.errors,i=e.length;for(let r=0;r<i;r++){const n=e[r];n!=null&&!s.includes(n)&&s.push(n)}}get lastError(){const t=a.current;return t?.addDependency(this),this._error}get isPending(){const t=a.current;return t?.addDependency(this),(this.flags&A)!==0}get isResolved(){const t=a.current;return t?.addDependency(this),(this.flags&I)!==0}invalidate(){this.flags|=j,this._markDirty()}dispose(){(this.flags&$)===0&&(this._deps.disposeAll(),this._slots!=null&&this._slots.clear(),this.flags=$|d|v,this._error=null,this._value=void 0,this._hotIndex=-1)}[Symbol.dispose](){this.dispose()}addDependency(t){const s=this._trackEpoch;if(t._lastSeenEpoch===s)return;t._lastSeenEpoch=s;const e=this._trackCount++,i=this._deps,r=i.getAt(e);if(r!=null&&r.node===t)r.version=t.version;else if(!i.claimExisting(t,e)){const n=new x(t,t.version,t.subscribe(this));i.insertNew(e,n)}(t.flags&M)!==0&&(i.hasComputeds=!0)}_recompute(){if(this.isRecomputing)return;this.flags=(this.flags|O)&~j,this._trackEpoch=Q(),this._trackCount=0,this._deps.prepareTracking(),this._hotIndex=-1;let t=!1;try{const s=a.run(this,this._fn);this._deps.truncateFrom(this._trackCount),this._deps.seal(),t=!0,ct(s)?this._handleAsyncComputation(s):this._finalizeResolution(s)}catch(s){if(!t)try{this._deps.truncateFrom(this._trackCount)}catch{}this._handleError(s,_.COMPUTED_COMPUTATION_FAILED,!0)}finally{this._trackEpoch=y.UNINITIALIZED,this._trackCount=0,this.flags&=~O}}_handleAsyncComputation(t){this.flags=(this.flags|A)&~(v|d|I|T),this._notifySubscribers(void 0,void 0),this._asyncRetryCount=0,this._promiseId=(this._promiseId+1)%Z.MAX_PROMISE_ID;const s=this._promiseId;t.then(e=>{if(s===this._promiseId){if(this._isDirty()){const i=nt();return this._lastDriftEpoch!==i&&(this._lastDriftEpoch=i,this._asyncRetryCount=0),this._asyncRetryCount++<this._maxAsyncRetries?this._markDirty():this._handleError(new g(`Async drift threshold exceeded after ${this._maxAsyncRetries} retries.`),_.COMPUTED_ASYNC_COMPUTATION_FAILED)}this._finalizeResolution(e),this._notifySubscribers(e,void 0)}},e=>s===this._promiseId&&this._handleError(e,_.COMPUTED_ASYNC_COMPUTATION_FAILED))}_handleError(t,s,e=!1){const i=N(t,g,s);if(!e&&!this.isRejected&&(this.version=V(this.version)),this._error=i,this.flags=this.flags&~(v|d|A|I)|T|P,this._onError)try{this._onError(i)}catch(r){console.error(_.CALLBACK_ERROR_IN_ERROR_HANDLER,r)}if(e)throw i;this._notifySubscribers(void 0,void 0)}_finalizeResolution(t){const s=this.flags;((s&I)===0||!this._equal(this._value,t))&&(this.version=V(this.version)),this._value=t,this._error=null,this.flags=(s|I)&~(v|d|A|T|P)}execute(){this._markDirty()}_markDirty(){const t=this.flags;(t&(O|d))===0&&(this.flags=t|d,this._notifySubscribers(void 0,void 0))}_isDirty(){const t=this._deps;return t.hasComputeds?this._deepDirtyCheck():t.isDirtyFast()}_deepDirtyCheck(){const t=this._deps,s=a.current;a.current=null;try{const e=t.size;for(let i=0;i<e;i++){const r=t.getAt(i);if(r==null)continue;const n=r.node;if((n.flags&M)!==0)try{n.value}catch{}if(n.version!==r.version)return this._hotIndex=i,!0}return this._hotIndex=-1,!1}finally{a.current=s}}};function Rt(t,s={}){return new Ot(t,s)}var Ft=class extends X{constructor(t,s={}){super(),this[lt]=!0,this._cleanup=null,this._deps=new ht,this._currentEpoch=y.UNINITIALIZED,this._lastFlushEpoch=y.UNINITIALIZED,this._fn=t,this._onError=s.onError??null,this._sync=s.sync??!1,this._maxExecutions=s.maxExecutionsPerSecond??C.MAX_EXECUTIONS_PER_SECOND,this._maxExecutionsPerFlush=s.maxExecutionsPerFlush??C.MAX_EXECUTIONS_PER_EFFECT,this._executionsInEpoch=0,this._executionCount=0,this._windowStart=0,this._windowCount=0,this._execId=0,this._trackCount=0,this._sync?this._notifyCallback=()=>this.execute():this._notifyCallback=()=>b.schedule(this),U.attachDebugInfo(this,"effect",this.id)}run(){if(this.isDisposed)throw new D(_.EFFECT_DISPOSED);this.execute(!0)}dispose(){this.isDisposed||(this.flags|=S.DISPOSED,this._execCleanup(),this._deps?.disposeAll())}[Symbol.dispose](){this.dispose()}addDependency(t){if((this.flags&S.EXECUTING)===0)return;const s=this._currentEpoch;if(t._lastSeenEpoch===s)return;t._lastSeenEpoch=s;const e=this._trackCount++,i=this._deps;let r;switch(e){case 0:r=i._s0;break;case 1:r=i._s1;break;case 2:r=i._s2;break;case 3:r=i._s3;break;default:r=i.getAt(e)}r!=null&&r.node===t?r.version=t.version:i.claimExisting(t,e)||this._insertNewDependency(t,e),t.isComputed&&(i.hasComputeds=!0)}_insertNewDependency(t,s){let e;try{const i=t.subscribe(this._notifyCallback);e=new x(t,t.version,i)}catch(i){const r=N(i,D,_.EFFECT_EXECUTION_FAILED);if(console.error(r),this._onError)try{this._onError(r)}catch{}e=new x(t,t.version,void 0)}this._deps.insertNew(s,e)}execute(t=!1){const s=this.flags;if((s&(S.DISPOSED|S.EXECUTING))!==0)return;const e=this._deps;if(!t&&e.size>0&&!this._isDirty())return;this._checkInfiniteLoops(),this.flags=s|S.EXECUTING,this._execCleanup(),this._currentEpoch=Q(),this._trackCount=0,e.prepareTracking(),this._hotIndex=-1;let i=!1;try{const r=a.run(this,this._fn);e.truncateFrom(this._trackCount),e.seal(),i=!0,ct(r)?this._handleAsyncResult(r):this._cleanup=typeof r=="function"?r:null}catch(r){if(!i)try{e.truncateFrom(this._trackCount)}catch{}this._handleExecutionError(r),this._cleanup=null}finally{this.flags&=~S.EXECUTING}}_isDirty(){const t=this._deps;return t.hasComputeds?this._deepDirtyCheck():t.isDirtyFast()}_handleAsyncResult(t){const s=++this._execId;t.then(e=>{if(s!==this._execId||this.isDisposed){if(typeof e=="function")try{e()}catch(i){this._handleExecutionError(i,_.EFFECT_CLEANUP_FAILED)}return}typeof e=="function"&&(this._cleanup=e)},e=>s===this._execId&&this._handleExecutionError(e))}_deepDirtyCheck(){const t=a.current;a.current=null;const s=this._deps;try{const e=s.size;for(let i=0;i<e;i++){const r=s.getAt(i);if(r==null)continue;const n=r.node;if(n.isComputed&&this._tryPullComputed(n),n.version!==r.version)return this._hotIndex=i,!0}return!1}finally{a.current=t}}_tryPullComputed(t){try{t.value}catch{}}_execCleanup(){const t=this._cleanup;if(t!=null){this._cleanup=null;try{t()}catch(s){this._handleExecutionError(s,_.EFFECT_CLEANUP_FAILED)}}}_checkInfiniteLoops(){const t=nt();this._lastFlushEpoch!==t&&(this._lastFlushEpoch=t,this._executionsInEpoch=0),++this._executionsInEpoch>this._maxExecutionsPerFlush&&this._throwInfiniteLoopError("per-effect"),Dt()>C.MAX_EXECUTIONS_PER_FLUSH&&this._throwInfiniteLoopError("global"),this._executionCount++}_checkFrequencyLimit(){if(!Number.isFinite(this._maxExecutions))return;const t=Date.now();if(t-this._windowStart>=H.EFFECT_FREQUENCY_WINDOW){this._windowStart=t,this._windowCount=1;return}if(++this._windowCount>this._maxExecutions){const s=new D(_.EFFECT_FREQUENCY_LIMIT_EXCEEDED);throw this.dispose(),this._handleExecutionError(s),s}}get executionCount(){return this._executionCount}get isExecuting(){return(this.flags&S.EXECUTING)!==0}_throwInfiniteLoopError(t){const s=new D(`Infinite loop detected (${t}): effect executed ${this._executionsInEpoch} times in current flush. Total executions in flush: ${k}`);throw this.dispose(),console.error(s),s}_handleExecutionError(t,s=_.EFFECT_EXECUTION_FAILED){const e=N(t,D,s);if(console.error(e),this._onError)try{this._onError(e)}catch(i){console.error(N(i,D,_.CALLBACK_ERROR_IN_ERROR_HANDLER))}}};function wt(t,s={}){if(typeof t!="function")throw new D(_.EFFECT_MUST_BE_FUNCTION);const e=new Ft(t,s);return e.execute(),e}var Ut=Symbol.for("atom-effect/atom"),Lt=Symbol.for("atom-effect/writable");function q(t,s,e,i){if(e===s.length)return i;const r=s[e],n=t!=null&&typeof t=="object"?t:{},o=n[r],u=q(o,s,e+1,i);if(Object.is(o,u))return t;if(Array.isArray(n)){const l=n.slice(),h=Number.parseInt(r,10);return Number.isNaN(h)?l[r]=u:l[h]=u,l}return{...n,[r]:u}}function R(t,s){let e=t;const i=s.length;for(let r=0;r<i;r++){if(e==null)return;e=e[s[r]]}return e}function W(t,s){const e=s.includes(".")?s.split("."):[s],i=new Set,r=()=>{i.forEach(n=>n()),i.clear()};return{get value(){return R(t.value,e)},set value(n){const o=t.peek(),u=q(o,e,0,n);u!==o&&(t.value=u)},peek:()=>R(t.peek(),e),subscribe(n){const o=t.subscribe((u,l)=>{const h=R(u,e),f=R(l,e);Object.is(h,f)||n(h,f)});return i.add(o),()=>{o(),i.delete(o)}},subscriberCount:()=>i.size,dispose:r,[Symbol.dispose]:r,[Ut]:!0,[Lt]:!0}}var Pt=(t,s)=>W(t,s),Mt=t=>s=>W(t,s);function Bt(t){if(typeof t!="function")throw new TypeError(_.BATCH_CALLBACK_MUST_BE_FUNCTION);const s=b;s.startBatch();try{return t()}finally{s.endBatch()}}c.AsyncState=p,c.AtomError=m,c.ComputedError=g,c.DEBUG_CONFIG=H,c.DEBUG_RUNTIME=U,c.EffectError=D,c.SCHEDULER_CONFIG=C,c.SchedulerError=w,c.atom=yt,c.atomLens=W,c.batch=Bt,c.composeLens=Pt,c.computed=Rt,c.effect=wt,c.getPathValue=R,c.isAtom=Nt,c.isComputed=At,c.isEffect=bt,c.lensFor=Mt,c.scheduler=b,c.setDeepValue=q,c.untracked=gt});
1
+ (function(h,p){typeof exports=="object"&&typeof module<"u"?p(exports):typeof define=="function"&&define.amd?define(["exports"],p):(h=typeof globalThis<"u"?globalThis:h||self,p(h.AtomEffect={}))})(this,function(h){Object.defineProperty(h,Symbol.toStringTag,{value:"Module"});var p={IDLE:"idle",PENDING:"pending",RESOLVED:"resolved",REJECTED:"rejected"},S={DISPOSED:1,EXECUTING:8},M={DISPOSED:1,IS_COMPUTED:2,DIRTY:8,IDLE:16,PENDING:32,RESOLVED:64,REJECTED:128,RECOMPUTING:256,HAS_ERROR:512,FORCE_COMPUTE:1024},E={DISPOSED:1,SYNC:8,NOTIFICATION_SCHEDULED:16},C={MAX_EXECUTIONS_PER_SECOND:1e3,MAX_EXECUTIONS_PER_EFFECT:100,MAX_EXECUTIONS_PER_FLUSH:1e4,MAX_FLUSH_ITERATIONS:1e3,MIN_FLUSH_ITERATIONS:10,BATCH_QUEUE_SHRINK_THRESHOLD:1e3},B={WARN_INFINITE_LOOP:!0,EFFECT_FREQUENCY_WINDOW:1e3},lt={MAX_PROMISE_ID:Number.MAX_SAFE_INTEGER-1},y={UNINITIALIZED:-1,MIN:1},H=1073741823,Lt=(typeof process<"u"&&process.env,!1),K=Object.freeze([]),g=class extends Error{constructor(t,s=null,e=!0){super(t),this.cause=s,this.recoverable=e,this.name="AtomError"}},T=class extends g{constructor(t,s=null){super(t,s,!0),this.name="ComputedError"}},D=class extends g{constructor(t,s=null){super(t,s,!1),this.name="EffectError"}},R=class extends g{constructor(t,s=null){super(t,s,!1),this.name="SchedulerError"}},f={COMPUTED_MUST_BE_FUNCTION:"Computed target must be a function",COMPUTED_ASYNC_PENDING_NO_DEFAULT:"Async computation pending with no default value",COMPUTED_COMPUTATION_FAILED:"Computation execution failed",COMPUTED_ASYNC_COMPUTATION_FAILED:"Async computation execution failed",COMPUTED_CIRCULAR_DEPENDENCY:"Circular dependency detected",COMPUTED_DISPOSED:"Attempted to access disposed computed",ATOM_SUBSCRIBER_MUST_BE_FUNCTION:"Subscriber must be a function or Subscriber object",ATOM_INDIVIDUAL_SUBSCRIBER_FAILED:"Subscriber execution failed",EFFECT_MUST_BE_FUNCTION:"Effect target must be a function",EFFECT_EXECUTION_FAILED:"Effect execution failed",EFFECT_CLEANUP_FAILED:"Effect cleanup failed",EFFECT_DISPOSED:"Attempted to run disposed effect",SCHEDULER_FLUSH_OVERFLOW:(t,s)=>`Maximum flush iterations (${t}) exceeded. ${s} jobs dropped. Possible infinite loop.`,CALLBACK_ERROR_IN_ERROR_HANDLER:"Exception encountered in onError handler",EFFECT_FREQUENCY_LIMIT_EXCEEDED:"Effect executed too frequently within 1 second. Suspected infinite loop.",SCHEDULER_CALLBACK_MUST_BE_FUNCTION:"Scheduler callback must be a function",SCHEDULER_END_BATCH_WITHOUT_START:"endBatch() called without matching startBatch(). Ignoring.",BATCH_CALLBACK_MUST_BE_FUNCTION:"Batch callback must be a function"};function N(t,s,e){return t instanceof g?t:t instanceof Error?new s(`${t.name||t.constructor.name||"Error"} (${e}): ${t.message}`,t):new s(`Unexpected error (${e}): ${String(t)}`)}var Z=Symbol("AtomEffect.DebugName"),ht=Symbol("AtomEffect.Id"),J=Symbol("AtomEffect.Type"),z=Symbol("AtomEffect.NoDefaultValue"),ct=class{constructor(){this.enabled=!1,this.warnInfiniteLoop=B.WARN_INFINITE_LOOP}warn(t,s){}attachDebugInfo(t,s,e){}getDebugName(t){if(t!=null)return t[Z]}getDebugType(t){if(t!=null)return t[J]}},w=new ct,ft=1,_t=()=>ft++|0,tt=class{constructor(){this._s0=null,this._s1=null,this._s2=null,this._s3=null,this._count=0,this._overflow=null,this._freeIndices=null}get size(){return this._count}getAt(t){if(t<4)switch(t){case 0:return this._s0;case 1:return this._s1;case 2:return this._s2;case 3:return this._s3}const s=this._overflow;if(s!==null){const e=s[t-4];return e===void 0?null:e}return null}setAt(t,s){switch(t){case 0:this._s0=s;break;case 1:this._s1=s;break;case 2:this._s2=s;break;case 3:this._s3=s;break;default:this._overflow??=[],this._overflow[t-4]=s}t>=this._count&&(this._count=t+1)}truncateFrom(t){const s=this._count;if(t>=s)return;if(t<=3){if(t<=0){const i=this._s0;i!=null&&(this._onItemRemoved(i),this._s0=null)}if(t<=1){const i=this._s1;i!=null&&(this._onItemRemoved(i),this._s1=null)}if(t<=2){const i=this._s2;i!=null&&(this._onItemRemoved(i),this._s2=null)}if(t<=3){const i=this._s3;i!=null&&(this._onItemRemoved(i),this._s3=null)}}const e=this._overflow;if(e!==null&&s>4){const i=t>4?t-4:0,r=e.length;for(let n=i;n<r;n++){const o=e[n];o!=null&&(this._onItemRemoved(o),e[n]=null)}t<=4?(e.length=0,this._overflow=null):e.length=t-4}this._freeIndices!==null&&(this._freeIndices=null),this._count=t}_onItemRemoved(t){}add(t){if(this._s0===null){this._s0=t,this._count++;return}if(this._s1===null){this._s1=t,this._count++;return}if(this._s2===null){this._s2=t,this._count++;return}if(this._s3===null){this._s3=t,this._count++;return}this._addToOverflow(t)}_addToOverflow(t){const s=this._overflow;if(s===null)this._overflow=[t];else{const e=this._freeIndices;e!==null&&e.length>0?s[e.pop()]=t:s.push(t)}this._count++}remove(t){if(this._s0===t)return this._s0=null,this._count--,!0;if(this._s1===t)return this._s1=null,this._count--,!0;if(this._s2===t)return this._s2=null,this._count--,!0;if(this._s3===t)return this._s3=null,this._count--,!0;const s=this._overflow;if(s==null)return!1;for(let e=0,i=s.length;e<i;e++)if(s[e]===t){s[e]=null,this._count--;let r=this._freeIndices;return r===null&&(r=this._freeIndices=[]),r.push(e),!0}return!1}has(t){if(this._count===0)return!1;if(this._s0===t||this._s1===t||this._s2===t||this._s3===t)return!0;const s=this._overflow;if(s!=null){for(let e=0,i=s.length;e<i;e++)if(s[e]===t)return!0}return!1}forEach(t){const s=this._count;if(s===0)return;let e=0;const i=this._s0;if(i!=null&&(t(i),++e===s))return;const r=this._s1;if(r!=null&&(t(r),++e===s))return;const n=this._s2;if(n!=null&&(t(n),++e===s))return;const o=this._s3;if(o!=null&&(t(o),++e===s))return;const u=this._overflow;if(u!=null)for(let l=0,c=u.length;l<c;l++){const a=u[l];if(a!=null&&(t(a),++e===s))return}}forEachIndexed(t){const s=this._count;if(s===0)return 0;let e=0;const i=this._s0;if(i!=null&&(t(i),++e===s))return e;const r=this._s1;if(r!=null&&(t(r),++e===s))return e;const n=this._s2;if(n!=null&&(t(n),++e===s))return e;const o=this._s3;if(o!=null&&(t(o),++e===s))return e;const u=this._overflow;if(u!=null)for(let l=0,c=u.length;l<c;l++){const a=u[l];if(a!=null&&(t(a),++e===s))return e}return e}compact(){const t=this._overflow;if(t===null)return;let s=t.length;if(s===0)return;let e=0;for(;e<s;)if(t[e]===null){for(;s>e&&t[s-1]===null;)t.pop(),s--;s>e&&(t[e]=t.pop(),s--,e++)}else e++;this._freeIndices=null,s===0&&(this._overflow=null)}clear(){this._s0=null,this._s1=null,this._s2=null,this._s3=null,this._count=0,this._overflow!==null&&(this._overflow.length=0,this._overflow=null),this._freeIndices=null}dispose(){this.clear()}},st=class extends tt{constructor(...t){super(...t),this._map=null,this._SCAN_THRESHOLD=32,this.hasComputeds=!1}prepareTracking(){this.hasComputeds=!1}_onItemRemoved(t){const s=t.unsub;s&&s()}claimExisting(t,s){const e=this._count;if(s>=e)return!1;const i=e-s;if(this._map!==null||i>this._SCAN_THRESHOLD)return this._claimViaMap(t,s);if(s<4)switch(s){case 0:{const n=this._s0;if(n&&n.node===t&&n.unsub)return n.version=t.version,!0}case 1:if(e>1){const n=this._s1;if(n&&n.node===t&&n.unsub)return n.version=t.version,s!==1&&(this._s1=this._s0,this._s0=n),!0}case 2:if(e>2){const n=this._s2;if(n&&n.node===t&&n.unsub){if(n.version=t.version,s!==2){const o=s===0?this._s0:this._s1;s===0?this._s0=n:this._s1=n,this._s2=o}return!0}}case 3:if(e>3){const n=this._s3;if(n&&n.node===t&&n.unsub){if(n.version=t.version,s!==3){let o;s===0?(o=this._s0,this._s0=n):s===1?(o=this._s1,this._s1=n):(o=this._s2,this._s2=n),this._s3=o}return!0}}}const r=this._overflow;if(r){const n=t.version,o=s>4?s:4,u=r.length;for(let l=o-4;l<u;l++){const c=r[l];if(c&&c.node===t&&c.unsub)return c.version=n,this._swapGeneral(l+4,s,c),!0}}return!1}_claimViaMap(t,s){let e=this._map;if(e===null){e=this._map=new Map;const n=this._count;if(s<4){const u=this._s0;s<=0&&u?.unsub&&e.set(u.node,0);const l=this._s1;s<=1&&l?.unsub&&e.set(l.node,1);const c=this._s2;s<=2&&c?.unsub&&e.set(c.node,2);const a=this._s3;s<=3&&a?.unsub&&e.set(a.node,3)}const o=this._overflow;if(o&&n>4){const u=s>4?s:4,l=o.length;for(let c=u-4;c<l;c++){const a=o[c];a?.unsub&&e.set(a.node,c+4)}}}const i=e.get(t);if(i===void 0||i<s)return!1;const r=this.getAt(i);if(r==null||!r.unsub)return!1;if(r.version=t.version,i!==s){let n;s===0?n=this._s0:s===1?n=this._s1:s===2?n=this._s2:s===3?n=this._s3:n=this._overflow[s-4]??null,this.setAt(s,r),this.setAt(i,n),n?.unsub&&e.set(n.node,i),e.set(t,s)}return!0}_swapGeneral(t,s,e){if(t===s)return;let i;if(s===0?i=this._s0:s===1?i=this._s1:s===2?i=this._s2:s===3?i=this._s3:i=this._overflow[s-4]??null,this.setAt(s,e),t===0)this._s0=i;else if(t===1)this._s1=i;else if(t===2)this._s2=i;else if(t===3)this._s3=i;else{const r=this._overflow;r[t-4]=i}}insertNew(t,s){const e=this._count;if(t<e){let i;t===0?i=this._s0:t===1?i=this._s1:t===2?i=this._s2:t===3?i=this._s3:i=this._overflow[t-4]??null,i!=null&&(this._addToOverflow(i),this._map!==null&&i.unsub&&this._map.set(i.node,this._count-1))}if(t===0)this._s0=s;else if(t===1)this._s1=s;else if(t===2)this._s2=s;else if(t===3)this._s3=s;else{let i=this._overflow;i||(i=[],this._overflow=i),i[t-4]=s}t>=e&&(this._count=t+1)}truncateFrom(t){t>=this._count||(super.truncateFrom(t),this._map!==null&&(this._map.clear(),this._map=null))}disposeAll(){this._count>0&&this.truncateFrom(0),this.hasComputeds=!1}remove(t){throw new Error("remove() is strictly prohibited in DepSlotBuffer to preserve sequential cache paths.")}compact(){}},x=class{constructor(t,s,e=void 0){this.node=t,this.version=s,this.unsub=e}},at=class{constructor(t,s){this.fn=t,this.sub=s}notify(t,s){const e=this.fn;if(e!==void 0){e(t,s);return}const i=this.sub;i!==void 0&&i.execute()}},Et=class{constructor(){this.current=null}run(t,s){if(this.current===t)return s();const e=this.current;this.current=t;try{return s()}finally{this.current=e}}},_=new Et;function dt(t){const s=_,e=s.current;if(e===null)return t();s.current=null;try{return t()}finally{s.current=e}}var G=class{constructor(){this.flags=0,this.version=0,this._lastSeenEpoch=y.UNINITIALIZED,this._notifying=0,this._hotIndex=-1,this._slots=null,this._deps=null,this.id=_t()&H}get isDisposed(){return(this.flags&M.DISPOSED)!==0}get isComputed(){return(this.flags&M.IS_COMPUTED)!==0}get hasError(){return!1}subscribe(t){const s=typeof t=="function";if(!s&&(!t||typeof t.execute!="function"))throw N(new TypeError("Invalid subscriber"),g,f.ATOM_SUBSCRIBER_MUST_BE_FUNCTION);let e=this._slots;e||(e=new tt,this._slots=e);let i=!1;if(e._s0!=null&&(s?e._s0.fn===t:e._s0.sub===t))i=!0;else if(e._s1!=null&&(s?e._s1.fn===t:e._s1.sub===t))i=!0;else if(e._s2!=null&&(s?e._s2.fn===t:e._s2.sub===t))i=!0;else if(e._s3!=null&&(s?e._s3.fn===t:e._s3.sub===t))i=!0;else{const n=e._overflow;if(n!=null)for(let o=0,u=n.length;o<u;o++){const l=n[o];if(l!=null&&(s?l.fn===t:l.sub===t)){i=!0;break}}}if(i)return()=>{};const r=new at(s?t:void 0,s?void 0:t);return e.add(r),()=>this._unsubscribe(r)}_unsubscribe(t){const s=this._slots;s&&(s.remove(t),this._notifying===0&&s.compact())}subscriberCount(){const t=this._slots;return t===null?0:t.size}_notifySubscribers(t,s){const e=this._slots;if(!(e===null||e.size===0)){this._notifying++;try{let i=e._s0;if(i!=null)try{i.notify(t,s)}catch(n){this._logNotifyError(n)}if(i=e._s1,i!=null)try{i.notify(t,s)}catch(n){this._logNotifyError(n)}if(i=e._s2,i!=null)try{i.notify(t,s)}catch(n){this._logNotifyError(n)}if(i=e._s3,i!=null)try{i.notify(t,s)}catch(n){this._logNotifyError(n)}const r=e._overflow;if(r!=null)for(let n=0,o=r.length;n<o;n++){const u=r[n];if(u!=null)try{u.notify(t,s)}catch(l){this._logNotifyError(l)}}}finally{--this._notifying===0&&e.compact()}}}_logNotifyError(t){console.error(N(t,g,f.ATOM_INDIVIDUAL_SUBSCRIBER_FAILED))}_isDirty(){const t=this._deps;if(t===null||t.size===0)return!1;const s=this._hotIndex;if(s!==-1){const e=t.getAt(s);if(e!=null&&e.node.version!==e.version)return!0}return this._deepDirtyCheck()}},X=Symbol.for("atom-effect/atom"),et=Symbol.for("atom-effect/computed"),it=Symbol.for("atom-effect/effect"),pt=Symbol.for("atom-effect/writable"),Q=0;function V(){const t=Q+1&H;return Q=t===0?1:t,Q}function k(t){const s=t+1&H;return s===0?1:s}var $=0,U=!1,nt=0;function Ct(){return nt}function rt(){return U?!1:(U=!0,nt=V(),$=0,!0)}function ot(){U=!1}function It(){if(!U)return 0;const t=++$;if(t<=C.MAX_EXECUTIONS_PER_FLUSH)return t;throw new Error(`[atom-effect] Infinite loop detected: flush execution count exceeded ${C.MAX_EXECUTIONS_PER_FLUSH}`)}var Dt=class{constructor(){this._queueBuffer=[[],[]],this._bufferIndex=0,this._size=0,this._epoch=0,this._isProcessing=!1,this._isFlushingSync=!1,this._batchDepth=0,this._batchQueue=[],this._batchQueueSize=0,this._maxFlushIterations=C.MAX_FLUSH_ITERATIONS,this.onOverflow=null,this._boundRunLoop=this._runLoop.bind(this)}get queueSize(){return this._size}get isBatching(){return this._batchDepth>0}schedule(t){const s=this._epoch;if(t._nextEpoch===s)return;if(t._nextEpoch=s,this._batchDepth>0||this._isFlushingSync){this._batchQueue[this._batchQueueSize++]=t;return}const e=this._bufferIndex,i=this._queueBuffer[e];i[this._size++]=t,this._isProcessing||this._flush()}_flush(){this._isProcessing||this._size===0||(this._isProcessing=!0,queueMicrotask(this._boundRunLoop))}_runLoop(){try{if(this._size===0)return;const t=rt();this._drainQueue(),t&&ot()}finally{this._isProcessing=!1,this._size>0&&this._batchDepth===0&&this._flush()}}_flushSync(){this._isFlushingSync=!0;const t=rt();try{this._mergeBatchQueue(),this._drainQueue()}finally{this._isFlushingSync=!1,t&&ot()}}_mergeBatchQueue(){const t=this._batchQueueSize;if(t===0)return;const s=++this._epoch,e=this._batchQueue,i=this._bufferIndex,r=this._queueBuffer[i];let n=this._size;for(let o=0;o<t;o++){const u=e[o];u._nextEpoch!==s&&(u._nextEpoch=s,r[n++]=u)}this._size=n,this._batchQueueSize=0,e.length=0}_drainQueue(){let t=0;for(;this._size>0;){if(++t>this._maxFlushIterations){this._handleFlushOverflow();return}this._processQueue(),this._mergeBatchQueue()}}_processQueue(){const t=this._bufferIndex,s=this._queueBuffer[t],e=this._size;this._bufferIndex=t^1,this._size=0,this._epoch=this._epoch+1|0;for(let i=0;i<e;i++){const r=s[i];try{typeof r=="function"?r():r.execute()}catch(n){console.error(new R("Error occurred during scheduler execution",n))}}s.length=0}_handleFlushOverflow(){const t=this._size+this._batchQueueSize,s=this._maxFlushIterations;console.error(new R(f.SCHEDULER_FLUSH_OVERFLOW(s,t))),this._size=0;const e=this._bufferIndex;this._queueBuffer[e].length=0,this._batchQueueSize=0;const i=this.onOverflow;if(i)try{i(t)}catch{}}startBatch(){this._batchDepth++}endBatch(){this._batchDepth!==0&&--this._batchDepth===0&&this._flushSync()}setMaxFlushIterations(t){if(t<C.MIN_FLUSH_ITERATIONS)throw new R(`Max flush iterations must be at least ${C.MIN_FLUSH_ITERATIONS}`);this._maxFlushIterations=t}},A=new Dt;function vt(t){if(typeof t!="function")throw new TypeError(f.BATCH_CALLBACK_MUST_BE_FUNCTION);const s=A;s.startBatch();try{return t()}finally{s.endBatch()}}var St=class extends G{constructor(t,s){super(),this[X]=!0,this[pt]=!0,this._value=t,s&&(this.flags|=E.SYNC),w.attachDebugInfo(this,"atom",this.id)}get isNotificationScheduled(){return(this.flags&E.NOTIFICATION_SCHEDULED)!==0}get isSync(){return(this.flags&E.SYNC)!==0}get value(){const t=_.current;return t?.addDependency(this),this._value}set value(t){const s=this._value;if(Object.is(s,t))return;this._value=t,this.version=k(this.version);const e=this.flags;if((e&E.NOTIFICATION_SCHEDULED)!==0)return;const i=this._slots;i==null||i.size===0||(this._pendingOldValue=s,this.flags=e|E.NOTIFICATION_SCHEDULED,(e&E.SYNC)!==0&&!A.isBatching?this._flushNotifications():A.schedule(this))}execute(){this._flushNotifications()}_flushNotifications(){const t=this.flags;if((t&(E.NOTIFICATION_SCHEDULED|E.DISPOSED))!==E.NOTIFICATION_SCHEDULED)return;const s=this._pendingOldValue;this._pendingOldValue=void 0,this.flags=t&~E.NOTIFICATION_SCHEDULED,this._notifySubscribers(this._value,s)}peek(){return this._value}dispose(){const t=this.flags;(t&E.DISPOSED)===0&&(this._slots?.clear(),this.flags=t|E.DISPOSED,this._value=void 0,this._pendingOldValue=void 0)}_deepDirtyCheck(){return!1}[Symbol.dispose](){this.dispose()}};function gt(t,s={}){return new St(t,s.sync??!1)}function mt(t){return typeof t=="object"&&t!==null&&X in t}function Tt(t){return typeof t=="object"&&t!==null&&et in t}function Nt(t){return typeof t=="object"&&t!==null&&it in t}function ut(t){return typeof t=="object"&&t!==null&&typeof t.then=="function"}var{IDLE:v,DIRTY:d,PENDING:b,RESOLVED:I,REJECTED:m,HAS_ERROR:L,RECOMPUTING:O,DISPOSED:Y,IS_COMPUTED:P,FORCE_COMPUTE:j}=M,bt=class extends G{constructor(t,s={}){if(typeof t!="function")throw new T(f.COMPUTED_MUST_BE_FUNCTION);if(super(),this[X]=!0,this[et]=!0,this._error=null,this._promiseId=0,this._deps=new st,this._trackEpoch=y.UNINITIALIZED,this._trackCount=0,this._value=void 0,this.flags=P|d|v,this._equal=s.equal??Object.is,this._fn=t,this._defaultValue="defaultValue"in s?s.defaultValue:z,this._onError=s.onError??null,w.attachDebugInfo(this,"computed",this.id),s.lazy===!1)try{this._recompute()}catch{}}get isDirty(){return(this.flags&d)!==0}get isRejected(){return(this.flags&m)!==0}get isRecomputing(){return(this.flags&O)!==0}get _hasErrorInternal(){return(this.flags&L)!==0}_track(){_.current?.addDependency(this)}get value(){const t=_.current;t?.addDependency(this);let s=this.flags;if((s&(I|d|v))===I)return this._value;if((s&Y)!==0)throw new T(f.COMPUTED_DISPOSED);if((s&O)!==0){const r=this._defaultValue;if(r!==z)return r;throw new T(f.COMPUTED_CIRCULAR_DEPENDENCY)}if((s&(d|v))!==0){const r=this._deps;if((s&v)===0&&(s&j)===0&&r.size>0&&!this._isDirty()?s=this.flags&=~d:(this._recompute(),s=this.flags),(s&I)!==0)return this._value}const e=this._defaultValue,i=e!==z;if((s&b)!==0){if(i)return e;throw new T(f.COMPUTED_ASYNC_PENDING_NO_DEFAULT)}if((s&m)!==0){if(i)return e;throw this._error}return this._value}peek(){return this._value}get state(){const t=_.current;t?.addDependency(this);const s=this.flags;return(s&I)!==0?p.RESOLVED:(s&b)!==0?p.PENDING:(s&m)!==0?p.REJECTED:p.IDLE}get hasError(){const t=_.current;if(t?.addDependency(this),(this.flags&(m|L))!==0)return!0;const s=this._deps;if(!s.hasComputeds)return!1;const e=s.size;for(let i=0;i<e;i++)if(s.getAt(i)?.node.hasError)return!0;return!1}get isValid(){return!this.hasError}get errors(){const t=_.current;t?.addDependency(this);const s=this._error,e=this._deps;if(!e.hasComputeds)return s==null?K:Object.freeze([s]);const i=[];s!=null&&i.push(s);const r=e.size;for(let n=0;n<r;n++){const o=e.getAt(n);if(o==null)continue;const u=o.node;(u.flags&P)!==0&&u.hasError&&this._collectErrorsFromDep(u,i)}return i.length===0?K:Object.freeze(i)}_collectErrorsFromDep(t,s){const e=t.errors,i=e.length;for(let r=0;r<i;r++){const n=e[r];n!=null&&!s.includes(n)&&s.push(n)}}get lastError(){const t=_.current;return t?.addDependency(this),this._error}get isPending(){const t=_.current;return t?.addDependency(this),(this.flags&b)!==0}get isResolved(){const t=_.current;return t?.addDependency(this),(this.flags&I)!==0}invalidate(){this.flags|=j,this._markDirty()}dispose(){(this.flags&Y)===0&&(this._deps.disposeAll(),this._slots!=null&&this._slots.clear(),this.flags=Y|d|v,this._error=null,this._value=void 0,this._hotIndex=-1)}[Symbol.dispose](){this.dispose()}addDependency(t){const s=this._trackEpoch;if(t._lastSeenEpoch===s)return;t._lastSeenEpoch=s;const e=this._trackCount++,i=this._deps,r=i.getAt(e);if(r!=null&&r.node===t)r.version=t.version;else if(!i.claimExisting(t,e)){const n=new x(t,t.version,t.subscribe(this));i.insertNew(e,n)}(t.flags&P)!==0&&(i.hasComputeds=!0)}_recompute(){if(this.isRecomputing)return;this.flags=(this.flags|O)&~j,this._trackEpoch=V(),this._trackCount=0,this._deps.prepareTracking(),this._hotIndex=-1;let t=!1;try{const s=_.run(this,this._fn);this._deps.truncateFrom(this._trackCount),t=!0,ut(s)?this._handleAsyncComputation(s):this._finalizeResolution(s)}catch(s){if(!t)try{this._deps.truncateFrom(this._trackCount)}catch{}this._handleError(s,f.COMPUTED_COMPUTATION_FAILED,!0)}finally{this._trackEpoch=y.UNINITIALIZED,this._trackCount=0,this.flags&=~O}}_handleAsyncComputation(t){this.flags=(this.flags|b)&~(v|d|I|m),this._notifySubscribers(void 0,void 0),this._promiseId=(this._promiseId+1)%lt.MAX_PROMISE_ID;const s=this._promiseId;t.then(e=>{if(s===this._promiseId){if(this._isDirty())return this._markDirty();this._finalizeResolution(e),this._notifySubscribers(e,void 0)}},e=>s===this._promiseId&&this._handleError(e,f.COMPUTED_ASYNC_COMPUTATION_FAILED))}_handleError(t,s,e=!1){const i=N(t,T,s);if(!e&&!this.isRejected&&(this.version=k(this.version)),this._error=i,this.flags=this.flags&~(v|d|b|I)|m|L,this._onError)try{this._onError(i)}catch(r){console.error(f.CALLBACK_ERROR_IN_ERROR_HANDLER,r)}if(e)throw i;this._notifySubscribers(void 0,void 0)}_finalizeResolution(t){const s=this.flags;((s&I)===0||!this._equal(this._value,t))&&(this.version=k(this.version)),this._value=t,this._error=null,this.flags=(s|I)&~(v|d|b|m|L)}execute(){this._markDirty()}_markDirty(){const t=this.flags;(t&(O|d))===0&&(this.flags=t|d,this._notifySubscribers(void 0,void 0))}_deepDirtyCheck(){const t=this._deps,s=_.current;_.current=null;try{const e=t.size;for(let i=0;i<e;i++){const r=t.getAt(i);if(r==null)continue;const n=r.node;if((n.flags&P)!==0)try{n.value}catch{}if(n.version!==r.version)return this._hotIndex=i,!0}return this._hotIndex=-1,!1}finally{_.current=s}}};function yt(t,s={}){return new bt(t,s)}var At=class extends G{constructor(t,s={}){super(),this[it]=!0,this._cleanup=null,this._deps=new st,this._currentEpoch=y.UNINITIALIZED,this._lastFlushEpoch=y.UNINITIALIZED,this._fn=t,this._onError=s.onError??null,this._sync=s.sync??!1,this._maxExecutions=s.maxExecutionsPerSecond??C.MAX_EXECUTIONS_PER_SECOND,this._maxExecutionsPerFlush=s.maxExecutionsPerFlush??C.MAX_EXECUTIONS_PER_EFFECT,this._executionsInEpoch=0,this._executionCount=0,this._windowStart=0,this._windowCount=0,this._execId=0,this._trackCount=0,this._sync?this._notifyCallback=()=>this.execute():this._notifyCallback=()=>A.schedule(this),w.attachDebugInfo(this,"effect",this.id)}run(){if(this.isDisposed)throw new D(f.EFFECT_DISPOSED);this.execute(!0)}dispose(){this.isDisposed||(this.flags|=S.DISPOSED,this._execCleanup(),this._deps?.disposeAll())}[Symbol.dispose](){this.dispose()}addDependency(t){if((this.flags&S.EXECUTING)===0)return;const s=this._currentEpoch;if(t._lastSeenEpoch===s)return;t._lastSeenEpoch=s;const e=this._trackCount++,i=this._deps;let r;switch(e){case 0:r=i._s0;break;case 1:r=i._s1;break;case 2:r=i._s2;break;case 3:r=i._s3;break;default:r=i.getAt(e)}r!=null&&r.node===t?r.version=t.version:i.claimExisting(t,e)||this._insertNewDependency(t,e),t.isComputed&&(i.hasComputeds=!0)}_insertNewDependency(t,s){let e;try{const i=t.subscribe(this._notifyCallback);e=new x(t,t.version,i)}catch(i){const r=N(i,D,f.EFFECT_EXECUTION_FAILED);if(console.error(r),this._onError)try{this._onError(r)}catch{}e=new x(t,t.version,void 0)}this._deps.insertNew(s,e)}execute(t=!1){const s=this.flags;if((s&(S.DISPOSED|S.EXECUTING))!==0)return;const e=this._deps;if(!t&&e.size>0&&!this._isDirty())return;this._checkInfiniteLoops(),this.flags=s|S.EXECUTING,this._execCleanup(),this._currentEpoch=V(),this._trackCount=0,e.prepareTracking(),this._hotIndex=-1;let i=!1;try{const r=_.run(this,this._fn);e.truncateFrom(this._trackCount),i=!0,ut(r)?this._handleAsyncResult(r):this._cleanup=typeof r=="function"?r:null}catch(r){if(!i)try{e.truncateFrom(this._trackCount)}catch{}this._handleExecutionError(r),this._cleanup=null}finally{this.flags&=~S.EXECUTING}}_handleAsyncResult(t){const s=++this._execId;t.then(e=>{if(s!==this._execId||this.isDisposed){if(typeof e=="function")try{e()}catch(i){this._handleExecutionError(i,f.EFFECT_CLEANUP_FAILED)}return}typeof e=="function"&&(this._cleanup=e)},e=>s===this._execId&&this._handleExecutionError(e))}_deepDirtyCheck(){const t=_.current;_.current=null;const s=this._deps;try{const e=s.size;for(let i=0;i<e;i++){const r=s.getAt(i);if(r==null)continue;const n=r.node;if(n.isComputed&&this._tryPullComputed(n),n.version!==r.version)return this._hotIndex=i,!0}return!1}finally{_.current=t}}_tryPullComputed(t){try{t.value}catch{}}_execCleanup(){const t=this._cleanup;if(t!=null){this._cleanup=null;try{t()}catch(s){this._handleExecutionError(s,f.EFFECT_CLEANUP_FAILED)}}}_checkInfiniteLoops(){const t=Ct();this._lastFlushEpoch!==t&&(this._lastFlushEpoch=t,this._executionsInEpoch=0),++this._executionsInEpoch>this._maxExecutionsPerFlush&&this._throwInfiniteLoopError("per-effect"),It()>C.MAX_EXECUTIONS_PER_FLUSH&&this._throwInfiniteLoopError("global"),this._executionCount++}_checkFrequencyLimit(){if(!Number.isFinite(this._maxExecutions))return;const t=Date.now();if(t-this._windowStart>=B.EFFECT_FREQUENCY_WINDOW){this._windowStart=t,this._windowCount=1;return}if(++this._windowCount>this._maxExecutions){const s=new D(f.EFFECT_FREQUENCY_LIMIT_EXCEEDED);throw this.dispose(),this._handleExecutionError(s),s}}get executionCount(){return this._executionCount}get isExecuting(){return(this.flags&S.EXECUTING)!==0}_throwInfiniteLoopError(t){const s=new D(`Infinite loop detected (${t}): effect executed ${this._executionsInEpoch} times in current flush. Total executions in flush: ${$}`);throw this.dispose(),console.error(s),s}_handleExecutionError(t,s=f.EFFECT_EXECUTION_FAILED){const e=N(t,D,s);if(console.error(e),this._onError)try{this._onError(e)}catch(i){console.error(N(i,D,f.CALLBACK_ERROR_IN_ERROR_HANDLER))}}};function Ot(t,s={}){if(typeof t!="function")throw new D(f.EFFECT_MUST_BE_FUNCTION);const e=new At(t,s);return e.execute(),e}var Ft=Symbol.for("atom-effect/atom"),Rt=Symbol.for("atom-effect/writable");function q(t,s,e,i){if(e===s.length)return i;const r=s[e],n=t!=null&&typeof t=="object"?t:{},o=n[r],u=q(o,s,e+1,i);if(Object.is(o,u))return t;if(Array.isArray(n)){const l=n.slice(),c=Number.parseInt(r,10);return Number.isNaN(c)?l[r]=u:l[c]=u,l}return{...n,[r]:u}}function F(t,s){let e=t;const i=s.length;for(let r=0;r<i;r++){if(e==null)return;e=e[s[r]]}return e}function W(t,s){const e=s.includes(".")?s.split("."):[s],i=new Set,r=()=>{i.forEach(n=>n()),i.clear()};return{get value(){return F(t.value,e)},set value(n){const o=t.peek(),u=q(o,e,0,n);u!==o&&(t.value=u)},peek:()=>F(t.peek(),e),subscribe(n){const o=t.subscribe((u,l)=>{const c=F(u,e),a=F(l,e);Object.is(c,a)||n(c,a)});return i.add(o),()=>{o(),i.delete(o)}},subscriberCount:()=>i.size,dispose:r,[Symbol.dispose]:r,[Ft]:!0,[Rt]:!0}}var wt=(t,s)=>W(t,s),Ut=t=>s=>W(t,s);h.AsyncState=p,h.AtomError=g,h.ComputedError=T,h.DEBUG_CONFIG=B,h.DEBUG_RUNTIME=w,h.EffectError=D,h.SCHEDULER_CONFIG=C,h.SchedulerError=R,h.atom=gt,h.atomLens=W,h.batch=vt,h.composeLens=wt,h.computed=yt,h.effect=Ot,h.getPathValue=F,h.isAtom=mt,h.isComputed=Tt,h.isEffect=Nt,h.lensFor=Ut,h.scheduler=A,h.setDeepValue=q,h.untracked=dt});
2
2
 
3
3
  //# sourceMappingURL=atom-effect.min.js.map