@but212/atom-effect 0.31.0 → 0.32.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.
- package/README.md +21 -11
- package/dist/atom-effect.min.js +1 -1
- package/dist/atom-effect.min.js.map +1 -1
- package/dist/constants.d.ts +157 -0
- package/dist/constants.d.ts.map +1 -0
- package/dist/core/atom.d.ts +19 -0
- package/dist/core/atom.d.ts.map +1 -0
- package/dist/core/base.d.ts +136 -0
- package/dist/core/base.d.ts.map +1 -0
- package/dist/core/buffers.d.ts +113 -0
- package/dist/core/buffers.d.ts.map +1 -0
- package/dist/core/computed.d.ts +84 -0
- package/dist/core/computed.d.ts.map +1 -0
- package/dist/core/effect.d.ts +52 -0
- package/dist/core/effect.d.ts.map +1 -0
- package/dist/core/index.d.ts +8 -0
- package/dist/core/index.d.ts.map +1 -0
- package/dist/core/lens.d.ts +102 -0
- package/dist/core/lens.d.ts.map +1 -0
- package/dist/core/scheduler.d.ts +145 -0
- package/dist/core/scheduler.d.ts.map +1 -0
- package/dist/core/tracking.d.ts +123 -0
- package/dist/core/tracking.d.ts.map +1 -0
- package/dist/errors.d.ts +163 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +8 -488
- package/dist/index.d.ts.map +1 -0
- package/dist/index.mjs +1053 -937
- package/dist/index.mjs.map +1 -1
- package/dist/symbols.d.ts +30 -0
- package/dist/symbols.d.ts.map +1 -0
- package/dist/types.d.ts +259 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/utils/debug.d.ts +20 -0
- package/dist/utils/debug.d.ts.map +1 -0
- package/dist/utils/index.d.ts +13 -0
- package/dist/utils/index.d.ts.map +1 -0
- package/dist/utils/type-guards.d.ts +81 -0
- package/dist/utils/type-guards.d.ts.map +1 -0
- package/package.json +14 -13
package/dist/index.cjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});var h={DISPOSED:1,IS_COMPUTED:2,DIRTY:256,RECOMPUTING:512,HAS_ERROR:1024,FORCE_COMPUTE:2048,IDLE:65536,PENDING:1<<17,RESOLVED:1<<18,REJECTED:1<<19,ATOM_SYNC:1<<24,ATOM_NOTIFICATION_SCHEDULED:1<<25,EFFECT_EXECUTING:1<<28},kt=Object.freeze({ASYNC_STATE:h.IDLE|h.PENDING|h.RESOLVED|h.REJECTED,COMPUTED_DIRTY_MASK:h.DIRTY|h.RECOMPUTING|h.FORCE_COMPUTE}),U=Object.freeze({IDLE:"idle",PENDING:"pending",RESOLVED:"resolved",REJECTED:"rejected"}),v=Object.freeze({DISPOSED:h.DISPOSED,EXECUTING:h.EFFECT_EXECUTING}),W=Object.freeze({DISPOSED:h.DISPOSED,IS_COMPUTED:h.IS_COMPUTED,DIRTY:h.DIRTY,IDLE:h.IDLE,PENDING:h.PENDING,RESOLVED:h.RESOLVED,REJECTED:h.REJECTED,RECOMPUTING:h.RECOMPUTING,HAS_ERROR:h.HAS_ERROR,FORCE_COMPUTE:h.FORCE_COMPUTE}),D=Object.freeze({DISPOSED:h.DISPOSED,SYNC:h.ATOM_SYNC,NOTIFICATION_SCHEDULED:h.ATOM_NOTIFICATION_SCHEDULED}),p=Object.freeze({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}),X=1073741823,H=Object.freeze({WARN_INFINITE_LOOP:!0,EFFECT_FREQUENCY_WINDOW:1e3,LOOP_THRESHOLD:100}),Et=Object.freeze({MAX_PROMISE_ID:X}),x=Object.freeze({UNINITIALIZED:-1,MIN:1}),ct=!1;try{ct=!!(typeof globalThis<"u"&&globalThis.__ATOM_DEBUG__||typeof sessionStorage<"u"&&sessionStorage.getItem("__ATOM_DEBUG__")==="true")}catch{}var f=(typeof process<"u"&&process.env,typeof __DEV__<"u"&&!!__DEV__||ct),rt=Object.freeze([]),b=class j extends Error{constructor(e,s=null,i=!0,n){super(e),this.cause=s,this.recoverable=i,this.code=n,this.name="AtomError",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}getChain(){const e=this.cause;if(e==null)return[this];const s=[this];let i=e,n=null;for(;i!=null&&(s.push(i),!(i===this||n?.has(i)));){if(i instanceof j)i=i.cause;else if(i instanceof Error)i=i.cause;else break;s.length>3&&(n===null?n=new Set(s):n.add(i))}return s}toJSON(e){const s=e??new Set;if(s.has(this))return{name:this.name,message:"[Circular Reference]",recoverable:this.recoverable,code:this.code};s.add(this);let i=this.cause;return i instanceof j?i=i.toJSON(s):i instanceof Error&&(i={name:i.name,message:i.message,stack:i.stack,cause:i.cause}),{name:this.name,message:this.message,code:this.code,recoverable:this.recoverable,stack:this.stack,cause:i}}static format(e,s,i){return`${e} (${s}): ${i}`}},y=class extends b{constructor(...t){super(...t),this.name="ComputedError"}},m=class extends b{constructor(t,e=null,s=!1,i){super(t,e,s,i),this.name="EffectError"}},L=class extends b{constructor(t,e=null,s=!1,i){super(t,e,s,i),this.name="SchedulerError"}},l={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,e)=>`Maximum flush iterations (${t}) exceeded. ${e} jobs dropped. Possible infinite loop.`,CALLBACK_ERROR_IN_ERROR_HANDLER:"Exception encountered in onError handler",EFFECT_FREQUENCY_LIMIT_EXCEEDED:"Effect executed too frequently within 1 second. Suspected infinite loop.",SCHEDULER_CALLBACK_MUST_BE_FUNCTION:"Scheduler callback must be a function",SCHEDULER_END_BATCH_WITHOUT_START:"endBatch() called without matching startBatch(). Ignoring.",BATCH_CALLBACK_MUST_BE_FUNCTION:"Batch callback must be a function"};function w(t,e,s){return t instanceof b?new e(`${t.name} (${s}): ${t.message}`,t,t.recoverable,t.code):t instanceof Error?new e(`${t.name||"Error"} (${s}): ${t.message}`,t):new e(`Unexpected error (${s}): ${String(t)}`,t)}var ot=Symbol("AtomEffect.DebugName"),dt=Symbol("AtomEffect.Id"),ut=Symbol("AtomEffect.Type"),Q=Symbol("AtomEffect.NoDefaultValue"),pt="[Atom Effect]",z=()=>{},It=class{constructor(){this.enabled=!0,this.warnInfiniteLoop=H.WARN_INFINITE_LOOP,this._updateCounts=new Map,this._nodeRegistry=new Map,this._threshold=H.LOOP_THRESHOLD,this._cleanupScheduled=!1,this.warn=(t,e)=>{this.enabled&&t&&console.warn(`${pt} ${e}`)},this.registerNode=t=>{this._nodeRegistry.set(t.id,new WeakRef(t))},this.attachDebugInfo=(t,e,s,i)=>{if(!this.enabled)return;const n=t;n[ot]=i??`${e}_${s}`,n[dt]=s,n[ut]=e,this.registerNode(t)},this.trackUpdate=(t,e)=>{if(!this.enabled||!this.warnInfiniteLoop)return;const s=this._updateCounts,i=(s.get(t)??0)+1;i>this._threshold?this.warn(!0,`Infinite loop detected for ${e??`dependency ${t}`}. Over ${this._threshold} updates in a single execution scope.`):s.set(t,i),this._cleanupScheduled||(this._cleanupScheduled=!0,queueMicrotask(()=>{this._updateCounts.clear(),this._cleanupScheduled=!1}))},this.dumpGraph=()=>{const t=[];for(const[e,s]of this._nodeRegistry){const i=s.deref();i?t.push({id:e,name:this.getDebugName(i),type:this.getDebugType(i),updateCount:this._updateCounts.get(e)??0}):(this._nodeRegistry.delete(e),this._updateCounts.delete(e))}return t},this.getDebugName=t=>{if(t!=null)return t[ot]},this.getDebugType=t=>{if(t!=null)return t[ut]}}},Ct={enabled:!1,warnInfiniteLoop:!1,warn:z,registerNode:z,attachDebugInfo:z,trackUpdate:z,dumpGraph:()=>[],getDebugName:()=>{},getDebugType:()=>{}},E=f?new It:Ct,Dt=1,gt=()=>Dt++|0,_t=class{constructor(){this._count=0,this._actualCount=0,this._s0=null,this._s1=null,this._s2=null,this._s3=null,this._overflow=null,this._freeIndices=null}_rawWrite(t,e){if(t<4)t===0?this._s0=e:t===1?this._s1=e:t===2?this._s2=e:this._s3=e;else{this._overflow===null&&(this._overflow=[]);const s=this._overflow;s[t-4]=e}}_rawAdd(t){if(this._s0===null)return this._s0=t,0;if(this._s1===null)return this._s1=t,1;if(this._s2===null)return this._s2=t,2;if(this._s3===null)return this._s3=t,3;this._overflow===null&&(this._overflow=[]);const e=this._overflow,s=this._freeIndices;if(s!==null&&s.length>0){const i=s.pop();return e[i]=t,i+4}return e.push(t),3+e.length}_rawSwap(t,e){if(t===e)return;const s=this.getAt(t),i=this.getAt(e);this._rawWrite(t,i),this._rawWrite(e,s)}get size(){return this._actualCount}get physicalSize(){return this._count}getAt(t){if(t<4)return t===0?this._s0:t===1?this._s1:t===2?this._s2:t===3?this._s3:null;const e=this._overflow;return e===null?null:e[t-4]??null}setAt(t,e){const s=this.getAt(t);s!==e&&(this._rawWrite(t,e),s===null?this._actualCount++:e===null&&this._actualCount--,e!==null?t>=this._count&&(this._count=t+1):this._shrinkPhysicalSizeFrom(t))}_shrinkPhysicalSizeFrom(t){if(t===this._count-1){if(this._count--,this._count>4){const e=this._overflow;for(;this._count>4&&e[this._count-5]===null;)this._count--}this._count===4&&this._s3===null&&(this._count=3,this._s2===null&&(this._count=2,this._s1===null&&(this._count=1,this._s0===null&&(this._count=0))))}}truncateFrom(t){t<=3&&(t<=3&&this._s3!==null&&(this._onItemRemoved(this._s3),this._s3=null,this._actualCount--),t<=2&&this._s2!==null&&(this._onItemRemoved(this._s2),this._s2=null,this._actualCount--),t<=1&&this._s1!==null&&(this._onItemRemoved(this._s1),this._s1=null,this._actualCount--),t<=0&&this._s0!==null&&(this._onItemRemoved(this._s0),this._s0=null,this._actualCount--));const e=this._overflow;if(e!==null){const s=t>4?t-4:0,i=e.length;for(let n=s;n<i;n++){const r=e[n];r!=null&&(this._onItemRemoved(r),e[n]=null,this._actualCount--)}t<=4?this._overflow=null:e.length=t-4}this._count=t,this._actualCount<0&&(this._actualCount=0),this._freeIndices=null}_onItemRemoved(t){}add(t){const e=this._rawAdd(t);return e>=this._count&&(this._count=e+1),this._actualCount++,e}remove(t){let e=-1;if(this._s0===t)e=0;else if(this._s1===t)e=1;else if(this._s2===t)e=2;else if(this._s3===t)e=3;else{const s=this._overflow;s!==null&&(e=s.indexOf(t),e!==-1&&(e+=4))}return e!==-1?(this._rawWrite(e,null),this._shrinkPhysicalSizeFrom(e),this._actualCount--,e>=4&&(this._freeIndices===null&&(this._freeIndices=[]),this._freeIndices.push(e-4)),!0):!1}has(t){if(this._actualCount===0)return!1;if(this._s0===t||this._s1===t||this._s2===t||this._s3===t)return!0;const e=this._overflow;return e!==null?e.indexOf(t)!==-1:!1}forEach(t){const e=this._actualCount;if(e===0)return;if(e===this._count){if(t(this._s0),e>1&&(t(this._s1),e>2&&(t(this._s2),e>3&&(t(this._s3),e>4)))){const n=this._overflow;for(let r=0,o=n.length;r<o;r++)t(n[r])}return}let s=0;if(this._s0!==null&&(t(this._s0),++s>=e)||this._s1!==null&&(t(this._s1),++s>=e)||this._s2!==null&&(t(this._s2),++s>=e)||this._s3!==null&&(t(this._s3),++s>=e))return;const i=this._overflow;if(i!==null)for(let n=0,r=i.length;n<r;n++){const o=i[n];if(o!=null&&(t(o),++s>=e))return}}compact(){const t=this._actualCount;if(t===this._count)return;if(t===0){this.clear();return}let e=0;const s=this._count;for(let i=0;i<s;i++){const n=this.getAt(i);if(n!==null&&(i!==e&&(this._rawWrite(e,n),this._rawWrite(i,null)),e++,e===t))break}this._count=t,this._overflow!==null&&(e<=4?this._overflow=null:this._overflow.length=e-4),this._freeIndices=null}clear(){this._s0=this._s1=this._s2=this._s3=null,this._count=0,this._actualCount=0,this._overflow=null,this._freeIndices=null}dispose(){this.clear()}},ft=class extends _t{constructor(...t){super(...t),this._map=null,this._SCAN_THRESHOLD=32,this.hasComputeds=!1}prepareTracking(){this.hasComputeds=!1}_onItemRemoved(t){t.unsub?.()}setAt(t,e){const s=this.getAt(t);super.setAt(t,e),this._map!==null&&(s!==null&&this._map.delete(s.node),e!==null&&this._map.set(e.node,t))}claimExisting(t,e){const s=this._count;if(s<=e)return!1;let i=null;if(e<4?e===0?i=this._s0:e===1?i=this._s1:e===2?i=this._s2:i=this._s3:i=this._overflow[e-4]??null,i&&i.node===t&&i.unsub)return i.version=t.version,!0;if(this._map!==null||s-e>this._SCAN_THRESHOLD)return this._claimViaMap(t,e);let n=-1,r=null,o=e+1;for(;o<4&&o<s;o++){const u=o===1?this._s1:o===2?this._s2:this._s3;if(u&&u.node===t&&u.unsub){n=o,r=u;break}}if(n===-1&&o<s){const u=this._overflow;for(let c=o-4,C=s-4;c<C;c++){const d=u[c];if(d&&d.node===t&&d.unsub){n=c+4,r=d;break}}}return n!==-1?(r.version=t.version,this._rawWrite(e,r),this._rawWrite(n,i),!0):!1}_claimViaMap(t,e){this._map===null&&(this._map=this._initMap());const s=this._map,i=s.get(t);if(i===void 0||i<e)return!1;const n=this.getAt(i);if(n===null||!n.unsub)return!1;if(n.version=t.version,i!==e){const r=this.getAt(e);this._rawSwap(i,e),s.set(t,e),r?.unsub&&s.set(r.node,i)}return!0}_initMap(){const t=new Map;this._s0?.unsub&&t.set(this._s0.node,0),this._s1?.unsub&&t.set(this._s1.node,1),this._s2?.unsub&&t.set(this._s2.node,2),this._s3?.unsub&&t.set(this._s3.node,3);const e=this._overflow;if(e!==null)for(let s=0,i=e.length;s<i;s++){const n=e[s];n?.unsub&&t.set(n.node,s+4)}return t}insertNew(t,e){let s=null;if(t<4)t===0?(s=this._s0,this._s0=e):t===1?(s=this._s1,this._s1=e):t===2?(s=this._s2,this._s2=e):(s=this._s3,this._s3=e);else{this._overflow===null&&(this._overflow=[]);const i=this._overflow;s=i[t-4]??null,i[t-4]=e}if(s!==null){const i=this._rawAdd(s);i>=this._count&&(this._count=i+1),this._map!==null&&s.unsub&&this._map.set(s.node,i)}t>=this._count&&(this._count=t+1),this._actualCount++,this._map!==null&&e.unsub&&this._map.set(e.node,t)}add(t){const e=super.add(t);return this._map!==null&&t.unsub&&this._map.set(t.node,e),e}remove(t){throw new Error("remove() prohibited")}compact(){}truncateFrom(t){super.truncateFrom(t),this._map!==null&&(this._map=null)}disposeAll(){this.truncateFrom(0),this.hasComputeds=!1}},M=Symbol.for("atom-effect/brand"),I={Atom:1,Writable:2,Computed:4,Effect:8};function J(t,e){return!t||typeof t!="object"&&typeof t!="function"?!1:!!(t[M]&e)}function St(t){return J(t,I.Atom)}function vt(t){return J(t,I.Computed)}function Tt(t){return J(t,I.Effect)}function Z(t){return t instanceof Promise?!0:t===null||typeof t!="object"?!1:typeof t.then=="function"}var q=class{constructor(t,e,s=void 0){this.node=t,this.version=e,this.unsub=s}},mt=class{constructor(t=void 0,e=void 0){this.fn=t,this.sub=e}notify(t,e){const s=this.fn,i=this.sub;if(s===void 0&&i===void 0)return;const n=_,r=n.current;if(r===null){s!==void 0&&s(t,e),i!==void 0&&i.execute();return}n.current=null;try{s!==void 0&&s(t,e),i!==void 0&&i.execute()}finally{n.current=r}}},Ot=class{constructor(){this.current=null}run(t,e){if(this.current===t)return e();const s=this.current;this.current=t;try{if(!f)return e();const i=e();return E.warn(Z(i),'Detected Promise returned within tracking context. Dependencies accessed after "await" will NOT be tracked. Consider using synchronous tracking before the async boundary.'),i}finally{this.current=s}}},_=new Ot;function B(t){const e=_,s=e.current;if(s===null)return t();e.current=null;try{return t()}finally{e.current=s}}var tt=class{constructor(){this.flags=0,this.version=0,this._lastSeenEpoch=x.UNINITIALIZED,this._notifying=0,this._hotIndex=-1,this.id=gt()&X,this._nextEpoch=void 0,this._slots=null,this._deps=null}get isDisposed(){return(this.flags&W.DISPOSED)!==0}get isComputed(){return(this.flags&W.IS_COMPUTED)!==0}get hasError(){return!1}subscribe(t){const e=typeof t=="function";if(!e&&(t===null||typeof t.execute!="function"))throw w(new TypeError("Invalid subscriber"),b,l.ATOM_SUBSCRIBER_MUST_BE_FUNCTION);let s=this._slots;if(s===null&&(s=new _t,this._slots=s),s.size>0){let n=!1;if(s._s0!==null&&(s._s0.fn===t||s._s0.sub===t)||s._s1!==null&&(s._s1.fn===t||s._s1.sub===t)||s._s2!==null&&(s._s2.fn===t||s._s2.sub===t)||s._s3!==null&&(s._s3.fn===t||s._s3.sub===t))n=!0;else{const r=s._overflow;if(r!==null){const o=r.length;if(e)for(let u=0;u<o;u++){const c=r[u];if(c!==null&&c?.fn===t){n=!0;break}}else for(let u=0;u<o;u++){const c=r[u];if(c!==null&&c?.sub===t){n=!0;break}}}}if(n)return f&&console.warn(`[atom-effect] Duplicate subscription ignored on node ${this.id}`),()=>{}}const i=new mt(e?t:void 0,e?void 0:t);return s.add(i),()=>this._unsubscribe(i)}_unsubscribe(t){const e=this._slots;e!==null&&(e.remove(t),this._notifying===0&&e.compact())}subscriberCount(){const t=this._slots;return t===null?0:t.size}_notifySubscribers(t,e){const s=this._slots;if(!(s===null||s.size===0)){this._notifying++;try{if(s._s0!==null)try{s._s0.notify(t,e)}catch(n){this._logNotifyError(n)}if(s._s1!==null)try{s._s1.notify(t,e)}catch(n){this._logNotifyError(n)}if(s._s2!==null)try{s._s2.notify(t,e)}catch(n){this._logNotifyError(n)}if(s._s3!==null)try{s._s3.notify(t,e)}catch(n){this._logNotifyError(n)}const i=s._overflow;if(i!==null)for(let n=0,r=i.length;n<r;n++){const o=i[n];if(o!==null)try{o?.notify(t,e)}catch(u){this._logNotifyError(u)}}}finally{--this._notifying===0&&s.compact()}}}_logNotifyError(t){console.error(w(t,b,l.ATOM_INDIVIDUAL_SUBSCRIBER_FAILED))}_isDirty(){const t=this._deps;if(t===null||t.size===0)return!1;const e=this._hotIndex;if(e!==-1){const s=t.getAt(e);if(s!==null&&s.node.version!==s.version)return!0}return this._deepDirtyCheck()}},V=0;function et(){const t=V+1&X;return V=t===0?1:t,V}function K(t){const e=t+1&X;return e===0?1:e}var st=0,G=!1,at=0;function Nt(){return at}function ht(){return G?(f&&console.warn("startFlush() called during flush - ignored"),!1):(G=!0,at=et(),st=0,!0)}function lt(){G=!1}function bt(){if(!G)return 0;const t=++st;if(t<=p.MAX_EXECUTIONS_PER_FLUSH)return t;throw new Error(`[atom-effect] Infinite loop detected: flush execution count exceeded ${p.MAX_EXECUTIONS_PER_FLUSH}`)}var At=class{constructor(){this._bufferIndex=0,this._size=0,this._epoch=0,this._batchDepth=0,this._batchQueueSize=0,this._maxFlushIterations=p.MAX_FLUSH_ITERATIONS,this._isProcessing=!1,this._isFlushingSync=!1,this._buffer0=[],this._buffer1=[],this._batchQueue=[],this.onOverflow=null,this._boundRunLoop=this._runLoop.bind(this)}get queueSize(){return this._size+this._batchQueueSize}get isBatching(){return this._batchDepth>0}schedule(t){if(f&&typeof t!="function"&&(!t||typeof t.execute!="function"))throw new L(l.SCHEDULER_CALLBACK_MUST_BE_FUNCTION);const e=this._epoch;if(t._nextEpoch===e)return;if(t._nextEpoch=e,this._batchDepth>0||this._isFlushingSync){this._batchQueue[this._batchQueueSize++]=t;return}const s=this._bufferIndex===0?this._buffer0:this._buffer1;s[this._size++]=t,this._isProcessing||this._flush()}_flush(){this._isProcessing||this._size===0&&this._batchQueueSize===0||(this._isProcessing=!0,queueMicrotask(this._boundRunLoop))}_runLoop(){try{if(this._size===0&&this._batchQueueSize===0)return;const t=ht();this._drainQueue(),t&<()}finally{this._isProcessing=!1}}_flushSync(){if(this._size===0&&this._batchQueueSize===0)return;const t=this._isFlushingSync;this._isFlushingSync=!0;const e=ht();try{this._mergeBatchQueue(),this._drainQueue()}finally{this._isFlushingSync=t,e&<()}}_mergeBatchQueue(){const t=this._batchQueueSize;if(t===0)return;const e=++this._epoch|0,s=this._batchQueue,i=this._bufferIndex===0?this._buffer0:this._buffer1;let n=this._size;for(let r=0;r<t;r++){const o=s[r];o._nextEpoch!==e&&(o._nextEpoch=e,i[n++]=o),s[r]=void 0}this._size=n,this._batchQueueSize=0,s.length>p.BATCH_QUEUE_SHRINK_THRESHOLD&&(s.length=0)}_drainQueue(){let t=0;for(;this._size>0||this._batchQueueSize>0;){if(++t>this._maxFlushIterations){this._handleFlushOverflow();return}this._batchQueueSize>0&&this._mergeBatchQueue(),this._size>0&&this._processQueue()}}_processQueue(){const t=this._bufferIndex,e=t===0?this._buffer0:this._buffer1,s=this._size;this._bufferIndex=t^1,this._size=0,this._epoch=this._epoch+1|0;for(let i=0;i<s;i++){const n=e[i];e[i]=void 0;try{typeof n=="function"?n():n.execute()}catch(r){console.error(new L("Error occurred during scheduler execution",r))}}}_handleFlushOverflow(){const t=this._size+this._batchQueueSize;console.error(new L(l.SCHEDULER_FLUSH_OVERFLOW(this._maxFlushIterations,t))),this._size=0,this._buffer0.length=0,this._buffer1.length=0,this._batchQueueSize=0,this._batchQueue.length=0;const e=this.onOverflow;if(e)try{e(t)}catch{}}startBatch(){this._batchDepth++}endBatch(){if(this._batchDepth===0){f&&console.warn(l.SCHEDULER_END_BATCH_WITHOUT_START);return}--this._batchDepth===0&&(this._isFlushingSync||this._flushSync())}setMaxFlushIterations(t){if(t<p.MIN_FLUSH_ITERATIONS)throw new L(`Max iterations must be at least ${p.MIN_FLUSH_ITERATIONS}`);this._maxFlushIterations=t}},S=new At;function yt(t){if(f&&typeof t!="function")throw new TypeError(l.BATCH_CALLBACK_MUST_BE_FUNCTION);S.startBatch();try{return t()}finally{S.endBatch()}}var R=null;function wt(t){return t?new Promise((e,s)=>{S.schedule(()=>{try{t(),e()}catch(i){s(i)}})}):R||(R=new Promise(e=>{S.schedule(()=>{R=null,e()})}),R)}var Rt=class extends tt{constructor(t,e){super(),this[M]=I.Atom|I.Writable,this._value=t,this._equal=e.equal??Object.is,e.sync&&(this.flags|=D.SYNC),f&&E.attachDebugInfo(this,"atom",this.id,e.name)}get isNotificationScheduled(){return(this.flags&D.NOTIFICATION_SCHEDULED)!==0}get isSync(){return(this.flags&D.SYNC)!==0}get value(){const t=_.current;return t?.addDependency(this),this._value}set value(t){const e=this._value;if(this._equal(e,t))return;this._value=t,this.version=K(this.version),f&&E.trackUpdate(this.id,E.getDebugName(this));const s=this.flags,i=D.NOTIFICATION_SCHEDULED;if((s&i)!==0)return;const n=this._slots;if(n===null||n.size===0)return;this._pendingOldValue=e;const r=s|i;if(this.flags=r,(r&D.SYNC)!==0&&!S.isBatching){this._notifying===0&&this._flushNotifications();return}S.schedule(this)}execute(){this._flushNotifications()}_flushNotifications(){const t=D.NOTIFICATION_SCHEDULED,e=D.DISPOSED,s=D.SYNC,i=t|e;let n=this.flags;for(;(n&i)===t;){const r=this._pendingOldValue;this._pendingOldValue=void 0,this.flags=n&=~t;const o=this._value;if(this._equal(o,r)||this._notifySubscribers(o,r),n=this.flags,(n&s)===0||S.isBatching)break}}peek(){return this._value}dispose(){const t=this.flags,e=D.DISPOSED;(t&e)===0&&(this.flags=t|e,this._slots?.clear(),this._value=void 0,this._pendingOldValue=void 0,this._equal=Object.is)}_deepDirtyCheck(){return!1}};function Ft(t,e={}){return new Rt(t,e)}var{IDLE:T,DIRTY:a,PENDING:A,RESOLVED:g,REJECTED:O,HAS_ERROR:Y,RECOMPUTING:N,DISPOSED:k,IS_COMPUTED:F,FORCE_COMPUTE:$}=W,Ut=class extends tt{constructor(t,e={}){if(typeof t!="function")throw new y(l.COMPUTED_MUST_BE_FUNCTION);if(super(),this[M]=I.Atom|I.Computed,this._promiseId=0,this._trackEpoch=x.UNINITIALIZED,this._trackCount=0,this._error=null,this._deps=new ft,this._value=void 0,this.flags=F|a|T,this._equal=e.equal??Object.is,this._computation=t,this._defaultValue="defaultValue"in e?e.defaultValue:Q,this._onError=e.onError??null,E.attachDebugInfo(this,"computed",this.id,e.name),e.lazy===!1)try{this._recompute()}catch{}}get isDirty(){return(this.flags&a)!==0}get isRejected(){return(this.flags&O)!==0}get isRecomputing(){return(this.flags&N)!==0}get value(){const t=_.current;t!==null&&t.addDependency(this);const e=this.flags;if((e&(g|a|T|k|N))===g)return this._value;if((e&k)!==0)throw new y(l.COMPUTED_DISPOSED);if((e&N)!==0){const n=this._defaultValue;if(n!==Q)return n;throw new y(l.COMPUTED_CIRCULAR_DEPENDENCY)}if((e&(a|T))!==0){const n=this._deps;if((e&(T|$))!==0||n.size===0||this._isDirty()?this._recompute():this.flags&=~a,(this.flags&g)!==0)return this._value}const s=this._defaultValue,i=s!==Q;if((this.flags&A)!==0){if(i)return s;throw new y(l.COMPUTED_ASYNC_PENDING_NO_DEFAULT)}if((this.flags&O)!==0){if(i)return s;throw this._error}return this._value}peek(){return this._value}get state(){const t=_.current;t!==null&&t.addDependency(this);const e=this.flags;return(e&g)!==0?U.RESOLVED:(e&A)!==0?U.PENDING:(e&O)!==0?U.REJECTED:U.IDLE}get hasError(){const t=_.current;if(t!==null&&t.addDependency(this),(this.flags&(O|Y))!==0)return!0;const e=this._deps;return e.hasComputeds?B(()=>{const s=e.size;for(let i=0;i<s;i++)if(e.getAt(i)?.node.hasError)return!0;return!1}):!1}get isValid(){return!this.hasError}get errors(){const t=_.current;t!==null&&t.addDependency(this);const e=this._error,s=this._deps;if(!s.hasComputeds)return e===null?rt:Object.freeze([e]);const i=[];return e!==null&&i.push(e),B(()=>{const n=s.size;for(let r=0;r<n;r++){const o=s.getAt(r)?.node;o!==void 0&&(o.flags&F)!==0&&this._accumulateErrors(o,i)}}),i.length===0?rt:Object.freeze(i)}_accumulateErrors(t,e){const s=t._error;s!==null&&!e.includes(s)&&e.push(s);const i=t._deps;if(!i.hasComputeds)return;const n=i.size;for(let r=0;r<n;r++){const o=i.getAt(r)?.node;o!==void 0&&(o.flags&F)!==0&&this._accumulateErrors(o,e)}}get lastError(){const t=_.current;return t!==null&&t.addDependency(this),this._error}get isPending(){const t=_.current;return t!==null&&t.addDependency(this),(this.flags&A)!==0}get isResolved(){const t=_.current;return t!==null&&t.addDependency(this),(this.flags&g)!==0}invalidate(){this.flags|=$,this._markDirty()}dispose(){(this.flags&k)===0&&(this._deps.disposeAll(),this._slots!==null&&this._slots.clear(),this.flags=k|a|T,this._error=null,this._value=void 0,this._hotIndex=-1)}addDependency(t){const e=this._trackEpoch;if(t._lastSeenEpoch===e)return;t._lastSeenEpoch=e;const s=this._trackCount++,i=this._deps;let n=null;if(s<4)s===0?n=i._s0:s===1?n=i._s1:s===2?n=i._s2:n=i._s3;else{const r=i._overflow;r!==null&&(n=r[s-4]??null)}if(n!==null&&n.node===t)n.version=t.version;else if(!i.claimExisting(t,s)){const r=new q(t,t.version,t.subscribe(this));i.insertNew(s,r)}(t.flags&F)!==0&&(i.hasComputeds=!0)}_recompute(){if((this.flags&N)!==0)return;this.flags=(this.flags|N)&~$,this._trackEpoch=et(),this._trackCount=0,this._deps.prepareTracking(),this._hotIndex=-1;let t=!1;try{const e=_.run(this,this._computation);this._deps.truncateFrom(this._trackCount),t=!0,Z(e)?this._handleAsyncComputation(e):this._finalizeResolution(e)}catch(e){if(!t)try{this._deps.truncateFrom(this._trackCount)}catch(s){f&&console.warn("[atom-effect] _commitDeps failed during error recovery:",s)}this._handleError(e,l.COMPUTED_COMPUTATION_FAILED,!0)}finally{this._trackEpoch=x.UNINITIALIZED,this._trackCount=0,this.flags&=~N}}_handleAsyncComputation(t){this.flags=(this.flags|A)&~(T|a|g|O),this._notifySubscribers(void 0,void 0),this._promiseId=(this._promiseId+1)%Et.MAX_PROMISE_ID;const e=this._promiseId;t.then(s=>{if(e===this._promiseId){if(this._isDirty())return this._markDirty();this._finalizeResolution(s),this._notifySubscribers(s,void 0)}},s=>e===this._promiseId&&this._handleError(s,l.COMPUTED_ASYNC_COMPUTATION_FAILED))}_handleError(t,e,s=!1){const i=w(t,y,e);if((!this.isRejected||this._error!==i)&&(this.version=K(this.version)),this._error=i,this.flags=this.flags&~(T|a|A|g)|O|Y,this._onError)try{this._onError(i)}catch(n){console.error(l.CALLBACK_ERROR_IN_ERROR_HANDLER,n)}if(this._notifySubscribers(void 0,void 0),s)throw i}_finalizeResolution(t){const e=this.flags;((e&g)===0||!this._equal(this._value,t))&&(this.version=K(this.version)),this._value=t,this._error=null,this.flags=(e|g)&~(T|a|A|O|Y)}execute(){this._markDirty()}_markDirty(){const t=this.flags;(t&(N|a))===0&&(this.flags=t|a,E.trackUpdate(this.id,E.getDebugName(this)),this._notifySubscribers(void 0,void 0))}_deepDirtyCheck(){const t=this._deps,e=t.size,s=this._hotIndex;return B(()=>{if(s!==-1&&s<e){const i=t.getAt(s);if(i!==null&&this._checkLinkDirty(i))return!0}for(let i=0;i<e;i++){if(i===s)continue;const n=t.getAt(i);if(n!==null&&this._checkLinkDirty(n))return this._hotIndex=i,!0}return this._hotIndex=-1,!1})}_checkLinkDirty(t){const e=t.node;if((e.flags&F)!==0)try{e.value}catch{f&&console.warn(`[atom-effect] Dependency #${e.id} threw during check`)}return e.version!==t.version}};function Lt(t,e={}){return new Ut(t,e)}var Pt=class extends tt{constructor(t,e={}){super(),this[M]=I.Effect,this._currentEpoch=x.UNINITIALIZED,this._lastFlushEpoch=x.UNINITIALIZED,this._executionsInEpoch=0,this._executionCount=0,this._windowStart=0,this._windowCount=0,this._execId=0,this._trackCount=0,this._cleanup=null,this._deps=new ft,this._fn=t,this._onError=e.onError??null,this._sync=e.sync??!1,this._maxExecutions=e.maxExecutionsPerSecond??p.MAX_EXECUTIONS_PER_SECOND,this._maxExecutionsPerFlush=e.maxExecutionsPerFlush??p.MAX_EXECUTIONS_PER_EFFECT,this._sync?this._notifyCallback=()=>this.execute():this._notifyCallback=()=>S.schedule(this),E.attachDebugInfo(this,"effect",this.id,e.name)}run(){if(this.isDisposed)throw new m(l.EFFECT_DISPOSED);this.execute(!0)}dispose(){this.isDisposed||(this.flags|=v.DISPOSED,this._execCleanup(),this._deps?.disposeAll())}addDependency(t){if((this.flags&v.EXECUTING)===0||t._lastSeenEpoch===this._currentEpoch)return;t._lastSeenEpoch=this._currentEpoch;const e=this._trackCount++,s=this._deps,i=t.version;let n=null;if(e<4)e===0?n=s._s0:e===1?n=s._s1:e===2?n=s._s2:n=s._s3;else{const r=s._overflow;r!==null&&(n=r[e-4]??null)}n!==null&&n.node===t?n.version=i:s.claimExisting(t,e)||this._insertNewDependency(t,e,i),t.isComputed&&!s.hasComputeds&&(s.hasComputeds=!0)}_insertNewDependency(t,e,s){let i;try{i=new q(t,s,t.subscribe(this._notifyCallback))}catch(n){const r=w(n,m,l.EFFECT_EXECUTION_FAILED);if(console.error(r),this._onError)try{this._onError(r)}catch{}i=new q(t,s,void 0)}this._deps.insertNew(e,i)}execute(t=!1){const e=this.flags;if((e&(v.DISPOSED|v.EXECUTING))!==0)return;const s=this._deps;if(!t&&s.physicalSize>0&&!this._isDirty())return;this._checkInfiniteLoops(),E.trackUpdate(this.id,E.getDebugName(this)),this.flags=e|v.EXECUTING,this._execCleanup(),this._currentEpoch=et(),this._trackCount=0,s.prepareTracking(),this._hotIndex=-1;let i=!1;try{const n=_.run(this,this._fn);s.truncateFrom(this._trackCount),i=!0,typeof n=="function"?this._cleanup=n:Z(n)?this._handleAsyncResult(n):this._cleanup=null}catch(n){if(!i)try{s.truncateFrom(this._trackCount)}catch(r){f&&console.warn("[atom-effect] _commitDeps failed during error recovery:",r)}this._handleExecutionError(n),this._cleanup=null}finally{this.flags&=~v.EXECUTING}}_handleAsyncResult(t){const e=++this._execId;t.then(s=>{if(e!==this._execId||(this.flags&v.DISPOSED)!==0){if(typeof s=="function")try{s()}catch(i){this._handleExecutionError(i,l.EFFECT_CLEANUP_FAILED)}return}typeof s=="function"&&(this._cleanup=s)},s=>e===this._execId&&this._handleExecutionError(s))}_isDirty(){const t=this._deps,e=t.size;if(e===0)return!1;const s=this._hotIndex;if(s!==-1&&s<e){const i=t.getAt(s);if(i!==null){const n=i.node;if(!n.isComputed&&n.version!==i.version)return!0}}return this._deepDirtyCheck()}_deepDirtyCheck(){const t=this._deps,e=t.size,s=this._hotIndex,i=_.current;_.current=null;try{for(let n=0;n<e;n++){if(n===s)continue;const r=t.getAt(n);if(r===null)continue;const o=r.node;if(o.isComputed)try{o.value}catch{f&&console.warn(`[atom-effect] Dependency #${o.id} error in check`)}if(o.version!==r.version)return this._hotIndex=n,!0}return this._hotIndex=-1,!1}finally{_.current=i}}_execCleanup(){const t=this._cleanup;if(t!=null){this._cleanup=null;try{t()}catch(e){this._handleExecutionError(e,l.EFFECT_CLEANUP_FAILED)}}}_checkInfiniteLoops(){const t=Nt();this._lastFlushEpoch!==t&&(this._lastFlushEpoch=t,this._executionsInEpoch=0),++this._executionsInEpoch>this._maxExecutionsPerFlush&&this._throwInfiniteLoopError("per-effect"),bt()>p.MAX_EXECUTIONS_PER_FLUSH&&this._throwInfiniteLoopError("global"),this._executionCount++,f&&this._checkFrequencyLimit()}_checkFrequencyLimit(){if(!Number.isFinite(this._maxExecutions))return;const t=Date.now();if(t-this._windowStart>=H.EFFECT_FREQUENCY_WINDOW){this._windowStart=t,this._windowCount=1;return}if(++this._windowCount>this._maxExecutions){const e=new m(l.EFFECT_FREQUENCY_LIMIT_EXCEEDED);throw this.dispose(),this._handleExecutionError(e),e}}get executionCount(){return this._executionCount}get isExecuting(){return(this.flags&v.EXECUTING)!==0}_throwInfiniteLoopError(t){const e=new m(`Infinite loop detected (${t}): effect executed ${this._executionsInEpoch} times in current flush. Total executions in flush: ${st}`);throw this.dispose(),console.error(e),e}_handleExecutionError(t,e=l.EFFECT_EXECUTION_FAILED){const s=w(t,m,e);if(console.error(s),this._onError)try{this._onError(s)}catch(i){console.error(w(i,m,l.CALLBACK_ERROR_IN_ERROR_HANDLER))}}};function xt(t,e={}){if(typeof t!="function")throw new m(l.EFFECT_MUST_BE_FUNCTION);const s=new Pt(t,e);return s.execute(),s}function it(t,e,s,i){if(s===e.length)return i;const n=e[s];if(n==="__proto__"||n==="constructor"||n==="prototype")return t;const r=t!=null&&typeof t=="object"?t:{},o=r[n],u=it(o,e,s+1,i);if(Object.is(o,u))return t;if(Array.isArray(r)){const C=r.slice(),d=+n;return n.trim()!==""&&d>=0&&d%1===0?C[d]=u:C[n]=u,C}const c={...r};return c[n]=u,c}function P(t,e){let s=t;const i=e.length;for(let n=0;n<i;n++){if(s==null)return;const r=e[n];if(r==="__proto__"||r==="constructor"||r==="prototype")return;s=s[r]}return s}function nt(t,e){const s=e.includes(".")?e.split("."):[e],i=new Set;return{get value(){return P(t.value,s)},set value(r){const o=t.peek(),u=it(o,s,0,r);u!==o&&(t.value=u)},peek:()=>P(t.peek(),s),subscribe(r){let o=P(t.peek(),s);const u=t.subscribe(c=>{const C=P(c,s);if(!Object.is(C,o)){const d=o;o=C,r(C,d)}});return i.add(u),()=>{u(),i.delete(u)}},subscriberCount:()=>i.size,dispose:()=>{i.forEach(r=>r()),i.clear()},[M]:I.Atom|I.Writable}}var Mt=(t,e)=>nt(t,e),zt=t=>e=>nt(t,e);exports.AsyncState=U;exports.AtomError=b;exports.ComputedError=y;exports.DEBUG_CONFIG=H;exports.EffectError=m;exports.SCHEDULER_CONFIG=p;exports.SchedulerError=L;exports.aeNextTick=wt;exports.atom=Ft;exports.atomLens=nt;exports.batch=yt;exports.composeLens=Mt;exports.computed=Lt;exports.effect=xt;exports.getPathValue=P;exports.globalScheduler=S;exports.isAtom=St;exports.isComputed=vt;exports.isEffect=Tt;exports.lensFor=zt;exports.runtimeDebug=E;exports.setDeepValue=it;exports.untracked=B;
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});var E={CORE:0,COMPUTED:8,ASYNC:16,PRIMITIVE:24},c={DISPOSED:1<<E.CORE+0,IS_COMPUTED:1<<E.CORE+1,DIRTY:1<<E.COMPUTED+0,RECOMPUTING:1<<E.COMPUTED+1,HAS_ERROR:1<<E.COMPUTED+2,FORCE_COMPUTE:1<<E.COMPUTED+3,IDLE:1<<E.ASYNC+0,PENDING:1<<E.ASYNC+1,RESOLVED:1<<E.ASYNC+2,REJECTED:1<<E.ASYNC+3,ATOM_SYNC:1<<E.PRIMITIVE+0,ATOM_NOTIFICATION_SCHEDULED:1<<E.PRIMITIVE+1,EFFECT_EXECUTING:1<<E.PRIMITIVE+4},je=Object.freeze({ASYNC_STATE:c.IDLE|c.PENDING|c.RESOLVED|c.REJECTED,COMPUTED_DIRTY_MASK:c.DIRTY|c.RECOMPUTING|c.FORCE_COMPUTE}),k=Object.freeze({IDLE:"idle",PENDING:"pending",RESOLVED:"resolved",REJECTED:"rejected"}),N=Object.freeze({DISPOSED:c.DISPOSED,EXECUTING:c.EFFECT_EXECUTING}),U=Object.freeze({DISPOSED:c.DISPOSED,IS_COMPUTED:c.IS_COMPUTED,DIRTY:c.DIRTY,IDLE:c.IDLE,PENDING:c.PENDING,RESOLVED:c.RESOLVED,REJECTED:c.REJECTED,RECOMPUTING:c.RECOMPUTING,HAS_ERROR:c.HAS_ERROR,FORCE_COMPUTE:c.FORCE_COMPUTE}),g=Object.freeze({DISPOSED:c.DISPOSED,SYNC:c.ATOM_SYNC,NOTIFICATION_SCHEDULED:c.ATOM_NOTIFICATION_SCHEDULED}),T=Object.freeze({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}),Dt=1073741823,st=Object.freeze({WARN_INFINITE_LOOP:!0,EFFECT_FREQUENCY_WINDOW:1e3,LOOP_THRESHOLD:100}),M=Object.freeze({UNINITIALIZED:-1,MIN:1}),Xt=()=>{try{return!!(typeof globalThis<"u"&&globalThis.__ATOM_DEBUG__||typeof sessionStorage<"u"&&sessionStorage.getItem("__ATOM_DEBUG__")==="true")}catch{return!1}},Wt=()=>{try{return!1}catch{return!1}},V={node:typeof process<"u"&&process.env&&process.env.NODE_ENV!=="production",bundler:typeof __DEV__<"u"&&!!__DEV__,esm:typeof process>"u"&&Wt(),runtime:Xt()},d=V.node||V.bundler||V.esm||V.runtime,$t=Object.freeze([]),Kt=Symbol.for("atom-effect.Option"),Qt=Symbol.for("atom-effect.Result"),Xe=Object.freeze({ok:!1,value:void 0,[Kt]:!0}),We=Object.freeze({ok:!0,value:void 0,error:void 0,[Qt]:!0}),qt=[0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,-1],_=4,Jt=15,It=class{constructor(){this._count=0,this._actualCount=0,this._mask=0,this._s0=null,this._s1=null,this._s2=null,this._s3=null,this._overflow=null,this._freeIndices=null,this._lockCount=0,this._pendingCompact=!1}_firstFreeSlot(t){return qt[t&Jt]}_rawWrite(t,e){if(t<_){const s=1<<t;e===null?this._mask&=~s:this._mask|=s,t===0?this._s0=e:t===1?this._s1=e:t===2?this._s2=e:t===3&&(this._s3=e)}else this._overflow||(this._overflow=[]),this._overflow[t-_]=e}_rawAdd(t){const e=this._mask,s=this._firstFreeSlot(e);if(s!==-1)return this._mask=e|1<<s,s===0?this._s0=t:s===1?this._s1=t:s===2?this._s2=t:this._s3=t,s;this._overflow||(this._overflow=[]);const r=this._overflow,i=this._freeIndices;if(i?.length){const n=i.pop();return r[n]=t,n+_}return r.push(t),_-1+r.length}_rawSwap(t,e){if(t===e)return;const s=this.at(t),r=this.at(e);this._rawWrite(t,r),this._rawWrite(e,s)}get length(){return this._count}get size(){return this._actualCount}at(t){if(t<_)return t===0?this._s0:t===1?this._s1:t===2?this._s2:t===3?this._s3:null;const e=this._overflow;return e?e[t-_]??null:null}setAt(t,e){const s=this.at(t);s!==e&&(this._rawWrite(t,e),s===null?this._actualCount++:e===null&&this._actualCount--,e!==null?t>=this._count&&(this._count=t+1):this._shrinkPhysicalSizeFrom(t))}_shrinkPhysicalSizeFrom(t){if(t===this._count-1){if(this._count--,this._count>_){const e=this._overflow;for(;this._count>_&&e[this._count-(_+1)]==null;)this._count--}this._count<=_&&(this._count=32-Math.clz32(this._mask))}}truncateFrom(t){const e=this._count;if(!(t>=e)){for(let s=t;s<e;s++)this.at(s)!==null&&this._actualCount--;t<_?(this._mask&=(1<<t)-1,t<=0&&(this._s0=null),t<=1&&(this._s1=null),t<=2&&(this._s2=null),t<=3&&(this._s3=null),this._overflow=null):this._overflow&&(this._overflow.length=t-_),this._count=t,this._freeIndices=null}}push(t){const e=this._rawAdd(t);return e>=this._count&&(this._count=e+1),this._actualCount++,e}remove(t){if(this._actualCount===0)return!1;const e=this._mask;if(e&1&&this._s0===t)return this._removeAt(0);if(e&2&&this._s1===t)return this._removeAt(1);if(e&4&&this._s2===t)return this._removeAt(2);if(e&8&&this._s3===t)return this._removeAt(3);const s=this._overflow;if(s){for(let r=0,i=s.length;r<i;r++)if(s[r]===t)return s[r]=null,this._actualCount--,this._shrinkPhysicalSizeFrom(r+_),this._freeIndices||(this._freeIndices=[]),this._freeIndices.push(r),!0}return!1}_removeAt(t){return this._rawWrite(t,null),this._actualCount--,this._shrinkPhysicalSizeFrom(t),!0}has(t){if(this._actualCount===0)return!1;const e=this._mask;if(e&1&&this._s0===t||e&2&&this._s1===t||e&4&&this._s2===t||e&8&&this._s3===t)return!0;const s=this._overflow;if(s){for(let r=0,i=s.length;r<i;r++)if(s[r]===t)return!0}return!1}forEach(t){if(this._actualCount===0)return;const e=this._mask;e&1&&t(this._s0),e&2&&t(this._s1),e&4&&t(this._s2),e&8&&t(this._s3);const s=this._overflow;if(s)for(let r=0,i=s.length;r<i;r++){const n=s[r];n!=null&&t(n)}}some(t){if(this._actualCount===0)return!1;const e=this._mask;if(e&1&&t(this._s0)||e&2&&t(this._s1)||e&4&&t(this._s2)||e&8&&t(this._s3))return!0;const s=this._overflow;if(s)for(let r=0,i=s.length;r<i;r++){const n=s[r];if(n!=null&&t(n))return!0}return!1}compact(){if(this._lockCount>0){this._pendingCompact=!0;return}const t=this._actualCount,e=this._count;if(t===e)return;if(t===0){this.clear();return}let s=0;const r=this._overflow;for(let i=0;i<e;i++){const n=this.at(i);if(n!==null&&(i!==s&&(this._rawWrite(s,n),this._rawWrite(i,null)),++s===t))break}this._count=t,r!==null&&(s<=_?this._overflow=null:r.length=s-_),this._freeIndices=null,this._pendingCompact=!1}lock(){this._lockCount++}unlock(){--this._lockCount===0&&this._pendingCompact&&this.compact()}clear(){this._s0=this._s1=this._s2=this._s3=null,this._count=0,this._actualCount=0,this._mask=0,this._overflow=null,this._freeIndices=null,this._pendingCompact=!1}dispose(){this.clear()}get isLocked(){return this._lockCount>0}};function ut(t){return t instanceof Promise?!0:t===null||typeof t!="object"&&typeof t!="function"?!1:typeof t.then=="function"}var Zt=Object.prototype.hasOwnProperty;function te(t,e){if(t===e)return!0;if(t===null||e===null||typeof t!="object"||typeof e!="object")return!1;const s=t,r=e,i=Object.keys(s);if(i.length!==Object.keys(r).length)return!1;for(const n of i)if(!Zt.call(r,n)||!Object.is(s[n],r[n]))return!1;return!0}var v=class extends Error{constructor(t,e=null,s=!0,r){super(t),this.cause=e,this.recoverable=s,this.code=r,this.name="AtomError",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}getChain(){const t=[],e=new Set;let s=this;for(;s!=null&&!e.has(s);)t.push(s),e.add(s),s=s?.cause;return t}toJSON(t=new Set){return t.has(this)?{name:this.name,message:"[Circular Reference]",recoverable:this.recoverable,code:this.code}:(t.add(this),{name:this.name,message:this.message,code:this.code,recoverable:this.recoverable,stack:this.stack,cause:Tt(this.cause,t)})}static format(t,e,s){return`${t} (${e}): ${s}`}},y=class extends v{constructor(...t){super(...t),this.name="ComputedError"}},b=class extends v{constructor(t,e=null,s=!1,r){super(t,e,s,r),this.name="EffectError"}},K=class extends v{constructor(t,e=null,s=!1,r){super(t,e,s,r),this.name="SchedulerError"}},h={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,e)=>`Maximum flush iterations (${t}) exceeded. ${e} jobs dropped. Possible infinite loop.`,CALLBACK_ERROR_IN_ERROR_HANDLER:"Exception encountered in onError handler",EFFECT_FREQUENCY_LIMIT_EXCEEDED:"Effect executed too frequently within 1 second. Suspected infinite loop.",SCHEDULER_CALLBACK_MUST_BE_FUNCTION:"Scheduler callback must be a function",SCHEDULER_END_BATCH_WITHOUT_START:"endBatch() called without matching startBatch(). Ignoring.",BATCH_CALLBACK_MUST_BE_FUNCTION:"Batch callback must be a function"};function X(t,e,s){const r=ee(t);return new e(v.format(r.name,s,r.message),t,r.recoverable,r.code)}function ee(t){return t instanceof v?{name:t.name,message:t.message,recoverable:t.recoverable,code:t.code}:t instanceof Error?{name:t.name,message:t.message,recoverable:!0,code:t?.code}:{name:"Unexpected error",message:String(t),recoverable:!0,code:void 0}}function Tt(t,e){return t==null||typeof t!="object"?t:e.has(t)?"[Circular Reference]":t instanceof v?t.toJSON(e):t instanceof Error?(e.add(t),{name:t.name,message:t.message,stack:t.stack,cause:Tt(t.cause,e)}):t}var O=Symbol.for("atom-effect/brand"),l={Atom:1,Writable:2,Computed:4,Effect:8},rt=Symbol("AtomEffect.NoDefaultValue"),se={[l.Atom]:"atom",[l.Computed]:"computed",[l.Effect]:"effect"},re=l.Atom|l.Computed|l.Effect,Z="[Atom Effect]",F=()=>{},ie=class{constructor(){this.enabled=!0,this.warnInfiniteLoop=st.WARN_INFINITE_LOOP,this._updateCounts=new Map,this._registry=new Map,this.trackGraph=!1,this._finalizer=new FinalizationRegistry(t=>{this._registry.delete(t),this._updateCounts.delete(t)}),this._threshold=st.LOOP_THRESHOLD,this._cleanupScheduled=!1,this._failedEvaluations=new Set,this._failureCleanupScheduled=!1,this._resetUpdateCounts=()=>{this._updateCounts.clear(),this._cleanupScheduled=!1},this._resetFailedEvaluations=()=>{this._failedEvaluations.clear(),this._failureCleanupScheduled=!1}}warn(t,e){this.enabled&&t&&console.warn(`${Z} ${e}`)}registerNode(t){const e=t.id,s=this._getOrCreateMetadata(t,e);s.ref=new WeakRef(t),this._finalizer.register(t,e)}attachDebugInfo(t,e,s,r){if(!this.enabled||r===void 0&&!this.trackGraph)return;let i=this._registry.get(s);i?(r!==void 0&&(i.name=r),i.type=e):(i={name:r??`${e}_${s}`,type:e},this._registry.set(s,i)),this.registerNode(t)}trackUpdate(t,e){if(!this.enabled||!this.warnInfiniteLoop)return;const s=this._updateCounts,r=(s.get(t)||0)+1;s.set(t,r),r>this._threshold&&r===this._threshold+1&&console.warn(`${Z} Infinite loop detected for ${e??`dependency ${t}`}. Detected ${r} updates within a single execution scope, exceeding the threshold of ${this._threshold}.`),this._cleanupScheduled||(this._cleanupScheduled=!0,queueMicrotask(this._resetUpdateCounts))}trackEvaluationFailure(t){!this.enabled||this._failedEvaluations.has(t)||(this._failedEvaluations.add(t),console.warn(`${Z} Dependency #${t} evaluation failed during dirty check.`),this._failureCleanupScheduled||(this._failureCleanupScheduled=!0,queueMicrotask(this._resetFailedEvaluations)))}dumpGraph(){const t=this._registry;if(t.size===0)return[];const e=[],s=this._updateCounts;for(const[r,i]of t)this.trackGraph&&i.ref?.deref()===void 0||e.push({id:r,name:i.name,type:i.type,updateCount:s.get(r)??0});return e}getDebugName(t){if(!this.enabled||!t)return;const e=t.id;if(e===void 0)return;const s=this._registry.get(e);return s?s.name:`${this._getTypeFromBrand(t)??"unknown"}_${e}`}getDebugType(t){if(!this.enabled||!t)return;const e=t.id;if(e===void 0)return;const s=this._registry.get(e);return s?s.type:this._getTypeFromBrand(t)}_getOrCreateMetadata(t,e){let s=this._registry.get(e);if(!s){const r=this._getTypeFromBrand(t)??"unknown";s={name:`${r}_${e}`,type:r},this._registry.set(e,s)}return s}_getTypeFromBrand(t){const e=t[O];return e!==void 0?se[e&re]:void 0}},ne={enabled:!1,warnInfiniteLoop:!1,trackGraph:!1,warn:F,registerNode:F,attachDebugInfo:F,trackUpdate:F,dumpGraph:()=>[],getDebugName:()=>{},getDebugType:()=>{},trackEvaluationFailure:F},C=d?new ie:ne,oe=1,ue=()=>oe++,Q={get:()=>{},set:()=>{},delete:()=>{}},vt=class extends Map{};function Ot(){return{slots:new It,map:Q,hasComputeds:!1}}function mt(t){t.hasComputeds=!1}function Nt(t,e,s){const{slots:r}=t;if(r.length<=s)return!1;const i=r.at(s);if(i?.node===e&&i.unsub)return i.version=e.version,!0;const n=ce(t,e,s);if(n===-1)return!1;const o=r.at(n);o.version=e.version;const u=r.at(s);return it(t,s,o),it(t,n,u),!0}function ce(t,e,s){const r=t.map.get(e);if(r!==void 0)return r>=s?r:-1;const i=t.slots;for(let n=s+1,o=i.length;n<o;n++){const u=i.at(n);if(u?.node===e&&u.unsub)return n}return-1}function bt(t,e,s){const r=t.slots.at(e);it(t,e,s),r!==null&&ae(t,r)}function it(t,e,s){const r=t.slots.at(e);t.slots.setAt(e,s),r&&t.map.delete(r.node),s?.unsub&&(t.map===Q&&(t.map=new vt),t.map.set(s.node,e))}function ae(t,e){const s=t.slots.push(e);return e.unsub&&(t.map===Q&&(t.map=new vt),t.map.set(e.node,s)),s}var le={0:t=>t.node.version!==t.version,[U.IS_COMPUTED]:t=>{const e=t.node;try{e.value}catch{d&&C.trackEvaluationFailure(e.id)}return e.version!==t.version}};function B(t){const e=t.slots,s=e.length;if(e.size===0)return!1;const r=le;for(let i=0;i<s;i++){const n=e.at(i);if(n&&r[n.node.flags&U.IS_COMPUTED](n))return!0}return!1}function he(t){const e=t.slots,s=e.length;for(let r=0;r<s;r++){const i=e.at(r);if(!i)continue;const n=i.node;if(n.version!==i.version||(n.flags&U.DIRTY)!==0)return!0}return!1}function ct(t,e){const s=t.slots,r=s.length;for(let i=e;i<r;i++){const n=s.at(i);if(n){const o=n.unsub;if(o)try{o()}catch(u){d&&console.error("[atom-effect] Unsubscribe failed:",u)}}}s.truncateFrom(e),t.map=Q}function At(t){ct(t,0),t.hasComputeds=!1}function Rt(t,e,s=void 0){return{node:t,version:e,unsub:s}}function pt(t=void 0,e=void 0){return{fn:t,sub:e}}function fe(t,e,s){if(t!==null)try{const{fn:r,sub:i}=t;r!==void 0&&r(e,s),i!==void 0&&i.execute()}catch(r){console.error("[atom-effect] Subscriber failed:",r)}}function _e(){return{stack:[],current:null}}function at(t,e){t.stack.push(e),t.current=e}function yt(t){const e=t.stack;e.pop();const s=e.length;t.current=s>0?e[s-1]:null}function lt(t,e){const s=t.stack;s.length=e;const r=s.length;t.current=r>0?s[r-1]:null}function Ut(t,e,s){if(t.current===e)return s();at(t,e);try{return s()}finally{yt(t)}}function Ee(t){t.stack.length=0,t.current=null}var a=_e();function nt(t){if(a.current===null)return t();at(a,null);try{return t()}finally{yt(a)}}var ht=class{constructor(){this.flags=0,this.version=0,this._lastSeenEpoch=M.UNINITIALIZED,this._nextEpoch=void 0,this.id=ue()&Dt,this._slots=null,this._deps=null}get isDisposed(){return(this.flags&U.DISPOSED)!==0}get isComputed(){return(this.flags&U.IS_COMPUTED)!==0}get isNotifying(){return this._slots?.isLocked??!1}_hasFlag(t){return(this.flags&t)!==0}get hasError(){return!1}subscribe(t){let e;if(typeof t=="function"?e=pt(t,void 0):t!=null&&typeof t.execute=="function"&&(e=pt(void 0,t)),!e)throw X(new TypeError("Invalid subscriber"),v,h.ATOM_SUBSCRIBER_MUST_BE_FUNCTION);let s=this._slots;if(s===null)this._slots=s=new It;else if(this._hasSubscription(t))return d&&console.warn(`[atom-effect] Duplicate subscription ignored on node ${this.id}`),()=>{};return s.push(e),()=>this._unsubscribe(e)}_hasSubscription(t){const e=this._slots;return!e||e.size===0?!1:e.some(s=>s.fn===t||s.sub===t)}_unsubscribe(t){const e=this._slots;e!==null&&(e.remove(t),e.compact())}subscriberCount(){return this._slots?.size??0}_notifySubscribers(t,e){const s=this._slots;if(!s||s.size===0)return;const r=a.stack.length;at(a,null),s.lock();try{s.forEach(i=>{fe(i,t,e)})}finally{lt(a,r),s.unlock()}}_isDirty(){return this._deps?B(this._deps):!1}_isShallowDirty(){return this._deps?he(this._deps):!1}},Ft=t=>{const e=t+1&Dt;return e===0?1:e};function ot(t){return Ft(t)}var de=0,tt=1,ft=2,q=4,pe=ft|q;function Ce(){return{size:0,epoch:0,batchQueueSize:0,state:de,batchDepth:0,maxFlushIterations:T.MAX_FLUSH_ITERATIONS,sessionActive:!1,sessionEpoch:0,sessionExecutionCount:0,activeBuffer:[],standbyBuffer:[],batchBuffer:[],onOverflow:null}}function wt(t,e){const s=t.batchQueueSize;if(s===0)return;const r=e(),i=t.batchBuffer,n=t.activeBuffer;let o=t.size;for(let u=0;u<s;u++){const m=i[u];m._nextEpoch!==r&&(m._nextEpoch=r,n[o++]=m),i[u]=void 0}t.size=o,t.batchQueueSize=0,i.length>T.BATCH_QUEUE_SHRINK_THRESHOLD&&(i.length=0)}function kt(t,e,s,r){let i=0;const n=t.maxFlushIterations;for(;t.size>0||t.batchQueueSize>0;){if(++i>n){r(t);return}t.batchQueueSize>0&&wt(t,e),t.size>0&&s(t)}}function Pt(t,e){const s=t.activeBuffer,r=t.size;t.activeBuffer=t.standbyBuffer,t.standbyBuffer=s,t.size=0,e();for(let i=0;i<r;i++){const n=s[i];s[i]=void 0;try{typeof n=="function"?n():n.execute()}catch(o){console.error(new K("Error occurred during scheduler execution",o))}}}function Lt(t){const e=t.size+t.batchQueueSize;if(console.error(new K(h.SCHEDULER_FLUSH_OVERFLOW(t.maxFlushIterations,e))),t.size=0,t.activeBuffer.length=0,t.standbyBuffer.length=0,t.batchQueueSize=0,t.batchBuffer.length=0,t.onOverflow)try{t.onOverflow(e)}catch{}}function A(t){return t.epoch=Ft(t.epoch),t.epoch}function Mt(t){return t.sessionActive?(d&&console.warn("startFlush() called during flush - ignored"),!1):(t.sessionActive=!0,t.sessionEpoch=A(t),t.sessionExecutionCount=0,!0)}function Bt(t){t.sessionActive=!1}function Se(t){if(!t.sessionActive)return 0;const e=++t.sessionExecutionCount;if(e<=T.MAX_EXECUTIONS_PER_FLUSH)return e;throw new Error(`[atom-effect] Infinite loop detected: flush execution count exceeded ${T.MAX_EXECUTIONS_PER_FLUSH}`)}function W(t,e){if(d&&typeof e!="function"&&(!e||typeof e.execute!="function"))throw new K(h.SCHEDULER_CALLBACK_MUST_BE_FUNCTION);e._nextEpoch!==t.epoch&&(e._nextEpoch=t.epoch,(t.state&pe)===0?t.activeBuffer[t.size++]=e:t.batchBuffer[t.batchQueueSize++]=e,(t.state&tt)===0&&(t.state|=tt,queueMicrotask(()=>{try{if(t.size===0&&t.batchQueueSize===0)return;const s=Mt(t);kt(t,()=>A(t),r=>Pt(r,()=>A(r)),r=>Lt(r)),s&&Bt(t)}catch(s){throw Ee(a),s}finally{t.state&=~tt}})))}function ge(t){if(t.size===0&&t.batchQueueSize===0)return;const e=t.state;t.state|=ft;const s=Mt(t);try{wt(t,()=>A(t)),kt(t,()=>A(t),r=>Pt(r,()=>A(r)),r=>Lt(r))}finally{t.state=e,s&&Bt(t)}}function De(t){t.batchDepth++,t.state|=q}function Ie(t){if(t.batchDepth===0){d&&console.warn(h.SCHEDULER_END_BATCH_WITHOUT_START);return}--t.batchDepth===0&&(t.state&=~q,(t.state&ft)===0&&ge(t))}function Ct(t){return(t.state&q)!==0}var p=Ce(),xt=()=>A(p),Te=()=>p.sessionEpoch,ve=()=>Se(p);function zt(t){if(d&&typeof t!="function")throw new TypeError(h.BATCH_CALLBACK_MUST_BE_FUNCTION);De(p);try{return t()}finally{Ie(p)}}var w=null;function Oe(t){return t?new Promise((e,s)=>{W(p,()=>{try{t(),e()}catch(r){s(r)}})}):w||(w=new Promise(e=>{W(p,()=>{w=null,e()})}),w)}var me=class extends ht{constructor(t,e){super(),this[O]=l.Atom|l.Writable,this._value=t,this._equal=e.equal??Object.is,e.sync&&(this.flags|=g.SYNC),C.attachDebugInfo(this,"atom",this.id,e.name)}get isNotificationScheduled(){return(this.flags&g.NOTIFICATION_SCHEDULED)!==0}get isSync(){return(this.flags&g.SYNC)!==0}get value(){return a.current?.addDependency(this),this._value}set value(t){if(this._equal(this._value,t))return;const e=this._value;this._value=t,this.version=ot(this.version),d&&C.trackUpdate(this.id,C.getDebugName(this)),this._scheduleNotification(e)}_scheduleNotification(t){const e=this.flags,s=g.NOTIFICATION_SCHEDULED;(e&s)!==0||!this._slots?.length||(this._pendingOldValue=t,this.flags|=s,(e&g.SYNC)!==0&&!Ct(p)?this.isNotifying||this._flushNotifications():W(p,this))}execute(){this._flushNotifications()}_flushNotifications(){const t=g.NOTIFICATION_SCHEDULED,e=t|g.DISPOSED,s=(this.flags&g.SYNC)!==0&&!Ct(p);for(;(this.flags&e)===t;){const r=this._pendingOldValue,i=this._value;if(this._pendingOldValue=void 0,this.flags&=~t,this._equal(i,r)||this._notifySubscribers(i,r),!s)break}}peek(){return this._value}dispose(){const t=g.DISPOSED;(this.flags&t)===0&&(this.flags|=t,this._slots?.clear(),this._value=void 0,this._pendingOldValue=void 0,this._equal=Object.is)}_deepDirtyCheck(){return!1}};function Ne(t,e={}){return new me(t,e)}function J(t,e){return!t||typeof t!="object"&&typeof t!="function"?!1:!!(t[O]&e)}function be(t){return J(t,l.Atom)}function Ae(t){return J(t,l.Writable)}function Re(t){return J(t,l.Computed)}function ye(t){return J(t,l.Effect)}function P(t,e=!1){const s={};for(let r=0;r<t.length;r++){const i=e?t[r].peek():t[r].value;i&&typeof i=="object"&&Object.assign(s,i)}return s}var{IDLE:L,DIRTY:D,PENDING:x,RESOLVED:I,REJECTED:R,HAS_ERROR:_t,RECOMPUTING:S,DISPOSED:G,IS_COMPUTED:St,FORCE_COMPUTE:$}=U,Ht=x|R,Ue=L|$,Vt=R|_t,et=L|D|x|I|R|_t,Y={TO_RECOMPUTING:{clear:$,set:S},TO_RESOLVED:{clear:et|S,set:I},TO_PENDING:{clear:et|S,set:x},TO_REJECTED:{clear:et|S,set:R|_t}},j=(t,e)=>t&~e.clear|e.set;function Fe(t,e,s,r){if((t&I)!==0)return e;const i=r!==rt,n=t&Ht;if(n===0)return e;if(i)return r;throw n===R?s??new Error("REJECTED without error"):new y(h.COMPUTED_ASYNC_PENDING_NO_DEFAULT)}function we(t,e){const s=(t&Ht)!==0;return(t&Ue)!==0||B(e)||!s&&e.slots.size===0}function gt(t,e){const s=[],r=new Set,i=n=>{if(r.has(n.id))return!1;if(r.add(n.id),(n.flags&Vt)!==0&&(s.push(n.lastError??new Error("Internal Inconsistency: MASK_ERROR flag set but error is null")),e))return!0;const o=n._deps;if(o?.hasComputeds)for(let u=0,m=o.slots.length;u<m;u++){const f=o.slots.at(u);if(f?.node.isComputed&&i(f.node))return!0}return!1};return i(t),s}var ke=class extends ht{constructor(t,e={}){if(typeof t!="function")throw new y(h.COMPUTED_MUST_BE_FUNCTION);if(super(),this[O]=l.Atom|l.Computed,this._activeSessionId=0,this._sessionCounter=0,this._trackEpoch=M.UNINITIALIZED,this._trackCount=0,this._error=null,this._deps=Ot(),this._value=void 0,this.flags=St|D|L,this._equal=e.equal??Object.is,this._computation=t,this._defaultValue="defaultValue"in e?e.defaultValue:rt,this._onError=e.onError??null,C.attachDebugInfo(this,"computed",this.id,e.name),e.lazy===!1)try{this._recompute()}catch{}}get isDirty(){return(this.flags&D)!==0}get isRejected(){return(this.flags&R)!==0}get isRecomputing(){return(this.flags&S)!==0}get value(){if(a.current?.addDependency(this),this._isStable())return this._value;if(this._ensureNotDisposed(),(this.flags&S)!==0){if(this._defaultValue!==rt)return this._defaultValue;throw new y(h.COMPUTED_CIRCULAR_DEPENDENCY)}return we(this.flags,this._deps)?this._recompute():this.flags&=~D,Fe(this.flags,this._value,this._error,this._defaultValue)}_isStable(){const t=I|D|L|G|S;return(this.flags&t)===I}_ensureNotDisposed(){if((this.flags&G)!==0)throw new y(h.COMPUTED_DISPOSED)}peek(){return this._value}get state(){a.current?.addDependency(this);const t=this.flags;return(t&I)!==0?k.RESOLVED:(t&x)!==0?k.PENDING:(t&R)!==0?k.REJECTED:k.IDLE}get hasError(){return a.current?.addDependency(this),(this.flags&Vt)!==0?!0:this._deps.hasComputeds?nt(()=>gt(this,!0).length>0):!1}get isValid(){return!this.hasError}get errors(){return a.current?.addDependency(this),this._deps.hasComputeds?nt(()=>Object.freeze(gt(this,!1))):this._error?Object.freeze([this._error]):$t}get lastError(){return a.current?.addDependency(this),this._error}get isPending(){return a.current?.addDependency(this),(this.flags&x)!==0}get isResolved(){return a.current?.addDependency(this),(this.flags&I)!==0}invalidate(){this.flags|=$,this._markDirty()}dispose(){(this.flags&G)===0&&(At(this._deps),this._slots?.clear(),this.flags=G|D|L,this._error=null,this._value=void 0)}addDependency(t){const e=this._trackEpoch;if(t._lastSeenEpoch===e)return;t._lastSeenEpoch=e;const s=this._trackCount++,r=this._deps,i=r.slots.at(s);i?.node===t?i.version=t.version:Nt(r,t,s)||bt(r,s,Rt(t,t.version,t.subscribe(this))),(t.flags&St)!==0&&(r.hasComputeds=!0)}_recompute(){if((this.flags&S)!==0)return;this.flags=j(this.flags,Y.TO_RECOMPUTING);const t=a.stack.length;this._startTracking();let e,s=!1,r;try{try{e=Ut(a,this,this._computation)}catch(i){throw lt(a,t),i}}catch(i){s=!0,r=i}s?(this._commitDeps(),this._handleError(r,h.COMPUTED_COMPUTATION_FAILED,!1)):(this._commitDeps(),ut(e)?this._handleAsyncComputation(e):this._finalizeResolution(e)),this._trackEpoch=M.UNINITIALIZED,this._trackCount=0,this.flags&=~S}_startTracking(){this._trackEpoch=xt(),this._trackCount=0,mt(this._deps)}_commitDeps(){try{ct(this._deps,this._trackCount)}catch(t){d&&console.warn("[atom-effect] _commitDeps failed during error recovery:",t)}}_handleAsyncComputation(t){this.flags=j(this.flags,Y.TO_PENDING),this._notifySubscribers(void 0,void 0);const e=++this._sessionCounter;this._activeSessionId=e,t.then(s=>{if(this._activeSessionId===e){if(this._isDirty())return this._markDirty();this._finalizeResolution(s),this._notifySubscribers(s,void 0)}},s=>{this._activeSessionId===e&&this._handleError(s,h.COMPUTED_ASYNC_COMPUTATION_FAILED)})}_handleError(t,e,s=!1){const r=X(t,y,e),i=this._error;if((!this.isRejected||i!==r)&&(this.version=ot(this.version)),this._error=r,this.flags=j(this.flags,Y.TO_REJECTED),this._onError)try{this._onError(r)}catch(n){console.error(h.CALLBACK_ERROR_IN_ERROR_HANDLER,n)}if(this._notifySubscribers(void 0,void 0),s)throw r}_finalizeResolution(t){((this.flags&I)===0||!this._equal(this._value,t))&&(this.version=ot(this.version)),this._value=t,this._error=null,this.flags=j(this.flags,Y.TO_RESOLVED)}execute(){this._markDirty()}_markDirty(){const t=this.flags;(t&(S|D))!==0||!(t&$)&&!this._isShallowDirty()||(this.flags=t|D,C.trackUpdate(this.id,C.getDebugName(this)),this._notifySubscribers(void 0,void 0))}_deepDirtyCheck(){return B(this._deps)}};function Gt(t,e={}){return new ke(t,e)}function Pe(...t){return Gt(()=>P(t))}function Le(){return{loopCount:0,lastFlushEpoch:M.UNINITIALIZED,windowCount:0,windowStart:0,totalExecutions:0}}function Me(t,e,s,r,i){t.lastFlushEpoch!==s&&(t.lastFlushEpoch=s,t.loopCount=0),++t.loopCount>e&&i("per-effect"),r()>T.MAX_EXECUTIONS_PER_FLUSH&&i("global"),t.totalExecutions++}function Be(t,e,s){if(!Number.isFinite(e))return;const r=Date.now();if(r-t.windowStart>=st.EFFECT_FREQUENCY_WINDOW){t.windowStart=r,t.windowCount=1;return}++t.windowCount>e&&s()}var xe=class extends ht{constructor(t,e={}){super(),this[O]=l.Effect,this._trackEpoch=M.UNINITIALIZED,this._trackCount=0,this._trackSessionId=0,this._budget=Le(),this._deps=Ot(),this._cleanup=null,this._fn=t,this._onError=e.onError??null,this._sync=e.sync??!1,this._maxExecutions=e.maxExecutionsPerSecond??T.MAX_EXECUTIONS_PER_SECOND,this._maxExecutionsPerFlush=e.maxExecutionsPerFlush??T.MAX_EXECUTIONS_PER_EFFECT,this._notifyCallback=this._sync?()=>this.execute():()=>W(p,this),C.attachDebugInfo(this,"effect",this.id,e.name)}run(){if(this.isDisposed)throw new b(h.EFFECT_DISPOSED);this.execute(!0)}dispose(){this.isDisposed||(this.flags|=N.DISPOSED,this._execCleanup(),this._deps&&At(this._deps))}get executionCount(){return this._budget.totalExecutions}get isExecuting(){return(this.flags&N.EXECUTING)!==0}get isDisposed(){return(this.flags&N.DISPOSED)!==0}execute(t=!1){if(!this._prepareExecution(t))return;this._execCleanup(),this._startTracking();const e=a.stack.length;let s,r=!1,i;try{try{s=Ut(a,this,this._fn)}catch(n){throw lt(a,e),n}}catch(n){r=!0,i=n}this._commitDeps(),r?this._handleExecutionError(i):this._handleResult(s),this.flags&=~N.EXECUTING}_prepareExecution(t){return(this.flags&(N.DISPOSED|N.EXECUTING))!==0||!(t||this._deps.slots.length===0||this._isDirty())?!1:(this._validateBudget(),C.trackUpdate(this.id,C.getDebugName(this)),this.flags|=N.EXECUTING,!0)}addDependency(t){if(!this.isExecuting||t._lastSeenEpoch===this._trackEpoch)return;t._lastSeenEpoch=this._trackEpoch;const e=this._trackCount++,s=this._deps,r=t.version,i=s.slots.at(e);i?.node===t?i.version=r:Nt(s,t,e)||this._insertNewDependency(t,e,r),t.isComputed&&!s.hasComputeds&&(s.hasComputeds=!0)}_insertNewDependency(t,e,s){const r=Rt(t,s,t.subscribe(this._notifyCallback));bt(this._deps,e,r)}_startTracking(){this._trackEpoch=xt(),this._trackCount=0,mt(this._deps)}_commitDeps(){try{ct(this._deps,this._trackCount)}catch(t){d&&console.warn("[atom-effect] _commitDeps failed during error recovery:",t)}}_handleResult(t){typeof t=="function"?this._cleanup=t:ut(t)?this._handleAsyncResult(t):this._cleanup=null}_handleAsyncResult(t){const e=++this._trackSessionId;t.then(s=>{if(this._trackSessionId!==e||this.isDisposed){if(typeof s=="function")try{s()}catch(r){this._handleExecutionError(r,h.EFFECT_CLEANUP_FAILED)}return}typeof s=="function"&&(this._cleanup=s)},s=>{this._trackSessionId===e&&this._handleExecutionError(s)})}_execCleanup(){const t=this._cleanup;if(t){this._cleanup=null;try{t()}catch(e){this._handleExecutionError(e,h.EFFECT_CLEANUP_FAILED)}}}_validateBudget(){Me(this._budget,this._maxExecutionsPerFlush,Te(),ve,t=>this._abortExecution(t)),d&&Be(this._budget,this._maxExecutions,()=>{const t=new b(h.EFFECT_FREQUENCY_LIMIT_EXCEEDED);throw this.dispose(),this._handleExecutionError(t),t})}_abortExecution(t){const e=new b(t==="per-effect"?`Infinite loop detected (per-effect): executed ${this._budget.loopCount} times in current flush.`:"Infinite loop detected (global): exceeded total execution limit per flush.");throw this.dispose(),console.error(e),e}_handleExecutionError(t,e=h.EFFECT_EXECUTION_FAILED){const s=X(t,b,e);if(console.error(s),this._onError)try{this._onError(s)}catch(r){console.error(X(r,b,h.CALLBACK_ERROR_IN_ERROR_HANDLER))}}_isDirty(){return B(this._deps)}_deepDirtyCheck(){return B(this._deps)}};function ze(t,e={}){if(typeof t!="function")throw new b(h.EFFECT_MUST_BE_FUNCTION);const s=new xe(t,e);return s.execute(),s}var Yt=new Set(["__proto__","constructor","prototype"]);function He(t,e,s){if(Array.isArray(t)){const n=[...t];return n[e]=s,n}if(t instanceof Map){const n=new Map(t);return n.set(e,s),n}const r=Object.getPrototypeOf(t);if(r===Object.prototype||r===null)return{...t,[e]:s};const i=Object.create(r);return Object.assign(i,t),i[e]=s,i}function Et(t,e,s,r){if(s===e.length)return r;const i=e[s];if(Yt.has(i)||t==null||typeof t!="object")return t;const n=t instanceof Map?t.get(i):t[i],o=Et(n,e,s+1,r);return Object.is(n,o)?t:He(t,i,o)}function jt(t,e){let s=t;const r=e.length;for(let i=0;i<r;i++){if(s==null)return;s instanceof Map?s=s.get(e[i]):s=s[e[i]]}return s}function dt(t,e){const s=e.split("."),r=s.some(f=>Yt.has(f)),i=new Set;let n=null,o;const u=f=>r?void 0:jt(f,s),m=()=>{const f=u(t.peek());if(!Object.is(f,o)){const z=o;o=f,i.forEach(H=>H(f,z))}};return{get value(){return u(t.value)},set value(f){if(r)return;const z=t.peek(),H=Et(z,s,0,f);H!==z&&(t.value=H)},peek:()=>u(t.peek()),subscribe(f){return i.size===0&&(o=u(t.peek()),n=t.subscribe(m)),i.add(f),()=>{i.delete(f),i.size===0&&n&&(n(),n=null)}},subscriberCount:()=>i.size,dispose:()=>{n?.(),n=null,i.clear()},[O]:l.Atom|l.Writable}}var Ve=(t,e)=>dt(t,e),Ge=t=>e=>dt(t,e);function Ye(...t){let e;const s=new Set,r=[],i=()=>{const n=P(t,!0);if(!te(n,e)){const o=e;e=n;for(const u of s)u(n,o)}};return{get value(){return P(t)},set value(n){zt(()=>{for(let o=0;o<t.length;o++)t[o].value=n})},peek:()=>P(t,!0),subscribe:n=>{if(s.size===0){e=P(t,!0);for(let o=0;o<t.length;o++)r.push(t[o].subscribe(i))}return s.add(n),()=>{if(s.delete(n),s.size===0){for(const o of r)o();r.length=0}}},subscriberCount:()=>s.size,dispose:()=>{for(const n of r)n();r.length=0,s.clear()},[O]:l.Atom|l.Writable}}exports.AsyncState=k;exports.AtomError=v;exports.BRAND=O;exports.BrandFlags=l;exports.ComputedError=y;exports.EffectError=b;exports.IS_DEV=d;exports.SCHEDULER_CONFIG=T;exports.SchedulerError=K;exports.aeNextTick=Oe;exports.atom=Ne;exports.atomLens=dt;exports.batch=zt;exports.composeLens=Ve;exports.computed=Gt;exports.effect=ze;exports.getPathValue=jt;exports.globalScheduler=p;exports.isAtom=be;exports.isComputed=Re;exports.isEffect=ye;exports.isPromise=ut;exports.isWritable=Ae;exports.lensFor=Ge;exports.mergeAtoms=Pe;exports.mergeLenses=Ye;exports.runtimeDebug=C;exports.setDeepValue=Et;exports.untracked=nt;
|
|
2
2
|
|
|
3
3
|
//# sourceMappingURL=index.cjs.map
|