@but212/atom-effect 0.25.0 → 0.26.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(l,p){typeof exports=="object"&&typeof module<"u"?p(exports):typeof define=="function"&&define.amd?define(["exports"],p):(l=typeof globalThis<"u"?globalThis:l||self,p(l.AtomEffect={}))})(this,function(l){Object.defineProperty(l,Symbol.toStringTag,{value:"Module"});var p={IDLE:"idle",PENDING:"pending",RESOLVED:"resolved",REJECTED:"rejected"},f={DISPOSED:1,EXECUTING:8},L={DISPOSED:1,IS_COMPUTED:2,DIRTY:8,IDLE:16,PENDING:32,RESOLVED:64,REJECTED:128,RECOMPUTING:256,HAS_ERROR:512,FORCE_COMPUTE:1024},I={DISPOSED:1,SYNC:8,NOTIFICATION_SCHEDULED:16},g={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},M={WARN_INFINITE_LOOP:!0,EFFECT_FREQUENCY_WINDOW:1e3},W={MAX_ASYNC_RETRIES:3,MAX_PROMISE_ID:Number.MAX_SAFE_INTEGER-1},v={UNINITIALIZED:-1,MIN:1},P=1073741823,K={VERSION_BITS:16},Ot=(typeof process<"u"&&process.env,!1),Z=Object.freeze([]),B=class{constructor(t,s,e=void 0){this.node=t,this.version=s,this.unsub=e}},lt=class{constructor(t,s){this.fn=t,this.sub=s}notify(t,s){this.fn?this.fn(t,s):this.sub&&this.sub.execute()}},m=class extends Error{constructor(t,s=null,e=!0){super(t),this.cause=s,this.recoverable=e,this.name="AtomError"}},T=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"}},R=class extends m{constructor(t,s=null){super(t,s,!1),this.name="SchedulerError"}},c={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"},J=class{constructor(){this._s0=null,this._s1=null,this._s2=null,this._s3=null,this._count=0,this._overflow=null}get size(){return this._count}getAt(t){switch(t){case 0:return this._s0;case 1:return this._s1;case 2:return this._s2;case 3:return this._s3;default:{const s=this._overflow;if(s!==null&&t>=4){const e=t-4;if(e<s.length)return s[e]??null}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??=[];const e=this._overflow;e[t-4]=s}}t>=this._count&&(this._count=t+1)}truncateFrom(t){const s=this._count;if(t>=s)return;if(t<=3)switch(t){case 0:{const i=this._s0;i!=null&&(this._onItemRemoved(i),this._s0=null)}case 1:{const i=this._s1;i!=null&&(this._onItemRemoved(i),this._s1=null)}case 2:{const i=this._s2;i!=null&&(this._onItemRemoved(i),this._s2=null)}case 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,n=e.length;for(let r=i;r<n;r++){const o=e[r];o!=null&&(this._onItemRemoved(o),e[r]=null)}t<=4?(e.length=0,this._overflow=null):e.length=t-4}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}if(this._overflow===null)this._overflow=[t];else{const s=this._overflow;for(let e=0,i=s.length;e<i;e++)if(s[e]===null){s[e]=t,this._count++;return}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)return s[e]=null,this._count--,!0;return!1}has(t){const s=this._count;if(s===0)return!1;if(this._s0===t||this._s1===t||this._s2===t||this._s3===t)return!0;if(s<=4)return!1;const e=this._overflow;if(e!=null){let i=0;this._s0!=null&&i++,this._s1!=null&&i++,this._s2!=null&&i++,this._s3!=null&&i++;for(let n=0,r=e.length;n<r;n++){const o=e[n];if(o!=null){if(o===t)return!0;if(++i===s)break}}}return!1}forEach(t){const s=this._count;if(s===0)return;const e=this._s0;e!=null&&t(e);const i=this._s1;i!=null&&t(i);const n=this._s2;n!=null&&t(n);const r=this._s3;if(r!=null&&t(r),s<=4)return;const o=this._overflow;if(o!=null){let h=0;e!=null&&h++,i!=null&&h++,n!=null&&h++,r!=null&&h++;for(let u=0,d=o.length;u<d;u++){const a=o[u];if(a!=null&&(t(a),++h===s))return}}}forEachIndexed(t){const s=this._count;if(s===0)return 0;let e=0;const i=this._s0;i!=null&&(t(i),e++);const n=this._s1;n!=null&&(t(n),e++);const r=this._s2;r!=null&&(t(r),e++);const o=this._s3;if(o!=null&&(t(o),e++),s<=4||e===s)return e;const h=this._overflow;if(h!=null)for(let u=0,d=h.length;u<d;u++){const a=h[u];if(a!=null&&(t(a),++e===s))break}return e}compact(){const t=this._overflow;if(t===null||t.length===0)return;let s=0;for(;s<t.length;)if(t[s]===null){const e=t.pop();s<t.length&&e!=null&&(t[s]=e)}else s++;t.length===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)}dispose(){this.clear()}},tt=Symbol("AtomEffect.DebugName"),ct=Symbol("AtomEffect.Id"),st=Symbol("AtomEffect.Type"),H=Symbol("AtomEffect.NoDefaultValue"),U={enabled:!1,warnInfiniteLoop:M.WARN_INFINITE_LOOP,warn(t,s){},attachDebugInfo(t,s,e){},getDebugName:t=>t?.[tt],getDebugType:t=>t?.[st]},_t=1,ft=()=>_t++;function N(t,s,e){if(t instanceof m)return t;const i=t instanceof Error,n=i?t.message:String(t),r=i?t:void 0;return new s(`${i?t.constructor.name:"Unexpected error"} (${e}): ${n}`,r)}var x=class{constructor(){this.flags=0,this.version=0,this._lastSeenEpoch=v.UNINITIALIZED,this._notifying=0,this._hotIndex=-1,this._slots=null,this._deps=null,this.id=ft()&P}subscribe(t){const s=typeof t=="function";if(!s&&(!t||typeof t.execute!="function"))throw N(new TypeError("Invalid subscriber"),m,c.ATOM_SUBSCRIBER_MUST_BE_FUNCTION);let e=this._slots;e||(e=new J,this._slots=e);let i=!1;if(e.forEach(r=>{(s?r.fn===t:r.sub===t)&&(i=!0)}),i)return()=>{};const n=new lt(s?t:void 0,s?void 0:t);return e.add(n),()=>this._unsubscribe(n)}_unsubscribe(t){if(this._slots){if(this._notifying>0){this._slots.remove(t);return}this._slots.remove(t),this._slots.compact()}}subscriberCount(){return this._slots?this._slots.size:0}_notifySubscribers(t,s){const e=this._slots;if(!(!e||e.size===0)){this._notifying++;try{e.forEach(i=>{try{i.notify(t,s)}catch(n){console.error(N(n,m,c.ATOM_INDIVIDUAL_SUBSCRIBER_FAILED))}})}finally{this._notifying--,this._notifying===0&&e.compact()}}}_isDirty(){const t=this._deps;if(!t||t.size===0)return!1;if(this._hotIndex!==-1){const s=t.getAt(this._hotIndex);if(s!=null&&s.node.version!==s.version)return!0}return!t.hasComputeds&&!t.isDirtyFast()?!1:this._deepDirtyCheck()}},z=0,k=()=>(z=z+1&1073741823||1,z),G=t=>t+1&P,X=0,w=!1,et=0,it=()=>et;function nt(){return w?!1:(w=!0,et=k(),X=0,!0)}var rt=()=>{w=!1},at=()=>w?++X:0,V=(function(t){return t[t.IDLE=0]="IDLE",t[t.BATCHING=1]="BATCHING",t[t.FLUSHING=2]="FLUSHING",t})({}),Et=class{constructor(){this._queueBuffer=[[],[]],this._bufferIndex=0,this._size=0,this._epoch=0,this._isProcessing=!1,this._isBatching=!1,this._isFlushingSync=!1,this._batchDepth=0,this._batchQueue=[],this._batchQueueSize=0,this._maxFlushIterations=g.MAX_FLUSH_ITERATIONS,this.onOverflow=null,this._boundRunLoop=this._runLoop.bind(this)}get phase(){return this._isProcessing||this._isFlushingSync?V.FLUSHING:this._isBatching?V.BATCHING:V.IDLE}get queueSize(){return this._size}get isBatching(){return this._isBatching}schedule(t){if(t._nextEpoch!==this._epoch){if(t._nextEpoch=this._epoch,this._isBatching||this._isFlushingSync){this._batchQueue[this._batchQueueSize++]=t;return}this._queueBuffer[this._bufferIndex][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=nt();this._drainQueue(),t&&rt()}finally{this._isProcessing=!1,this._size>0&&!this._isBatching&&this._flush()}}_flushSync(){this._isFlushingSync=!0;const t=nt();try{this._mergeBatchQueue(),this._drainQueue()}finally{this._isFlushingSync=!1,t&&rt()}}_mergeBatchQueue(){if(this._batchQueueSize===0)return;const t=++this._epoch,s=this._batchQueue,e=this._queueBuffer[this._bufferIndex];let i=this._size;for(let n=0;n<this._batchQueueSize;n++){const r=s[n];r._nextEpoch!==t&&(r._nextEpoch=t,e[i++]=r)}this._size=i,this._batchQueueSize=0,s.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++;for(let i=0;i<e;i++)try{const n=s[i];typeof n=="function"?n():n.execute()}catch(n){console.error(new R("Error occurred during scheduler execution",n))}s.length=0}_handleFlushOverflow(){const t=this._size+this._batchQueueSize;if(console.error(new R(c.SCHEDULER_FLUSH_OVERFLOW(this._maxFlushIterations,t))),this._size=0,this._queueBuffer[this._bufferIndex].length=0,this._batchQueueSize=0,this.onOverflow)try{this.onOverflow(t)}catch{}}startBatch(){this._batchDepth++,this._isBatching=!0}endBatch(){this._batchDepth!==0&&--this._batchDepth===0&&(this._flushSync(),this._isBatching=!1)}setMaxFlushIterations(t){if(t<g.MIN_FLUSH_ITERATIONS)throw new R(`Max flush iterations must be at least ${g.MIN_FLUSH_ITERATIONS}`);this._maxFlushIterations=t}},O=new Et,Q=Symbol.for("atom-effect/atom"),ot=Symbol.for("atom-effect/computed"),ht=Symbol.for("atom-effect/effect"),dt=Symbol.for("atom-effect/writable"),_={current:null,run(t,s){const e=this.current;this.current=t;try{return s()}finally{this.current=e}}};function pt(t){const s=_.current;if(s===null)return t();_.current=null;try{return t()}finally{_.current=s}}var It=class extends x{constructor(t,s){super(),this[Q]=!0,this[dt]=!0,this._value=t,this._pendingOldValue=void 0,s&&(this.flags|=I.SYNC),U.attachDebugInfo(this,"atom",this.id)}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=G(this.version);const e=this._slots,i=this.flags;if(e==null||e.size===0||i&I.NOTIFICATION_SCHEDULED)return;this._pendingOldValue=s;const n=i|I.NOTIFICATION_SCHEDULED;if(this.flags=n,(n&I.SYNC)!==0&&!O.isBatching){this._flushNotifications();return}O.schedule(this)}execute(){this._flushNotifications()}_flushNotifications(){const t=this.flags;if(!(t&I.NOTIFICATION_SCHEDULED)||t&I.DISPOSED)return;const s=this._pendingOldValue;this._pendingOldValue=void 0,this.flags&=~I.NOTIFICATION_SCHEDULED,this._notifySubscribers(this._value,s)}peek(){return this._value}dispose(){this.flags&I.DISPOSED||(this._slots?.clear(),this.flags|=I.DISPOSED,this._value=void 0,this._pendingOldValue=void 0)}_deepDirtyCheck(){return!1}[Symbol.dispose](){this.dispose()}};function Ct(t,s={}){return new It(t,s.sync??!1)}var Y=class extends J{constructor(){super(),this._map=null,this._SCAN_THRESHOLD=32,this.hasComputeds=!1,this._depsHash=0,this._map=null,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 o=this._s0;if(o&&o.node===t&&o.unsub)return o.version=t.version,!0}case 1:if(e>1){const o=this._s1;if(o&&o.node===t&&o.unsub)return o.version=t.version,s!==1&&(this._s1=this._s0,this._s0=o),!0}case 2:if(e>2){const o=this._s2;if(o&&o.node===t&&o.unsub){if(o.version=t.version,s!==2){const h=s===0?this._s0:this._s1;s===0?this._s0=o:this._s1=o,this._s2=h}return!0}}case 3:if(e>3){const o=this._s3;if(o&&o.node===t&&o.unsub){if(o.version=t.version,s!==3){let h;s===0?(h=this._s0,this._s0=o):s===1?(h=this._s1,this._s1=o):(h=this._s2,this._s2=o),this._s3=h}return!0}}}const n=s>4?s:4,r=this._overflow;if(r)for(let o=n-4,h=r.length;o<h;o++){const u=r[o];if(u&&u.node===t&&u.unsub)return u.version=t.version,this._swapGeneral(o+4,s,u),!0}return!1}_claimViaMap(t,s){if(this._map===null){this._map=new Map;const n=this._count;s<4&&(s<=0&&this._s0?.unsub&&this._map.set(this._s0.node,0),s<=1&&this._s1?.unsub&&this._map.set(this._s1.node,1),s<=2&&this._s2?.unsub&&this._map.set(this._s2.node,2),s<=3&&this._s3?.unsub&&this._map.set(this._s3.node,3));const r=this._overflow;if(r&&n>4){const o=s>4?s:4;for(let h=o-4,u=r.length;h<u;h++){const d=r[h];d?.unsub&&this._map.set(d.node,h+4)}}}const e=this._map.get(t);if(e===void 0||e<s)return!1;const i=this.getAt(e);if(i==null||!i.unsub)return!1;if(i.version=t.version,e!==s){const n=this.getAt(s);this.setAt(s,i),this.setAt(e,n),n?.unsub&&this._map.set(n.node,e),this._map.set(t,s)}return!0}_swapInline(t,s,e){const i=this.getAt(s);this.setAt(s,e),this.setAt(t,i)}_swapGeneral(t,s,e){if(t===s)return;const i=this.getAt(s);if(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 n=this._overflow;n[t-4]=i}}insertNew(t,s){const e=this._count;if(t<e){const i=this.getAt(t);i!=null&&(this.add(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(){const t=this._count,s=K.VERSION_BITS;let e=0;switch(t){case 0:this._depsHash=0;return;case 1:{const i=this._s0;e=e+(i.version<<s)+i.node.id|0;break}case 2:{const i=this._s0,n=this._s1;e=e+(i.version<<s)+i.node.id|0,e=e+(n.version<<s)+n.node.id|0;break}case 3:{const i=this._s0,n=this._s1,r=this._s2;e=e+(i.version<<s)+i.node.id|0,e=e+(n.version<<s)+n.node.id|0,e=e+(r.version<<s)+r.node.id|0;break}default:{const i=this._s0,n=this._s1,r=this._s2,o=this._s3;if(e=e+(i.version<<s)+i.node.id|0,e=e+(n.version<<s)+n.node.id|0,e=e+(r.version<<s)+r.node.id|0,e=e+(o.version<<s)+o.node.id|0,t>4){const h=this._overflow;for(let u=0,d=h.length;u<d;u++){const a=h[u];e=e+(a.version<<s)+a.node.id|0}}}}this._depsHash=e}isDirtyFast(){const t=this._count,s=K.VERSION_BITS;let e=0;switch(t){case 0:return!1;case 1:{const i=this._s0.node;e=e+(i.version<<s)+i.id|0;break}case 2:{const i=this._s0.node,n=this._s1.node;e=e+(i.version<<s)+i.id|0,e=e+(n.version<<s)+n.id|0;break}case 3:{const i=this._s0.node,n=this._s1.node,r=this._s2.node;e=e+(i.version<<s)+i.id|0,e=e+(n.version<<s)+n.id|0,e=e+(r.version<<s)+r.id|0;break}default:{const i=this._s0.node,n=this._s1.node,r=this._s2.node,o=this._s3.node;if(e=e+(i.version<<s)+i.id|0,e=e+(n.version<<s)+n.id|0,e=e+(r.version<<s)+r.id|0,e=e+(o.version<<s)+o.id|0,t>4){const h=this._overflow;for(let u=0,d=h.length;u<d;u++){const a=h[u].node;e=e+(a.version<<s)+a.id|0}}}}return e!==this._depsHash}disposeAll(){this._count>0&&this.truncateFrom(0),this.hasComputeds=!1,this._map!==null&&(this._map.clear(),this._map=null)}remove(t){throw new Error("remove() is strictly prohibited in DepSlotBuffer to preserve sequential cache paths.")}compact(){}};function vt(t){return t!==null&&typeof t=="object"&&Q in t}function Dt(t){return t!==null&&typeof t=="object"&&ot in t}function St(t){return t!==null&&typeof t=="object"&&ht in t}function ut(t){return t!==null&&typeof t=="object"&&typeof t.then=="function"}var{IDLE:S,DIRTY:E,PENDING:y,RESOLVED:C,REJECTED:A,HAS_ERROR:b,RECOMPUTING:F,DISPOSED:j,IS_COMPUTED:$,FORCE_COMPUTE:q}=L,gt=class extends x{constructor(t,s={}){if(typeof t!="function")throw new T(c.COMPUTED_MUST_BE_FUNCTION);if(super(),this[Q]=!0,this[ot]=!0,this._error=null,this._promiseId=0,this._deps=new Y,this._asyncRetryCount=0,this._lastDriftEpoch=v.UNINITIALIZED,this._trackEpoch=v.UNINITIALIZED,this._trackCount=0,this._value=void 0,this.flags=$|E|S,this._equal=s.equal??Object.is,this._fn=t,this._defaultValue="defaultValue"in s?s.defaultValue:H,this._onError=s.onError??null,this._maxAsyncRetries=(s.maxAsyncRetries??W.MAX_ASYNC_RETRIES)&P,U.attachDebugInfo(this,"computed",this.id),s.lazy===!1)try{this._recompute()}catch{}}_track(){_.current?.addDependency(this)}get value(){this._track();const t=this.flags;if((t&(C|E|S))===C)return this._value;if(t&j)throw new T(c.COMPUTED_DISPOSED);if(t&F){if(this._defaultValue!==H)return this._defaultValue;throw new T(c.COMPUTED_CIRCULAR_DEPENDENCY)}if(t&(E|S)&&((t&S)===0&&(t&q)===0&&this._deps.size>0&&!this._isDirty()?this.flags&=~E:this._recompute(),this.flags&C))return this._value;const s=this._defaultValue,e=s!==H;if(this.flags&y){if(e)return s;throw new T(c.COMPUTED_ASYNC_PENDING_NO_DEFAULT)}if(this.flags&A){if(e)return s;throw this._error}return this._value}peek(){return this._value}get state(){this._track();const t=this.flags;return t&C?p.RESOLVED:t&y?p.PENDING:t&A?p.REJECTED:p.IDLE}get hasError(){if(this._track(),this.flags&(A|b))return!0;const t=this._deps;if(!t.hasComputeds)return!1;const s=t.size;for(let e=0;e<s;e++){const i=t.getAt(e);if(i!=null&&i.node.flags&b)return!0}return!1}get isValid(){return!this.hasError}get errors(){this._track();const t=[];this._error&&t.push(this._error);const s=this._deps;if(!s.hasComputeds)return t.length===0?Z:Object.freeze(t);const e=s.size;for(let i=0;i<e;i++){const n=s.getAt(i);if(n==null)continue;const r=n.node;r.flags&b&&this._collectErrorsFromDep(r,t)}return t.length===0?Z:Object.freeze(t)}_collectErrorsFromDep(t,s){const e=t.errors,i=e.length;for(let n=0;n<i;n++){const r=e[n];r!=null&&!s.includes(r)&&s.push(r)}}get lastError(){return this._track(),this._error}get isPending(){return this._track(),(this.flags&y)!==0}get isResolved(){return this._track(),(this.flags&C)!==0}invalidate(){this.flags|=q,this._markDirty()}dispose(){this.flags&j||(this._deps.disposeAll(),this._slots?.clear(),this.flags=j|E|S,this._error=null,this._value=void 0,this._hotIndex=-1)}[Symbol.dispose](){this.dispose()}addDependency(t){if(t._lastSeenEpoch===this._trackEpoch)return;t._lastSeenEpoch=this._trackEpoch;const s=this._trackCount,e=this._deps.getAt(s);if(e!=null&&e.node===t)e.version=t.version;else if(!this._deps.claimExisting(t,s)){const i=new B(t,t.version,t.subscribe(this));this._deps.insertNew(s,i)}t.flags&$&&(this._deps.hasComputeds=!0),this._trackCount=s+1}_recompute(){if(this.flags&F)return;this.flags=(this.flags|F)&~q,this._trackEpoch=k(),this._trackCount=0,this._deps.prepareTracking(),this._hotIndex=-1;let t=!1;try{const s=_.run(this,this._fn);this._deps.truncateFrom(this._trackCount),this._deps.seal(),t=!0,ut(s)?this._handleAsyncComputation(s):this._finalizeResolution(s)}catch(s){if(!t)try{this._deps.truncateFrom(this._trackCount)}catch{}this._handleError(s,c.COMPUTED_COMPUTATION_FAILED,!0)}finally{this._trackEpoch=v.UNINITIALIZED,this._trackCount=0,this.flags&=~F}}_handleAsyncComputation(t){this.flags=(this.flags|y)&~(S|E|C|A),this._notifySubscribers(void 0,void 0),this._asyncRetryCount=0,this._promiseId=(this._promiseId+1)%W.MAX_PROMISE_ID;const s=this._promiseId;t.then(e=>{if(s===this._promiseId){if(this._isDirty()){const i=it();return this._lastDriftEpoch!==i&&(this._lastDriftEpoch=i,this._asyncRetryCount=0),this._asyncRetryCount++<this._maxAsyncRetries?this._markDirty():this._handleError(new T(`Async drift threshold exceeded after ${this._maxAsyncRetries} retries.`),c.COMPUTED_ASYNC_COMPUTATION_FAILED)}this._finalizeResolution(e),this._notifySubscribers(e,void 0)}},e=>s===this._promiseId&&this._handleError(e,c.COMPUTED_ASYNC_COMPUTATION_FAILED))}_handleError(t,s,e=!1){const i=N(t,T,s);if(!e&&!(this.flags&A)&&(this.version=G(this.version)),this._error=i,this.flags=this.flags&~(S|E|y|C)|A|b,this._onError)try{this._onError(i)}catch(n){console.error(c.CALLBACK_ERROR_IN_ERROR_HANDLER,n)}if(e)throw i;this._notifySubscribers(void 0,void 0)}_finalizeResolution(t){(!(this.flags&C)||!this._equal(this._value,t))&&(this.version=G(this.version)),this._value=t,this._error=null,this.flags=(this.flags|C)&~(S|E|y|A|b)}execute(){this._markDirty()}_markDirty(){this.flags&(F|E)||(this.flags|=E,this._notifySubscribers(void 0,void 0))}_isDirty(){const t=this._deps;return t.hasComputeds?this._deepDirtyCheck():t.isDirtyFast()}_deepDirtyCheck(){const t=this._deps,s=_.current;_.current=null;try{const e=t.size;for(let i=0;i<e;i++){const n=t.getAt(i);if(n==null)continue;const r=n.node;if(r.flags&$)try{r.value}catch{}if(r.version!==n.version)return this._hotIndex=i,!0}return this._hotIndex=-1,!1}finally{_.current=s}}};function mt(t,s={}){return new gt(t,s)}var Tt=class extends x{constructor(t,s={}){super(),this[ht]=!0,this._cleanup=null,this._deps=new Y,this._currentEpoch=v.UNINITIALIZED,this._lastFlushEpoch=v.UNINITIALIZED,this._fn=t,this._onError=s.onError??null,this._sync=s.sync??!1,this._maxExecutions=s.maxExecutionsPerSecond??g.MAX_EXECUTIONS_PER_SECOND,this._maxExecutionsPerFlush=s.maxExecutionsPerFlush??g.MAX_EXECUTIONS_PER_EFFECT,this._cleanup=null,this._deps=new Y,this._currentEpoch=v.UNINITIALIZED,this._lastFlushEpoch=v.UNINITIALIZED,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=()=>O.schedule(this),U.attachDebugInfo(this,"effect",this.id)}run(){if(this.flags&f.DISPOSED)throw new D(c.EFFECT_DISPOSED);this.execute(!0)}dispose(){this.flags&f.DISPOSED||(this.flags|=f.DISPOSED,this._execCleanup(),this._deps?.disposeAll())}[Symbol.dispose](){this.dispose()}addDependency(t){if(!(this.flags&f.EXECUTING))return;const s=this._currentEpoch;if(t._lastSeenEpoch===s)return;t._lastSeenEpoch=s;const e=this._trackCount,i=this._deps;let n;e===0?n=i._s0:e===1?n=i._s1:e===2?n=i._s2:e===3?n=i._s3:n=i.getAt(e),n!=null&&n.node===t?n.version=t.version:i.claimExisting(t,e)||this._insertNewDependency(t,e),t.flags&L.IS_COMPUTED&&(i.hasComputeds=!0),this._trackCount=e+1}_insertNewDependency(t,s){let e;try{const i=t.subscribe(this._notifyCallback);e=new B(t,t.version,i)}catch(i){const n=N(i,D,c.EFFECT_EXECUTION_FAILED);if(console.error(n),this._onError)try{this._onError(n)}catch{}e=new B(t,t.version,void 0)}this._deps.insertNew(s,e)}execute(t=!1){if(this.flags&(f.DISPOSED|f.EXECUTING))return;const s=this._deps;if(!t&&s.size>0&&!this._isDirty())return;this._checkInfiniteLoops(),this.flags|=f.EXECUTING,this._execCleanup(),this._currentEpoch=k(),this._trackCount=0,s.prepareTracking(),this._hotIndex=-1;let e=!1;try{const i=_.run(this,this._fn);s.truncateFrom(this._trackCount),s.seal(),e=!0,ut(i)?this._handleAsyncResult(i):this._cleanup=typeof i=="function"?i:null}catch(i){if(!e)try{s.truncateFrom(this._trackCount)}catch{}this._handleExecutionError(i),this._cleanup=null}finally{this.flags&=~f.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.flags&f.DISPOSED){if(typeof e=="function")try{e()}catch(i){this._handleExecutionError(i,c.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 n=s.getAt(i);if(n==null)continue;const r=n.node;if(r.flags&L.IS_COMPUTED&&this._tryPullComputed(r),r.version!==n.version)return this._hotIndex=i,!0}return!1}finally{_.current=t}}_tryPullComputed(t){try{t.value}catch{}}_execCleanup(){if(this._cleanup){try{this._cleanup()}catch(t){this._handleExecutionError(t,c.EFFECT_CLEANUP_FAILED)}this._cleanup=null}}_checkInfiniteLoops(){const t=it();this._lastFlushEpoch!==t&&(this._lastFlushEpoch=t,this._executionsInEpoch=0),++this._executionsInEpoch>this._maxExecutionsPerFlush&&this._throwInfiniteLoopError("per-effect"),at()>g.MAX_EXECUTIONS_PER_FLUSH&&this._throwInfiniteLoopError("global"),this._executionCount++}_checkFrequencyLimit(){if(!Number.isFinite(this._maxExecutions))return;const t=Date.now();if(t-this._windowStart>=M.EFFECT_FREQUENCY_WINDOW){this._windowStart=t,this._windowCount=1;return}if(++this._windowCount>this._maxExecutions){const s=new D(c.EFFECT_FREQUENCY_LIMIT_EXCEEDED);throw this.dispose(),this._handleExecutionError(s),s}}get isDisposed(){return(this.flags&f.DISPOSED)!==0}get executionCount(){return this._executionCount}get isExecuting(){return(this.flags&f.EXECUTING)!==0}_throwInfiniteLoopError(t){const s=new D(`Infinite loop detected (${t}): effect executed ${this._executionsInEpoch} times in current flush. Total executions in flush: ${X}`);throw this.dispose(),console.error(s),s}_handleExecutionError(t,s=c.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,c.CALLBACK_ERROR_IN_ERROR_HANDLER))}}};function At(t,s={}){if(typeof t!="function")throw new D(c.EFFECT_MUST_BE_FUNCTION);const e=new Tt(t,s);return e.execute(),e}function Nt(t){if(typeof t!="function")throw new TypeError(c.BATCH_CALLBACK_MUST_BE_FUNCTION);O.startBatch();try{return t()}finally{O.endBatch()}}l.AsyncState=p,l.AtomError=m,l.ComputedError=T,l.DEBUG_CONFIG=M,l.DEBUG_RUNTIME=U,l.EffectError=D,l.SCHEDULER_CONFIG=g,l.SchedulerError=R,l.atom=Ct,l.batch=Nt,l.computed=mt,l.effect=At,l.isAtom=vt,l.isComputed=Dt,l.isEffect=St,l.scheduler=O,l.untracked=pt});
1
+ (function(h,E){typeof exports=="object"&&typeof module<"u"?E(exports):typeof define=="function"&&define.amd?define(["exports"],E):(h=typeof globalThis<"u"?globalThis:h||self,E(h.AtomEffect={}))})(this,function(h){Object.defineProperty(h,Symbol.toStringTag,{value:"Module"});var E={IDLE:"idle",PENDING:"pending",RESOLVED:"resolved",REJECTED:"rejected"},f={DISPOSED:1,EXECUTING:8},w={DISPOSED:1,IS_COMPUTED:2,DIRTY:8,IDLE:16,PENDING:32,RESOLVED:64,REJECTED:128,RECOMPUTING:256,HAS_ERROR:512,FORCE_COMPUTE:1024},d={DISPOSED:1,SYNC:8,NOTIFICATION_SCHEDULED:16},p={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},L={WARN_INFINITE_LOOP:!0,EFFECT_FREQUENCY_WINDOW:1e3},j={MAX_ASYNC_RETRIES:3,MAX_PROMISE_ID:Number.MAX_SAFE_INTEGER-1},C={UNINITIALIZED:-1,MIN:1},q=1073741823,W={VERSION_BITS:16},Ot=(typeof process<"u"&&process.env,!1),K=Object.freeze([]),M=class{constructor(t,s,e=void 0){this.node=t,this.version=s,this.unsub=e}},lt=class{constructor(t,s){this.fn=t,this.sub=s}notify(t,s){this.fn?this.fn(t,s):this.sub&&this.sub.execute()}},S=class extends Error{constructor(t,s=null,e=!0){super(t),this.cause=s,this.recoverable=e,this.name="AtomError"}},g=class extends S{constructor(t,s=null){super(t,s,!0),this.name="ComputedError"}},D=class extends S{constructor(t,s=null){super(t,s,!1),this.name="EffectError"}},F=class extends S{constructor(t,s=null){super(t,s,!1),this.name="SchedulerError"}},u={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"},Z=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){switch(t){case 0:return this._s0;case 1:return this._s1;case 2:return this._s2;case 3:return this._s3;default:{const s=this._overflow;if(s!==null&&t>=4){const e=t-4;if(e<s.length)return s[e]??null}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??=[];const e=this._overflow;e[t-4]=s}}t>=this._count&&(this._count=t+1)}truncateFrom(t){const s=this._count;if(t>=s)return;if(t<=3)switch(t){case 0:{const i=this._s0;i!=null&&(this._onItemRemoved(i),this._s0=null)}case 1:{const i=this._s1;i!=null&&(this._onItemRemoved(i),this._s1=null)}case 2:{const i=this._s2;i!=null&&(this._onItemRemoved(i),this._s2=null)}case 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,n=e.length;for(let o=i;o<n;o++){const r=e[o];r!=null&&(this._onItemRemoved(r),e[o]=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){if(this._overflow===null)this._overflow=[t];else{const s=this._freeIndices;s!==null&&s.length>0?this._overflow[s.pop()]=t:this._overflow.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)return s[e]=null,this._count--,this._freeIndices===null&&(this._freeIndices=[]),this._freeIndices.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){if(this._count===0)return;const s=this._s0;s!=null&&t(s);const e=this._s1;e!=null&&t(e);const i=this._s2;i!=null&&t(i);const n=this._s3;n!=null&&t(n);const o=this._overflow;if(o!=null)for(let r=0,l=o.length;r<l;r++){const _=o[r];_!=null&&t(_)}}forEachIndexed(t){const s=this._count;if(s===0)return 0;let e=0;const i=this._s0;i!=null&&(t(i),e++);const n=this._s1;n!=null&&(t(n),e++);const o=this._s2;o!=null&&(t(o),e++);const r=this._s3;if(r!=null&&(t(r),e++),e===s)return e;const l=this._overflow;if(l!=null)for(let _=0,U=l.length;_<U;_++){const ut=l[_];ut!=null&&(t(ut),e++)}return e}compact(){const t=this._overflow;if(t===null||t.length===0)return;let s=0;for(;s<t.length;)if(t[s]===null){for(;t.length>s&&t[t.length-1]===null;)t.pop();t.length>s&&(t[s]=t.pop(),s++)}else s++;this._freeIndices=null,t.length===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()}},J=Symbol("AtomEffect.DebugName"),_t=Symbol("AtomEffect.Id"),tt=Symbol("AtomEffect.Type"),P=Symbol("AtomEffect.NoDefaultValue"),b={enabled:!1,warnInfiniteLoop:L.WARN_INFINITE_LOOP,warn(t,s){},attachDebugInfo(t,s,e){},getDebugName:t=>t?.[J],getDebugType:t=>t?.[tt]},ct=1,ft=()=>ct++;function T(t,s,e){if(t instanceof S)return t;const i=t instanceof Error,n=i?t.message:String(t),o=i?t:void 0;return new s(`${i?t.constructor.name:"Unexpected error"} (${e}): ${n}`,o)}var B=class{constructor(){this.flags=0,this.version=0,this._lastSeenEpoch=C.UNINITIALIZED,this._notifying=0,this._hotIndex=-1,this._slots=null,this._deps=null,this.id=ft()&q}subscribe(t){const s=typeof t=="function";if(!s&&(!t||typeof t.execute!="function"))throw T(new TypeError("Invalid subscriber"),S,u.ATOM_SUBSCRIBER_MUST_BE_FUNCTION);let e=this._slots;e||(e=new Z,this._slots=e);let i=!1;if(e.forEach(o=>{(s?o.fn===t:o.sub===t)&&(i=!0)}),i)return()=>{};const n=new lt(s?t:void 0,s?void 0:t);return e.add(n),()=>this._unsubscribe(n)}_unsubscribe(t){if(this._slots){if(this._notifying>0){this._slots.remove(t);return}this._slots.remove(t),this._slots.compact()}}subscriberCount(){return this._slots?this._slots.size:0}_notifySubscribers(t,s){const e=this._slots;if(!(!e||e.size===0)){this._notifying++;try{e.forEach(i=>{try{i.notify(t,s)}catch(n){console.error(T(n,S,u.ATOM_INDIVIDUAL_SUBSCRIBER_FAILED))}})}finally{this._notifying--,this._notifying===0&&e.compact()}}}_isDirty(){const t=this._deps;if(!t||t.size===0)return!1;if(this._hotIndex!==-1){const s=t.getAt(this._hotIndex);if(s!=null&&s.node.version!==s.version)return!0}return!t.hasComputeds&&!t.isDirtyFast()?!1:this._deepDirtyCheck()}},x=0,H=()=>(x=x+1&1073741823||1,x),z=t=>t+1&1073741823||1,G=0,R=!1,st=0,et=()=>st;function it(){return R?!1:(R=!0,st=H(),G=0,!0)}var nt=()=>{R=!1},at=()=>{if(!R)return 0;const t=++G;if(t>p.MAX_EXECUTIONS_PER_FLUSH)throw new Error(`[atom-effect] Infinite loop detected: flush execution count exceeded ${p.MAX_EXECUTIONS_PER_FLUSH}`);return t},k=(function(t){return t[t.IDLE=0]="IDLE",t[t.BATCHING=1]="BATCHING",t[t.FLUSHING=2]="FLUSHING",t})({}),Et=class{constructor(){this._queueBuffer=[[],[]],this._bufferIndex=0,this._size=0,this._epoch=0,this._isProcessing=!1,this._isBatching=!1,this._isFlushingSync=!1,this._batchDepth=0,this._batchQueue=[],this._batchQueueSize=0,this._maxFlushIterations=p.MAX_FLUSH_ITERATIONS,this.onOverflow=null,this._boundRunLoop=this._runLoop.bind(this)}get phase(){return this._isProcessing||this._isFlushingSync?k.FLUSHING:this._isBatching?k.BATCHING:k.IDLE}get queueSize(){return this._size}get isBatching(){return this._isBatching}schedule(t){if(t._nextEpoch!==this._epoch){if(t._nextEpoch=this._epoch,this._isBatching||this._isFlushingSync){this._batchQueue[this._batchQueueSize++]=t;return}this._queueBuffer[this._bufferIndex][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=it();this._drainQueue(),t&&nt()}finally{this._isProcessing=!1,this._size>0&&!this._isBatching&&this._flush()}}_flushSync(){this._isFlushingSync=!0;const t=it();try{this._mergeBatchQueue(),this._drainQueue()}finally{this._isFlushingSync=!1,t&&nt()}}_mergeBatchQueue(){if(this._batchQueueSize===0)return;const t=++this._epoch,s=this._batchQueue,e=this._queueBuffer[this._bufferIndex];let i=this._size;for(let n=0;n<this._batchQueueSize;n++){const o=s[n];o._nextEpoch!==t&&(o._nextEpoch=t,e[i++]=o)}this._size=i,this._batchQueueSize=0,s.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++;for(let i=0;i<e;i++)try{const n=s[i];typeof n=="function"?n():n.execute()}catch(n){console.error(new F("Error occurred during scheduler execution",n))}s.length=0}_handleFlushOverflow(){const t=this._size+this._batchQueueSize;if(console.error(new F(u.SCHEDULER_FLUSH_OVERFLOW(this._maxFlushIterations,t))),this._size=0,this._queueBuffer[this._bufferIndex].length=0,this._batchQueueSize=0,this.onOverflow)try{this.onOverflow(t)}catch{}}startBatch(){this._batchDepth++,this._isBatching=!0}endBatch(){this._batchDepth!==0&&--this._batchDepth===0&&(this._flushSync(),this._isBatching=!1)}setMaxFlushIterations(t){if(t<p.MIN_FLUSH_ITERATIONS)throw new F(`Max flush iterations must be at least ${p.MIN_FLUSH_ITERATIONS}`);this._maxFlushIterations=t}},N=new Et,X=Symbol.for("atom-effect/atom"),rt=Symbol.for("atom-effect/computed"),ot=Symbol.for("atom-effect/effect"),dt=Symbol.for("atom-effect/writable"),c={current:null,run(t,s){const e=this.current;this.current=t;try{return s()}finally{this.current=e}}};function pt(t){const s=c.current;if(s===null)return t();c.current=null;try{return t()}finally{c.current=s}}var It=class extends B{constructor(t,s){super(),this[X]=!0,this[dt]=!0,this._value=t,this._pendingOldValue=void 0,s&&(this.flags|=d.SYNC),b.attachDebugInfo(this,"atom",this.id)}get value(){const t=c.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=z(this.version);const e=this._slots,i=this.flags;if(e==null||e.size===0||i&d.NOTIFICATION_SCHEDULED)return;this._pendingOldValue=s;const n=i|d.NOTIFICATION_SCHEDULED;if(this.flags=n,(n&d.SYNC)!==0&&!N.isBatching){this._flushNotifications();return}N.schedule(this)}execute(){this._flushNotifications()}_flushNotifications(){const t=this.flags;if(!(t&d.NOTIFICATION_SCHEDULED)||t&d.DISPOSED)return;const s=this._pendingOldValue;this._pendingOldValue=void 0,this.flags&=~d.NOTIFICATION_SCHEDULED,this._notifySubscribers(this._value,s)}peek(){return this._value}dispose(){this.flags&d.DISPOSED||(this._slots?.clear(),this.flags|=d.DISPOSED,this._value=void 0,this._pendingOldValue=void 0)}_deepDirtyCheck(){return!1}[Symbol.dispose](){this.dispose()}};function Ct(t,s={}){return new It(t,s.sync??!1)}var V=class extends Z{constructor(){super(),this._map=null,this._SCAN_THRESHOLD=32,this.hasComputeds=!1,this._depsHash=0,this._map=null,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 r=this._s0;if(r&&r.node===t&&r.unsub)return r.version=t.version,!0}case 1:if(e>1){const r=this._s1;if(r&&r.node===t&&r.unsub)return r.version=t.version,s!==1&&(this._s1=this._s0,this._s0=r),!0}case 2:if(e>2){const r=this._s2;if(r&&r.node===t&&r.unsub){if(r.version=t.version,s!==2){const l=s===0?this._s0:this._s1;s===0?this._s0=r:this._s1=r,this._s2=l}return!0}}case 3:if(e>3){const r=this._s3;if(r&&r.node===t&&r.unsub){if(r.version=t.version,s!==3){let l;s===0?(l=this._s0,this._s0=r):s===1?(l=this._s1,this._s1=r):(l=this._s2,this._s2=r),this._s3=l}return!0}}}const n=s>4?s:4,o=this._overflow;if(o)for(let r=n-4,l=o.length;r<l;r++){const _=o[r];if(_&&_.node===t&&_.unsub)return _.version=t.version,this._swapGeneral(r+4,s,_),!0}return!1}_claimViaMap(t,s){if(this._map===null){this._map=new Map;const n=this._count;s<4&&(s<=0&&this._s0?.unsub&&this._map.set(this._s0.node,0),s<=1&&this._s1?.unsub&&this._map.set(this._s1.node,1),s<=2&&this._s2?.unsub&&this._map.set(this._s2.node,2),s<=3&&this._s3?.unsub&&this._map.set(this._s3.node,3));const o=this._overflow;if(o&&n>4){const r=s>4?s:4;for(let l=r-4,_=o.length;l<_;l++){const U=o[l];U?.unsub&&this._map.set(U.node,l+4)}}}const e=this._map.get(t);if(e===void 0||e<s)return!1;const i=this.getAt(e);if(i==null||!i.unsub)return!1;if(i.version=t.version,e!==s){const n=this.getAt(s);this.setAt(s,i),this.setAt(e,n),n?.unsub&&this._map.set(n.node,e),this._map.set(t,s)}return!0}_swapGeneral(t,s,e){if(t===s)return;const i=this.getAt(s);if(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 n=this._overflow;n[t-4]=i}}insertNew(t,s){const e=this._count;if(t<e){const i=this.getAt(t);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(){const t=this._count;if(t===0){this._depsHash=0;return}const s=W.VERSION_BITS;let e=0;if(t>=1){const i=this._s0;e=e+(i.version<<s)+i.node.id|0}if(t>=2){const i=this._s1;e=e+(i.version<<s)+i.node.id|0}if(t>=3){const i=this._s2;e=e+(i.version<<s)+i.node.id|0}if(t>=4){const i=this._s3;e=e+(i.version<<s)+i.node.id|0}if(t>4){const i=this._overflow;for(let n=0,o=i.length;n<o;n++){const r=i[n];e=e+(r.version<<s)+r.node.id|0}}this._depsHash=e}isDirtyFast(){const t=this._count;if(t===0)return!1;const s=W.VERSION_BITS;let e=0;if(t>=1){const i=this._s0.node;e=e+(i.version<<s)+i.id|0}if(t>=2){const i=this._s1.node;e=e+(i.version<<s)+i.id|0}if(t>=3){const i=this._s2.node;e=e+(i.version<<s)+i.id|0}if(t>=4){const i=this._s3.node;e=e+(i.version<<s)+i.id|0}if(t>4){const i=this._overflow;for(let n=0,o=i.length;n<o;n++){const r=i[n].node;e=e+(r.version<<s)+r.id|0}}return e!==this._depsHash}disposeAll(){this._count>0&&this.truncateFrom(0),this.hasComputeds=!1,this._map!==null&&(this._map.clear(),this._map=null)}remove(t){throw new Error("remove() is strictly prohibited in DepSlotBuffer to preserve sequential cache paths.")}compact(){}};function Dt(t){return t!==null&&typeof t=="object"&&X in t}function vt(t){return t!==null&&typeof t=="object"&&rt in t}function St(t){return t!==null&&typeof t=="object"&&ot in t}function ht(t){return t!==null&&typeof t=="object"&&typeof t.then=="function"}var{IDLE:v,DIRTY:a,PENDING:A,RESOLVED:I,REJECTED:m,HAS_ERROR:O,RECOMPUTING:y,DISPOSED:Q,IS_COMPUTED:Y,FORCE_COMPUTE:$}=w,gt=class extends B{constructor(t,s={}){if(typeof t!="function")throw new g(u.COMPUTED_MUST_BE_FUNCTION);if(super(),this[X]=!0,this[rt]=!0,this._error=null,this._promiseId=0,this._deps=new V,this._asyncRetryCount=0,this._lastDriftEpoch=C.UNINITIALIZED,this._trackEpoch=C.UNINITIALIZED,this._trackCount=0,this._value=void 0,this.flags=Y|a|v,this._equal=s.equal??Object.is,this._fn=t,this._defaultValue="defaultValue"in s?s.defaultValue:P,this._onError=s.onError??null,this._maxAsyncRetries=(s.maxAsyncRetries??j.MAX_ASYNC_RETRIES)&q,b.attachDebugInfo(this,"computed",this.id),s.lazy===!1)try{this._recompute()}catch{}}_track(){c.current?.addDependency(this)}get value(){this._track();const t=this.flags;if((t&(I|a|v))===I)return this._value;if(t&Q)throw new g(u.COMPUTED_DISPOSED);if(t&y){if(this._defaultValue!==P)return this._defaultValue;throw new g(u.COMPUTED_CIRCULAR_DEPENDENCY)}if(t&(a|v)&&((t&v)===0&&(t&$)===0&&this._deps.size>0&&!this._isDirty()?this.flags&=~a:this._recompute(),this.flags&I))return this._value;const s=this._defaultValue,e=s!==P;if(this.flags&A){if(e)return s;throw new g(u.COMPUTED_ASYNC_PENDING_NO_DEFAULT)}if(this.flags&m){if(e)return s;throw this._error}return this._value}peek(){return this._value}get state(){this._track();const t=this.flags;return t&I?E.RESOLVED:t&A?E.PENDING:t&m?E.REJECTED:E.IDLE}get hasError(){if(this._track(),this.flags&(m|O))return!0;const t=this._deps;if(!t.hasComputeds)return!1;const s=t.size;for(let e=0;e<s;e++){const i=t.getAt(e);if(i!=null&&i.node.flags&O)return!0}return!1}get isValid(){return!this.hasError}get errors(){this._track();const t=[];this._error&&t.push(this._error);const s=this._deps;if(!s.hasComputeds)return t.length===0?K:Object.freeze(t);const e=s.size;for(let i=0;i<e;i++){const n=s.getAt(i);if(n==null)continue;const o=n.node;o.flags&O&&this._collectErrorsFromDep(o,t)}return t.length===0?K:Object.freeze(t)}_collectErrorsFromDep(t,s){const e=t.errors,i=e.length;for(let n=0;n<i;n++){const o=e[n];o!=null&&!s.includes(o)&&s.push(o)}}get lastError(){return this._track(),this._error}get isPending(){return this._track(),(this.flags&A)!==0}get isResolved(){return this._track(),(this.flags&I)!==0}invalidate(){this.flags|=$,this._markDirty()}dispose(){this.flags&Q||(this._deps.disposeAll(),this._slots?.clear(),this.flags=Q|a|v,this._error=null,this._value=void 0,this._hotIndex=-1)}[Symbol.dispose](){this.dispose()}addDependency(t){if(t._lastSeenEpoch===this._trackEpoch)return;t._lastSeenEpoch=this._trackEpoch;const s=this._trackCount,e=this._deps.getAt(s);if(e!=null&&e.node===t)e.version=t.version;else if(!this._deps.claimExisting(t,s)){const i=new M(t,t.version,t.subscribe(this));this._deps.insertNew(s,i)}t.flags&Y&&(this._deps.hasComputeds=!0),this._trackCount=s+1}_recompute(){if(this.flags&y)return;this.flags=(this.flags|y)&~$,this._trackEpoch=H(),this._trackCount=0,this._deps.prepareTracking(),this._hotIndex=-1;let t=!1;try{const s=c.run(this,this._fn);this._deps.truncateFrom(this._trackCount),this._deps.seal(),t=!0,ht(s)?this._handleAsyncComputation(s):this._finalizeResolution(s)}catch(s){if(!t)try{this._deps.truncateFrom(this._trackCount)}catch{}this._handleError(s,u.COMPUTED_COMPUTATION_FAILED,!0)}finally{this._trackEpoch=C.UNINITIALIZED,this._trackCount=0,this.flags&=~y}}_handleAsyncComputation(t){this.flags=(this.flags|A)&~(v|a|I|m),this._notifySubscribers(void 0,void 0),this._asyncRetryCount=0,this._promiseId=(this._promiseId+1)%j.MAX_PROMISE_ID;const s=this._promiseId;t.then(e=>{if(s===this._promiseId){if(this._isDirty()){const i=et();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.`),u.COMPUTED_ASYNC_COMPUTATION_FAILED)}this._finalizeResolution(e),this._notifySubscribers(e,void 0)}},e=>s===this._promiseId&&this._handleError(e,u.COMPUTED_ASYNC_COMPUTATION_FAILED))}_handleError(t,s,e=!1){const i=T(t,g,s);if(!e&&!(this.flags&m)&&(this.version=z(this.version)),this._error=i,this.flags=this.flags&~(v|a|A|I)|m|O,this._onError)try{this._onError(i)}catch(n){console.error(u.CALLBACK_ERROR_IN_ERROR_HANDLER,n)}if(e)throw i;this._notifySubscribers(void 0,void 0)}_finalizeResolution(t){(!(this.flags&I)||!this._equal(this._value,t))&&(this.version=z(this.version)),this._value=t,this._error=null,this.flags=(this.flags|I)&~(v|a|A|m|O)}execute(){this._markDirty()}_markDirty(){this.flags&(y|a)||(this.flags|=a,this._notifySubscribers(void 0,void 0))}_isDirty(){const t=this._deps;return t.hasComputeds?this._deepDirtyCheck():t.isDirtyFast()}_deepDirtyCheck(){const t=this._deps,s=c.current;c.current=null;try{const e=t.size;for(let i=0;i<e;i++){const n=t.getAt(i);if(n==null)continue;const o=n.node;if(o.flags&Y)try{o.value}catch{}if(o.version!==n.version)return this._hotIndex=i,!0}return this._hotIndex=-1,!1}finally{c.current=s}}};function mt(t,s={}){return new gt(t,s)}var Tt=class extends B{constructor(t,s={}){super(),this[ot]=!0,this._cleanup=null,this._deps=new V,this._currentEpoch=C.UNINITIALIZED,this._lastFlushEpoch=C.UNINITIALIZED,this._fn=t,this._onError=s.onError??null,this._sync=s.sync??!1,this._maxExecutions=s.maxExecutionsPerSecond??p.MAX_EXECUTIONS_PER_SECOND,this._maxExecutionsPerFlush=s.maxExecutionsPerFlush??p.MAX_EXECUTIONS_PER_EFFECT,this._cleanup=null,this._deps=new V,this._currentEpoch=C.UNINITIALIZED,this._lastFlushEpoch=C.UNINITIALIZED,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=()=>N.schedule(this),b.attachDebugInfo(this,"effect",this.id)}run(){if(this.flags&f.DISPOSED)throw new D(u.EFFECT_DISPOSED);this.execute(!0)}dispose(){this.flags&f.DISPOSED||(this.flags|=f.DISPOSED,this._execCleanup(),this._deps?.disposeAll())}[Symbol.dispose](){this.dispose()}addDependency(t){if(!(this.flags&f.EXECUTING))return;const s=this._currentEpoch;if(t._lastSeenEpoch===s)return;t._lastSeenEpoch=s;const e=this._trackCount,i=this._deps;let n;e===0?n=i._s0:e===1?n=i._s1:e===2?n=i._s2:e===3?n=i._s3:n=i.getAt(e),n!=null&&n.node===t?n.version=t.version:i.claimExisting(t,e)||this._insertNewDependency(t,e),t.flags&w.IS_COMPUTED&&(i.hasComputeds=!0),this._trackCount=e+1}_insertNewDependency(t,s){let e;try{const i=t.subscribe(this._notifyCallback);e=new M(t,t.version,i)}catch(i){const n=T(i,D,u.EFFECT_EXECUTION_FAILED);if(console.error(n),this._onError)try{this._onError(n)}catch{}e=new M(t,t.version,void 0)}this._deps.insertNew(s,e)}execute(t=!1){if(this.flags&(f.DISPOSED|f.EXECUTING))return;const s=this._deps;if(!t&&s.size>0&&!this._isDirty())return;this._checkInfiniteLoops(),this.flags|=f.EXECUTING,this._execCleanup(),this._currentEpoch=H(),this._trackCount=0,s.prepareTracking(),this._hotIndex=-1;let e=!1;try{const i=c.run(this,this._fn);s.truncateFrom(this._trackCount),s.seal(),e=!0,ht(i)?this._handleAsyncResult(i):this._cleanup=typeof i=="function"?i:null}catch(i){if(!e)try{s.truncateFrom(this._trackCount)}catch{}this._handleExecutionError(i),this._cleanup=null}finally{this.flags&=~f.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.flags&f.DISPOSED){if(typeof e=="function")try{e()}catch(i){this._handleExecutionError(i,u.EFFECT_CLEANUP_FAILED)}return}typeof e=="function"&&(this._cleanup=e)},e=>s===this._execId&&this._handleExecutionError(e))}_deepDirtyCheck(){const t=c.current;c.current=null;const s=this._deps;try{const e=s.size;for(let i=0;i<e;i++){const n=s.getAt(i);if(n==null)continue;const o=n.node;if(o.flags&w.IS_COMPUTED&&this._tryPullComputed(o),o.version!==n.version)return this._hotIndex=i,!0}return!1}finally{c.current=t}}_tryPullComputed(t){try{t.value}catch{}}_execCleanup(){if(this._cleanup){try{this._cleanup()}catch(t){this._handleExecutionError(t,u.EFFECT_CLEANUP_FAILED)}this._cleanup=null}}_checkInfiniteLoops(){const t=et();this._lastFlushEpoch!==t&&(this._lastFlushEpoch=t,this._executionsInEpoch=0),++this._executionsInEpoch>this._maxExecutionsPerFlush&&this._throwInfiniteLoopError("per-effect"),at()>p.MAX_EXECUTIONS_PER_FLUSH&&this._throwInfiniteLoopError("global"),this._executionCount++}_checkFrequencyLimit(){if(!Number.isFinite(this._maxExecutions))return;const t=Date.now();if(t-this._windowStart>=L.EFFECT_FREQUENCY_WINDOW){this._windowStart=t,this._windowCount=1;return}if(++this._windowCount>this._maxExecutions){const s=new D(u.EFFECT_FREQUENCY_LIMIT_EXCEEDED);throw this.dispose(),this._handleExecutionError(s),s}}get isDisposed(){return(this.flags&f.DISPOSED)!==0}get executionCount(){return this._executionCount}get isExecuting(){return(this.flags&f.EXECUTING)!==0}_throwInfiniteLoopError(t){const s=new D(`Infinite loop detected (${t}): effect executed ${this._executionsInEpoch} times in current flush. Total executions in flush: ${G}`);throw this.dispose(),console.error(s),s}_handleExecutionError(t,s=u.EFFECT_EXECUTION_FAILED){const e=T(t,D,s);if(console.error(e),this._onError)try{this._onError(e)}catch(i){console.error(T(i,D,u.CALLBACK_ERROR_IN_ERROR_HANDLER))}}};function Nt(t,s={}){if(typeof t!="function")throw new D(u.EFFECT_MUST_BE_FUNCTION);const e=new Tt(t,s);return e.execute(),e}function At(t){if(typeof t!="function")throw new TypeError(u.BATCH_CALLBACK_MUST_BE_FUNCTION);N.startBatch();try{return t()}finally{N.endBatch()}}h.AsyncState=E,h.AtomError=S,h.ComputedError=g,h.DEBUG_CONFIG=L,h.DEBUG_RUNTIME=b,h.EffectError=D,h.SCHEDULER_CONFIG=p,h.SchedulerError=F,h.atom=Ct,h.batch=At,h.computed=mt,h.effect=Nt,h.isAtom=Dt,h.isComputed=vt,h.isEffect=St,h.scheduler=N,h.untracked=pt});
2
2
 
3
3
  //# sourceMappingURL=atom-effect.min.js.map