@but212/atom-effect 0.16.0 → 0.16.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +10 -10
- package/dist/atom-effect.min.js +1 -1
- package/dist/atom-effect.min.js.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +17 -14
- package/dist/index.mjs +608 -604
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const ae={ONE_SECOND_MS:1e3},k={IDLE:"idle",PENDING:"pending",RESOLVED:"resolved",REJECTED:"rejected"},b={DISPOSED:1,HAS_FN_SUBS:2,HAS_OBJ_SUBS:4},I={...b,EXECUTING:8},o={...b,DIRTY:8,IDLE:16,PENDING:32,RESOLVED:64,REJECTED:128,RECOMPUTING:256,HAS_ERROR:512},O={...b,SYNC:8,NOTIFICATION_SCHEDULED:16},le={MAX_SIZE:1e3,WARMUP_SIZE:100},A={MAX_EXECUTIONS_PER_SECOND:1e3,CLEANUP_THRESHOLD:1e3,MAX_EXECUTIONS_PER_EFFECT:100,MAX_EXECUTIONS_PER_FLUSH:1e4,MAX_FLUSH_ITERATIONS:1e3,MIN_FLUSH_ITERATIONS:10,BATCH_QUEUE_SHRINK_THRESHOLD:1e3},Q={MAX_DEPENDENCIES:1e3,WARN_INFINITE_LOOP:!0},v=1073741823,M=typeof process<"u"&&process.env&&process.env.NODE_ENV!=="production",fe=Object.freeze([]);class R extends Error{constructor(e,t=null,s=!0){super(e),this.name="AtomError",this.cause=t,this.recoverable=s,this.timestamp=new Date}}class N extends R{constructor(e,t=null){super(e,t,!0),this.name="ComputedError"}}class x extends R{constructor(e,t=null){super(e,t,!1),this.name="EffectError"}}class B extends R{constructor(e,t=null){super(e,t,!1),this.name="SchedulerError"}}const f={COMPUTED_MUST_BE_FUNCTION:"Computed function must be a function",COMPUTED_ASYNC_PENDING_NO_DEFAULT:"Async computation is pending. No default value provided",COMPUTED_COMPUTATION_FAILED:"Computed computation failed",COMPUTED_ASYNC_COMPUTATION_FAILED:"Async computed computation failed",COMPUTED_CIRCULAR_DEPENDENCY:"Circular dependency detected during computation",COMPUTED_DISPOSED:"Cannot access a disposed computed",ATOM_SUBSCRIBER_MUST_BE_FUNCTION:"Subscription listener must be a function or Subscriber object",ATOM_INDIVIDUAL_SUBSCRIBER_FAILED:"Error during individual atom subscriber execution",EFFECT_MUST_BE_FUNCTION:"Effect function must be a function",EFFECT_EXECUTION_FAILED:"Effect execution failed",EFFECT_CLEANUP_FAILED:"Effect cleanup function execution failed",EFFECT_DISPOSED:"Cannot run a disposed effect",LARGE_DEPENDENCY_GRAPH:i=>`Large dependency graph detected: ${i} dependencies`,CALLBACK_ERROR_IN_ERROR_HANDLER:"Error occurred during onError callback execution"},X=Symbol("debugName"),Ee=Symbol("id"),Y=Symbol("type"),q=Symbol("noDefaultValue");function de(i){return"dependencies"in i&&Array.isArray(i.dependencies)}function se(i,e,t){if(!t.has(i.id)){if(t.add(i.id),i===e)throw new N("Indirect circular dependency detected");if(de(i)){const s=i.dependencies;for(let n=0;n<s.length;n++){const r=s[n];r&&se(r,e,t)}}}}const C={enabled:typeof process<"u"&&process.env?.NODE_ENV==="development",maxDependencies:Q.MAX_DEPENDENCIES,warnInfiniteLoop:Q.WARN_INFINITE_LOOP,warn(i,e){this.enabled&&i&&console.warn(`[Atom Effect] ${e}`)},checkCircular(i,e){if(i===e)throw new N("Direct circular dependency detected");this.enabled&&se(i,e,new Set)},attachDebugInfo(i,e,t){if(!this.enabled)return;const s=i;s[X]=`${e}_${t}`,s[Ee]=t,s[Y]=e},getDebugName(i){if(i!=null&&X in i)return i[X]},getDebugType(i){if(i!=null&&Y in i)return i[Y]}};let pe=1;const Se=()=>pe++;class ie{constructor(){this.flags=0,this.version=0,this._lastSeenEpoch=-1,this._modifiedAtEpoch=-1,this.id=Se()&v,this._tempUnsub=void 0}}class ne extends ie{subscribe(e){if(typeof e=="function")return this._addSubscriber(this._fnSubs,e,b.HAS_FN_SUBS);if(e!==null&&typeof e=="object"&&"execute"in e)return this._addSubscriber(this._objSubs,e,b.HAS_OBJ_SUBS);throw new R(f.ATOM_SUBSCRIBER_MUST_BE_FUNCTION)}_addSubscriber(e,t,s){return e.indexOf(t)!==-1?(M&&console.warn("Attempted to subscribe the same listener twice. Ignoring duplicate subscription."),()=>{}):(e.push(t),this.flags|=s,()=>{const n=e.indexOf(t);if(n===-1)return;const r=e.pop();n<e.length&&(e[n]=r),e.length===0&&(this.flags&=~s)})}subscriberCount(){return this._fnSubs.length+this._objSubs.length}_notifySubscribers(e,t){const s=this.flags;if(s&(b.HAS_FN_SUBS|b.HAS_OBJ_SUBS)){if(s&b.HAS_FN_SUBS){const n=this._fnSubs;for(let r=0;r<n.length;r++)try{n[r](e,t)}catch(h){this._handleNotifyError(h)}}if(s&b.HAS_OBJ_SUBS){const n=this._objSubs;for(let r=0;r<n.length;r++)try{n[r].execute()}catch(h){this._handleNotifyError(h)}}}}_handleNotifyError(e){console.error(new R(f.ATOM_INDIVIDUAL_SUBSCRIBER_FAILED,e))}}class ge{constructor(){this.frozen=0,this.tooLarge=0,this.poolFull=0}}class De{constructor(){this.acquired=0,this.released=0,this.rejected=new ge}}class ${constructor(){this.pool=[],this.maxPoolSize=50,this.maxReusableCapacity=256,this.stats=M?new De:null}acquire(){const e=this.stats;return e&&e.acquired++,this.pool.pop()??[]}release(e,t){const s=this.stats;if(t&&e===t)return;if(Object.isFrozen(e)){s&&s.rejected.frozen++;return}if(e.length>this.maxReusableCapacity){s&&s.rejected.tooLarge++;return}const n=this.pool;if(n.length>=this.maxPoolSize){s&&s.rejected.poolFull++;return}e.length=0,n.push(e),s&&s.released++}getStats(){const e=this.stats;if(!e)return null;const{acquired:t,released:s,rejected:n}=e,{frozen:r,tooLarge:h,poolFull:c}=n;return{acquired:t,released:s,rejected:{frozen:r,tooLarge:h,poolFull:c},leaked:t-s-(r+h+c),poolSize:this.pool.length}}reset(){this.pool.length=0;const e=this.stats;e&&(e.acquired=0,e.released=0,e.rejected.frozen=0,e.rejected.tooLarge=0,e.rejected.poolFull=0)}}const g=Object.freeze([]),F=Object.freeze([]),S=Object.freeze([]),P=new $,L=new $,T=new $;function U(i,e,t,s){if(e!=null){if(typeof e.addDependency=="function"){e.addDependency(i);return}if(typeof e=="function"){const n=e;t.indexOf(n)===-1&&(t.push(n),i.flags|=b.HAS_FN_SUBS);return}if(typeof e.execute=="function"){const n=e;s.indexOf(n)===-1&&(s.push(n),i.flags|=b.HAS_OBJ_SUBS)}}}function Ie(i,e,t,s){const n=e.length;if(n>0)for(let c=0;c<n;c++){const a=e[c];a&&(a._tempUnsub=t[c])}const r=i.length,h=L.acquire();h.length=r;for(let c=0;c<r;c++){const a=i[c];if(!a)continue;const E=a._tempUnsub;E?(h[c]=E,a._tempUnsub=void 0):(C.checkCircular(a,s),h[c]=a.subscribe(s))}if(n>0)for(let c=0;c<n;c++){const a=e[c];if(a){const E=a._tempUnsub;E&&(E(),a._tempUnsub=void 0)}}return t!==F&&L.release(t),h}let G=0;function re(){return G=G+1&v||1,G}function be(){return G}let J=0,K=0,z=!1;function W(){return z?(M&&console.warn("Warning: startFlush() called during flush - ignored to prevent infinite loop detection bypass"),!1):(z=!0,J=J+1&v||1,K=0,!0)}function Z(){z=!1}function Ce(){return z?++K:0}class Oe{constructor(){this._queueBuffer=[[],[]],this._bufferIndex=0,this._size=0,this._epoch=0,this._isProcessing=!1,this._isBatching=!1,this._batchDepth=0,this._batchQueue=[],this._batchQueueSize=0,this._isFlushingSync=!1,this._maxFlushIterations=A.MAX_FLUSH_ITERATIONS}get phase(){return this._isProcessing||this._isFlushingSync?2:this._isBatching?1:0}get queueSize(){return this._size}get isBatching(){return this._isBatching}schedule(e){if(M&&typeof e!="function")throw new B("Scheduler callback must be a function");const t=this._epoch;if(e._nextEpoch===t)return;if(e._nextEpoch=t,this._isBatching||this._isFlushingSync){this._batchQueue[this._batchQueueSize++]=e;return}const s=this._bufferIndex,n=this._size;this._queueBuffer[s][n]=e,this._size=n+1,this._isProcessing||this.flush()}flush(){this._isProcessing||this._size===0||(this._isProcessing=!0,queueMicrotask(()=>{try{if(this._size===0)return;const e=W();this._drainQueue(),e&&Z()}finally{this._isProcessing=!1,this._size>0&&!this._isBatching&&this.flush()}}))}flushSync(){this._isFlushingSync=!0;const e=W();try{this._mergeBatchQueue(),this._drainQueue()}finally{this._isFlushingSync=!1,e&&Z()}}_mergeBatchQueue(){const e=this._batchQueueSize;if(e===0)return;const t=++this._epoch,s=this._batchQueue,n=this._queueBuffer[this._bufferIndex];let r=this._size;for(let h=0;h<e;h++){const c=s[h];c._nextEpoch!==t&&(c._nextEpoch=t,n[r++]=c)}this._size=r,this._batchQueueSize=0,s.length>A.BATCH_QUEUE_SHRINK_THRESHOLD&&(s.length=0)}_drainQueue(){let e=0;const t=this._maxFlushIterations;for(;this._size>0;){if(++e>t){this._handleFlushOverflow();return}this._processQueue(),this._mergeBatchQueue()}}_processQueue(){const e=this._bufferIndex,t=this._queueBuffer[e],s=this._size;this._bufferIndex=e^1,this._size=0,this._epoch++,this._processJobs(t,s)}_handleFlushOverflow(){console.error(new B(`Maximum flush iterations (${this._maxFlushIterations}) exceeded. Possible infinite loop.`)),this._size=0,this._queueBuffer[this._bufferIndex].length=0,this._batchQueueSize=0}_processJobs(e,t){for(let s=0;s<t;s++)try{const n=e[s];n&&n()}catch(n){console.error(new B("Error occurred during scheduler execution",n))}e.length=0}startBatch(){this._batchDepth++,this._isBatching=!0}endBatch(){const e=this._batchDepth;if(e===0){M&&console.warn("endBatch() called without matching startBatch(). Ignoring.");return}const t=e-1;this._batchDepth=t,t===0&&(this.flushSync(),this._isBatching=!1)}setMaxFlushIterations(e){if(e<A.MIN_FLUSH_ITERATIONS)throw new B(`Max flush iterations must be at least ${A.MIN_FLUSH_ITERATIONS}`);this._maxFlushIterations=e}}const w=new Oe;class Ne{constructor(){this.current=null}run(e,t){const s=this.current;this.current=e;try{return t()}finally{this.current=s}}getCurrent(){return this.current}}const d=new Ne;function oe(i){if(typeof i!="function")throw new R("Untracked callback must be a function");const e=d.current;d.current=null;try{return i()}finally{d.current=e}}class ye extends ne{constructor(e,t){super(),this._value=e,this._pendingOldValue=void 0,this._notifyTask=void 0,this._fnSubs=[],this._objSubs=[],t&&(this.flags|=O.SYNC),C.attachDebugInfo(this,"atom",this.id)}get value(){const e=d.current;return e&&U(this,e,this._fnSubs,this._objSubs),this._value}set value(e){const t=this._value;if(t===e||Object.is(t,e))return;this._value=e,this.version=this.version+1&v,this.flags&(O.HAS_FN_SUBS|O.HAS_OBJ_SUBS)&&this._scheduleNotification(t)}_scheduleNotification(e){let t=this.flags;if(t&O.NOTIFICATION_SCHEDULED||(this._pendingOldValue=e,t|=O.NOTIFICATION_SCHEDULED,this.flags=t),t&O.SYNC&&!w.isBatching){this._flushNotifications();return}this._notifyTask||(this._notifyTask=()=>this._flushNotifications());const s=this._notifyTask;w.schedule(s)}_flushNotifications(){const e=this.flags;if(!(e&O.NOTIFICATION_SCHEDULED)||e&O.DISPOSED)return;const t=this._pendingOldValue;this._pendingOldValue=void 0,this.flags=e&-17,this._notifySubscribers(this._value,t)}peek(){return this._value}dispose(){const e=this.flags;e&O.DISPOSED||(this._fnSubs.length=0,this._objSubs.length=0,this.flags=e|O.DISPOSED,this._value=void 0,this._pendingOldValue=void 0,this._notifyTask=void 0)}}function Te(i,e={}){return new ye(i,e.sync??!1)}function V(i,e,t){if(i instanceof TypeError)return new e(`Type error (${t}): ${i.message}`,i);if(i instanceof ReferenceError)return new e(`Reference error (${t}): ${i.message}`,i);if(i instanceof R)return i;const s=i instanceof Error?i.message:String(i),n=i instanceof Error?i:null;return new e(`Unexpected error (${t}): ${s}`,n)}function ce(i){return i!==null&&typeof i=="object"&&"value"in i&&typeof i.subscribe=="function"}function Ae(i){return C.enabled&&i!=null&&typeof i=="object"&&C.getDebugType(i)==="computed"?!0:ce(i)&&typeof i.invalidate=="function"}function Re(i){return i!==null&&typeof i=="object"&&typeof i.dispose=="function"&&typeof i.run=="function"}function he(i){return i!=null&&typeof i.then=="function"}const ue=o.RESOLVED|o.PENDING|o.REJECTED,j=Array(ue+1).fill(k.IDLE);j[o.RESOLVED]=k.RESOLVED;j[o.PENDING]=k.PENDING;j[o.REJECTED]=k.REJECTED;const ee=3,te=Number.MAX_SAFE_INTEGER-1;class _e extends ne{constructor(e,t={}){if(typeof e!="function")throw new N(f.COMPUTED_MUST_BE_FUNCTION);if(super(),this._value=void 0,this.flags=o.DIRTY|o.IDLE,this._error=null,this._promiseId=0,this._equal=t.equal??Object.is,this._fn=e,this._defaultValue="defaultValue"in t?t.defaultValue:q,this._onError=t.onError??null,this._fnSubs=[],this._objSubs=[],this._dependencies=g,this._dependencyVersions=S,this._unsubscribes=F,this._cachedErrors=null,this._errorCacheEpoch=-1,this._asyncStartAggregateVersion=0,this._asyncRetryCount=0,this._trackEpoch=-1,this._trackDeps=g,this._trackVersions=S,this._trackCount=0,C.attachDebugInfo(this,"computed",this.id),C.enabled){const s=this;s.subscriberCount=this.subscriberCount.bind(this),s.isDirty=()=>(this.flags&o.DIRTY)!==0,s.dependencies=this._dependencies}if(t.lazy===!1)try{this._recompute()}catch{}}get value(){const e=d.current;e&&U(this,e,this._fnSubs,this._objSubs);let t=this.flags;if((t&(o.RESOLVED|o.DIRTY|o.IDLE))===o.RESOLVED)return this._value;if(t&o.DISPOSED)throw new N(f.COMPUTED_DISPOSED);if(t&o.RECOMPUTING){const r=this._defaultValue;if(r!==q)return r;throw new N(f.COMPUTED_CIRCULAR_DEPENDENCY)}if(t&(o.DIRTY|o.IDLE)&&(this._recompute(),t=this.flags),t&o.RESOLVED)return this._value;const s=this._defaultValue,n=s!==q;if(t&o.PENDING){if(n)return s;throw new N(f.COMPUTED_ASYNC_PENDING_NO_DEFAULT)}if(t&o.REJECTED){const r=this._error;if(r?.recoverable&&n)return s;throw r}return this._value}peek(){return this._value}get state(){const e=d.current;return e&&U(this,e,this._fnSubs,this._objSubs),j[this.flags&ue]}get hasError(){const e=d.current;if(e&&U(this,e,this._fnSubs,this._objSubs),this.flags&(o.REJECTED|o.HAS_ERROR))return!0;const s=this._dependencies;for(let n=0,r=s.length;n<r;n++)if(s[n].flags&o.HAS_ERROR)return!0;return!1}get isValid(){return!this.hasError}get errors(){const e=d.current;if(e&&U(this,e,this._fnSubs,this._objSubs),!this.hasError)return fe;const t=be();if(this._errorCacheEpoch===t&&this._cachedErrors!==null)return this._cachedErrors;const s=new Set,n=this._error;n&&s.add(n);const r=this._dependencies;for(let c=0,a=r.length;c<a;c++){const E=r[c];if(E.flags&o.HAS_ERROR){const D=E.errors;if(D)for(let y=0,u=D.length;y<u;y++){const l=D[y];l&&s.add(l)}}}const h=Object.freeze(Array.from(s));return this._errorCacheEpoch=t,this._cachedErrors=h,h}get lastError(){const e=d.current;return e&&U(this,e,this._fnSubs,this._objSubs),this._error}get isPending(){const e=d.current;return e&&U(this,e,this._fnSubs,this._objSubs),(this.flags&o.PENDING)!==0}get isResolved(){const e=d.current;return e&&U(this,e,this._fnSubs,this._objSubs),(this.flags&o.RESOLVED)!==0}invalidate(){this._markDirty();const e=this._dependencyVersions;e!==S&&(T.release(e),this._dependencyVersions=S),this._errorCacheEpoch=-1,this._cachedErrors=null}dispose(){if(this.flags&o.DISPOSED)return;const t=this._unsubscribes;if(t!==F){for(let r=0,h=t.length;r<h;r++){const c=t[r];c&&c()}L.release(t),this._unsubscribes=F}const s=this._dependencies;s!==g&&(P.release(s),this._dependencies=g);const n=this._dependencyVersions;n!==S&&(T.release(n),this._dependencyVersions=S),this._fnSubs.length=0,this._objSubs.length=0,this.flags=o.DISPOSED|o.DIRTY|o.IDLE,this._error=null,this._value=void 0,this._promiseId=(this._promiseId+1)%te,this._cachedErrors=null,this._errorCacheEpoch=-1}addDependency(e){if(e._lastSeenEpoch===this._trackEpoch)return;e._lastSeenEpoch=this._trackEpoch;const t=this._trackCount,s=this._trackDeps,n=this._trackVersions;t<s.length?(s[t]=e,n[t]=e.version):(s.push(e),n.push(e.version)),this._trackCount=t+1}_commitDeps(e){const t=this._trackDeps,s=this._trackVersions,n=this._trackCount;t.length=n,s.length=n,this._unsubscribes=Ie(t,e,this._unsubscribes,this),this._dependencies=t,this._dependencyVersions=s}_recompute(){if(this.flags&o.RECOMPUTING)return;this.flags|=o.RECOMPUTING;const e=this._dependencies,t=this._dependencyVersions;this._trackEpoch=re(),this._trackDeps=P.acquire(),this._trackVersions=T.acquire(),this._trackCount=0;let s=!1;try{const n=d.run(this,this._fn);this._commitDeps(e),s=!0,he(n)?this._handleAsyncComputation(n):this._finalizeResolution(n)}catch(n){let r=n;if(!s)try{this._commitDeps(e),s=!0}catch(h){r=h}this._handleComputationError(r)}finally{s?(e!==g&&P.release(e),t!==S&&T.release(t)):(P.release(this._trackDeps),T.release(this._trackVersions)),this._trackEpoch=-1,this._trackDeps=g,this._trackVersions=S,this._trackCount=0,this.flags&=-257}}_handleAsyncComputation(e){this.flags=(this.flags|o.PENDING)&-217,this._notifySubscribers(void 0,void 0),this._asyncStartAggregateVersion=this._captureVersionSnapshot(),this._asyncRetryCount=0,this._promiseId=(this._promiseId+1)%te;const t=this._promiseId;e.then(s=>{if(t===this._promiseId){if(this._captureVersionSnapshot()!==this._asyncStartAggregateVersion){if(this._asyncRetryCount<ee){this._asyncRetryCount++,this._markDirty();return}this._handleAsyncRejection(new N(`Async drift threshold exceeded after ${ee} retries.`));return}this._finalizeResolution(s),this._notifySubscribers(s,void 0)}}).catch(s=>{t===this._promiseId&&this._handleAsyncRejection(s)})}_captureVersionSnapshot(){let e=0;const t=this._dependencies;for(let s=0,n=t.length;s<n;s++){const r=t[s];if(r){const h=r.version;e=((e<<5)-e|0)+h&v}}return e}_handleAsyncRejection(e){const t=V(e,N,f.COMPUTED_ASYNC_COMPUTATION_FAILED);this.flags&o.REJECTED||(this.version=this.version+1&v),this._error=t,this.flags=this.flags&-121|(o.REJECTED|o.HAS_ERROR);const s=this._onError;if(s)try{s(t)}catch(n){console.error(f.CALLBACK_ERROR_IN_ERROR_HANDLER,n)}this._notifySubscribers(void 0,void 0)}_finalizeResolution(e){(!(this.flags&o.RESOLVED)||!this._equal(this._value,e))&&(this.version=this.version+1&v),this._value=e,this._error=null,this.flags=(this.flags|o.RESOLVED)&-697,this._cachedErrors=null,this._errorCacheEpoch=-1}_handleComputationError(e){const t=V(e,N,f.COMPUTED_COMPUTATION_FAILED);this._error=t,this.flags=this.flags&-121|(o.REJECTED|o.HAS_ERROR);const s=this._onError;if(s)try{s(t)}catch(n){console.error(f.CALLBACK_ERROR_IN_ERROR_HANDLER,n)}throw t}execute(){this._markDirty()}_markDirty(){const e=this.flags;e&(o.RECOMPUTING|o.DIRTY)||(this.flags=e|o.DIRTY,this._notifySubscribers(void 0,void 0))}}Object.freeze(_e.prototype);function me(i,e={}){return new _e(i,e)}class Ue extends ie{constructor(e,t={}){super(),this._cleanup=null,this._dependencies=g,this._dependencyVersions=S,this._unsubscribes=F,this._nextDeps=null,this._nextVersions=null,this._nextUnsubs=null,this._executeTask=void 0,this._onError=t.onError??null,this._currentEpoch=-1,this._lastFlushEpoch=-1,this._executionsInEpoch=0,this._fn=e,this._sync=t.sync??!1,this._maxExecutions=t.maxExecutionsPerSecond??A.MAX_EXECUTIONS_PER_SECOND,this._maxExecutionsPerFlush=t.maxExecutionsPerFlush??A.MAX_EXECUTIONS_PER_EFFECT,this._trackModifications=t.trackModifications??!1,this._executionCount=0,this._historyPtr=0;const s=Number.isFinite(this._maxExecutions),n=s?Math.min(this._maxExecutions+1,A.MAX_EXECUTIONS_PER_SECOND+1):0;this._historyCapacity=n,this._history=M&&s&&n>0?new Array(n).fill(0):null,this._execId=0,C.attachDebugInfo(this,"effect",this.id)}run(){if(this.flags&I.DISPOSED)throw new x(f.EFFECT_DISPOSED);this.execute(!0)}dispose(){const e=this.flags;if(e&I.DISPOSED)return;if(this.flags=e|I.DISPOSED,this._cleanup){try{this._cleanup()}catch(r){this._handleExecutionError(r,f.EFFECT_CLEANUP_FAILED)}this._cleanup=null}const t=this._unsubscribes;if(t!==F){for(let r=0,h=t.length;r<h;r++){const c=t[r];c&&c()}L.release(t),this._unsubscribes=F}const s=this._dependencies;s!==g&&(P.release(s),this._dependencies=g);const n=this._dependencyVersions;n!==S&&(T.release(n),this._dependencyVersions=S),this._executeTask=void 0}addDependency(e){if(!(this.flags&I.EXECUTING))return;const s=this._currentEpoch;if(e._lastSeenEpoch===s)return;e._lastSeenEpoch=s;const n=this._nextDeps,r=this._nextVersions,h=this._nextUnsubs;n.push(e),r.push(e.version);const c=e._tempUnsub;if(c){h.push(c),e._tempUnsub=void 0;return}try{const a=this._sync,E=this._trackModifications,D=e.subscribe(()=>{if(E&&this.flags&I.EXECUTING&&(e._modifiedAtEpoch=this._currentEpoch),a){this.execute();return}this._executeTask||(this._executeTask=()=>this.execute());const y=this._executeTask;w.schedule(y)});h.push(D)}catch(a){console.error(V(a,x,f.EFFECT_EXECUTION_FAILED)),h.push(()=>{})}}execute(e=!1){if(this.flags&(I.DISPOSED|I.EXECUTING))return;if(!e){const u=this._dependencies,l=u.length;if(l>0){const _=this._dependencyVersions;let p=!1;for(let m=0;m<l;m++){const H=u[m];if(H.version!==_[m]){p=!0;break}if("value"in H)try{if(oe(()=>H.value),H.version!==_[m]){p=!0;break}}catch{p=!0;break}}if(!p)return}}const s=J;this._lastFlushEpoch!==s&&(this._lastFlushEpoch=s,this._executionsInEpoch=0),++this._executionsInEpoch>this._maxExecutionsPerFlush&&this._throwInfiniteLoopError("per-effect"),Ce()>A.MAX_EXECUTIONS_PER_FLUSH&&this._throwInfiniteLoopError("global"),this._executionCount++;const n=this._history;if(n){const u=Date.now(),l=this._historyPtr;n[l]=u;const _=(l+1)%this._historyCapacity;this._historyPtr=_;const p=n[_]||0;if(p>0&&u-p<ae.ONE_SECOND_MS){const m=new x("Effect executed too frequently within 1 second. Suspected infinite loop.");if(this.dispose(),this._handleExecutionError(m),M)throw m;return}}if(this.flags|=I.EXECUTING,this._cleanup){try{this._cleanup()}catch(u){this._handleExecutionError(u,f.EFFECT_CLEANUP_FAILED)}this._cleanup=null}const r=this._dependencies,h=this._dependencyVersions,c=this._unsubscribes;if(r!==g)for(let u=0,l=r.length;u<l;u++){const _=r[u];_&&(_._tempUnsub=c[u])}const a=P.acquire(),E=T.acquire(),D=L.acquire();this._nextDeps=a,this._nextVersions=E,this._nextUnsubs=D,this._currentEpoch=re();let y=!1;try{const u=d.run(this,this._fn);this._dependencies=a,this._dependencyVersions=E,this._unsubscribes=D,y=!0,this._checkLoopWarnings();const l=++this._execId;he(u)?u.then(_=>{if(l!==this._execId||this.flags&I.DISPOSED){if(typeof _=="function")try{_()}catch(p){this._handleExecutionError(p,f.EFFECT_CLEANUP_FAILED)}return}typeof _=="function"&&(this._cleanup=_)}).catch(_=>{l===this._execId&&this._handleExecutionError(_)}):this._cleanup=typeof u=="function"?u:null}catch(u){y=!0,this._handleExecutionError(u),this._cleanup=null}finally{if(this._nextDeps=null,this._nextVersions=null,this._nextUnsubs=null,y){if(r!==g){for(let u=0,l=r.length;u<l;u++){const _=r[u],p=_?_._tempUnsub:void 0;p&&(p(),_&&(_._tempUnsub=void 0))}P.release(r)}h!==S&&T.release(h),c!==F&&L.release(c)}else{P.release(a),T.release(E);for(let u=0,l=D.length;u<l;u++){const _=D[u];_&&_()}if(L.release(D),r!==g)for(let u=0,l=r.length;u<l;u++){const _=r[u];_&&(_._tempUnsub=void 0)}}this.flags&=-9}}get isDisposed(){return(this.flags&I.DISPOSED)!==0}get executionCount(){return this._executionCount}get isExecuting(){return(this.flags&I.EXECUTING)!==0}_throwInfiniteLoopError(e){const t=new x(`Infinite loop detected (${e}): effect executed ${this._executionsInEpoch} times in current flush. Total executions in flush: ${K}`);throw this.dispose(),console.error(t),t}_handleExecutionError(e,t=f.EFFECT_EXECUTION_FAILED){const s=V(e,x,t);console.error(s);const n=this._onError;if(n)try{n(s)}catch(r){console.error(V(r,x,f.CALLBACK_ERROR_IN_ERROR_HANDLER))}}_checkLoopWarnings(){if(this._trackModifications&&C.enabled){const e=this._dependencies,t=this._currentEpoch;for(let s=0,n=e.length;s<n;s++){const r=e[s];r&&r._modifiedAtEpoch===t&&C.warn(!0,`Effect is reading a dependency (${C.getDebugName(r)||"unknown"}) that it just modified. Infinite loop may occur`)}}}}function xe(i,e={}){if(typeof i!="function")throw new x(f.EFFECT_MUST_BE_FUNCTION);const t=new Ue(i,e);return t.execute(),t}function Fe(i){if(typeof i!="function")throw new R("Batch callback must be a function");w.startBatch();try{return i()}finally{w.endBatch()}}exports.AsyncState=k;exports.AtomError=R;exports.ComputedError=N;exports.DEBUG_CONFIG=Q;exports.DEBUG_RUNTIME=C;exports.EffectError=x;exports.POOL_CONFIG=le;exports.SCHEDULER_CONFIG=A;exports.SchedulerError=B;exports.atom=Te;exports.batch=Fe;exports.computed=me;exports.effect=xe;exports.isAtom=ce;exports.isComputed=Ae;exports.isEffect=Re;exports.scheduler=w;exports.untracked=oe;
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const nt={ONE_SECOND_MS:1e3},F={IDLE:"idle",PENDING:"pending",RESOLVED:"resolved",REJECTED:"rejected"},C={DISPOSED:1,HAS_FN_SUBS:2,HAS_OBJ_SUBS:4},S={...C,EXECUTING:8},h={...C,DIRTY:8,IDLE:16,PENDING:32,RESOLVED:64,REJECTED:128,RECOMPUTING:256,HAS_ERROR:512},I={...C,SYNC:8,NOTIFICATION_SCHEDULED:16},rt={MAX_SIZE:1e3,WARMUP_SIZE:100},b={MAX_EXECUTIONS_PER_SECOND:1e3,CLEANUP_THRESHOLD:1e3,MAX_EXECUTIONS_PER_EFFECT:100,MAX_EXECUTIONS_PER_FLUSH:1e4,MAX_FLUSH_ITERATIONS:1e3,MIN_FLUSH_ITERATIONS:10,BATCH_QUEUE_SHRINK_THRESHOLD:1e3},G={MAX_DEPENDENCIES:1e3,WARN_INFINITE_LOOP:!0},m=1073741823,y=typeof process<"u"&&process.env&&process.env.NODE_ENV!=="production",ot=Object.freeze([]);class O extends Error{constructor(t,e=null,s=!0){super(t),this.name="AtomError",this.cause=e,this.recoverable=s,this.timestamp=new Date}}class D extends O{constructor(t,e=null){super(t,e,!0),this.name="ComputedError"}}class A extends O{constructor(t,e=null){super(t,e,!1),this.name="EffectError"}}class L extends O{constructor(t,e=null){super(t,e,!1),this.name="SchedulerError"}}const M=Symbol("debugName"),ct=Symbol("id"),B=Symbol("type"),H=Symbol("noDefaultValue");function ht(i){return"dependencies"in i&&Array.isArray(i.dependencies)}function J(i,t,e){if(!e.has(i.id)){if(e.add(i.id),i===t)throw new D("Indirect circular dependency detected");if(ht(i)){const s=i.dependencies;for(let n=0;n<s.length;n++){const r=s[n];r&&J(r,t,e)}}}}const g={enabled:typeof process<"u"&&process.env?.NODE_ENV==="development",maxDependencies:G.MAX_DEPENDENCIES,warnInfiniteLoop:G.WARN_INFINITE_LOOP,warn(i,t){this.enabled&&i&&console.warn(`[Atom Effect] ${t}`)},checkCircular(i,t){if(i===t)throw new D("Direct circular dependency detected");this.enabled&&J(i,t,new Set)},attachDebugInfo(i,t,e){if(!this.enabled)return;const s=i;s[M]=`${t}_${e}`,s[ct]=e,s[B]=t},getDebugName(i){if(i!=null&&M in i)return i[M]},getDebugType(i){if(i!=null&&B in i)return i[B]}};let ut=1;const lt=()=>ut++;function T(i,t,e){if(t==null)return;const s=t;if(typeof s.addDependency=="function"){s.addDependency(i);return}if(typeof t=="function"){const r=t,o=e.length;for(let l=0;l<o;l++)if(e[l].fn===r)return;e.push(new P(r)),i.flags|=C.HAS_FN_SUBS;return}const n=t;if(typeof n.execute=="function"){const r=e.length;for(let o=0;o<r;o++)if(e[o].sub===n)return;e.push(new P(void 0,n)),i.flags|=C.HAS_OBJ_SUBS}}function at(i,t,e){const s=t.length,n=i.length;if(s>0)for(let r=0;r<s;r++){const o=t[r];o&&(o.node._tempUnsub=o.unsub)}for(let r=0;r<n;r++){const o=i[r];if(!o)continue;const l=o.node,c=l._tempUnsub;c!==void 0?(o.unsub=c,l._tempUnsub=void 0):(g.checkCircular(l,e),o.unsub=l.subscribe(e))}if(s>0)for(let r=0;r<s;r++){const o=t[r];if(o){const l=o.node,c=l._tempUnsub;c!==void 0&&(c(),l._tempUnsub=void 0),o.unsub=void 0}}}class z{constructor(t,e,s=void 0){this.node=t,this.version=e,this.unsub=s}}class P{constructor(t,e){this.fn=t,this.sub=e}}const _={COMPUTED_MUST_BE_FUNCTION:"Computed function must be a function",COMPUTED_ASYNC_PENDING_NO_DEFAULT:"Async computation is pending. No default value provided",COMPUTED_COMPUTATION_FAILED:"Computed computation failed",COMPUTED_ASYNC_COMPUTATION_FAILED:"Async computed computation failed",COMPUTED_CIRCULAR_DEPENDENCY:"Circular dependency detected during computation",COMPUTED_DISPOSED:"Cannot access a disposed computed",ATOM_SUBSCRIBER_MUST_BE_FUNCTION:"Subscription listener must be a function or Subscriber object",ATOM_INDIVIDUAL_SUBSCRIBER_FAILED:"Error during individual atom subscriber execution",EFFECT_MUST_BE_FUNCTION:"Effect function must be a function",EFFECT_EXECUTION_FAILED:"Effect execution failed",EFFECT_CLEANUP_FAILED:"Effect cleanup function execution failed",EFFECT_DISPOSED:"Cannot run a disposed effect",LARGE_DEPENDENCY_GRAPH:i=>`Large dependency graph detected: ${i} dependencies`,CALLBACK_ERROR_IN_ERROR_HANDLER:"Error occurred during onError callback execution"};class ${constructor(){this.flags=0,this.version=0,this._lastSeenEpoch=-1,this._modifiedAtEpoch=-1,this.id=lt()&m,this._tempUnsub=void 0}}class K extends ${subscribe(t){const e=this._subscribers,s=typeof t=="function";if(!s&&(t===null||typeof t!="object"||typeof t.execute!="function"))throw new O(_.ATOM_SUBSCRIBER_MUST_BE_FUNCTION);const n=e.length;if(s){for(let o=0;o<n;o++)if(e[o].fn===t)return y&&console.warn("Attempted to subscribe the same listener twice. Ignoring duplicate subscription."),()=>{}}else for(let o=0;o<n;o++)if(e[o].sub===t)return y&&console.warn("Attempted to subscribe the same listener twice. Ignoring duplicate subscription."),()=>{};const r=s?new P(t):new P(void 0,t);return e.push(r),this.flags|=s?C.HAS_FN_SUBS:C.HAS_OBJ_SUBS,()=>{const o=e.indexOf(r);if(o===-1)return;const l=e.pop();o<e.length&&(e[o]=l);const c=e.length;if(c===0)this.flags&=-7;else{let a=!1,u=!1;for(let d=0;d<c&&(e[d].fn?a=!0:u=!0,!(a&&u));d++);let f=this.flags;a||(f&=-3),u||(f&=-5),this.flags=f}}}subscriberCount(){return this._subscribers.length}_notifySubscribers(t,e){if(!(this.flags&(C.HAS_FN_SUBS|C.HAS_OBJ_SUBS)))return;const n=this._subscribers,r=n.length;for(let o=0;o<r;o++){const l=n[o];try{l.fn?l.fn(t,e):l.sub&&l.sub.execute()}catch(c){this._handleNotifyError(c)}}}_handleNotifyError(t){console.error(new O(_.ATOM_INDIVIDUAL_SUBSCRIBER_FAILED,t))}}let x=0;function W(){return x=x+1&m||1,x}function ft(){return x}let V=0,X=0,v=!1;function Y(){return v?(y&&console.warn("Warning: startFlush() called during flush - ignored to prevent infinite loop detection bypass"),!1):(v=!0,V=V+1&m||1,X=0,!0)}function j(){v=!1}function _t(){return v?++X:0}class Et{constructor(){this._queueBuffer=[[],[]],this._bufferIndex=0,this._size=0,this._epoch=0,this._isProcessing=!1,this._isBatching=!1,this._batchDepth=0,this._batchQueue=[],this._batchQueueSize=0,this._isFlushingSync=!1,this._maxFlushIterations=b.MAX_FLUSH_ITERATIONS}get phase(){return this._isProcessing||this._isFlushingSync?2:this._isBatching?1:0}get queueSize(){return this._size}get isBatching(){return this._isBatching}schedule(t){if(y&&typeof t!="function")throw new L("Scheduler callback must be a function");const e=this._epoch;if(t._nextEpoch===e)return;if(t._nextEpoch=e,this._isBatching||this._isFlushingSync){this._batchQueue[this._batchQueueSize++]=t;return}const s=this._bufferIndex,n=this._size;this._queueBuffer[s][n]=t,this._size=n+1,this._isProcessing||this.flush()}flush(){this._isProcessing||this._size===0||(this._isProcessing=!0,queueMicrotask(()=>{try{if(this._size===0)return;const t=Y();this._drainQueue(),t&&j()}finally{this._isProcessing=!1,this._size>0&&!this._isBatching&&this.flush()}}))}flushSync(){this._isFlushingSync=!0;const t=Y();try{this._mergeBatchQueue(),this._drainQueue()}finally{this._isFlushingSync=!1,t&&j()}}_mergeBatchQueue(){const t=this._batchQueueSize;if(t===0)return;const e=++this._epoch,s=this._batchQueue,n=this._queueBuffer[this._bufferIndex];let r=this._size;for(let o=0;o<t;o++){const l=s[o];l._nextEpoch!==e&&(l._nextEpoch=e,n[r++]=l)}this._size=r,this._batchQueueSize=0,s.length>b.BATCH_QUEUE_SHRINK_THRESHOLD&&(s.length=0)}_drainQueue(){let t=0;const e=this._maxFlushIterations;for(;this._size>0;){if(++t>e){this._handleFlushOverflow();return}this._processQueue(),this._mergeBatchQueue()}}_processQueue(){const t=this._bufferIndex,e=this._queueBuffer[t],s=this._size;this._bufferIndex=t^1,this._size=0,this._epoch++,this._processJobs(e,s)}_handleFlushOverflow(){console.error(new L(`Maximum flush iterations (${this._maxFlushIterations}) exceeded. Possible infinite loop.`)),this._size=0,this._queueBuffer[this._bufferIndex].length=0,this._batchQueueSize=0}_processJobs(t,e){for(let s=0;s<e;s++)try{const n=t[s];n&&n()}catch(n){console.error(new L("Error occurred during scheduler execution",n))}t.length=0}startBatch(){this._batchDepth++,this._isBatching=!0}endBatch(){const t=this._batchDepth;if(t===0){y&&console.warn("endBatch() called without matching startBatch(). Ignoring.");return}const e=t-1;this._batchDepth=e,e===0&&(this.flushSync(),this._isBatching=!1)}setMaxFlushIterations(t){if(t<b.MIN_FLUSH_ITERATIONS)throw new L(`Max flush iterations must be at least ${b.MIN_FLUSH_ITERATIONS}`);this._maxFlushIterations=t}}const U=new Et;class dt{constructor(){this.current=null}run(t,e){const s=this.current;this.current=t;try{return e()}finally{this.current=s}}getCurrent(){return this.current}}const E=new dt;function Z(i){if(typeof i!="function")throw new O("Untracked callback must be a function");const t=E.current;E.current=null;try{return i()}finally{E.current=t}}class pt extends K{constructor(t,e){super(),this._value=t,this._pendingOldValue=void 0,this._notifyTask=void 0,this._subscribers=[],e&&(this.flags|=I.SYNC),g.attachDebugInfo(this,"atom",this.id)}get value(){const t=E.current;return t&&T(this,t,this._subscribers),this._value}set value(t){const e=this._value;if(e===t||Object.is(e,t))return;this._value=t,this.version=this.version+1&m;let s=this.flags;if(s&(I.HAS_FN_SUBS|I.HAS_OBJ_SUBS)){if(s&I.NOTIFICATION_SCHEDULED)return;if(this._pendingOldValue=e,s|=I.NOTIFICATION_SCHEDULED,this.flags=s,s&I.SYNC&&!U.isBatching){this._flushNotifications();return}this._notifyTask||(this._notifyTask=()=>this._flushNotifications()),U.schedule(this._notifyTask)}}_flushNotifications(){const t=this.flags;if(!(t&I.NOTIFICATION_SCHEDULED)||t&I.DISPOSED)return;const e=this._pendingOldValue;this._pendingOldValue=void 0,this.flags=t&-17,this._notifySubscribers(this._value,e)}peek(){return this._value}dispose(){const t=this.flags;t&I.DISPOSED||(this._subscribers.length=0,this.flags=t|I.DISPOSED,this._value=void 0,this._pendingOldValue=void 0,this._notifyTask=void 0)}}function St(i,t={}){return new pt(i,t.sync??!1)}class gt{constructor(){this.frozen=0,this.tooLarge=0,this.poolFull=0}}class It{constructor(){this.acquired=0,this.released=0,this.rejected=new gt}}class Dt{constructor(){this.pool=[],this.maxPoolSize=50,this.maxReusableCapacity=256,this.stats=y?new It:null}acquire(){const t=this.stats;return t&&t.acquired++,this.pool.pop()??[]}release(t,e){const s=this.stats;if(e&&t===e)return;if(Object.isFrozen(t)){s&&s.rejected.frozen++;return}if(t.length>this.maxReusableCapacity){s&&s.rejected.tooLarge++;return}const n=this.pool;if(n.length>=this.maxPoolSize){s&&s.rejected.poolFull++;return}t.length=0,n.push(t),s&&s.released++}getStats(){const t=this.stats;if(!t)return null;const{acquired:e,released:s,rejected:n}=t,{frozen:r,tooLarge:o,poolFull:l}=n;return{acquired:e,released:s,rejected:{frozen:r,tooLarge:o,poolFull:l},leaked:e-s-(r+o+l),poolSize:this.pool.length}}reset(){this.pool.length=0;const t=this.stats;t&&(t.acquired=0,t.released=0,t.rejected.frozen=0,t.rejected.tooLarge=0,t.rejected.poolFull=0)}}const p=Object.freeze([]),R=new Dt;function k(i,t,e){if(i instanceof TypeError)return new t(`Type error (${e}): ${i.message}`,i);if(i instanceof ReferenceError)return new t(`Reference error (${e}): ${i.message}`,i);if(i instanceof O)return i;const s=i instanceof Error?i.message:String(i),n=i instanceof Error?i:null;return new t(`Unexpected error (${e}): ${s}`,n)}function tt(i){return i!==null&&typeof i=="object"&&"value"in i&&typeof i.subscribe=="function"}function Ct(i){return g.enabled&&i!=null&&typeof i=="object"&&g.getDebugType(i)==="computed"?!0:tt(i)&&typeof i.invalidate=="function"}function bt(i){return i!==null&&typeof i=="object"&&typeof i.dispose=="function"&&typeof i.run=="function"}function et(i){return i!=null&&typeof i.then=="function"}const st=h.RESOLVED|h.PENDING|h.REJECTED,w=Array(st+1).fill(F.IDLE);w[h.RESOLVED]=F.RESOLVED;w[h.PENDING]=F.PENDING;w[h.REJECTED]=F.REJECTED;const Q=3,q=Number.MAX_SAFE_INTEGER-1;class it extends K{constructor(t,e={}){if(typeof t!="function")throw new D(_.COMPUTED_MUST_BE_FUNCTION);if(super(),this._value=void 0,this.flags=h.DIRTY|h.IDLE,this._error=null,this._promiseId=0,this._equal=e.equal??Object.is,this._fn=t,this._defaultValue="defaultValue"in e?e.defaultValue:H,this._onError=e.onError??null,this._subscribers=[],this._links=p,this._cachedErrors=null,this._errorCacheEpoch=-1,this._asyncStartAggregateVersion=0,this._asyncRetryCount=0,this._trackEpoch=-1,this._trackLinks=p,this._trackCount=0,g.attachDebugInfo(this,"computed",this.id),g.enabled){const s=this;s.subscriberCount=this.subscriberCount.bind(this),s.isDirty=()=>(this.flags&h.DIRTY)!==0,s.links=this._links}if(e.lazy===!1)try{this._recompute()}catch{}}get value(){const t=E.current;t&&T(this,t,this._subscribers);let e=this.flags;if((e&(h.RESOLVED|h.DIRTY|h.IDLE))===h.RESOLVED)return this._value;if(e&h.DISPOSED)throw new D(_.COMPUTED_DISPOSED);if(e&h.RECOMPUTING){const r=this._defaultValue;if(r!==H)return r;throw new D(_.COMPUTED_CIRCULAR_DEPENDENCY)}if(e&(h.DIRTY|h.IDLE)&&(this._recompute(),e=this.flags),e&h.RESOLVED)return this._value;const s=this._defaultValue,n=s!==H;if(e&h.PENDING){if(n)return s;throw new D(_.COMPUTED_ASYNC_PENDING_NO_DEFAULT)}if(e&h.REJECTED){const r=this._error;if(r?.recoverable&&n)return s;throw r}return this._value}peek(){return this._value}get state(){const t=E.current;return t&&T(this,t,this._subscribers),w[this.flags&st]}get hasError(){const t=E.current;if(t&&T(this,t,this._subscribers),this.flags&(h.REJECTED|h.HAS_ERROR))return!0;const s=this._links;for(let n=0,r=s.length;n<r;n++)if(s[n].node.flags&h.HAS_ERROR)return!0;return!1}get isValid(){return!this.hasError}get errors(){const t=E.current;if(t&&T(this,t,this._subscribers),!this.hasError)return ot;const e=ft();if(this._errorCacheEpoch===e&&this._cachedErrors!==null)return this._cachedErrors;const s=new Set,n=this._error;n&&s.add(n);const r=this._links;for(let l=0,c=r.length;l<c;l++){const a=r[l].node;if(a.flags&h.HAS_ERROR){const u=a.errors;if(u)for(let f=0,d=u.length;f<d;f++){const N=u[f];N&&s.add(N)}}}const o=Object.freeze(Array.from(s));return this._errorCacheEpoch=e,this._cachedErrors=o,o}get lastError(){const t=E.current;return t&&T(this,t,this._subscribers),this._error}get isPending(){const t=E.current;return t&&T(this,t,this._subscribers),(this.flags&h.PENDING)!==0}get isResolved(){const t=E.current;return t&&T(this,t,this._subscribers),(this.flags&h.RESOLVED)!==0}invalidate(){this._markDirty(),this._errorCacheEpoch=-1,this._cachedErrors=null}dispose(){if(this.flags&h.DISPOSED)return;const e=this._links;if(e!==p){for(let s=0,n=e.length;s<n;s++){const r=e[s];r?.unsub&&r.unsub()}R.release(e),this._links=p}this._subscribers.length=0,this.flags=h.DISPOSED|h.DIRTY|h.IDLE,this._error=null,this._value=void 0,this._promiseId=(this._promiseId+1)%q,this._cachedErrors=null,this._errorCacheEpoch=-1}addDependency(t){const e=this._trackEpoch;if(t._lastSeenEpoch===e)return;t._lastSeenEpoch=e;const s=this._trackCount,n=this._trackLinks;if(s<n.length){const r=n[s];r.node=t,r.version=t.version}else n.push(new z(t,t.version));this._trackCount=s+1}_commitDeps(t){const e=this._trackLinks,s=this._trackCount;e.length=s,at(e,t,this),this._links=e}_recompute(){if(this.flags&h.RECOMPUTING)return;this.flags|=h.RECOMPUTING;const t=this._links;this._trackEpoch=W(),this._trackLinks=R.acquire(),this._trackCount=0;let e=!1;try{const s=E.run(this,this._fn);this._commitDeps(t),e=!0,et(s)?this._handleAsyncComputation(s):this._finalizeResolution(s)}catch(s){let n=s;if(!e)try{this._commitDeps(t),e=!0}catch(r){n=r}this._handleComputationError(n)}finally{e?t!==p&&R.release(t):R.release(this._trackLinks),this._trackEpoch=-1,this._trackLinks=p,this._trackCount=0,this.flags&=-257}}_handleAsyncComputation(t){this.flags=(this.flags|h.PENDING)&-217,this._notifySubscribers(void 0,void 0),this._asyncStartAggregateVersion=this._captureVersionSnapshot(),this._asyncRetryCount=0,this._promiseId=(this._promiseId+1)%q;const e=this._promiseId;t.then(s=>{if(e===this._promiseId){if(this._captureVersionSnapshot()!==this._asyncStartAggregateVersion){if(this._asyncRetryCount<Q){this._asyncRetryCount++,this._markDirty();return}this._handleAsyncRejection(new D(`Async drift threshold exceeded after ${Q} retries.`));return}this._finalizeResolution(s),this._notifySubscribers(s,void 0)}}).catch(s=>{e===this._promiseId&&this._handleAsyncRejection(s)})}_captureVersionSnapshot(){let t=0;const e=this._links;for(let s=0,n=e.length;s<n;s++){const r=e[s].node.version;t=((t<<5)-t|0)+r&m}return t}_handleAsyncRejection(t){const e=k(t,D,_.COMPUTED_ASYNC_COMPUTATION_FAILED);this.flags&h.REJECTED||(this.version=this.version+1&m),this._error=e,this.flags=this.flags&-121|(h.REJECTED|h.HAS_ERROR);const s=this._onError;if(s)try{s(e)}catch(n){console.error(_.CALLBACK_ERROR_IN_ERROR_HANDLER,n)}this._notifySubscribers(void 0,void 0)}_finalizeResolution(t){(!(this.flags&h.RESOLVED)||!this._equal(this._value,t))&&(this.version=this.version+1&m),this._value=t,this._error=null,this.flags=(this.flags|h.RESOLVED)&-697,this._cachedErrors=null,this._errorCacheEpoch=-1}_handleComputationError(t){const e=k(t,D,_.COMPUTED_COMPUTATION_FAILED);this._error=e,this.flags=this.flags&-121|(h.REJECTED|h.HAS_ERROR);const s=this._onError;if(s)try{s(e)}catch(n){console.error(_.CALLBACK_ERROR_IN_ERROR_HANDLER,n)}throw e}execute(){this._markDirty()}_markDirty(){const t=this.flags;t&(h.RECOMPUTING|h.DIRTY)||(this.flags=t|h.DIRTY,this._notifySubscribers(void 0,void 0))}}Object.freeze(it.prototype);function Ot(i,t={}){return new it(i,t)}class Nt extends ${constructor(t,e={}){super(),this._cleanup=null,this._links=p,this._nextLinks=null,this._executeTask=void 0,this._onError=e.onError??null,this._currentEpoch=-1,this._lastFlushEpoch=-1,this._executionsInEpoch=0,this._fn=t,this._sync=e.sync??!1,this._maxExecutions=e.maxExecutionsPerSecond??b.MAX_EXECUTIONS_PER_SECOND,this._maxExecutionsPerFlush=e.maxExecutionsPerFlush??b.MAX_EXECUTIONS_PER_EFFECT,this._trackModifications=e.trackModifications??!1,this._executionCount=0,this._historyPtr=0;const s=Number.isFinite(this._maxExecutions),n=s?Math.min(this._maxExecutions+1,b.MAX_EXECUTIONS_PER_SECOND+1):0;this._historyCapacity=n,this._history=y&&s&&n>0?new Array(n).fill(0):null,this._execId=0,g.attachDebugInfo(this,"effect",this.id)}run(){if(this.flags&S.DISPOSED)throw new A(_.EFFECT_DISPOSED);this.execute(!0)}dispose(){const t=this.flags;if(t&S.DISPOSED)return;if(this.flags=t|S.DISPOSED,this._cleanup){try{this._cleanup()}catch(s){this._handleExecutionError(s,_.EFFECT_CLEANUP_FAILED)}this._cleanup=null}const e=this._links;if(e!==p){for(let s=0,n=e.length;s<n;s++){const r=e[s];r?.unsub&&r.unsub()}R.release(e),this._links=p}this._executeTask=void 0}addDependency(t){if(!(this.flags&S.EXECUTING))return;const s=this._currentEpoch;if(t._lastSeenEpoch===s)return;t._lastSeenEpoch=s;const n=this._nextLinks,r=t._tempUnsub;if(r){n.push(new z(t,t.version,r)),t._tempUnsub=void 0;return}try{const o=this._sync,l=this._trackModifications,c=t.subscribe(()=>{if(l&&this.flags&S.EXECUTING&&(t._modifiedAtEpoch=this._currentEpoch),o){this.execute();return}this._executeTask||(this._executeTask=()=>this.execute());const a=this._executeTask;U.schedule(a)});n.push(new z(t,t.version,c))}catch(o){console.error(k(o,A,_.EFFECT_EXECUTION_FAILED))}}execute(t=!1){if(this.flags&(S.DISPOSED|S.EXECUTING))return;if(!t){const c=this._links,a=c.length;if(a>0){let u=!1;for(let f=0;f<a;f++){const d=c[f],N=d.node;if(N.version!==d.version){u=!0;break}if("value"in N)try{if(Z(()=>N.value),N.version!==d.version){u=!0;break}}catch{u=!0;break}}if(!u)return}}const s=V;this._lastFlushEpoch!==s&&(this._lastFlushEpoch=s,this._executionsInEpoch=0),++this._executionsInEpoch>this._maxExecutionsPerFlush&&this._throwInfiniteLoopError("per-effect"),_t()>b.MAX_EXECUTIONS_PER_FLUSH&&this._throwInfiniteLoopError("global"),this._executionCount++;const n=this._history;if(n){const c=Date.now(),a=this._historyPtr;n[a]=c;const u=(a+1)%this._historyCapacity;this._historyPtr=u;const f=n[u]||0;if(f>0&&c-f<nt.ONE_SECOND_MS){const d=new A("Effect executed too frequently within 1 second. Suspected infinite loop.");if(this.dispose(),this._handleExecutionError(d),y)throw d;return}}if(this.flags|=S.EXECUTING,this._cleanup){try{this._cleanup()}catch(c){this._handleExecutionError(c,_.EFFECT_CLEANUP_FAILED)}this._cleanup=null}const r=this._links;if(r!==p)for(let c=0,a=r.length;c<a;c++){const u=r[c];u&&(u.node._tempUnsub=u.unsub)}const o=R.acquire();this._nextLinks=o,this._currentEpoch=W();let l=!1;try{const c=E.run(this,this._fn);this._links=o,l=!0,this._checkLoopWarnings();const a=++this._execId;et(c)?c.then(u=>{if(a!==this._execId||this.flags&S.DISPOSED){if(typeof u=="function")try{u()}catch(f){this._handleExecutionError(f,_.EFFECT_CLEANUP_FAILED)}return}typeof u=="function"&&(this._cleanup=u)}).catch(u=>{a===this._execId&&this._handleExecutionError(u)}):this._cleanup=typeof c=="function"?c:null}catch(c){l=!0,this._handleExecutionError(c),this._cleanup=null}finally{if(this._nextLinks=null,l){if(r!==p){for(let c=0,a=r.length;c<a;c++){const u=r[c],f=u?u.node._tempUnsub:void 0;f&&(f(),u&&(u.node._tempUnsub=void 0))}R.release(r)}}else{for(let c=0,a=o.length;c<a;c++){const u=o[c];u?.unsub&&u.unsub()}if(R.release(o),r!==p)for(let c=0,a=r.length;c<a;c++){const u=r[c];u&&(u.node._tempUnsub=void 0)}}this.flags&=-9}}get isDisposed(){return(this.flags&S.DISPOSED)!==0}get executionCount(){return this._executionCount}get isExecuting(){return(this.flags&S.EXECUTING)!==0}_throwInfiniteLoopError(t){const e=new A(`Infinite loop detected (${t}): effect executed ${this._executionsInEpoch} times in current flush. Total executions in flush: ${X}`);throw this.dispose(),console.error(e),e}_handleExecutionError(t,e=_.EFFECT_EXECUTION_FAILED){const s=k(t,A,e);console.error(s);const n=this._onError;if(n)try{n(s)}catch(r){console.error(k(r,A,_.CALLBACK_ERROR_IN_ERROR_HANDLER))}}_checkLoopWarnings(){if(this._trackModifications&&g.enabled){const t=this._links,e=this._currentEpoch;for(let s=0,n=t.length;s<n;s++){const o=t[s].node;o&&o._modifiedAtEpoch===e&&g.warn(!0,`Effect is reading a dependency (${g.getDebugName(o)||"unknown"}) that it just modified. Infinite loop may occur`)}}}}function Tt(i,t={}){if(typeof i!="function")throw new A(_.EFFECT_MUST_BE_FUNCTION);const e=new Nt(i,t);return e.execute(),e}function At(i){if(typeof i!="function")throw new O("Batch callback must be a function");U.startBatch();try{return i()}finally{U.endBatch()}}exports.AsyncState=F;exports.AtomError=O;exports.ComputedError=D;exports.DEBUG_CONFIG=G;exports.DEBUG_RUNTIME=g;exports.EffectError=A;exports.POOL_CONFIG=rt;exports.SCHEDULER_CONFIG=b;exports.SchedulerError=L;exports.atom=St;exports.batch=At;exports.computed=Ot;exports.effect=Tt;exports.isAtom=tt;exports.isComputed=Ct;exports.isEffect=bt;exports.scheduler=U;exports.untracked=Z;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|