@but212/atom-effect-jquery 0.14.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- (function(p,h){typeof exports=="object"&&typeof module<"u"?h(exports,require("jquery")):typeof define=="function"&&define.amd?define(["exports","jquery"],h):(p=typeof globalThis<"u"?globalThis:p||self,h(p.AtomEffectJQuery={},p.jQuery))})(this,(function(p,h){"use strict";const Ye={ONE_SECOND_MS:1e3},ne={IDLE:"idle",PENDING:"pending",RESOLVED:"resolved",REJECTED:"rejected"},A={DISPOSED:1,HAS_FN_SUBS:2,HAS_OBJ_SUBS:4},C={...A,EXECUTING:8},a={...A,DIRTY:8,IDLE:16,PENDING:32,RESOLVED:64,REJECTED:128,RECOMPUTING:256,HAS_ERROR:512},U={...A,SYNC:8,NOTIFICATION_SCHEDULED:16},M={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},De={MAX_DEPENDENCIES:1e3,WARN_INFINITE_LOOP:!0},O=1073741823,Je=20,fe=1<<Je-1,R=typeof process<"u"&&process.env&&process.env.NODE_ENV!=="production",Ke=Object.freeze([]);class w extends Error{constructor(e,t=null,n=!0){super(e),this.name="AtomError",this.cause=t,this.recoverable=n,this.timestamp=new Date}}class X extends w{constructor(e,t=null){super(e,t,!0),this.name="ComputedError"}}class q extends w{constructor(e,t=null){super(e,t,!1),this.name="EffectError"}}class ie extends w{constructor(e,t=null){super(e,t,!1),this.name="SchedulerError"}}const m={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",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",CALLBACK_ERROR_IN_ERROR_HANDLER:"Error occurred during onError callback execution"},_e=Symbol("debugName"),We=Symbol("id"),de=Symbol("type"),Ce=Symbol("noDefaultValue");function Ze(s){return"dependencies"in s&&Array.isArray(s.dependencies)}let Ne=0;function Te(s,e,t){if(s._visitedEpoch!==t){if(s._visitedEpoch=t,s===e)throw new X("Indirect circular dependency detected");if(Ze(s)){const n=s.dependencies;for(let i=0;i<n.length;i++){const o=n[i];o&&Te(o,e,t)}}}}const x={enabled:typeof process<"u"&&process.env?.NODE_ENV==="development",maxDependencies:De.MAX_DEPENDENCIES,warnInfiniteLoop:De.WARN_INFINITE_LOOP,warn(s,e){this.enabled&&s&&console.warn(`[Atom Effect] ${e}`)},checkCircular(s,e){if(s===e)throw new X("Direct circular dependency detected");this.enabled&&(Ne++,Te(s,e,Ne))},attachDebugInfo(s,e,t){if(!this.enabled)return;const n=s;n[_e]=`${e}_${t}`,n[We]=t,n[de]=e},getDebugName(s){if(s!=null&&_e in s)return s[_e]},getDebugType(s){if(s!=null&&de in s)return s[de]}};let $e=1;const et=()=>$e++;class ve{constructor(){this.flags=0,this.version=0,this._lastSeenEpoch=-1,this._modifiedAtEpoch=-1,this._visitedEpoch=-1,this.id=et()&O,this._tempUnsub=void 0}getShift(e){return this.version-e&O}}class Ae extends ve{subscribe(e){if(typeof e=="function")return this._addSubscriber(this._fnSubs,e,A.HAS_FN_SUBS);if(e!==null&&typeof e=="object"&&"execute"in e)return this._addSubscriber(this._objSubs,e,A.HAS_OBJ_SUBS);throw new w(m.ATOM_SUBSCRIBER_MUST_BE_FUNCTION)}subscriberCount(){return this._fnSubs.length+this._objSubs.length}_addSubscriber(e,t,n){if(e.indexOf(t)!==-1)return()=>{};e.push(t),this.flags|=n;let i=!1;return()=>{if(i)return;i=!0;const o=e.indexOf(t);if(o!==-1){const r=e.pop();o<e.length&&(e[o]=r),this.flags&=~(e.length===0?n:0)}}}_notifySubscribers(e,t){const n=this.flags,i=A.HAS_FN_SUBS|A.HAS_OBJ_SUBS;if(n&i){if(n&A.HAS_FN_SUBS){const o=this._fnSubs;for(let r=0,c=o.length;r<c;r++){const u=o[r];if(u)try{u(e,t)}catch(l){console.error(new w(m.ATOM_INDIVIDUAL_SUBSCRIBER_FAILED,l))}}}if(n&A.HAS_OBJ_SUBS){const o=this._objSubs;for(let r=0,c=o.length;r<c;r++){const u=o[r];if(u)try{u.execute()}catch(l){console.error(new w(m.ATOM_INDIVIDUAL_SUBSCRIBER_FAILED,l))}}}}}}class tt{constructor(){this.acquired=0,this.released=0,this.rejected=new st}}class st{constructor(){this.frozen=0,this.tooLarge=0,this.poolFull=0}}class pe{constructor(){this.pool=[],this.maxPoolSize=50,this.maxReusableCapacity=256,this.stats=R?new tt:null}acquire(){const e=this.stats;return R&&e&&e.acquired++,this.pool.pop()??[]}release(e,t){if(t&&e===t||Object.isFrozen(e)){const c=this.stats;R&&c&&e!==t&&c.rejected.frozen++;return}const n=e.length,i=this.pool,o=i.length;if(n>this.maxReusableCapacity||o>=this.maxPoolSize){const c=this.stats;R&&c&&(n>this.maxReusableCapacity?c.rejected.tooLarge++:c.rejected.poolFull++);return}e.length=0,i.push(e);const r=this.stats;R&&r&&r.released++}getStats(){const e=this.stats;if(!R||!e)return null;const{acquired:t,released:n,rejected:i}=e,o=i.frozen+i.tooLarge+i.poolFull;return{acquired:t,released:n,rejected:{frozen:i.frozen,tooLarge:i.tooLarge,poolFull:i.poolFull},leaked:t-n-o,poolSize:this.pool.length}}reset(){this.pool.length=0;const e=this.stats;R&&e&&(e.acquired=0,e.released=0,e.rejected.frozen=0,e.rejected.tooLarge=0,e.rejected.poolFull=0)}}const y=Object.freeze([]),V=Object.freeze([]),N=Object.freeze([]),B=new pe,Q=new pe,F=new pe;function j(s,e,t,n){if(e!=null){if((typeof e=="object"||typeof e=="function")&&typeof e.addDependency=="function"){e.addDependency(s);return}if(typeof e=="function"){const i=e;t.indexOf(i)===-1&&(t.push(i),s.flags|=A.HAS_FN_SUBS);return}typeof e=="object"&&typeof e.execute=="function"&&n.indexOf(e)===-1&&(n.push(e),s.flags|=A.HAS_OBJ_SUBS)}}function Oe(s,e,t,n){const i=s.length,o=e.length,r=e!==y&&o>0;if(r)for(let u=0;u<o;u++){const l=e[u];l&&(l._tempUnsub=t[u])}const c=Q.acquire();c.length=i;for(let u=0;u<i;u++){const l=s[u];if(!l)continue;const _=l._tempUnsub;_?(c[u]=_,l._tempUnsub=void 0):(x.checkCircular(l,n),c[u]=l.subscribe(n))}if(r)for(let u=0;u<o;u++){const l=e[u];if(l){const _=l._tempUnsub;_&&(_(),l._tempUnsub=void 0)}}return t!==V&&Q.release(t),c}let oe=0;function Re(){return oe=oe+1&O||1,oe}function nt(){return oe}let Ee=0,ge=0,re=!1;function xe(){return re?(R&&console.warn("Warning: startFlush() called during flush - ignored to prevent infinite loop detection bypass"),!1):(re=!0,Ee=Ee+1&O,ge=0,!0)}function Ue(){re=!1}function it(){return re?++ge:0}class ot{constructor(){this._queueBuffers=[[[],[]],[[],[]]],this._bufferIndices=new Uint8Array(2),this._sizes=new Uint32Array(2),this._activeQueues=[this._queueBuffers[0][0],this._queueBuffers[1][0]],this._epoch=0,this.isProcessing=!1,this.isBatching=!1,this.batchDepth=0,this.batchQueue=[],this.batchQueueSize=0,this.isFlushingSync=!1,this.maxFlushIterations=M.MAX_FLUSH_ITERATIONS}get phase(){return this.isProcessing||this.isFlushingSync?2:this.isBatching?1:0}get queueSize(){return this._sizes[0]}get urgentQueueSize(){return this._sizes[1]}schedule(e,t){if(typeof e!="function")throw new ie("Scheduler callback must be a function");const n=this._epoch;if(e._nextEpoch===n)return;if(e._nextEpoch=n,this.isBatching||this.isFlushingSync){this.batchQueue[this.batchQueueSize++]=e;return}const i=this._calculateUrgency(e,t);this._activeQueues[i][this._sizes[i]++]=e,this.isProcessing||this.flush()}_calculateUrgency(e,t){if(!t||e._cachedVersion===void 0)return 0;const n=t.getShift(e._cachedVersion);return fe-1-n>>>31&1}flush(){this.isProcessing||this._sizes[0]===0&&this._sizes[1]===0||(this.isProcessing=!0,queueMicrotask(()=>{try{if(this._sizes[0]===0&&this._sizes[1]===0)return;const e=xe();this._drainQueue(),e&&Ue()}finally{this.isProcessing=!1,(this._sizes[0]>0||this._sizes[1]>0)&&!this.isBatching&&this.flush()}}))}flushSync(){this.isFlushingSync=!0;const e=xe();try{this._mergeBatchQueue(),this._drainQueue()}finally{this.isFlushingSync=!1,e&&Ue()}}_mergeBatchQueue(){const e=this.batchQueueSize;if(e===0)return;const t=++this._epoch,n=this.batchQueue,i=this._activeQueues[0];let o=this._sizes[0];for(let r=0;r<e;r++){const c=n[r];c._nextEpoch!==t&&(c._nextEpoch=t,i[o++]=c)}this._sizes[0]=o,this.batchQueueSize=0,n.length>M.BATCH_QUEUE_SHRINK_THRESHOLD&&(n.length=0)}_drainQueue(){let e=0;const t=this.maxFlushIterations;for(;this._sizes[1]>0||this._sizes[0]>0;){if(++e>t){this._handleFlushOverflow();return}this._sizes[1]>0&&this._processQueue(1),this._sizes[0]>0&&this._processQueue(0),this._mergeBatchQueue()}}_processQueue(e){const t=this._queueBuffers[e],n=this._bufferIndices[e],i=t[n],o=this._sizes[e],r=n^1;this._bufferIndices[e]=r,this._activeQueues[e]=t[r],this._sizes[e]=0,this._epoch++,this._processJobs(i,o)}_handleFlushOverflow(){console.error(new ie(`Maximum flush iterations (${this.maxFlushIterations}) exceeded. Possible infinite loop.`)),this._sizes[0]=0,this._activeQueues[0].length=0,this._sizes[1]=0,this._activeQueues[1].length=0,this.batchQueueSize=0}_processJobs(e,t){for(let n=0;n<t;n++)try{e[n]()}catch(i){console.error(new ie("Error occurred during scheduler execution",i))}e.length=0}startBatch(){this.batchDepth++,this.isBatching=!0}endBatch(){this.batchDepth=Math.max(0,this.batchDepth-1),this.batchDepth===0&&(this.flushSync(),this.isBatching=!1)}setMaxFlushIterations(e){if(e<M.MIN_FLUSH_ITERATIONS)throw new ie(`Max flush iterations must be at least ${M.MIN_FLUSH_ITERATIONS}`);this.maxFlushIterations=e}}const $=new ot;class rt{constructor(){this.current=null}run(e,t){const n=this.current;this.current=e;try{return t()}finally{this.current=n}}getCurrent(){return this.current}}const I=new rt;function be(s){if(typeof s!="function")throw new w("Untracked callback must be a function");const e=I.current;I.current=null;try{return s()}finally{I.current=e}}class ct extends Ae{constructor(e,t){super(),this._value=e,this._pendingOldValue=void 0,this._notifyTask=void 0,this._fnSubs=[],this._objSubs=[],t&&(this.flags|=U.SYNC),x.attachDebugInfo(this,"atom",this.id)}get value(){const e=I.current;return e&&j(this,e,this._fnSubs,this._objSubs),this._value}set value(e){const t=this._value;if(Object.is(t,e))return;this._value=e,this.version=this.version+1&O;const n=this.flags,i=U.HAS_FN_SUBS|U.HAS_OBJ_SUBS;n&i&&this._scheduleNotification(t)}_scheduleNotification(e){let t=this.flags;if(t&U.NOTIFICATION_SCHEDULED||(this._pendingOldValue=e,this.flags=t|=U.NOTIFICATION_SCHEDULED),t&U.SYNC&&!$.isBatching){this._flushNotifications();return}let n=this._notifyTask;n||(n=this._notifyTask=()=>this._flushNotifications()),$.schedule(n)}_flushNotifications(){if(!(this.flags&U.NOTIFICATION_SCHEDULED))return;const e=this._pendingOldValue,t=this._value;this._pendingOldValue=void 0,this.flags&=-17,this._notifySubscribers(t,e)}peek(){return this._value}dispose(){this.flags&U.DISPOSED||(this._fnSubs=[],this._objSubs=[],this.flags|=U.DISPOSED,this._value=void 0,this._pendingOldValue=void 0,this._notifyTask=void 0)}}function we(s,e={}){return new ct(s,e.sync??!1)}function ee(s,e,t){if(s instanceof TypeError)return new e(`Type error (${t}): ${s.message}`,s);if(s instanceof ReferenceError)return new e(`Reference error (${t}): ${s.message}`,s);if(s instanceof w)return s;const n=s instanceof Error?s.message:String(s),i=s instanceof Error?s:null;return new e(`Unexpected error (${t}): ${n}`,i)}function me(s){return s!==null&&typeof s=="object"&&"value"in s&&"subscribe"in s&&typeof s.subscribe=="function"}function Fe(s){if(x.enabled&&(s==null||typeof s=="object")){const e=x.getDebugType(s);if(e)return e==="computed"}return me(s)&&"invalidate"in s&&typeof s.invalidate=="function"}function Le(s){return s!=null&&typeof s.then=="function"}const ke=a.RESOLVED|a.PENDING|a.REJECTED,ce=Array(ke+1).fill(ne.IDLE);ce[a.RESOLVED]=ne.RESOLVED,ce[a.PENDING]=ne.PENDING,ce[a.REJECTED]=ne.REJECTED;class ut{constructor(e){this._owner=e,this._epoch=-1,this._nextDeps=y,this._nextVersions=N,this._depCount=0}execute(){this._owner._markDirty()}addDependency(e){if(e._lastSeenEpoch===this._epoch)return;e._lastSeenEpoch=this._epoch;const t=this._depCount,n=this._nextDeps,i=this._nextVersions;t<n.length?(n[t]=e,i[t]=e.version):(n.push(e),i.push(e.version)),this._depCount=t+1}reset(){this._epoch=-1,this._nextDeps=y,this._nextVersions=N,this._depCount=0}}class Pe extends Ae{constructor(e,t={}){if(typeof e!="function")throw new X(m.COMPUTED_MUST_BE_FUNCTION);if(super(),this.MAX_ASYNC_RETRIES=3,this._value=void 0,this.flags=a.DIRTY|a.IDLE,this._error=null,this._promiseId=0,this._equal=t.equal??Object.is,this._fn=e,this._defaultValue="defaultValue"in t?t.defaultValue:Ce,this._hasDefaultValue=this._defaultValue!==Ce,this._onError=t.onError??null,this.MAX_PROMISE_ID=Number.MAX_SAFE_INTEGER-1,this._fnSubs=[],this._objSubs=[],this._dependencies=y,this._dependencyVersions=N,this._unsubscribes=V,this._cachedErrors=null,this._errorCacheEpoch=-1,this._asyncStartAggregateVersion=0,this._asyncRetryCount=0,this._trackable=new ut(this),x.attachDebugInfo(this,"computed",this.id),x.enabled){const n=this;n.subscriberCount=this.subscriberCount.bind(this),n.isDirty=()=>(this.flags&a.DIRTY)!==0,n.dependencies=this._dependencies,n.stateFlags=""}if(t.lazy===!1)try{this._recompute()}catch{}}get value(){const e=I.current;e&&j(this,e,this._fnSubs,this._objSubs);const t=this.flags;if(t&a.RECOMPUTING)return this._value;t&(a.DIRTY|a.IDLE)&&this._recompute();const n=this.flags;return n&a.PENDING?this._handlePending():n&a.REJECTED?this._handleRejected():this._value}peek(){return this._value}get state(){const e=I.current;return e&&j(this,e,this._fnSubs,this._objSubs),ce[this.flags&ke]}get hasError(){const e=I.current;if(e&&j(this,e,this._fnSubs,this._objSubs),this.flags&(a.REJECTED|a.HAS_ERROR))return!0;const t=this._dependencies;for(let n=0,i=t.length;n<i;n++){const o=t[n];if(o&&o.flags&a.HAS_ERROR)return!0}return!1}get isValid(){return!this.hasError}get errors(){const e=I.current;if(e&&j(this,e,this._fnSubs,this._objSubs),!this.hasError)return Ke;const t=nt();if(this._errorCacheEpoch===t&&this._cachedErrors!==null)return this._cachedErrors;const n=new Set;this._error&&n.add(this._error);const i=this._dependencies;for(let r=0,c=i.length;r<c;r++){const u=i[r];if(u&&"errors"in u){const l=u.errors;for(let _=0,H=l.length;_<H;_++){const D=l[_];D&&n.add(D)}}}const o=Object.freeze([...n]);return this._cachedErrors=o,this._errorCacheEpoch=t,o}get lastError(){const e=I.current;return e&&j(this,e,this._fnSubs,this._objSubs),this._error}get isPending(){const e=I.current;return e&&j(this,e,this._fnSubs,this._objSubs),(this.flags&a.PENDING)!==0}get isResolved(){const e=I.current;return e&&j(this,e,this._fnSubs,this._objSubs),(this.flags&a.RESOLVED)!==0}invalidate(){this._markDirty();const e=this._dependencyVersions;e!==N&&(F.release(e),this._dependencyVersions=N),this._errorCacheEpoch=-1,this._cachedErrors=null}dispose(){const e=this._unsubscribes;if(e!==V){for(let i=0,o=e.length;i<o;i++){const r=e[i];r&&r()}Q.release(e),this._unsubscribes=V}const t=this._dependencies;t!==y&&(B.release(t),this._dependencies=y);const n=this._dependencyVersions;n!==N&&(F.release(n),this._dependencyVersions=N),this._fnSubs=[],this._objSubs=[],this.flags=a.DISPOSED|a.DIRTY|a.IDLE,this._error=null,this._value=void 0,this._promiseId=(this._promiseId+1)%this.MAX_PROMISE_ID,this._cachedErrors=null,this._errorCacheEpoch=-1}_clearDirty(){this.flags&=-9}_setPending(){this.flags=(this.flags|a.PENDING)&-209}_isResolved(){return(this.flags&a.RESOLVED)!==0}_setResolved(){this.flags=(this.flags|a.RESOLVED)&-689}_isRejected(){return(this.flags&a.REJECTED)!==0}_setRejected(){this.flags=this.flags&-113|(a.REJECTED|a.HAS_ERROR)}_setRecomputing(e){const t=a.RECOMPUTING;this.flags=this.flags&~t|(e?-1:0)&t}_recompute(){if(this.flags&a.RECOMPUTING)return;this._setRecomputing(!0);const e=this._trackable,t=this._dependencies,n=this._dependencyVersions;e._epoch=Re(),e._nextDeps=B.acquire(),e._nextVersions=F.acquire(),e._depCount=0;let i=!1;try{const o=I.run(e,this._fn),r=e._nextDeps,c=e._nextVersions,u=e._depCount;r.length=u,c.length=u,this._unsubscribes=Oe(r,t,this._unsubscribes,this),this._dependencies=r,this._dependencyVersions=c,i=!0,Le(o)?this._handleAsyncComputation(o):this._finalizeResolution(o)}catch(o){let r=o;if(!i)try{const c=e._nextDeps,u=e._nextVersions,l=e._depCount;c.length=l,u.length=l,this._unsubscribes=Oe(c,t,this._unsubscribes,this),this._dependencies=c,this._dependencyVersions=u,i=!0}catch(c){r=c}this._handleComputationError(r)}finally{i?(t!==y&&B.release(t),n!==N&&F.release(n)):(B.release(e._nextDeps),F.release(e._nextVersions)),e.reset(),this._setRecomputing(!1)}}_getAggregateShift(){let e=0;const t=this._dependencies,n=this._dependencyVersions;for(let i=0,o=t.length;i<o;i++){const r=t[i],c=n[i];r&&c!==void 0&&(e=e+r.getShift(c)&O)}return e}isUrgent(){return this._getAggregateShift()>=fe}_handleAsyncComputation(e){this._setPending(),this._clearDirty(),this._notifySubscribers(void 0,void 0),this._asyncStartAggregateVersion=this._captureVersionSnapshot(),this._asyncRetryCount=0,this._promiseId=(this._promiseId+1)%this.MAX_PROMISE_ID;const t=this._promiseId;e.then(n=>{if(t!==this._promiseId)return;const i=this._captureVersionSnapshot()-this._asyncStartAggregateVersion&O;if(fe-1-i>>>31&1){if(this._asyncRetryCount<this.MAX_ASYNC_RETRIES){this._asyncRetryCount++,this._markDirty();return}const o=new X(`Async drift exceeded threshold after ${this.MAX_ASYNC_RETRIES} retries.`);this._handleAsyncRejection(o);return}this._finalizeResolution(n),this._notifySubscribers(n,void 0)}).catch(n=>{t===this._promiseId&&this._handleAsyncRejection(n)})}_captureVersionSnapshot(){let e=0;const t=this._dependencies;for(let n=0,i=t.length;n<i;n++){const o=t[n];o&&(e=e+o.version&O)}return e}_handleAsyncRejection(e){const t=ee(e,X,m.COMPUTED_ASYNC_COMPUTATION_FAILED);this.flags&a.REJECTED||(this.version=this.version+1&O),this._error=t,this._setRejected(),this._clearDirty(),this._setRecomputing(!1);const n=this._onError;if(n)try{n(t)}catch(i){console.error(m.CALLBACK_ERROR_IN_ERROR_HANDLER,i)}this._notifySubscribers(void 0,void 0)}_finalizeResolution(e){(!(this.flags&a.RESOLVED)||!this._equal(this._value,e))&&(this.version=this.version+1&O),this._value=e,this._clearDirty(),this._setResolved(),this._error=null,this._setRecomputing(!1),this._cachedErrors=null,this._errorCacheEpoch=-1}_handleComputationError(e){const t=ee(e,X,m.COMPUTED_COMPUTATION_FAILED);this._error=t,this._setRejected(),this._clearDirty(),this._setRecomputing(!1);const n=this._onError;if(n)try{n(t)}catch(i){console.error(m.CALLBACK_ERROR_IN_ERROR_HANDLER,i)}throw t}_handlePending(){if(this._hasDefaultValue)return this._defaultValue;throw new X(m.COMPUTED_ASYNC_PENDING_NO_DEFAULT)}_handleRejected(){const e=this._error;if(e?.recoverable&&this._hasDefaultValue)return this._defaultValue;throw e}execute(){this._markDirty()}_markDirty(){const e=this.flags;e&(a.RECOMPUTING|a.DIRTY)||(this.flags=e|a.DIRTY,this._notifySubscribers(void 0,void 0))}}Object.freeze(Pe.prototype);function Me(s,e={}){return new Pe(s,e)}class ht extends ve{constructor(e,t={}){super(),this._cleanup=null,this._dependencies=y,this._dependencyVersions=N,this._unsubscribes=V,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??M.MAX_EXECUTIONS_PER_SECOND,this._maxExecutionsPerFlush=t.maxExecutionsPerFlush??M.MAX_EXECUTIONS_PER_EFFECT,this._trackModifications=t.trackModifications??!1,this._executionCount=0,this._historyPtr=0;const n=Number.isFinite(this._maxExecutions),i=n?Math.min(this._maxExecutions+1,M.MAX_EXECUTIONS_PER_SECOND+1):0;this._historyCapacity=i,this._history=R&&n&&i>0?new Array(i).fill(0):null,x.attachDebugInfo(this,"effect",this.id)}run(){if(this.flags&C.DISPOSED)throw new q(m.EFFECT_MUST_BE_FUNCTION);this.execute(!0)}dispose(){const e=this.flags;if(e&C.DISPOSED)return;this.flags=e|C.DISPOSED,this._safeCleanup();const t=this._unsubscribes;if(t!==V){for(let o=0,r=t.length;o<r;o++){const c=t[o];c&&c()}Q.release(t),this._unsubscribes=V}const n=this._dependencies;n!==y&&(B.release(n),this._dependencies=y);const i=this._dependencyVersions;i!==N&&(F.release(i),this._dependencyVersions=N),this._executeTask=void 0}addDependency(e){if(!(this.flags&C.EXECUTING))return;const t=this._currentEpoch;if(e._lastSeenEpoch===t)return;e._lastSeenEpoch=t;const n=this._nextDeps,i=this._nextVersions,o=this._nextUnsubs;if(!n||!i||!o)return;n.push(e),i.push(e.version);const r=e._tempUnsub;r?(o.push(r),e._tempUnsub=void 0):this._subscribeTo(e)}execute(e=!1){if(this.flags&(C.DISPOSED|C.EXECUTING)||!e&&!this._shouldExecute())return;this._checkInfiniteLoop(),this._setExecuting(!0),this._safeCleanup();const t=this._prepareEffectExecutionContext();let n=!1;try{const i=I.run(this,this._fn),o=t.nextDeps.length;t.nextDeps.length=o,t.nextVersions.length=o,this._dependencies=t.nextDeps,this._dependencyVersions=t.nextVersions,this._unsubscribes=t.nextUnsubs,n=!0,this._checkLoopWarnings(),Le(i)?i.then(r=>{!(this.flags&C.DISPOSED)&&typeof r=="function"&&(this._cleanup=r)}).catch(r=>this._handleExecutionError(r)):this._cleanup=typeof i=="function"?i:null}catch(i){n=!0,this._handleExecutionError(i),this._cleanup=null}finally{this._cleanupEffect(t,n),this._setExecuting(!1)}}_prepareEffectExecutionContext(){const e=this._dependencies,t=this._dependencyVersions,n=this._unsubscribes,i=B.acquire(),o=F.acquire(),r=Q.acquire(),c=Re();if(e!==y)for(let u=0,l=e.length;u<l;u++){const _=e[u];_&&(_._tempUnsub=n[u])}return this._nextDeps=i,this._nextVersions=o,this._nextUnsubs=r,this._currentEpoch=c,{prevDeps:e,prevVersions:t,prevUnsubs:n,nextDeps:i,nextVersions:o,nextUnsubs:r}}_cleanupEffect(e,t){this._nextDeps=null,this._nextVersions=null,this._nextUnsubs=null;const n=e.prevDeps;if(t){if(n!==y){for(let i=0,o=n.length;i<o;i++){const r=n[i],c=r?r._tempUnsub:void 0;c&&(c(),r&&(r._tempUnsub=void 0))}B.release(n)}e.prevUnsubs!==V&&Q.release(e.prevUnsubs),e.prevVersions!==N&&F.release(e.prevVersions)}else{B.release(e.nextDeps),F.release(e.nextVersions);const i=e.nextUnsubs;for(let o=0,r=i.length;o<r;o++)i[o]?.();if(Q.release(i),n!==y)for(let o=0,r=n.length;o<r;o++){const c=n[o];c&&(c._tempUnsub=void 0)}}}_subscribeTo(e){try{const t=e.subscribe(()=>{if(this._trackModifications&&this.flags&C.EXECUTING&&(e._modifiedAtEpoch=this._currentEpoch),this._sync){this.execute();return}let i=this._executeTask;i||(i=this._executeTask=()=>this.execute()),$.schedule(i)}),n=this._nextUnsubs;n&&n.push(t)}catch(t){console.error(ee(t,q,m.EFFECT_EXECUTION_FAILED));const n=this._nextUnsubs;n&&n.push(()=>{})}}get isDisposed(){return(this.flags&C.DISPOSED)!==0}get executionCount(){return this._executionCount}get isExecuting(){return(this.flags&C.EXECUTING)!==0}_setDisposed(){this.flags|=C.DISPOSED}_setExecuting(e){const t=C.EXECUTING;this.flags=this.flags&~t|(e?-1:0)&t}_safeCleanup(){const e=this._cleanup;if(e){try{e()}catch(t){console.error(ee(t,q,m.EFFECT_CLEANUP_FAILED))}this._cleanup=null}}_checkInfiniteLoop(){const e=Ee;this._lastFlushEpoch!==e&&(this._lastFlushEpoch=e,this._executionsInEpoch=0),++this._executionsInEpoch>this._maxExecutionsPerFlush&&this._throwInfiniteLoopError("per-effect"),it()>M.MAX_EXECUTIONS_PER_FLUSH&&this._throwInfiniteLoopError("global"),this._executionCount++;const t=this._history;if(t){const n=Date.now(),i=this._historyPtr,o=this._historyCapacity;t[i]=n;const r=(i+1)%o;this._historyPtr=r;const c=t[r]??0;if(c>0&&n-c<Ye.ONE_SECOND_MS){const u=new q(`Effect executed ${o} times within 1 second. Infinite loop suspected`);if(this.dispose(),console.error(u),this._onError&&this._onError(u),R)throw u}}}_throwInfiniteLoopError(e){const t=new q(`Infinite loop detected (${e}): effect executed ${this._executionsInEpoch} times in current flush. Total executions in flush: ${ge}`);throw this.dispose(),console.error(t),t}_shouldExecute(){const e=this._dependencies;if(e.length===0)return!0;const t=this._dependencyVersions;for(let n=0,i=e.length;n<i;n++){const o=e[n];if(o){if(o.version!==t[n])return!0;if("value"in o)try{be(()=>o.value)}catch{return!0}}}return!1}_handleExecutionError(e){const t=ee(e,q,m.EFFECT_EXECUTION_FAILED);console.error(t);const n=this._onError;n&&n(t)}_checkLoopWarnings(){if(this._trackModifications&&x.enabled){const e=this._dependencies,t=this._currentEpoch;for(let n=0,i=e.length;n<i;n++){const o=e[n];o&&o._modifiedAtEpoch===t&&x.warn(!0,`Effect is reading a dependency (${x.getDebugName(o)||"unknown"}) that it just modified. Infinite loop may occur`)}}}}function z(s,e={}){if(typeof s!="function")throw new q(m.EFFECT_MUST_BE_FUNCTION);const t=new ht(s,e);return t.execute(),t}function Se(s){if(typeof s!="function")throw new w("Batch callback must be a function");$.startBatch();try{return s()}finally{$.endBatch()}}function at(s){return s!==null&&typeof s=="object"&&"value"in s&&"subscribe"in s}function ue(s){if(!s)return"unknown";const e="jquery"in s?s[0]:s;if(!e)return"unknown";if(e.id)return`#${e.id}`;if(e.className){const t=String(e.className).split(/\s+/).filter(Boolean).join(".");return t?`${e.tagName.toLowerCase()}.${t}`:e.tagName.toLowerCase()}return e.tagName.toLowerCase()}function lt(s){const e=s.length;if(e===0)return new Int32Array(0);const t=new Int32Array(e),n=new Int32Array(e);let i=0;for(let r=0;r<e;r++){const c=s[r];if(c===-1)continue;if(i===0||s[n[i-1]]<c){t[r]=i>0?n[i-1]:-1,n[i++]=r;continue}let u=0,l=i-1;for(;u<l;){const _=u+l>>>1;s[n[_]]<c?u=_+1:l=_}c<s[n[u]]&&(u>0&&(t[r]=n[u-1]),n[u]=r)}const o=new Int32Array(i);for(let r=i-1,c=n[i-1];r>=0;r--)o[r]=c,c=t[c];return o}function ft(){if(typeof window<"u"){const s=window.__ATOM_DEBUG__;if(typeof s=="boolean")return s}try{if(typeof process<"u"&&process.env&&process.env.NODE_ENV==="development")return!0}catch{}return!1}let G=ft();const g={get enabled(){return G},set enabled(s){G=s},log(s,...e){G&&console.log(`[atom-effect-jquery] ${s}:`,...e)},atomChanged(s,e,t){G&&console.log(`[atom-effect-jquery] Atom "${s||"anonymous"}" changed:`,e,"→",t)},domUpdated(s,e,t){if(!G)return;const n=ue(s);console.log(`[atom-effect-jquery] DOM updated: ${n}.${e} =`,t),_t(s)},cleanup(s){G&&console.log(`[atom-effect-jquery] Cleanup: ${s}`)},warn(...s){G&&console.warn("[atom-effect-jquery]",...s)}};function _t(s){const e=s[0];if(!e||!document.contains(e))return;const t="atom_debug_timer",n="atom_debug_cleanup_timer",i="atom_debug_org_style";clearTimeout(s.data(t)),clearTimeout(s.data(n)),s.data(i)||s.data(i,{outline:s.css("outline"),outlineOffset:s.css("outline-offset"),transition:s.css("transition")}),s.css({outline:"2px solid rgba(255, 68, 68, 0.8)","outline-offset":"1px",transition:"none"});const o=setTimeout(()=>{const r=s.data(i);s.css("transition","outline 0.5s ease-out"),requestAnimationFrame(()=>{s.css({outline:r?.outline||"","outline-offset":r?.outlineOffset||""});const c=setTimeout(()=>{s.css("transition",r?.transition||""),s.removeData(t),s.removeData(n),s.removeData(i)},500);s.data(n,c)})},100);s.data(t,o)}const dt=new WeakMap;function Ve(s,e={}){const t=we(s,e);return e.name&&dt.set(t,{name:e.name}),t}Object.defineProperty(Ve,"debug",{get(){return g.enabled},set(s){g.enabled=s}});function pt(){return new Promise(s=>setTimeout(s,0))}h.extend({atom:Ve,computed:Me,effect:z,batch:Se,untracked:be,isAtom:me,isComputed:Fe,isReactive:s=>me(s)||Fe(s),nextTick:pt});const he="_aes-bound";class Et{effects=new WeakMap;cleanups=new WeakMap;boundElements=new WeakSet;preservedNodes=new WeakSet;ignoredNodes=new WeakSet;keep(e){this.preservedNodes.add(e)}isKept(e){return this.preservedNodes.has(e)}markIgnored(e){this.ignoredNodes.add(e)}isIgnored(e){return this.ignoredNodes.has(e)}trackEffect(e,t){let n=this.effects.get(e);n||(n=[],this.effects.set(e,n),this.boundElements.has(e)||(this.boundElements.add(e),e.classList.add(he))),n.push(t)}trackCleanup(e,t){let n=this.cleanups.get(e);n||(n=[],this.cleanups.set(e,n),this.boundElements.has(e)||(this.boundElements.add(e),e.classList.add(he))),n.push(t)}hasBind(e){return this.boundElements.has(e)}cleanup(e){if(!this.boundElements.delete(e))return;e.classList.remove(he),g.cleanup(ue(e));const t=this.effects.get(e);if(t){this.effects.delete(e);for(let i=0,o=t.length;i<o;i++){const r=t[i];if(r)try{r.dispose()}catch(c){g.warn("Effect dispose error:",c)}}}const n=this.cleanups.get(e);if(n){this.cleanups.delete(e);for(let i=0,o=n.length;i<o;i++){const r=n[i];if(r)try{r()}catch(c){g.warn("Cleanup error:",c)}}}}cleanupDescendants(e){const t=e.querySelectorAll(`.${he}`);for(let n=0,i=t.length;n<i;n++){const o=t[n];o&&this.boundElements.has(o)&&this.cleanup(o)}}cleanupTree(e){this.cleanupDescendants(e),this.cleanup(e)}}const d=new Et;let te=null;function Be(s=document.body){te||(te=new MutationObserver(e=>{for(let t=0,n=e.length;t<n;t++){const i=e[t];if(!i)continue;const o=i.removedNodes;for(let r=0,c=o.length;r<c;r++){const u=o[r];u&&(d.isKept(u)||d.isIgnored(u)||u.isConnected||u.nodeType===1&&d.cleanupTree(u))}}}),te.observe(s,{childList:!0,subtree:!0}))}function gt(){te?.disconnect(),te=null}function E(s,e,t,n){const i=h(s),o=s;if(at(e)){const r=z(()=>{const c=e.value;t(c),g.domUpdated(i,n,c)});d.trackEffect(o,r)}else t(e)}function je(){return{timeoutId:null,phase:"idle",hasFocus:!1}}function ze(s,e,t={}){const{debounce:n,event:i="input",parse:o=T=>T,format:r=T=>String(T??"")}=t,c=je(),u=()=>{c.phase="composing"},l=()=>{c.phase="idle",D()};s.on("compositionstart",u),s.on("compositionend",l);const _=()=>{c.hasFocus=!0},H=()=>{c.hasFocus=!1;const T=r(e.value);s.val()!==T&&s.val(T)};s.on("focus",_),s.on("blur",H);const D=()=>{c.phase==="idle"&&(c.phase="syncing-to-atom",e.value=o(s.val()),c.phase="idle")},L=()=>{c.phase==="idle"&&(n?(c.timeoutId&&clearTimeout(c.timeoutId),c.timeoutId=window.setTimeout(D,n)):D())};return s.on(i,L),s.on("change",L),{effect:()=>{const T=r(e.value),Z=s.val();if(Z!==T){if(c.hasFocus&&o(Z)===e.value)return;c.phase="syncing-to-dom",s.val(T),g.domUpdated(s,"val",T),c.phase="idle"}},cleanup:()=>{s.off(i,L),s.off("change",L),s.off("compositionstart",u),s.off("compositionend",l),s.off("focus",_),s.off("blur",H),c.timeoutId&&clearTimeout(c.timeoutId)}}}h.fn.atomText=function(s,e){return this.each(function(){E(this,s,t=>{const n=e?e(t):String(t??"");h(this).text(n)},"text")})},h.fn.atomHtml=function(s){return this.each(function(){E(this,s,e=>h(this).html(String(e??"")),"html")})},h.fn.atomClass=function(s,e){return this.each(function(){E(this,e,t=>h(this).toggleClass(s,!!t),`class.${s}`)})},h.fn.atomCss=function(s,e,t){return this.each(function(){E(this,e,n=>{const i=t?`${n}${t}`:n;h(this).css(s,i)},`css.${s}`)})},h.fn.atomAttr=function(s,e){return this.each(function(){E(this,e,t=>{const n=h(this);t==null||t===!1?n.removeAttr(s):t===!0?n.attr(s,s):n.attr(s,String(t))},`attr.${s}`)})},h.fn.atomProp=function(s,e){return this.each(function(){E(this,e,t=>h(this).prop(s,t),`prop.${s}`)})},h.fn.atomShow=function(s){return this.each(function(){E(this,s,e=>h(this).toggle(!!e),"show")})},h.fn.atomHide=function(s){return this.each(function(){E(this,s,e=>h(this).toggle(!e),"hide")})},h.fn.atomVal=function(s,e={}){return this.each(function(){const t=h(this),{effect:n,cleanup:i}=ze(t,s,e),o=z(n);d.trackEffect(this,o),d.trackCleanup(this,i)})},h.fn.atomChecked=function(s){return this.each(function(){const e=h(this);let t=!1;const n=()=>{t||(s.value=!!e.prop("checked"))};e.on("change",n),d.trackCleanup(this,()=>e.off("change",n));const i=z(()=>{t=!0;const o=!!s.value;e.prop("checked",o),g.domUpdated(e,"checked",o),t=!1});d.trackEffect(this,i)})},h.fn.atomOn=function(s,e){return this.each(function(){const t=h(this);t.on(s,e),d.trackCleanup(this,()=>t.off(s,e))})},h.fn.atomUnbind=function(){return this.each(function(){d.cleanupTree(this)})};function bt(s,e){E(s.el,e,t=>{s.el.textContent=String(t??"")},"text")}function mt(s,e){E(s.el,e,t=>{s.el.innerHTML=String(t??"")},"html")}function St(s,e){for(const t in e)E(s.el,e[t],n=>{s.el.classList.toggle(t,!!n)},`class.${t}`)}function yt(s,e){const t=s.el.style;for(const n in e){const i=e[n];if(i===void 0)continue;const o=n.includes("-")?n.replace(/-./g,r=>r.charAt(1).toUpperCase()):n;if(Array.isArray(i)){const[r,c]=i;E(s.el,r,u=>{t[o]=`${u}${c}`},`css.${n}`)}else E(s.el,i,r=>{t[o]=r},`css.${n}`)}}function It(s,e){const t=s.el;for(const n in e){const i=e[n];E(t,i,o=>{if(o==null||o===!1){t.removeAttribute(n);return}t.setAttribute(n,o===!0?n:String(o))},`attr.${n}`)}}function Dt(s,e){const t=s.el;for(const n in e)E(t,e[n],i=>{t[n]=i},`prop.${n}`)}function Ct(s,e){E(s.el,e,t=>{s.$el.toggle(!!t)},"show")}function Nt(s,e){E(s.el,e,t=>{s.$el.toggle(!t)},"hide")}function Tt(s,e){const t=Array.isArray(e)?e[0]:e,n=Array.isArray(e)?e[1]:{},{effect:i,cleanup:o}=ze(s.$el,t,n),r=z(i);d.trackEffect(s.el,r),s.trackCleanup(o)}function vt(s,e){const t=je(),n=()=>{t.phase==="idle"&&(e.value=s.$el.prop("checked"))};s.$el.on("change",n),s.trackCleanup(()=>s.$el.off("change",n));const i=z(()=>{t.phase="syncing-to-dom";const o=!!e.value;s.$el.prop("checked",o),g.domUpdated(s.$el,"checked",o),t.phase="idle"});d.trackEffect(s.el,i)}function At(s,e){const t=s.el;for(const n in e){const i=e[n];if(typeof i!="function")continue;const o=r=>i.call(t,h.Event(r));t.addEventListener(n,o),s.trackCleanup(()=>t.removeEventListener(n,o))}}h.fn.atomBind=function(s){return this.each(function(){const t={$el:h(this),el:this,effects:[],trackCleanup:n=>d.trackCleanup(this,n)};s.text!==void 0&&bt(t,s.text),s.html!==void 0&&mt(t,s.html),s.class&&St(t,s.class),s.css&&yt(t,s.css),s.attr&&It(t,s.attr),s.prop&&Dt(t,s.prop),s.show!==void 0&&Ct(t,s.show),s.hide!==void 0&&Nt(t,s.hide),s.val!==void 0&&Tt(t,s.val),s.checked!==void 0&&vt(t,s.checked),s.on&&At(t,s.on)})},h.fn.atomList=function(s,e){const{key:t,render:n,bind:i,update:o,onAdd:r,onRemove:c,empty:u}=e,l=typeof t=="function"?t:_=>_[t];return this.each(function(){const _=h(this),H=ue(this),D=new Map,L=new Set;let Y=[],J=null;const T=z(()=>{const Z=s.value,k=Z.length;if(k===0?u&&!J&&(J=h(u).appendTo(_)):J&&(J.remove(),J=null),k===0&&D.size===0){Y=[];return}g.log("list",`${H} updating with ${k} items`);const le=new Array(k),Xe=new Set;for(let f=0;f<k;f++){const b=Z[f],v=l(b,f);le[f]=v,Xe.add(v)}for(const[f,b]of D){if(Xe.has(f)||L.has(f))continue;const v=()=>{b.$el.remove();const S=b.$el[0];S&&d.cleanup(S),L.delete(f),g.log("list",`${H} removed item:`,f)};if(D.delete(f),L.add(f),c){const S=c(b.$el);S instanceof Promise?S.then(v):v()}else v()}if(k===0){Y=[];return}const qe=new Map;for(let f=0;f<Y.length;f++){const b=Y[f];b!==void 0&&qe.set(b,f)}const Qe=new Int32Array(k);for(let f=0;f<k;f++){const b=le[f];Qe[f]=b!==void 0?qe.get(b)??-1:-1}const Ge=lt(Qe);let Ie=Ge.length-1,P=null;for(let f=k-1;f>=0;f--){const b=le[f],v=Z[f],S=D.get(b);if(S){S.item=v;const K=S.$el[0];if(!K)continue;o&&o(S.$el,v,f),Ie>=0&&Ge[Ie]===f?(Ie--,K.nextSibling!==P&&(P?S.$el.insertBefore(P):S.$el.appendTo(_))):P?S.$el.insertBefore(P):S.$el.appendTo(_),P=K}else{const K=n(v,f),W=(K instanceof Element,h(K));D.set(b,{$el:W,item:v}),P?W.insertBefore(P):W.appendTo(_),i&&i(W,v,f),r&&r(W),g.log("list",`${H} added item:`,b),P=W[0]||null}}Y=le});d.trackEffect(this,T),d.trackCleanup(this,()=>{D.clear(),L.clear(),Y=[],J?.remove()})})};const ae=new WeakMap;h.fn.atomMount=function(s,e={}){return this.each(function(){const t=h(this),n=ue(this),i=ae.get(this);i&&(g.log("mount",`${n} unmounting existing component`),i()),g.log("mount",`${n} mounting component`);let o;try{o=s(t,e)}catch(u){console.error("[atom-effect-jquery] Mount error:",u);return}let r=!1;const c=()=>{if(!r){if(r=!0,g.log("mount",`${n} full cleanup`),typeof o=="function")try{o()}catch{}d.cleanupTree(this),ae.delete(this)}};ae.set(this,c),d.trackCleanup(this,c)})},h.fn.atomUnmount=function(){return this.each(function(){ae.get(this)?.()})};const se=new WeakMap;let He=!1;function ye(){if(He)return;He=!0;const s=h.fn.on,e=h.fn.off,t=h.fn.remove,n=h.fn.empty,i=h.fn.detach;h.fn.remove=function(o){return(o?this.filter(o):this).each(function(){d.cleanupTree(this),d.markIgnored(this)}),t.call(this,o)},h.fn.empty=function(){return this.each(function(){d.cleanupDescendants(this)}),n.call(this)},h.fn.detach=function(o){return(o?this.filter(o):this).each(function(){d.keep(this)}),i.call(this,o)},h.fn.on=function(...o){let r=-1;for(let c=o.length-1;c>=0;c--)if(typeof o[c]=="function"){r=c;break}if(r!==-1){const c=o[r];let u;se.has(c)?u=se.get(c):(u=function(...l){return Se(()=>c.apply(this,l))},se.set(c,u)),o[r]=u}return s.apply(this,o)},h.fn.off=function(...o){let r=-1;for(let c=o.length-1;c>=0;c--)if(typeof o[c]=="function"){r=c;break}if(r!==-1){const c=o[r];se.has(c)&&(o[r]=se.get(c))}return e.apply(this,o)}}const Ot=ye;ye(),h(()=>{Be(document.body)}),p.default=h,p.atom=we,p.batch=Se,p.computed=Me,p.disableAutoCleanup=gt,p.effect=z,p.enableAutoCleanup=Be,p.enablejQueryBatching=Ot,p.enablejQueryOverrides=ye,p.registry=d,p.untracked=be,Object.defineProperties(p,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}));
1
+ (function(p,h){typeof exports=="object"&&typeof module<"u"?h(exports,require("jquery")):typeof define=="function"&&define.amd?define(["exports","jquery"],h):(p=typeof globalThis<"u"?globalThis:p||self,h(p.AtomEffectJQuery={},p.jQuery))})(this,(function(p,h){"use strict";const Qe={ONE_SECOND_MS:1e3},se={IDLE:"idle",PENDING:"pending",RESOLVED:"resolved",REJECTED:"rejected"},A={DISPOSED:1,HAS_FN_SUBS:2,HAS_OBJ_SUBS:4},x={...A,EXECUTING:8},l={...A,DIRTY:8,IDLE:16,PENDING:32,RESOLVED:64,REJECTED:128,RECOMPUTING:256,HAS_ERROR:512},U={...A,SYNC:8,NOTIFICATION_SCHEDULED:16},k={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},De={MAX_DEPENDENCIES:1e3,WARN_INFINITE_LOOP:!0},B=1073741823,D=typeof process<"u"&&process.env&&process.env.NODE_ENV!=="production",Ye=Object.freeze([]);class F extends Error{constructor(e,s=null,n=!0){super(e),this.name="AtomError",this.cause=s,this.recoverable=n,this.timestamp=new Date}}class M extends F{constructor(e,s=null){super(e,s,!0),this.name="ComputedError"}}class G extends F{constructor(e,s=null){super(e,s,!1),this.name="EffectError"}}class ne extends F{constructor(e,s=null){super(e,s,!1),this.name="SchedulerError"}}const E={COMPUTED_MUST_BE_FUNCTION:"Computed function must be a function",COMPUTED_SUBSCRIBER_MUST_BE_FUNCTION:"Subscriber listener must be a function or Subscriber object",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_DEPENDENCY_SUBSCRIPTION_FAILED:"Failed to subscribe to dependency",ATOM_SUBSCRIBER_MUST_BE_FUNCTION:"Subscription listener must be a function or Subscriber object",ATOM_SUBSCRIBER_EXECUTION_FAILED:"Error occurred while executing atom subscribers",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:t=>`Large dependency graph detected: ${t} dependencies`,UNSUBSCRIBE_NON_EXISTENT:"Attempted to unsubscribe a non-existent listener",CALLBACK_ERROR_IN_ERROR_HANDLER:"Error occurred during onError callback execution"},fe=Symbol("debugName"),Je=Symbol("id"),de=Symbol("type"),Ce=Symbol("noDefaultValue");function Ke(t){return"dependencies"in t&&Array.isArray(t.dependencies)}let Ne=0;function Te(t,e,s){if(t._visitedEpoch!==s){if(t._visitedEpoch=s,t===e)throw new M("Indirect circular dependency detected");if(Ke(t)){const n=t.dependencies;for(let i=0;i<n.length;i++){const o=n[i];o&&Te(o,e,s)}}}}const w={enabled:typeof process<"u"&&process.env?.NODE_ENV==="development",maxDependencies:De.MAX_DEPENDENCIES,warnInfiniteLoop:De.WARN_INFINITE_LOOP,warn(t,e){this.enabled&&t&&console.warn(`[Atom Effect] ${e}`)},checkCircular(t,e){if(t===e)throw new M("Direct circular dependency detected");this.enabled&&(Ne++,Te(t,e,Ne))},attachDebugInfo(t,e,s){if(!this.enabled)return;const n=t;n[fe]=`${e}_${s}`,n[Je]=s,n[de]=e},getDebugName(t){if(t!=null&&fe in t)return t[fe]},getDebugType(t){if(t!=null&&de in t)return t[de]}};let We=1;const Ze=()=>We++;class Oe{constructor(){this.flags=0,this.version=0,this._lastSeenEpoch=-1,this._modifiedAtEpoch=-1,this._visitedEpoch=-1,this.id=Ze()&B,this._tempUnsub=void 0}getShift(e){return this.version-e&B}}class Re extends Oe{subscribe(e){if(typeof e=="function")return this._addSubscriber(this._fnSubs,e,A.HAS_FN_SUBS);if(e!==null&&typeof e=="object"&&"execute"in e)return this._addSubscriber(this._objSubs,e,A.HAS_OBJ_SUBS);throw new F(E.ATOM_SUBSCRIBER_MUST_BE_FUNCTION)}subscriberCount(){return this._fnSubs.length+this._objSubs.length}_addSubscriber(e,s,n){if(e.indexOf(s)!==-1)return D&&console.warn("Attempted to subscribe the same listener twice. Ignoring duplicate subscription."),()=>{};e.push(s),this.flags|=n;let i=!1;return()=>{if(i)return;i=!0;const o=e.indexOf(s);if(o!==-1){const r=e.pop();o<e.length&&(e[o]=r),this.flags&=~(e.length===0?n:0)}}}_notifySubscribers(e,s){const n=this.flags,i=A.HAS_FN_SUBS|A.HAS_OBJ_SUBS;if(n&i){if(n&A.HAS_FN_SUBS){const o=this._fnSubs;for(let r=0,c=o.length;r<c;r++){const u=o[r];if(u)try{u(e,s)}catch(a){console.error(new F(E.ATOM_INDIVIDUAL_SUBSCRIBER_FAILED,a))}}}if(n&A.HAS_OBJ_SUBS){const o=this._objSubs;for(let r=0,c=o.length;r<c;r++){const u=o[r];if(u)try{u.execute()}catch(a){console.error(new F(E.ATOM_INDIVIDUAL_SUBSCRIBER_FAILED,a))}}}}}}class $e{constructor(){this.acquired=0,this.released=0,this.rejected=new et}}class et{constructor(){this.frozen=0,this.tooLarge=0,this.poolFull=0}}class _e{constructor(){this.pool=[],this.maxPoolSize=50,this.maxReusableCapacity=256,this.stats=D?new $e:null}acquire(){const e=this.stats;return D&&e&&e.acquired++,this.pool.pop()??[]}release(e,s){if(s&&e===s||Object.isFrozen(e)){const c=this.stats;D&&c&&e!==s&&c.rejected.frozen++;return}const n=e.length,i=this.pool,o=i.length;if(n>this.maxReusableCapacity||o>=this.maxPoolSize){const c=this.stats;D&&c&&(n>this.maxReusableCapacity?c.rejected.tooLarge++:c.rejected.poolFull++);return}e.length=0,i.push(e);const r=this.stats;D&&r&&r.released++}getStats(){const e=this.stats;if(!D||!e)return null;const{acquired:s,released:n,rejected:i}=e,o=i.frozen+i.tooLarge+i.poolFull;return{acquired:s,released:n,rejected:{frozen:i.frozen,tooLarge:i.tooLarge,poolFull:i.poolFull},leaked:s-n-o,poolSize:this.pool.length}}reset(){this.pool.length=0;const e=this.stats;D&&e&&(e.acquired=0,e.released=0,e.rejected.frozen=0,e.rejected.tooLarge=0,e.rejected.poolFull=0)}}const C=Object.freeze([]),j=Object.freeze([]),T=Object.freeze([]),V=new _e,Q=new _e,L=new _e;function H(t,e,s,n){if(e!=null){if((typeof e=="object"||typeof e=="function")&&typeof e.addDependency=="function"){e.addDependency(t);return}if(typeof e=="function"){const i=e;s.indexOf(i)===-1&&(s.push(i),t.flags|=A.HAS_FN_SUBS);return}typeof e=="object"&&typeof e.execute=="function"&&n.indexOf(e)===-1&&(n.push(e),t.flags|=A.HAS_OBJ_SUBS)}}function Ae(t,e,s,n){const i=t.length,o=e.length,r=e!==C&&o>0;if(r)for(let u=0;u<o;u++){const a=e[u];a&&(a._tempUnsub=s[u])}const c=Q.acquire();c.length=i;for(let u=0;u<i;u++){const a=t[u];if(!a)continue;const d=a._tempUnsub;d?(c[u]=d,a._tempUnsub=void 0):(w.checkCircular(a,n),c[u]=a.subscribe(n))}if(r)for(let u=0;u<o;u++){const a=e[u];if(a){const d=a._tempUnsub;d&&(d(),a._tempUnsub=void 0)}}return s!==j&&Q.release(s),c}let ie=0;function xe(){return ie=ie+1&B||1,ie}function tt(){return ie}let pe=0,Ee=0,oe=!1;function ve(){return oe?(D&&console.warn("Warning: startFlush() called during flush - ignored to prevent infinite loop detection bypass"),!1):(oe=!0,pe=pe+1&B||1,Ee=0,!0)}function Ue(){oe=!1}function st(){return oe?++Ee:0}class nt{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=k.MAX_FLUSH_ITERATIONS}get phase(){return this.isProcessing||this.isFlushingSync?2:this.isBatching?1:0}get queueSize(){return this._size}schedule(e){if(D&&typeof e!="function")throw new ne("Scheduler callback must be a function");const s=this._epoch;if(e._nextEpoch!==s){if(e._nextEpoch=s,this.isBatching||this.isFlushingSync){this.batchQueue[this.batchQueueSize++]=e;return}this._queueBuffer[this._bufferIndex][this._size++]=e,this.isProcessing||this.flush()}}flush(){this.isProcessing||this._size===0||(this.isProcessing=!0,queueMicrotask(()=>{try{if(this._size===0)return;const e=ve();this._drainQueue(),e&&Ue()}finally{this.isProcessing=!1,this._size>0&&!this.isBatching&&this.flush()}}))}flushSync(){this.isFlushingSync=!0;const e=ve();try{this._mergeBatchQueue(),this._drainQueue()}finally{this.isFlushingSync=!1,e&&Ue()}}_mergeBatchQueue(){const e=this.batchQueueSize;if(e===0)return;const s=++this._epoch,n=this.batchQueue,i=this._queueBuffer[this._bufferIndex];let o=this._size;for(let r=0;r<e;r++){const c=n[r];c._nextEpoch!==s&&(c._nextEpoch=s,i[o++]=c)}this._size=o,this.batchQueueSize=0,n.length>k.BATCH_QUEUE_SHRINK_THRESHOLD&&(n.length=0)}_drainQueue(){let e=0;const s=this.maxFlushIterations;for(;this._size>0;){if(++e>s){this._handleFlushOverflow();return}this._processQueue(),this._mergeBatchQueue()}}_processQueue(){const e=this._bufferIndex,s=this._queueBuffer[e],n=this._size,i=e^1;this._bufferIndex=i,this._size=0,this._epoch++,this._processJobs(s,n)}_handleFlushOverflow(){console.error(new ne(`Maximum flush iterations (${this.maxFlushIterations}) exceeded. Possible infinite loop.`)),this._size=0,this._queueBuffer[this._bufferIndex].length=0,this.batchQueueSize=0}_processJobs(e,s){for(let n=0;n<s;n++)try{e[n]()}catch(i){console.error(new ne("Error occurred during scheduler execution",i))}e.length=0}startBatch(){this.batchDepth++,this.isBatching=!0}endBatch(){if(this.batchDepth===0){D&&console.warn("endBatch() called without matching startBatch(). Ignoring.");return}this.batchDepth--,this.batchDepth===0&&(this.flushSync(),this.isBatching=!1)}setMaxFlushIterations(e){if(e<k.MIN_FLUSH_ITERATIONS)throw new ne(`Max flush iterations must be at least ${k.MIN_FLUSH_ITERATIONS}`);this.maxFlushIterations=e}}const Z=new nt;class it{constructor(){this.current=null}run(e,s){const n=this.current;this.current=e;try{return s()}finally{this.current=n}}getCurrent(){return this.current}}const N=new it;function ge(t){if(typeof t!="function")throw new F("Untracked callback must be a function");const e=N.current;N.current=null;try{return t()}finally{N.current=e}}class ot extends Re{constructor(e,s){super(),this._value=e,this._pendingOldValue=void 0,this._notifyTask=void 0,this._fnSubs=[],this._objSubs=[],s&&(this.flags|=U.SYNC),w.attachDebugInfo(this,"atom",this.id)}get value(){const e=N.current;return e&&H(this,e,this._fnSubs,this._objSubs),this._value}set value(e){const s=this._value;if(Object.is(s,e))return;this._value=e,this.version=this.version+1&B;const n=this.flags,i=U.HAS_FN_SUBS|U.HAS_OBJ_SUBS;n&i&&this._scheduleNotification(s)}_scheduleNotification(e){let s=this.flags;if(s&U.NOTIFICATION_SCHEDULED||(this._pendingOldValue=e,this.flags=s|=U.NOTIFICATION_SCHEDULED),s&U.SYNC&&!Z.isBatching){this._flushNotifications();return}let n=this._notifyTask;n||(n=this._notifyTask=()=>this._flushNotifications()),Z.schedule(n)}_flushNotifications(){const e=this.flags;if(!(e&U.NOTIFICATION_SCHEDULED)||e&U.DISPOSED)return;const s=this._pendingOldValue,n=this._value;this._pendingOldValue=void 0,this.flags&=-17,this._notifySubscribers(n,s)}peek(){return this._value}dispose(){this.flags&U.DISPOSED||(this._fnSubs=[],this._objSubs=[],this.flags|=U.DISPOSED,this._value=void 0,this._pendingOldValue=void 0,this._notifyTask=void 0)}}function we(t,e={}){return new ot(t,e.sync??!1)}function $(t,e,s){if(t instanceof TypeError)return new e(`Type error (${s}): ${t.message}`,t);if(t instanceof ReferenceError)return new e(`Reference error (${s}): ${t.message}`,t);if(t instanceof F)return t;const n=t instanceof Error?t.message:String(t),i=t instanceof Error?t:null;return new e(`Unexpected error (${s}): ${n}`,i)}function be(t){return t!==null&&typeof t=="object"&&"value"in t&&"subscribe"in t&&typeof t.subscribe=="function"}function Fe(t){if(w.enabled&&t!=null&&typeof t=="object"){const e=w.getDebugType(t);if(e)return e==="computed"}return be(t)&&"invalidate"in t&&typeof t.invalidate=="function"}function Le(t){return t!=null&&typeof t.then=="function"}const Pe=l.RESOLVED|l.PENDING|l.REJECTED,re=Array(Pe+1).fill(se.IDLE);re[l.RESOLVED]=se.RESOLVED,re[l.PENDING]=se.PENDING,re[l.REJECTED]=se.REJECTED;class rt{constructor(e){this._owner=e,this._epoch=-1,this._nextDeps=C,this._nextVersions=T,this._depCount=0}execute(){this._owner._markDirty()}addDependency(e){if(e._lastSeenEpoch===this._epoch)return;e._lastSeenEpoch=this._epoch;const s=this._depCount,n=this._nextDeps,i=this._nextVersions;s<n.length?(n[s]=e,i[s]=e.version):(n.push(e),i.push(e.version)),this._depCount=s+1}reset(){this._epoch=-1,this._nextDeps=C,this._nextVersions=T,this._depCount=0}}class ke extends Re{constructor(e,s={}){if(typeof e!="function")throw new M(E.COMPUTED_MUST_BE_FUNCTION);if(super(),this.MAX_ASYNC_RETRIES=3,this._value=void 0,this.flags=l.DIRTY|l.IDLE,this._error=null,this._promiseId=0,this._equal=s.equal??Object.is,this._fn=e,this._defaultValue="defaultValue"in s?s.defaultValue:Ce,this._hasDefaultValue=this._defaultValue!==Ce,this._onError=s.onError??null,this.MAX_PROMISE_ID=Number.MAX_SAFE_INTEGER-1,this._fnSubs=[],this._objSubs=[],this._dependencies=C,this._dependencyVersions=T,this._unsubscribes=j,this._cachedErrors=null,this._errorCacheEpoch=-1,this._asyncStartAggregateVersion=0,this._asyncRetryCount=0,this._trackable=new rt(this),w.attachDebugInfo(this,"computed",this.id),w.enabled){const n=this;n.subscriberCount=this.subscriberCount.bind(this),n.isDirty=()=>(this.flags&l.DIRTY)!==0,n.dependencies=this._dependencies,n.stateFlags=""}if(s.lazy===!1)try{this._recompute()}catch{}}get value(){const e=N.current;e&&H(this,e,this._fnSubs,this._objSubs);const s=this.flags;if(s&l.RECOMPUTING){if(this._hasDefaultValue)return this._defaultValue;throw new M(E.COMPUTED_CIRCULAR_DEPENDENCY)}s&(l.DIRTY|l.IDLE)&&this._recompute();const n=this.flags;return n&l.PENDING?this._handlePending():n&l.REJECTED?this._handleRejected():this._value}peek(){return this._value}get state(){const e=N.current;return e&&H(this,e,this._fnSubs,this._objSubs),re[this.flags&Pe]}get hasError(){const e=N.current;if(e&&H(this,e,this._fnSubs,this._objSubs),this.flags&(l.REJECTED|l.HAS_ERROR))return!0;const s=this._dependencies;for(let n=0,i=s.length;n<i;n++){const o=s[n];if(o&&o.flags&l.HAS_ERROR)return!0}return!1}get isValid(){return!this.hasError}get errors(){const e=N.current;if(e&&H(this,e,this._fnSubs,this._objSubs),!this.hasError)return Ye;const s=tt();if(this._errorCacheEpoch===s&&this._cachedErrors!==null)return this._cachedErrors;const n=new Set;this._error&&n.add(this._error);const i=this._dependencies;for(let r=0,c=i.length;r<c;r++){const u=i[r];if(u&&"errors"in u){const a=u.errors;for(let d=0,q=a.length;d<q;d++){const O=a[d];O&&n.add(O)}}}const o=Object.freeze([...n]);return this._cachedErrors=o,this._errorCacheEpoch=s,o}get lastError(){const e=N.current;return e&&H(this,e,this._fnSubs,this._objSubs),this._error}get isPending(){const e=N.current;return e&&H(this,e,this._fnSubs,this._objSubs),(this.flags&l.PENDING)!==0}get isResolved(){const e=N.current;return e&&H(this,e,this._fnSubs,this._objSubs),(this.flags&l.RESOLVED)!==0}invalidate(){this._markDirty();const e=this._dependencyVersions;e!==T&&(L.release(e),this._dependencyVersions=T),this._errorCacheEpoch=-1,this._cachedErrors=null}dispose(){const e=this._unsubscribes;if(e!==j){for(let i=0,o=e.length;i<o;i++){const r=e[i];r&&r()}Q.release(e),this._unsubscribes=j}const s=this._dependencies;s!==C&&(V.release(s),this._dependencies=C);const n=this._dependencyVersions;n!==T&&(L.release(n),this._dependencyVersions=T),this._fnSubs=[],this._objSubs=[],this.flags=l.DISPOSED|l.DIRTY|l.IDLE,this._error=null,this._value=void 0,this._promiseId=(this._promiseId+1)%this.MAX_PROMISE_ID,this._cachedErrors=null,this._errorCacheEpoch=-1}_clearDirty(){this.flags&=-9}_setPending(){this.flags=(this.flags|l.PENDING)&-209}_isResolved(){return(this.flags&l.RESOLVED)!==0}_setResolved(){this.flags=(this.flags|l.RESOLVED)&-689}_isRejected(){return(this.flags&l.REJECTED)!==0}_setRejected(){this.flags=this.flags&-113|(l.REJECTED|l.HAS_ERROR)}_setRecomputing(e){const s=l.RECOMPUTING;this.flags=this.flags&~s|(e?-1:0)&s}_recompute(){if(this.flags&l.RECOMPUTING)return;this._setRecomputing(!0);const e=this._trackable,s=this._dependencies,n=this._dependencyVersions;e._epoch=xe(),e._nextDeps=V.acquire(),e._nextVersions=L.acquire(),e._depCount=0;let i=!1;try{const o=N.run(e,this._fn),r=e._nextDeps,c=e._nextVersions,u=e._depCount;r.length=u,c.length=u,this._unsubscribes=Ae(r,s,this._unsubscribes,this),this._dependencies=r,this._dependencyVersions=c,i=!0,Le(o)?this._handleAsyncComputation(o):this._finalizeResolution(o)}catch(o){let r=o;if(!i)try{const c=e._nextDeps,u=e._nextVersions,a=e._depCount;c.length=a,u.length=a,this._unsubscribes=Ae(c,s,this._unsubscribes,this),this._dependencies=c,this._dependencyVersions=u,i=!0}catch(c){r=c}this._handleComputationError(r)}finally{i?(s!==C&&V.release(s),n!==T&&L.release(n)):(V.release(e._nextDeps),L.release(e._nextVersions)),e.reset(),this._setRecomputing(!1)}}_handleAsyncComputation(e){this._setPending(),this._clearDirty(),this._notifySubscribers(void 0,void 0),this._asyncStartAggregateVersion=this._captureVersionSnapshot(),this._asyncRetryCount=0,this._promiseId=(this._promiseId+1)%this.MAX_PROMISE_ID;const s=this._promiseId;e.then(n=>{if(s===this._promiseId){if(this._captureVersionSnapshot()!==this._asyncStartAggregateVersion){if(this._asyncRetryCount<this.MAX_ASYNC_RETRIES){this._asyncRetryCount++,this._markDirty();return}const i=new M(`Async drift exceeded threshold after ${this.MAX_ASYNC_RETRIES} retries.`);this._handleAsyncRejection(i);return}this._finalizeResolution(n),this._notifySubscribers(n,void 0)}}).catch(n=>{s===this._promiseId&&this._handleAsyncRejection(n)})}_captureVersionSnapshot(){let e=0;const s=this._dependencies;for(let n=0,i=s.length;n<i;n++){const o=s[n];if(o){const r=o.version;e=((e<<5)-e|0)+r&B}}return e}_handleAsyncRejection(e){const s=$(e,M,E.COMPUTED_ASYNC_COMPUTATION_FAILED);this.flags&l.REJECTED||(this.version=this.version+1&B),this._error=s,this._setRejected(),this._clearDirty();const n=this._onError;if(n)try{n(s)}catch(i){console.error(E.CALLBACK_ERROR_IN_ERROR_HANDLER,i)}this._notifySubscribers(void 0,void 0)}_finalizeResolution(e){(!(this.flags&l.RESOLVED)||!this._equal(this._value,e))&&(this.version=this.version+1&B),this._value=e,this._clearDirty(),this._setResolved(),this._error=null,this._setRecomputing(!1),this._cachedErrors=null,this._errorCacheEpoch=-1}_handleComputationError(e){const s=$(e,M,E.COMPUTED_COMPUTATION_FAILED);this._error=s,this._setRejected(),this._clearDirty(),this._setRecomputing(!1);const n=this._onError;if(n)try{n(s)}catch(i){console.error(E.CALLBACK_ERROR_IN_ERROR_HANDLER,i)}throw s}_handlePending(){if(this._hasDefaultValue)return this._defaultValue;throw new M(E.COMPUTED_ASYNC_PENDING_NO_DEFAULT)}_handleRejected(){const e=this._error;if(e?.recoverable&&this._hasDefaultValue)return this._defaultValue;throw e}execute(){this._markDirty()}_markDirty(){const e=this.flags;e&(l.RECOMPUTING|l.DIRTY)||(this.flags=e|l.DIRTY,this._notifySubscribers(void 0,void 0))}}Object.freeze(ke.prototype);function Be(t,e={}){return new ke(t,e)}class ct extends Oe{constructor(e,s={}){super(),this._cleanup=null,this._dependencies=C,this._dependencyVersions=T,this._unsubscribes=j,this._nextDeps=null,this._nextVersions=null,this._nextUnsubs=null,this._executeTask=void 0,this._onError=s.onError??null,this._currentEpoch=-1,this._lastFlushEpoch=-1,this._executionsInEpoch=0,this._fn=e,this._sync=s.sync??!1,this._maxExecutions=s.maxExecutionsPerSecond??k.MAX_EXECUTIONS_PER_SECOND,this._maxExecutionsPerFlush=s.maxExecutionsPerFlush??k.MAX_EXECUTIONS_PER_EFFECT,this._trackModifications=s.trackModifications??!1,this._executionCount=0,this._historyPtr=0;const n=Number.isFinite(this._maxExecutions),i=n?Math.min(this._maxExecutions+1,k.MAX_EXECUTIONS_PER_SECOND+1):0;this._historyCapacity=i,this._history=D&&n&&i>0?new Array(i).fill(0):null,this._execId=0,w.attachDebugInfo(this,"effect",this.id)}run(){if(this.flags&x.DISPOSED)throw new G(E.EFFECT_DISPOSED);this.execute(!0)}dispose(){const e=this.flags;if(e&x.DISPOSED)return;this.flags=e|x.DISPOSED,this._safeCleanup();const s=this._unsubscribes;if(s!==j){for(let o=0,r=s.length;o<r;o++){const c=s[o];c&&c()}Q.release(s),this._unsubscribes=j}const n=this._dependencies;n!==C&&(V.release(n),this._dependencies=C);const i=this._dependencyVersions;i!==T&&(L.release(i),this._dependencyVersions=T),this._executeTask=void 0}addDependency(e){if(!(this.flags&x.EXECUTING))return;const s=this._currentEpoch;if(e._lastSeenEpoch===s)return;e._lastSeenEpoch=s;const n=this._nextDeps,i=this._nextVersions,o=this._nextUnsubs;if(!n||!i||!o)return;n.push(e),i.push(e.version);const r=e._tempUnsub;r?(o.push(r),e._tempUnsub=void 0):this._subscribeTo(e)}execute(e=!1){if(this.flags&(x.DISPOSED|x.EXECUTING)||!e&&!this._shouldExecute())return;this._checkInfiniteLoop(),this._setExecuting(!0),this._safeCleanup();const s=this._prepareEffectExecutionContext();let n=!1;try{const i=N.run(this,this._fn),o=s.nextDeps.length;s.nextDeps.length=o,s.nextVersions.length=o,this._dependencies=s.nextDeps,this._dependencyVersions=s.nextVersions,this._unsubscribes=s.nextUnsubs,n=!0,this._checkLoopWarnings();const r=++this._execId;Le(i)?i.then(c=>{const u=r!==this._execId,a=this.flags&x.DISPOSED;if(u||a){if(typeof c=="function")try{c()}catch(d){this._handleExecutionError(d,E.EFFECT_CLEANUP_FAILED)}return}typeof c=="function"&&(this._cleanup=c)}).catch(c=>{r===this._execId&&this._handleExecutionError(c)}):this._cleanup=typeof i=="function"?i:null}catch(i){n=!0,this._handleExecutionError(i),this._cleanup=null}finally{this._cleanupEffect(s,n),this._setExecuting(!1)}}_prepareEffectExecutionContext(){const e=this._dependencies,s=this._dependencyVersions,n=this._unsubscribes,i=V.acquire(),o=L.acquire(),r=Q.acquire(),c=xe();if(e!==C)for(let u=0,a=e.length;u<a;u++){const d=e[u];d&&(d._tempUnsub=n[u])}return this._nextDeps=i,this._nextVersions=o,this._nextUnsubs=r,this._currentEpoch=c,{prevDeps:e,prevVersions:s,prevUnsubs:n,nextDeps:i,nextVersions:o,nextUnsubs:r}}_cleanupEffect(e,s){this._nextDeps=null,this._nextVersions=null,this._nextUnsubs=null;const n=e.prevDeps;if(s){if(n!==C){for(let i=0,o=n.length;i<o;i++){const r=n[i],c=r?r._tempUnsub:void 0;c&&(c(),r&&(r._tempUnsub=void 0))}V.release(n)}e.prevUnsubs!==j&&Q.release(e.prevUnsubs),e.prevVersions!==T&&L.release(e.prevVersions)}else{V.release(e.nextDeps),L.release(e.nextVersions);const i=e.nextUnsubs;for(let o=0,r=i.length;o<r;o++)i[o]?.();if(Q.release(i),n!==C)for(let o=0,r=n.length;o<r;o++){const c=n[o];c&&(c._tempUnsub=void 0)}}}_subscribeTo(e){try{const s=e.subscribe(()=>{if(this._trackModifications&&this.flags&x.EXECUTING&&(e._modifiedAtEpoch=this._currentEpoch),this._sync){this.execute();return}let i=this._executeTask;i||(i=this._executeTask=()=>this.execute()),Z.schedule(i)}),n=this._nextUnsubs;n&&n.push(s)}catch(s){console.error($(s,G,E.EFFECT_EXECUTION_FAILED));const n=this._nextUnsubs;n&&n.push(()=>{})}}get isDisposed(){return(this.flags&x.DISPOSED)!==0}get executionCount(){return this._executionCount}get isExecuting(){return(this.flags&x.EXECUTING)!==0}_setExecuting(e){const s=x.EXECUTING;this.flags=this.flags&~s|(e?-1:0)&s}_safeCleanup(){const e=this._cleanup;if(e){try{e()}catch(s){this._handleExecutionError(s,E.EFFECT_CLEANUP_FAILED)}this._cleanup=null}}_checkInfiniteLoop(){const e=pe;this._lastFlushEpoch!==e&&(this._lastFlushEpoch=e,this._executionsInEpoch=0),++this._executionsInEpoch>this._maxExecutionsPerFlush&&this._throwInfiniteLoopError("per-effect"),st()>k.MAX_EXECUTIONS_PER_FLUSH&&this._throwInfiniteLoopError("global"),this._executionCount++;const s=this._history;if(s){const n=Date.now(),i=this._historyPtr,o=this._historyCapacity;s[i]=n;const r=(i+1)%o;this._historyPtr=r;const c=s[r]??0;if(c>0&&n-c<Qe.ONE_SECOND_MS){const u=new G(`Effect executed ${o} times within 1 second. Infinite loop suspected`);if(this.dispose(),console.error(u),this._onError&&this._onError(u),D)throw u;return}}}_throwInfiniteLoopError(e){const s=new G(`Infinite loop detected (${e}): effect executed ${this._executionsInEpoch} times in current flush. Total executions in flush: ${Ee}`);throw this.dispose(),console.error(s),s}_shouldExecute(){const e=this._dependencies;if(e.length===0)return!0;const s=this._dependencyVersions;for(let n=0,i=e.length;n<i;n++){const o=e[n];if(o){if(o.version!==s[n])return!0;if("value"in o)try{ge(()=>o.value)}catch{return!0}}}return!1}_handleExecutionError(e,s=E.EFFECT_EXECUTION_FAILED){const n=$(e,G,s);console.error(n);const i=this._onError;if(i)try{i(n)}catch(o){console.error($(o,G,E.CALLBACK_ERROR_IN_ERROR_HANDLER))}}_checkLoopWarnings(){if(this._trackModifications&&w.enabled){const e=this._dependencies,s=this._currentEpoch;for(let n=0,i=e.length;n<i;n++){const o=e[n];o&&o._modifiedAtEpoch===s&&w.warn(!0,`Effect is reading a dependency (${w.getDebugName(o)||"unknown"}) that it just modified. Infinite loop may occur`)}}}}function z(t,e={}){if(typeof t!="function")throw new G(E.EFFECT_MUST_BE_FUNCTION);const s=new ct(t,e);return s.execute(),s}function ce(t){if(typeof t!="function")throw new F("Batch callback must be a function");Z.startBatch();try{return t()}finally{Z.endBatch()}}function ut(t){return t!==null&&typeof t=="object"&&"value"in t&&"subscribe"in t}function ue(t){if(!t)return"unknown";const e="jquery"in t?t[0]:t;if(!e)return"unknown";if(e.id)return`#${e.id}`;if(e.className){const s=String(e.className).split(/\s+/).filter(Boolean).join(".");return s?`${e.tagName.toLowerCase()}.${s}`:e.tagName.toLowerCase()}return e.tagName.toLowerCase()}function ht(t){const e=t.length;if(e===0)return new Int32Array(0);const s=new Int32Array(e),n=new Int32Array(e);let i=0;for(let r=0;r<e;r++){const c=t[r];if(c===-1)continue;if(i===0||t[n[i-1]]<c){s[r]=i>0?n[i-1]:-1,n[i++]=r;continue}let u=0,a=i-1;for(;u<a;){const d=u+a>>>1;t[n[d]]<c?u=d+1:a=d}c<t[n[u]]&&(u>0&&(s[r]=n[u-1]),n[u]=r)}const o=new Int32Array(i);for(let r=i-1,c=n[i-1];r>=0;r--)o[r]=c,c=s[c];return o}function at(){if(typeof window<"u"){const t=window.__ATOM_DEBUG__;if(typeof t=="boolean")return t}try{if(typeof process<"u"&&process.env&&process.env.NODE_ENV==="development")return!0}catch{}return!1}let Y=at();const g={get enabled(){return Y},set enabled(t){Y=t},log(t,...e){Y&&console.log(`[atom-effect-jquery] ${t}:`,...e)},atomChanged(t,e,s){Y&&console.log(`[atom-effect-jquery] Atom "${t||"anonymous"}" changed:`,e,"→",s)},domUpdated(t,e,s){if(!Y)return;const n=ue(t);console.log(`[atom-effect-jquery] DOM updated: ${n}.${e} =`,s),lt(t)},cleanup(t){Y&&console.log(`[atom-effect-jquery] Cleanup: ${t}`)},warn(...t){Y&&console.warn("[atom-effect-jquery]",...t)}};function lt(t){const e=t[0];if(!e||!document.contains(e))return;const s="atom_debug_timer",n="atom_debug_cleanup_timer",i="atom_debug_org_style";clearTimeout(t.data(s)),clearTimeout(t.data(n)),t.data(i)||t.data(i,{outline:t.css("outline"),outlineOffset:t.css("outline-offset"),transition:t.css("transition")}),t.css({outline:"2px solid rgba(255, 68, 68, 0.8)","outline-offset":"1px",transition:"none"});const o=setTimeout(()=>{const r=t.data(i);t.css("transition","outline 0.5s ease-out"),requestAnimationFrame(()=>{t.css({outline:r?.outline||"","outline-offset":r?.outlineOffset||""});const c=setTimeout(()=>{t.css("transition",r?.transition||""),t.removeData(s),t.removeData(n),t.removeData(i)},500);t.data(n,c)})},100);t.data(s,o)}const ft=new WeakMap;function Me(t,e={}){const s=we(t,e);return e.name&&ft.set(s,{name:e.name}),s}Object.defineProperty(Me,"debug",{get(){return g.enabled},set(t){g.enabled=t}});function dt(){return new Promise(t=>setTimeout(t,0))}h.extend({atom:Me,computed:Be,effect:z,batch:ce,untracked:ge,isAtom:be,isComputed:Fe,isReactive:t=>be(t)||Fe(t),nextTick:dt});const he="_aes-bound";class _t{effects=new WeakMap;cleanups=new WeakMap;boundElements=new WeakSet;preservedNodes=new WeakSet;ignoredNodes=new WeakSet;keep(e){this.preservedNodes.add(e)}isKept(e){return this.preservedNodes.has(e)}markIgnored(e){this.ignoredNodes.add(e)}isIgnored(e){return this.ignoredNodes.has(e)}trackEffect(e,s){let n=this.effects.get(e);n||(n=[],this.effects.set(e,n),this.boundElements.has(e)||(this.boundElements.add(e),e.classList.add(he))),n.push(s)}trackCleanup(e,s){let n=this.cleanups.get(e);n||(n=[],this.cleanups.set(e,n),this.boundElements.has(e)||(this.boundElements.add(e),e.classList.add(he))),n.push(s)}hasBind(e){return this.boundElements.has(e)}cleanup(e){if(!this.boundElements.delete(e))return;this.preservedNodes.delete(e),this.ignoredNodes.delete(e),e.classList.remove(he),g.cleanup(ue(e));const s=this.effects.get(e);if(s){this.effects.delete(e);for(let i=0,o=s.length;i<o;i++){const r=s[i];if(r)try{r.dispose()}catch(c){g.warn("Effect dispose error:",c)}}}const n=this.cleanups.get(e);if(n){this.cleanups.delete(e);for(let i=0,o=n.length;i<o;i++){const r=n[i];if(r)try{r()}catch(c){g.warn("Cleanup error:",c)}}}}cleanupDescendants(e){const s=e.querySelectorAll(`.${he}`);for(let n=0,i=s.length;n<i;n++){const o=s[n];o&&this.boundElements.has(o)&&this.cleanup(o)}}cleanupTree(e){this.cleanupDescendants(e),this.cleanup(e)}}const _=new _t;let ee=null;function je(t=document.body){ee||(ee=new MutationObserver(e=>{for(let s=0,n=e.length;s<n;s++){const i=e[s];if(!i)continue;const o=i.removedNodes;for(let r=0,c=o.length;r<c;r++){const u=o[r];u&&(_.isKept(u)||_.isIgnored(u)||u.isConnected||u.nodeType===1&&_.cleanupTree(u))}}}),ee.observe(t,{childList:!0,subtree:!0}))}function pt(){ee?.disconnect(),ee=null}function b(t,e,s,n){const i=h(t);if(ut(e)){const o=z(()=>{const r=e.value;s(r),g.domUpdated(i,n,r)});_.trackEffect(t,o)}else s(e),g.domUpdated(i,n,e)}function me(){return{timeoutId:null,phase:"idle",hasFocus:!1}}function Ve(t,e,s={}){const{debounce:n,event:i="input",parse:o=S=>S,format:r=S=>String(S??""),equal:c=Object.is}=s,u=me(),a=()=>{u.phase="composing"},d=()=>{u.phase="idle",X()};t.on("compositionstart",a),t.on("compositionend",d);const q=()=>{u.hasFocus=!0},O=()=>{u.hasFocus=!1;const S=r(e.value);t.val()!==S&&t.val(S)};t.on("focus",q),t.on("blur",O);const X=()=>{u.phase==="idle"&&(u.phase="syncing-to-atom",e.value=o(t.val()),u.phase="idle")},v=()=>{u.phase==="idle"&&(n?(u.timeoutId&&clearTimeout(u.timeoutId),u.timeoutId=window.setTimeout(X,n)):X())};return t.on(i,v),t.on("change",v),{effect:()=>{const S=r(e.value),R=t.val();if(R!==S){if(u.hasFocus&&c(o(R),e.value))return;u.phase="syncing-to-dom",t.val(S),g.domUpdated(t,"val",S),u.phase="idle"}},cleanup:()=>{t.off(i,v),t.off("change",v),t.off("compositionstart",a),t.off("compositionend",d),t.off("focus",q),t.off("blur",O),u.timeoutId&&clearTimeout(u.timeoutId)}}}h.fn.atomText=function(t,e){return this.each(function(){b(this,t,s=>{const n=e?e(s):String(s??"");h(this).text(n)},"text")})},h.fn.atomHtml=function(t){return this.each(function(){b(this,t,e=>h(this).html(String(e??"")),"html")})},h.fn.atomClass=function(t,e){return this.each(function(){b(this,e,s=>h(this).toggleClass(t,!!s),`class.${t}`)})},h.fn.atomCss=function(t,e,s){return this.each(function(){b(this,e,n=>{const i=s?`${n}${s}`:n;h(this).css(t,i)},`css.${t}`)})},h.fn.atomAttr=function(t,e){return this.each(function(){b(this,e,s=>{const n=h(this);s==null||s===!1?n.removeAttr(t):s===!0?n.attr(t,t):n.attr(t,String(s))},`attr.${t}`)})},h.fn.atomProp=function(t,e){return this.each(function(){b(this,e,s=>h(this).prop(t,s),`prop.${t}`)})},h.fn.atomShow=function(t){return this.each(function(){b(this,t,e=>h(this).toggle(!!e),"show")})},h.fn.atomHide=function(t){return this.each(function(){b(this,t,e=>h(this).toggle(!e),"hide")})},h.fn.atomVal=function(t,e={}){return this.each(function(){const s=h(this),{effect:n,cleanup:i}=Ve(s,t,e),o=z(n);_.trackEffect(this,o),_.trackCleanup(this,i)})},h.fn.atomChecked=function(t){return this.each(function(){const e=h(this),s=me(),n=()=>{s.phase==="idle"&&(t.value=!!e.prop("checked"))};e.on("change",n),_.trackCleanup(this,()=>e.off("change",n));const i=z(()=>{s.phase="syncing-to-dom";const o=!!t.value;e.prop("checked",o),g.domUpdated(e,"checked",o),s.phase="idle"});_.trackEffect(this,i)})},h.fn.atomOn=function(t,e){return this.each(function(){const s=h(this);s.on(t,e),_.trackCleanup(this,()=>s.off(t,e))})},h.fn.atomUnbind=function(){return this.each(function(){_.cleanupTree(this)})};function Et(t,e){b(t.el,e,s=>{t.el.textContent=String(s??"")},"text")}function gt(t,e){b(t.el,e,s=>{t.el.innerHTML=String(s??"")},"html")}function bt(t,e){for(const s in e)b(t.el,e[s],n=>{t.el.classList.toggle(s,!!n)},`class.${s}`)}function mt(t,e){const s=t.el.style;for(const n in e){const i=e[n];if(i===void 0)continue;const o=n.includes("-")?n.replace(/-./g,r=>r.charAt(1).toUpperCase()):n;if(Array.isArray(i)){const[r,c]=i;b(t.el,r,u=>{s[o]=`${u}${c}`},`css.${n}`)}else b(t.el,i,r=>{s[o]=r},`css.${n}`)}}function St(t,e){const s=t.el;for(const n in e){const i=e[n];b(s,i,o=>{if(o==null||o===!1){s.removeAttribute(n);return}s.setAttribute(n,o===!0?n:String(o))},`attr.${n}`)}}function yt(t,e){const s=t.el;for(const n in e)b(s,e[n],i=>{s[n]=i},`prop.${n}`)}function It(t,e){b(t.el,e,s=>{t.$el.toggle(!!s)},"show")}function Dt(t,e){b(t.el,e,s=>{t.$el.toggle(!s)},"hide")}function Ct(t,e){const s=Array.isArray(e)?e[0]:e,n=Array.isArray(e)?e[1]:{},{effect:i,cleanup:o}=Ve(t.$el,s,n),r=z(i);_.trackEffect(t.el,r),t.trackCleanup(o)}function Nt(t,e){const s=me(),n=()=>{s.phase==="idle"&&(e.value=t.$el.prop("checked"))};t.$el.on("change",n),t.trackCleanup(()=>t.$el.off("change",n));const i=z(()=>{s.phase="syncing-to-dom";const o=!!e.value;t.$el.prop("checked",o),g.domUpdated(t.$el,"checked",o),s.phase="idle"});_.trackEffect(t.el,i)}function Tt(t,e){const s=t.el;for(const n in e){const i=e[n];if(typeof i!="function")continue;const o=i,r=c=>{const u=h.Event(c.type,{originalEvent:c});ce(()=>o.call(s,u))};s.addEventListener(n,r),t.trackCleanup(()=>s.removeEventListener(n,r))}}h.fn.atomBind=function(t){return this.each(function(){const s={$el:h(this),el:this,trackCleanup:n=>_.trackCleanup(this,n)};t.text!==void 0&&Et(s,t.text),t.html!==void 0&&gt(s,t.html),t.class&&bt(s,t.class),t.css&&mt(s,t.css),t.attr&&St(s,t.attr),t.prop&&yt(s,t.prop),t.show!==void 0&&It(s,t.show),t.hide!==void 0&&Dt(s,t.hide),t.val!==void 0&&Ct(s,t.val),t.checked!==void 0&&Nt(s,t.checked),t.on&&Tt(s,t.on)})},h.fn.atomList=function(t,e){const{key:s,render:n,bind:i,update:o,onAdd:r,onRemove:c,empty:u}=e,a=typeof s=="function"?s:d=>d[s];return this.each(function(){const d=h(this),q=ue(this),O=new Map,X=new Set;let v=[],J=null;const ze=z(()=>{const S=t.value,R=S.length;if(R===0?u&&!J&&(J=h(u).appendTo(d)):J&&(J.remove(),J=null),R===0&&O.size===0){v=[];return}g.log("list",`${q} updating with ${R} items`);const le=new Array(R),ye=new Set;for(let f=0;f<R;f++){const m=S[f],y=a(m,f);g.enabled&&ye.has(y)&&console.warn(`[atomList] Duplicate key "${y}" at index ${f}. Items with duplicate keys may cause unexpected behavior.`),le[f]=y,ye.add(y)}for(const[f,m]of O){if(ye.has(f)||X.has(f))continue;const y=()=>{m.$el.remove();const I=m.$el[0];I&&_.cleanup(I),X.delete(f),g.log("list",`${q} removed item:`,f)};if(O.delete(f),X.add(f),c){const I=c(m.$el);I instanceof Promise?I.then(y):y()}else y()}if(R===0){v=[];return}const qe=new Map;for(let f=0;f<v.length;f++){const m=v[f];m!==void 0&&qe.set(m,f)}const Xe=new Int32Array(R);for(let f=0;f<R;f++){const m=le[f];Xe[f]=m!==void 0?qe.get(m)??-1:-1}const Ge=ht(Xe);let Ie=Ge.length-1,P=null;for(let f=R-1;f>=0;f--){const m=le[f],y=S[f],I=O.get(m);if(I){I.item=y;const K=I.$el[0];if(!K)continue;o&&o(I.$el,y,f),Ie>=0&&Ge[Ie]===f?(Ie--,K.nextSibling!==P&&(P?I.$el.insertBefore(P):I.$el.appendTo(d))):P?I.$el.insertBefore(P):I.$el.appendTo(d),P=K}else{const K=n(y,f),W=(K instanceof Element,h(K));O.set(m,{$el:W,item:y}),P?W.insertBefore(P):W.appendTo(d),i&&i(W,y,f),r&&r(W),g.log("list",`${q} added item:`,m),P=W[0]||null}}v=le});_.trackEffect(this,ze),_.trackCleanup(this,()=>{O.clear(),X.clear(),v=[],J?.remove()})})};const ae=new WeakMap;h.fn.atomMount=function(t,e={}){return this.each(function(){const s=h(this),n=ue(this),i=ae.get(this);i&&(g.log("mount",`${n} unmounting existing component`),i()),g.log("mount",`${n} mounting component`);let o;try{o=t(s,e)}catch(u){console.error("[atom-effect-jquery] Mount error:",u);return}let r=!1;const c=()=>{if(!r){if(r=!0,g.log("mount",`${n} full cleanup`),typeof o=="function")try{o()}catch(u){console.error("[atom-effect-jquery] Cleanup error:",u)}_.cleanupTree(this),ae.delete(this)}};ae.set(this,c),_.trackCleanup(this,c)})},h.fn.atomUnmount=function(){return this.each(function(){ae.get(this)?.()})};const te=new WeakMap;let He=!1;function Se(){if(He)return;He=!0;const t=h.fn.on,e=h.fn.off,s=h.fn.remove,n=h.fn.empty,i=h.fn.detach;h.fn.remove=function(o){return(o?this.filter(o):this).each(function(){_.cleanupTree(this),_.markIgnored(this)}),s.call(this,o)},h.fn.empty=function(){return this.each(function(){_.cleanupDescendants(this)}),n.call(this)},h.fn.detach=function(o){return(o?this.filter(o):this).each(function(){_.keep(this)}),i.call(this,o)},h.fn.on=function(...o){let r=-1;for(let c=o.length-1;c>=0;c--)if(typeof o[c]=="function"){r=c;break}if(r!==-1){const c=o[r];let u;te.has(c)?u=te.get(c):(u=function(a,...d){return ce(()=>c.call(this,a,...d))},te.set(c,u)),o[r]=u}return t.apply(this,o)},h.fn.off=function(...o){let r=-1;for(let c=o.length-1;c>=0;c--)if(typeof o[c]=="function"){r=c;break}if(r!==-1){const c=o[r];te.has(c)&&(o[r]=te.get(c))}return e.apply(this,o)}}const Ot=Se;Se(),h(()=>{je(document.body)}),p.default=h,p.atom=we,p.batch=ce,p.computed=Be,p.disableAutoCleanup=pt,p.effect=z,p.enableAutoCleanup=je,p.enablejQueryBatching=Ot,p.enablejQueryOverrides=Se,p.registry=_,p.untracked=ge,Object.defineProperties(p,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}));
2
2
  //# sourceMappingURL=atom-effect-jquery.min.js.map