@but212/atom-effect-jquery 0.22.0 → 0.22.2

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 CHANGED
@@ -17,7 +17,7 @@ npm install @but212/atom-effect-jquery jquery
17
17
  ### CDN
18
18
 
19
19
  ```html
20
- <script src="https://cdn.jsdelivr.net/npm/@but212/atom-effect-jquery@0.22.0"></script>
20
+ <script src="https://cdn.jsdelivr.net/npm/@but212/atom-effect-jquery@0.22.2"></script>
21
21
  ```
22
22
 
23
23
  ### Usage
@@ -1,2 +1,3 @@
1
- (function(E,c){typeof exports=="object"&&typeof module<"u"?c(exports,require("jquery")):typeof define=="function"&&define.amd?define(["exports","jquery"],c):(E=typeof globalThis<"u"?globalThis:E||self,c(E.AtomEffectJQuery={},E.jQuery))})(this,(function(E,c){"use strict";const at={IDLE:"idle",PENDING:"pending",RESOLVED:"resolved",REJECTED:"rejected"},L={DISPOSED:1,EXECUTING:8},Wt={DISPOSED:1,IS_COMPUTED:2,DIRTY:8,IDLE:16,PENDING:32,RESOLVED:64,REJECTED:128,RECOMPUTING:256,HAS_ERROR:512},F={DISPOSED:1,SYNC:8,NOTIFICATION_SCHEDULED:16},V={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},Me={WARN_INFINITE_LOOP:!0},Jt={MAX_ASYNC_RETRIES:3,MAX_PROMISE_ID:Number.MAX_SAFE_INTEGER-1},ut=1073741823,Fe=typeof process<"u"&&process.env&&!1||!1,Be=Object.freeze([]);class Y extends Error{constructor(t,s=null,n=!0){super(t),this.cause=s,this.recoverable=n,this.name="AtomError"}}class q extends Y{constructor(t,s=null){super(t,s,!0),this.name="ComputedError"}}class W extends Y{constructor(t,s=null){super(t,s,!1),this.name="EffectError"}}class Rt extends Y{constructor(t,s=null){super(t,s,!1),this.name="SchedulerError"}}const He=Symbol("AtomEffect.DebugName"),Ge=Symbol("AtomEffect.Type"),Ot=Symbol("AtomEffect.NoDefaultValue"),ht={enabled:Fe,warnInfiniteLoop:Me.WARN_INFINITE_LOOP,warn(e,t){},checkCircular(e,t){if(e===t)throw new q("Direct circular dependency detected")},attachDebugInfo(e,t,s){},getDebugName:e=>e?.[He],getDebugType:e=>e?.[Ge]};let je=1;const ze=()=>je++;function Zt(e,t,s){if(typeof t=="function"){const i=t;if(s.some(r=>r&&r.fn===i))return;s.push(new Nt(i,void 0));return}if("addDependency"in t){t.addDependency(e);return}const n=t;s.some(i=>i&&i.sub===n)||s.push(new Nt(void 0,n))}function te(e,t,s){const n=new Map;t.forEach(i=>{i?.unsub&&n.set(i.node,i.unsub)}),e.forEach(i=>{if(!i)return;const r=i.node,o=n.get(r);o!==void 0?(i.unsub=o,n.delete(r)):(ht.checkCircular(r,s),i.unsub=r.subscribe(s))}),n.forEach(i=>i())}class vt{constructor(t,s,n=void 0){this.node=t,this.version=s,this.unsub=n}}class Nt{constructor(t,s){this.fn=t,this.sub=s}}const y={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:(e,t)=>`Maximum flush iterations (${e}) exceeded. ${t} 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."};function J(e,t,s){if(e instanceof Y)return e;const n=e instanceof Error,i=n?e.message:String(e),r=n?e:void 0,o=`${n?e.constructor.name:"Unexpected error"} (${s}): ${i}`;return new t(o,r)}class ee{constructor(){this.flags=0,this.version=0,this._lastSeenEpoch=-1,this.id=ze()&ut}}class se extends ee{subscribe(t){const s=typeof t=="function";if(!s&&(!t||typeof t.execute!="function"))throw J(new TypeError("Invalid subscriber"),Y,y.ATOM_SUBSCRIBER_MUST_BE_FUNCTION);if(this._subscribers.some(i=>i?s?i.fn===t:i.sub===t:!1))return()=>{};const n=new Nt(s?t:void 0,s?void 0:t);return this._subscribers.push(n),()=>this._unsubscribe(n)}_unsubscribe(t){const s=this._subscribers,n=s.indexOf(t);if(n===-1)return;const i=s.pop();n<s.length&&i&&(s[n]=i)}subscriberCount(){return this._subscribers.length}_notifySubscribers(t,s){this._subscribers.length!==0&&this._subscribers.slice(0).forEach(n=>{if(n)try{n.fn?n.fn(t,s):n.sub&&n.sub.execute()}catch(i){this._handleNotifyError(i)}})}_handleNotifyError(t){console.error(J(t,Y,y.ATOM_INDIVIDUAL_SUBSCRIBER_FAILED))}}let At=0;const Dt=()=>(At=At+1&ut||1,At),Ut=e=>e+1&ut;let Lt=0,lt=!1,ne=0;const Ve=()=>ne;function ie(){return lt?!1:(lt=!0,ne=Dt(),Lt=0,!0)}const re=()=>{lt=!1},qe=()=>lt?++Lt:0;class Qe{constructor(){this._queueBuffer=[[],[]],this._bufferIndex=0,this._size=0,this._epoch=0,this._isProcessing=!1,this._isBatching=!1,this._isFlushingSync=!1,this._batchDepth=0,this._batchQueue=[],this._batchQueueSize=0,this._maxFlushIterations=V.MAX_FLUSH_ITERATIONS,this.onOverflow=null,this._boundRunLoop=this._runLoop.bind(this)}get phase(){return this._isProcessing||this._isFlushingSync?2:this._isBatching?1:0}get queueSize(){return this._size}get isBatching(){return this._isBatching}schedule(t){if(t._nextEpoch!==this._epoch){if(t._nextEpoch=this._epoch,this._isBatching||this._isFlushingSync){this._batchQueue[this._batchQueueSize++]=t;return}this._queueBuffer[this._bufferIndex][this._size++]=t,this._isProcessing||this._flush()}}_flush(){this._isProcessing||this._size===0||(this._isProcessing=!0,queueMicrotask(this._boundRunLoop))}_runLoop(){try{if(this._size===0)return;const t=ie();this._drainQueue(),t&&re()}finally{this._isProcessing=!1,this._size>0&&!this._isBatching&&this._flush()}}_flushSync(){this._isFlushingSync=!0;const t=ie();try{this._mergeBatchQueue(),this._drainQueue()}finally{this._isFlushingSync=!1,t&&re()}}_mergeBatchQueue(){if(this._batchQueueSize===0)return;const t=++this._epoch,s=this._batchQueue,n=this._queueBuffer[this._bufferIndex];let i=this._size;s.slice(0,this._batchQueueSize).forEach(r=>{r._nextEpoch!==t&&(r._nextEpoch=t,n[i++]=r)}),this._size=i,this._batchQueueSize=0,s.length>V.BATCH_QUEUE_SHRINK_THRESHOLD&&(s.length=0)}_drainQueue(){let t=0;for(;this._size>0;){if(++t>this._maxFlushIterations){this._handleFlushOverflow();return}this._processQueue(),this._mergeBatchQueue()}}_processQueue(){const t=this._bufferIndex,s=this._queueBuffer[t],n=this._size;this._bufferIndex=t^1,this._size=0,this._epoch++;for(let i=0;i<n;i++)try{s[i]()}catch(r){console.error(new Rt("Error occurred during scheduler execution",r))}s.length=0}_handleFlushOverflow(){const t=this._size+this._batchQueueSize;if(console.error(new Rt(y.SCHEDULER_FLUSH_OVERFLOW(this._maxFlushIterations,t))),this._size=0,this._queueBuffer[this._bufferIndex].length=0,this._batchQueueSize=0,this.onOverflow)try{this.onOverflow(t)}catch{}}startBatch(){this._batchDepth++,this._isBatching=!0}endBatch(){this._batchDepth!==0&&--this._batchDepth===0&&(this._flushSync(),this._isBatching=!1)}setMaxFlushIterations(t){if(t<V.MIN_FLUSH_ITERATIONS)throw new Rt(`Max flush iterations must be at least ${V.MIN_FLUSH_ITERATIONS}`);this._maxFlushIterations=t}}const st=new Qe,wt=Symbol.for("atom-effect/atom"),oe=Symbol.for("atom-effect/computed"),Xe=Symbol.for("atom-effect/effect"),w={current:null,run(e,t){const s=this.current;this.current=e;try{return t()}finally{this.current=s}}};function x(e){const t=w.current;if(t===null)return e();w.current=null;try{return e()}finally{w.current=t}}var ce;class $e extends se{constructor(t,s){super(),this._pendingOldValue=void 0,this._notifyTask=()=>this._flushNotifications(),this._subscribers=[],this[ce]=!0,this._value=t,s&&(this.flags|=F.SYNC),ht.attachDebugInfo(this,"atom",this.id)}get value(){const t=w.current;return t&&Zt(this,t,this._subscribers),this._value}set value(t){const s=this._value;if(Object.is(s,t))return;this._value=t,this.version=Ut(this.version);const n=this.flags;if(!(this._subscribers.length===0||n&F.NOTIFICATION_SCHEDULED)){if(this._pendingOldValue=s,this.flags=n|F.NOTIFICATION_SCHEDULED,n&F.SYNC&&!st.isBatching){this._flushNotifications();return}st.schedule(this._notifyTask)}}_flushNotifications(){const t=this.flags;if(!(t&F.NOTIFICATION_SCHEDULED)||t&F.DISPOSED)return;const s=this._pendingOldValue;this._pendingOldValue=void 0,this.flags&=-17,this._notifySubscribers(this._value,s)}peek(){return this._value}dispose(){this.flags&F.DISPOSED||(this._subscribers.length=0,this.flags|=F.DISPOSED,this._value=void 0,this._pendingOldValue=void 0)}[(ce=wt,Symbol.dispose)](){this.dispose()}}function ft(e,t={}){return new $e(e,t.sync??!1)}class Ke{constructor(t=50,s=256,n=!1){this.limit=t,this.capacity=s,this.pool=[],this.stats=null,this.stats=n?{acquired:0,released:0,rejected:{frozen:0,tooLarge:0,poolFull:0}}:null}acquire(){return this.stats&&this.stats.acquired++,this.pool.pop()??[]}release(t,s){if(!(s&&t===s)){if(t.length>this.capacity){this.stats&&this.stats.rejected.tooLarge++;return}if(this.pool.length>=this.limit){this.stats&&this.stats.rejected.poolFull++;return}if(Object.isFrozen(t)){this.stats&&this.stats.rejected.frozen++;return}t.length=0,this.pool.push(t),this.stats&&this.stats.released++}}getStats(){if(!this.stats)return null;const{acquired:t,released:s,rejected:n}=this.stats,i=t-s-(n.frozen+n.tooLarge+n.poolFull);return{acquired:t,released:s,rejected:{...n},leaked:i,poolSize:this.pool.length}}reset(){this.pool.length=0,this.stats&&(this.stats={acquired:0,released:0,rejected:{frozen:0,tooLarge:0,poolFull:0}})}}const O=Object.freeze([]),B=new Ke;function dt(e){return e!==null&&typeof e=="object"&&wt in e}function ae(e){return e!==null&&typeof e=="object"&&oe in e}function ue(e){return e!==null&&typeof e=="object"&&typeof e.then=="function"}var he,le;const{IDLE:_t,DIRTY:Z,PENDING:Et,RESOLVED:Q,REJECTED:nt,HAS_ERROR:pt,RECOMPUTING:it,DISPOSED:kt,IS_COMPUTED:Ye}=Wt;function We(e){return e&Q?at.RESOLVED:e&Et?at.PENDING:e&nt?at.REJECTED:at.IDLE}class Je extends se{constructor(t,s={}){if(typeof t!="function")throw new q(y.COMPUTED_MUST_BE_FUNCTION);super(),this[le]=!0,this[he]=!0,this._error=null,this._promiseId=0,this._subscribers=[],this._links=O,this._asyncStartAggregateVersion=0,this._asyncRetryCount=0,this._trackEpoch=-1,this._trackLinks=O,this._trackCount=0,this._value=void 0,this.flags=Ye|Z|_t,this._equal=s.equal??Object.is,this._fn=t,this._defaultValue="defaultValue"in s?s.defaultValue:Ot,this._onError=s.onError??null;const n=s.maxAsyncRetries;if(this._maxAsyncRetries=(n??Jt.MAX_ASYNC_RETRIES)&ut,ht.attachDebugInfo(this,"computed",this.id),s.lazy===!1)try{this._recompute()}catch{}}_track(){const t=w.current;t&&Zt(this,t,this._subscribers)}get value(){this._track();const t=this.flags;if((t&(Q|Z|_t))===Q)return this._value;if(t&kt)throw new q(y.COMPUTED_DISPOSED);if(t&it){if(this._defaultValue!==Ot)return this._defaultValue;throw new q(y.COMPUTED_CIRCULAR_DEPENDENCY)}if(t&(Z|_t)&&(this._recompute(),this.flags&Q))return this._value;const s=this._defaultValue,n=s!==Ot;if(this.flags&Et){if(n)return s;throw new q(y.COMPUTED_ASYNC_PENDING_NO_DEFAULT)}if(this.flags&nt){if(n)return s;throw this._error}return this._value}peek(){return this._value}get state(){return this._track(),We(this.flags)}get hasError(){return this._track(),this.flags&(nt|pt)?!0:this._links.some(t=>t?.node?.flags&pt)}get isValid(){return!this.hasError}get errors(){if(this._track(),!this.hasError)return Be;const t=[];return this._error&&t.push(this._error),this._links.forEach(s=>{const n=s.node;n.flags&pt&&n.errors.forEach(i=>{i&&!t.includes(i)&&t.push(i)})}),Object.freeze(t)}get lastError(){return this._track(),this._error}get isPending(){return this._track(),(this.flags&Et)!==0}get isResolved(){return this._track(),(this.flags&Q)!==0}invalidate(){this._markDirty()}dispose(){if(this.flags&kt)return;const t=this._links;t!==O&&(t.forEach(s=>s.unsub?.()),B.release(t),this._links=O),this._subscribers.length=0,this.flags=kt|Z|_t,this._error=null,this._value=void 0}[(le=wt,he=oe,Symbol.dispose)](){this.dispose()}addDependency(t){if(t._lastSeenEpoch!==this._trackEpoch){if(t._lastSeenEpoch=this._trackEpoch,this._trackCount<this._trackLinks.length){const s=this._trackLinks[this._trackCount];s.node=t,s.version=t.version}else this._trackLinks.push(new vt(t,t.version));this._trackCount++}}_recompute(){if(this.flags&it)return;this.flags|=it;const t=this._links;this._trackEpoch=Dt(),this._trackLinks=B.acquire(),this._trackCount=0;let s=!1;try{const n=w.run(this,this._fn);this._trackLinks.length=this._trackCount,te(this._trackLinks,t,this),this._links=this._trackLinks,s=!0,ue(n)?this._handleAsyncComputation(n):this._finalizeResolution(n)}catch(n){if(!s)try{this._trackLinks.length=this._trackCount,te(this._trackLinks,t,this),this._links=this._trackLinks,s=!0}catch{}this._handleError(n,y.COMPUTED_COMPUTATION_FAILED,!0)}finally{s&&t!==O?B.release(t):s||B.release(this._trackLinks),this._trackEpoch=-1,this._trackLinks=O,this._trackCount=0,this.flags&=~it}}_handleAsyncComputation(t){this.flags=(this.flags|Et)&-217,this._notifySubscribers(void 0,void 0),this._asyncStartAggregateVersion=this._captureVersionSnapshot(),this._asyncRetryCount=0,this._promiseId=(this._promiseId+1)%Jt.MAX_PROMISE_ID;const s=this._promiseId;t.then(n=>{if(s===this._promiseId){if(this._captureVersionSnapshot()!==this._asyncStartAggregateVersion)return this._asyncRetryCount++<this._maxAsyncRetries?this._markDirty():this._handleError(new q(`Async drift threshold exceeded after ${this._maxAsyncRetries} retries.`),y.COMPUTED_ASYNC_COMPUTATION_FAILED);this._finalizeResolution(n),this._notifySubscribers(n,void 0)}},n=>s===this._promiseId&&this._handleError(n,y.COMPUTED_ASYNC_COMPUTATION_FAILED))}_captureVersionSnapshot(){let t=0;const s=this._links;for(let n=0,i=s.length;n<i;n++)t=(t<<5)-t+s[n].node.version|0;return t}_handleError(t,s,n=!1){const i=J(t,q,s);if(!n&&!(this.flags&nt)&&(this.version=Ut(this.version)),this._error=i,this.flags=this.flags&-121|nt|pt,this._onError)try{this._onError(i)}catch(r){console.error(y.CALLBACK_ERROR_IN_ERROR_HANDLER,r)}if(n)throw i;this._notifySubscribers(void 0,void 0)}_finalizeResolution(t){(!(this.flags&Q)||!this._equal(this._value,t))&&(this.version=Ut(this.version)),this._value=t,this._error=null,this.flags=(this.flags|Q)&-697}execute(){this._markDirty()}_markDirty(){this.flags&(it|Z)||(this.flags|=Z,this._notifySubscribers(void 0,void 0))}}function rt(e,t={}){return new Je(e,t)}var fe;class Ze extends ee{constructor(t,s={}){super(),this[fe]=!0,this._cleanup=null,this._links=O,this._nextLinks=null,this._prevLinks=O,this._currentEpoch=-1,this._lastFlushEpoch=-1,this._executionsInEpoch=0,this._executionCount=0,this._windowStart=0,this._windowCount=0,this._execId=0,this._fn=t,this._onError=s.onError??null,this._sync=s.sync??!1,this._maxExecutions=s.maxExecutionsPerSecond??V.MAX_EXECUTIONS_PER_SECOND,this._maxExecutionsPerFlush=s.maxExecutionsPerFlush??V.MAX_EXECUTIONS_PER_EFFECT,this._sync?(this._executeTask=void 0,this._notifyCallback=()=>this.execute()):(this._executeTask=()=>this.execute(),this._notifyCallback=()=>st.schedule(this._executeTask)),ht.attachDebugInfo(this,"effect",this.id)}run(){if(this.flags&L.DISPOSED)throw new W(y.EFFECT_DISPOSED);this.execute(!0)}dispose(){this.flags&L.DISPOSED||(this.flags|=L.DISPOSED,this._execCleanup(),this._unsubLinks(this._links),this._links!==O&&B.release(this._links),this._links=O,this._prevLinks=O)}[(fe=Xe,Symbol.dispose)](){this.dispose()}addDependency(t){if(!(this.flags&L.EXECUTING))return;const s=this._currentEpoch;if(t._lastSeenEpoch===s)return;t._lastSeenEpoch=s;const n=this._nextLinks,i=this._prevLinks,r=i.findIndex(o=>o&&o.node===t&&o.unsub);if(r!==-1){const o=i[r];o.version=t.version,n.push(o),i[r]=null;return}try{const o=t.subscribe(this._notifyCallback);n.push(new vt(t,t.version,o))}catch(o){const f=J(o,W,y.EFFECT_EXECUTION_FAILED);if(console.error(f),this._onError)try{this._onError(f)}catch{}n.push(new vt(t,t.version,void 0))}}execute(t=!1){if(this.flags&(L.DISPOSED|L.EXECUTING)||!t&&this._links.length>0&&!this._isDirty())return;this._checkInfiniteLoops(),this.flags|=L.EXECUTING,this._execCleanup(),this._prevLinks=this._links;const s=B.acquire();this._nextLinks=s,this._currentEpoch=Dt();let n=!1;try{const i=w.run(this,this._fn);this._links=s,n=!0,ue(i)?this._handleAsyncResult(i):this._cleanup=typeof i=="function"?i:null}catch(i){this._links=s,n=!0,this._handleExecutionError(i),this._cleanup=null}finally{this._finalizeDependencies(n,this._prevLinks,s),this.flags&=-9}}_handleAsyncResult(t){const s=++this._execId;t.then(n=>{if(s!==this._execId||this.flags&L.DISPOSED){if(typeof n=="function")try{n()}catch(i){this._handleExecutionError(i,y.EFFECT_CLEANUP_FAILED)}return}typeof n=="function"&&(this._cleanup=n)},n=>s===this._execId&&this._handleExecutionError(n))}_finalizeDependencies(t,s,n){this._nextLinks=null,this._prevLinks=O,t?(s.forEach(i=>i?.unsub?.()),s!==O&&B.release(s)):(this._unsubLinks(n),B.release(n))}_unsubLinks(t){t.forEach(s=>s?.unsub?.())}_isDirty(){const t=this._links,s=w.current;w.current=null;try{return t.some(n=>{const i=n.node;if(i.flags&Wt.IS_COMPUTED)try{i.value}catch{return!0}return i.version!==n.version})}finally{w.current=s}}_execCleanup(){if(this._cleanup){try{this._cleanup()}catch(t){this._handleExecutionError(t,y.EFFECT_CLEANUP_FAILED)}this._cleanup=null}}_checkInfiniteLoops(){const t=Ve();this._lastFlushEpoch!==t&&(this._lastFlushEpoch=t,this._executionsInEpoch=0),++this._executionsInEpoch>this._maxExecutionsPerFlush&&this._throwInfiniteLoopError("per-effect"),qe()>V.MAX_EXECUTIONS_PER_FLUSH&&this._throwInfiniteLoopError("global"),this._executionCount++}get isDisposed(){return(this.flags&L.DISPOSED)!==0}get executionCount(){return this._executionCount}get isExecuting(){return(this.flags&L.EXECUTING)!==0}_throwInfiniteLoopError(t){const s=new W(`Infinite loop detected (${t}): effect executed ${this._executionsInEpoch} times in current flush. Total executions in flush: ${Lt}`);throw this.dispose(),console.error(s),s}_handleExecutionError(t,s=y.EFFECT_EXECUTION_FAILED){const n=J(t,W,s);if(console.error(n),this._onError)try{this._onError(n)}catch(i){console.error(J(i,W,y.CALLBACK_ERROR_IN_ERROR_HANDLER))}}}function H(e,t={}){if(typeof e!="function")throw new W(y.EFFECT_MUST_BE_FUNCTION);const s=new Ze(e,t);return s.execute(),s}function Pt(e){if(typeof e!="function")throw new TypeError("Batch callback must be a function");st.startBatch();try{return e()}finally{st.endBatch()}}const d={ROUTE:"[atom-route]",BINDING:"[atom-binding]",LIST:"[atom-list]",MOUNT:"[atom-mount]"},mt=Object.freeze({mode:"hash",basePath:"",autoBindLinks:!1,activeClass:"active"}),ts={EVENT:"input"},es=new Set(["input","select","textarea"]),ss=new Set(["innerHTML","outerHTML","srcdoc","__proto__","constructor","prototype"]),b={ROUTE_NOT_FOUND:e=>`Route "${e}" not found and no notFound route configured`,TEMPLATE_NOT_FOUND:e=>`Template "${e}" not found`,TARGET_NOT_FOUND:e=>`Target element "${e}" not found`,MALFORMED_URI:e=>`Malformed URI component: ${e}`,UNSAFE_CONTENT:()=>"Unsafe content neutralized during sanitization.",BLOCKED_DANGEROUS_CSS_VALUE:e=>`Blocked dangerous value in CSS style property "${e}".`,BLOCKED_EVENT_HANDLER:e=>`Blocked setting dangerous event handler attribute "${e}".`,BLOCKED_PROTOCOL:e=>`Blocked dangerous protocol in "${e}" attribute.`,BLOCKED_DANGEROUS_PROP:e=>`Blocked setting dangerous property "${e}". Use html binding for sanitized HTML.`,INVALID_INPUT_ELEMENT:e=>`Val binding used on non-input element <${e}>.`,MISSING_SOURCE:e=>`[${e}] source is required when prop/name is a string.`,MISSING_CONDITION:e=>`[${e}] condition is required when className is a string.`,DUPLICATE_KEY:(e,t)=>`Duplicate key "${e}" at index ${t}.`,UPDATER_ERROR:e=>`Updater threw in binding "${e}"`,EFFECT_DISPOSE_ERROR:()=>"Effect dispose error",BINDING_CLEANUP_ERROR:()=>"Binding cleanup error",PARSE_ERROR:()=>"parse() threw during DOM→Atom sync",MOUNT_ERROR:()=>"Mount error",MOUNT_CLEANUP_ERROR:()=>"Cleanup error"};function xt(e){return dt(e)}function Mt(e){const t=e.tagName.toLowerCase();if(e.id)return`${t}#${e.id}`;const s=e.classList,n=s.length;if(n===0)return t;let i=t;for(let r=0;r<n;r++)i+=`.${s[r]}`;return i}const ns=new Set(["href","src","action","formaction","xlink:href","data","poster","srcset","background","cite","longdesc","profile","usemap","classid","codebase"]),is=Object.prototype.hasOwnProperty,rs=/^\s*(?:javascript|vbscript)\s*:/i,os=/(?:expression\s*\(|behavior\s*:|(?:\\[0-9a-f]{1,6}\s*|[\s\x00-\x20/'"])*(?:j\s*a\s*v\s*a\s*s\s*c\s*r\s*i\s*p\s*t|v\s*b\s*s\s*c\s*r\s*i\s*p\s*t|d\s*a\s*t\s*a)\s*:(?!image\/))/i,cs=/url\s*\(\s*(?:["']?\s*)?(?:javascript|vbscript)\s*:/i,as=/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g,us=/<\?[\s\S]*?\?>/g,hs=/(<(script|iframe|object|embed|base|meta|applet|noscript|form|style|link)\b[^>]*>([\s\S]*?)<\/\2>|<(script|iframe|object|embed|base|meta|applet|noscript|form|style|link)\b[^>]*\/?>)/gi,ls=/(j\s*a\s*v\s*a\s*s\s*c\s*r\s*i\s*p\s*t|v\s*b\s*s\s*c\s*r\s*i\s*p\s*t)\s*:/gi,fs=/data\s*:\s*(?:text\/(?:html|javascript|vbscript|xml)|application\/(?:javascript|xhtml\+xml|xml|x-shockwave-flash)|image\/svg\+xml)/gi,ds=/\bon\w+\s*=/gim,_s=new RegExp(os.source,"gim");function Ft(e){let t=String(e??"");t=t.replace(as,""),t=t.replace(us,"");let s;do s=t,t=t.replace(hs,"");while(t!==s);return t=t.replace(ls,"data-unsafe-protocol:"),t=t.replace(fs,"data-unsafe-protocol:"),t=t.replace(ds,"data-unsafe-attr="),t=t.replace(_s,"data-unsafe-css:"),t}function Es(e,t){return ns.has(e.toLowerCase())?rs.test(t):!1}function ps(e){return e.toLowerCase().includes("url(")?cs.test(e):!1}function ms(e,t){if(e===t)return!0;if(e===null||t===null||typeof e!="object"||typeof t!="object")return!1;const s=Object.keys(e),n=Object.keys(t);if(s.length!==n.length)return!1;const i=e,r=t;for(let o=0;o<s.length;o++){const f=s[o];if(!is.call(r,f)||i[f]!==r[f])return!1}return!0}function gs(e){const t=e.length;if(t===0)return new Int32Array(0);const s=new Int32Array(t).fill(-1),n=new Int32Array(t);let i=0;for(let o=0;o<t;o++){const f=e[o];if(f===void 0||f===-1)continue;const g=i>0?n[i-1]:void 0;if(i===0||g!==void 0&&(e[g]??-1)<f){s[o]=g??-1,n[i++]=o;continue}let S=0,T=i-1;for(;S<T;){const m=S+T>>>1,I=n[m];I!==void 0&&(e[I]??-1)<f?S=m+1:T=m}const A=n[S];A!==void 0&&f<(e[A]??Number.MAX_SAFE_INTEGER)&&(S>0&&(s[o]=n[S-1]??-1),n[S]=o)}const r=new Int32Array(i);if(i>0){let o=n[i-1];for(let f=i-1;f>=0&&o!==void 0&&o!==-1;f--)r[f]=o,o=s[o]}return r}const Is={},de=600,ys=`${de/1e3}s`;function Cs(){if(typeof window<"u"){const e=window.__ATOM_DEBUG__;if(typeof e=="boolean")return e}return Is?.VITE_ATOM_DEBUG==="true"}let tt=Cs();const l={get enabled(){return tt},set enabled(e){tt=e},log(e,...t){tt&&console.log(`${d.MOUNT} ${e}:`,...t)},atomChanged(e,t,s){tt&&console.log(`${d.MOUNT} Atom "${e??"anonymous"}" changed:`,t,"→",s)},domUpdated(e,t,s){if(!tt)return;const n=e instanceof Element?e:e[0];n instanceof HTMLElement&&(console.log(`${d.MOUNT} DOM updated: ${Mt(n)}.${t} =`,s),Ts(n))},cleanup(e){tt&&console.log(`${d.MOUNT} Cleanup: ${e}`)},warn(e,t,...s){console.warn(`${e} ${t}`,...s)},error(e,t,s){console.error(`${e} ${t}`,s)}},Bt="atom-debug-highlight",bs="data-atom-debug";let _e;function Ss(){if(_e?.deref()?.isConnected)return;const e=document.createElement("style");e.setAttribute(bs,""),e.textContent=`.${Bt}{outline:2px solid rgba(255,68,68,0.8);outline-offset:1px;transition:outline ${ys} ease-out}`,document.head.appendChild(e),_e=new WeakRef(e)}const Ht=new WeakMap,Gt=new WeakMap;function Ts(e){if(!e.isConnected)return;Ss();const t=Gt.get(e);t!==void 0&&cancelAnimationFrame(t);const s=Ht.get(e);s!==void 0&&clearTimeout(s);const n=requestAnimationFrame(()=>{Gt.delete(e),e.classList.add(Bt),Ht.set(e,setTimeout(()=>{e.classList.remove(Bt),Ht.delete(e)},de))});Gt.set(e,n)}function Ee(e,t){return ft(e,t)}Object.defineProperty(Ee,"debug",{enumerable:!0,configurable:!0,get(){return l.enabled},set(e){l.enabled=e}});function pe(){return new Promise(e=>setTimeout(e,0))}const Rs={atom:Ee,computed:rt,effect:H,batch:Pt,untracked:x,isAtom:dt,isComputed:ae,isReactive:xt,nextTick:pe};c.extend(Rs);const et="_aes-bound";class Os{constructor(){this.records=new WeakMap,this.preservedNodes=new WeakSet,this.ignoredNodes=new WeakSet}keep(t){this.preservedNodes.add(t)}isKept(t){return this.preservedNodes.has(t)}markIgnored(t){this.ignoredNodes.add(t)}isIgnored(t){return this.ignoredNodes.has(t)}getOrCreateRecord(t){let s=this.records.get(t);return s||(s={},this.records.set(t,s),t.classList.add(et)),s}trackEffect(t,s){const n=this.getOrCreateRecord(t);n.effects??=[],n.effects.push(s)}trackCleanup(t,s){const n=this.getOrCreateRecord(t);n.cleanups??=[],n.cleanups.push(s)}setComponentCleanup(t,s){const n=this.getOrCreateRecord(t);n.componentCleanup=s}hasBind(t){return this.records.has(t)}cleanup(t){const s=this.records.get(t);if(!s){t.isConnected&&t.classList.remove(et),this.preservedNodes.delete(t),this.ignoredNodes.delete(t);return}if(this.records.delete(t),this.preservedNodes.delete(t),this.ignoredNodes.delete(t),t.isConnected&&t.classList.remove(et),l.enabled&&l.cleanup(Mt(t)),s.componentCleanup)try{s.componentCleanup()}catch(n){l.error(d.MOUNT,b.MOUNT_CLEANUP_ERROR(),n)}s.effects?.forEach(n=>{try{n.dispose()}catch(i){l.error(d.BINDING,b.EFFECT_DISPOSE_ERROR(),i)}}),s.cleanups?.forEach(n=>{try{n()}catch(i){l.error(d.BINDING,b.BINDING_CLEANUP_ERROR(),i)}})}cleanupDescendants(t){const s=t.querySelectorAll(`.${et}`);for(const n of s)this.records.has(n)?this.cleanup(n):(n.classList.remove(et),l.warn(d.BINDING,`${et} class found on unregistered element:`,n))}cleanupTree(t){this.cleanupDescendants(t),this.cleanup(t)}}const p=new Os;let ot=null,gt=null;function me(e){if(ot!==null){gt!==e&&l.warn(d.BINDING,"enableAutoCleanup() called with a different root while already active. Observation was NOT switched — call disableAutoCleanup() first.",{current:gt,requested:e});return}gt=e,ot=new MutationObserver(t=>{for(const s of t)for(const n of s.removedNodes)n.nodeType===1&&(n.isConnected||p.isKept(n)||p.isIgnored(n)||p.cleanupTree(n))}),ot.observe(e,{childList:!0,subtree:!0})}function vs(){ot?.disconnect(),ot=null,gt=null}function X(e,t,s,n){if(xt(t)){const i=t;p.trackEffect(e,H(()=>{const r=i.value;x(()=>{try{s(r)}catch(o){l.error(d.BINDING,`${b.UPDATER_ERROR(n)}:`,o);return}l.enabled&&l.domUpdated(e,n,r)})}))}else{try{s(t)}catch(i){l.error(d.BINDING,`${b.UPDATER_ERROR(n)} (static):`,i);return}l.enabled&&l.domUpdated(e,n,t)}}const G=Symbol("atom-effect-internal"),It=new WeakMap;let k=null;const ge=e=>{if(e[G])return e;let t=It.get(e);return t||(t=function(...s){return Pt(()=>e.apply(this,s))},t[G]=!0,It.set(e,t)),t};function Ns(e){const t={};return Object.keys(e).forEach(s=>{const n=e[s];n&&(t[s]=ge(n))}),t}function As(e){const t={};return Object.keys(e).forEach(s=>{const n=e[s];t[s]=n?It.get(n)??n:void 0}),t}function Ie(){if(k!==null)return;k={on:c.fn.on,off:c.fn.off,remove:c.fn.remove,empty:c.fn.empty,detach:c.fn.detach};const e=k;c.fn.remove=function(t){const s=t?this.filter(t):this;for(let n=0,i=s.length;n<i;n++){const r=s[n];r&&(p.markIgnored(r),p.cleanupTree(r))}return e.remove.call(this,t)},c.fn.empty=function(){for(let t=0,s=this.length;t<s;t++){const n=this[t];n&&p.cleanupDescendants(n)}return e.empty.call(this)},c.fn.detach=function(t){const s=t?this.filter(t):this;for(let n=0,i=s.length;n<i;n++){const r=s[n];r&&p.keep(r)}return e.detach.call(this,t)},c.fn.on=function(...t){const s=t[0];if(s&&typeof s=="object")t[0]=Ns(s);else for(let n=t.length-1;n>=0;n--)if(typeof t[n]=="function"){t[n]=ge(t[n]);break}return e.on.apply(this,t)},c.fn.off=function(...t){const s=t[0];if(s&&typeof s=="object")t[0]=As(s);else for(let n=t.length-1;n>=0;n--)if(typeof t[n]=="function"){const i=t[n];t[n]=It.get(i)??i;break}return e.off.apply(this,t)}}function Ds(){k!==null&&(c.fn.on=k.on,c.fn.off=k.off,c.fn.remove=k.remove,c.fn.empty=k.empty,c.fn.detach=k.detach,k=null)}var v=(e=>(e[e.None=0]="None",e[e.Focused=1]="Focused",e[e.Composing=2]="Composing",e[e.SyncingToAtom=4]="SyncingToAtom",e[e.SyncingToDom=8]="SyncingToDom",e[e.Busy=14]="Busy",e))(v||{});let Us=0;class Ls{constructor(t,s,n){this.flags=0,this.timeoutId=void 0,this.ns=`.atomBind-${++Us}`,this.handleCompositionStart=()=>{this.flags|=v.Composing},this.handleCompositionEnd=()=>{this.flags&=~v.Composing,this.handleInput()},this.handleFocus=()=>{this.flags|=v.Focused},this.handleBlur=()=>{this.flags&=~v.Focused,this.timeoutId!==void 0&&(clearTimeout(this.timeoutId),this.timeoutId=void 0,this.syncAtomFromDom());const r=this.options.format(this.atom.peek());this.el.value!==r&&(this.el.value=r)},this.syncDomFromAtom=()=>{const r=this.atom.value;x(()=>{const o=this.options.format(r),f=this.el.value;if(f===o)return;const g=!!(this.flags&v.Focused);if(g)try{if(this.options.equal(this.options.parse(f),r))return}catch{}this.flags|=v.SyncingToDom;try{if(g&&(this.el instanceof HTMLInputElement||this.el instanceof HTMLTextAreaElement)){const S=this.el.selectionStart,T=this.el.selectionEnd;this.el.value=o;const A=o.length;S!==null&&T!==null&&this.el.setSelectionRange(Math.min(S,A),Math.min(T,A))}else this.el.value=o;l.domUpdated(this.$el,"val",o)}finally{this.flags&=~v.SyncingToDom}})},this.cleanup=()=>{this.$el.off(this.ns),clearTimeout(this.timeoutId),this.timeoutId=void 0},this.$el=t,this.el=t[0],this.atom=s;const i=n.debounce??0;this.options={debounce:i,event:n.event??ts.EVENT,parse:n.parse??(r=>r),format:n.format??(r=>String(r??"")),equal:n.equal??Object.is},i>0?this.handleInput=()=>{this.flags&v.Composing||(clearTimeout(this.timeoutId),this.timeoutId=setTimeout(()=>this.syncAtomFromDom(),i))}:this.handleInput=()=>{this.flags&v.Composing||this.syncAtomFromDom()},this.handleFocus[G]=!0,this.handleBlur[G]=!0,this.handleCompositionStart[G]=!0,this.handleCompositionEnd[G]=!0,this.handleInput[G]=!0,this.bindEvents()}syncAtomFromDom(){if(!(this.flags&v.Busy)){this.flags|=v.SyncingToAtom;try{const t=this.options.parse(this.el.value);this.options.equal(this.atom.peek(),t)||(this.atom.value=t)}catch(t){l.warn(d.BINDING,`${b.PARSE_ERROR()}:`,t)}finally{this.flags&=~v.SyncingToAtom}}}bindEvents(){this.$el.on(`focus${this.ns}`,this.handleFocus).on(`blur${this.ns}`,this.handleBlur).on(`compositionstart${this.ns}`,this.handleCompositionStart).on(`compositionend${this.ns}`,this.handleCompositionEnd).on(`${this.options.event}${this.ns}`,this.handleInput)}}function ws(e,t,s){const n=new Ls(e,t,s);return{fx:H(n.syncDomFromAtom),cleanup:n.cleanup}}const ye=new Map;function ks(e){let t=ye.get(e);return t!==void 0||(t=e.includes("-")?e.replace(/-./g,s=>s[1].toUpperCase()):e,ye.set(e,t)),t}const Ce=new WeakMap;function Ps(e){let t=Ce.get(e);return t||(t=rt(()=>Ft(e.value)),Ce.set(e,t)),t}function N(e){return{$el:c(e),el:e,trackCleanup:t=>p.trackCleanup(e,t)}}function be(e,t,s){const n=e.el;X(n,t,i=>{const r=s?s(i):typeof i=="string"?i:String(i??"");n.textContent!==r&&(n.textContent=r)},"text")}function Se(e,t){const s=e.el,n=dt(t)?Ps(t):t;X(s,n,i=>{s.innerHTML!==i&&(p.cleanupDescendants(s),s.innerHTML=i)},"html")}function Te(e,t){Object.entries(t).forEach(([s,n])=>{X(e.el,n,i=>{e.el.classList.toggle(s,!!i)},`class.${s}`)})}function Re(e,t){const s=e.el,n=s.style;Object.entries(t).forEach(([i,r])=>{const o=ks(i),[f,g]=Array.isArray(r)?r:[r,""];X(s,f,S=>{const T=g?`${S}${g}`:String(S);ps(T)||(n[o]=T)},`css.${i}`)})}function Oe(e,t){const s=e.el;Object.keys(t).forEach(n=>{n.toLowerCase().startsWith("on")||X(s,t[n],i=>{if(i==null||i===!1){s.removeAttribute(n);return}const r=i===!0?n:String(i);Es(n,r)||s.getAttribute(n)!==r&&s.setAttribute(n,r)},`attr.${n}`)})}function ve(e,t){const s=e.el;Object.keys(t).forEach(n=>{ss.has(n)||X(e.el,t[n],i=>{s[n]!==i&&(s[n]=i)},`prop.${n}`)})}function yt(e,t,s){const n=e.el;X(n,t,r=>{const o=s!==!!r;n.style.display=o?"":"none"},s?"hide":"show")}function jt(e,t,s={}){const n=e.el.tagName.toLowerCase();if(!es.has(n)){console.warn(`${d.BINDING} ${b.INVALID_INPUT_ELEMENT(n)}`);return}const{fx:i,cleanup:r}=ws(e.$el,t,s);p.trackEffect(e.el,i),e.trackCleanup(r)}function Ne(e,t){const s=e.el,n=e.$el,i=()=>{const o=s.checked;t.value!==o&&(t.value=o)};i[G]=!0,n.on("change",i),e.trackCleanup(()=>n.off("change",i));const r=H(()=>{const o=!!t.value;x(()=>{s.checked!==o&&(s.checked=o,l.domUpdated(n,"checked",o))})});p.trackEffect(s,r)}function xs(e,t){const s=e.$el;s.on(t),e.trackCleanup(()=>s.off(t))}function Ms(e,t,s){const n=e.$el;n.on(t,s),e.trackCleanup(()=>n.off(t,s))}function Ae(e){p.cleanupTree(e)}c.fn.atomText=function(e,t){return this.each(function(){be(N(this),e,t)})},c.fn.atomHtml=function(e){return this.each(function(){Se(N(this),e)})},c.fn.atomClass=function(e,t){if(typeof e=="string"&&t===void 0)return console.warn(`${d.BINDING} ${b.MISSING_CONDITION("atomClass")}`),this;const s=typeof e=="string"?{[e]:t}:e;return this.each(function(){Te(N(this),s)})},c.fn.atomCss=function(e,t,s){if(typeof e=="string"&&t===void 0)return console.warn(`${d.BINDING} ${b.MISSING_SOURCE("atomCss")}`),this;const n=typeof e=="string"?{[e]:s?[t,s]:t}:e;return this.each(function(){Re(N(this),n)})},c.fn.atomAttr=function(e,t){if(typeof e=="string"&&t===void 0)return console.warn(`${d.BINDING} ${b.MISSING_SOURCE("atomAttr")}`),this;const s=typeof e=="string"?{[e]:t}:e;return this.each(function(){Oe(N(this),s)})},c.fn.atomProp=function(e,t){if(typeof e=="string"&&t===void 0)return console.warn(`${d.BINDING} ${b.MISSING_SOURCE("atomProp")}`),this;const s=typeof e=="string"?{[e]:t}:e;return this.each(function(){ve(N(this),s)})},c.fn.atomShow=function(e){return this.each(function(){yt(N(this),e,!1)})},c.fn.atomHide=function(e){return this.each(function(){yt(N(this),e,!0)})},c.fn.atomVal=function(e,t={}){return this.each(function(){jt(N(this),e,t)})},c.fn.atomChecked=function(e){return this.each(function(){Ne(N(this),e)})},c.fn.atomOn=function(e,t){return this.each(function(){Ms(N(this),e,t)})},c.fn.atomBind=function(e){return this.each(function(){const t=N(this);if(e.text!==void 0&&be(t,e.text),e.html!==void 0&&Se(t,e.html),e.class!==void 0&&Te(t,e.class),e.css!==void 0&&Re(t,e.css),e.attr!==void 0&&Oe(t,e.attr),e.prop!==void 0&&ve(t,e.prop),e.show!==void 0&&yt(t,e.show,!1),e.hide!==void 0&&yt(t,e.hide,!0),e.val!==void 0)if(Array.isArray(e.val)){const[s,n]=e.val;jt(t,s,n)}else jt(t,e.val);e.checked!==void 0&&Ne(t,e.checked),e.on!==void 0&&xs(t,e.on)})},c.fn.atomUnbind=function(){return this.each(function(){Ae(this)})};function Fs(e,t,s){t?.isConnected?e.insertBefore(t):e.appendTo(s)}c.fn.atomList=function(e,t){const{key:s,render:n,bind:i,update:r,onAdd:o,onRemove:f,empty:g}=t,S=typeof s=="function"?s:(T,A)=>T[s];return this.each(function(){const T=c(this),A=Mt(this),m=new Map,I=new Set;let j=[],P=null;const $=(D,R)=>{const K=()=>{zt?.isDisposed||(R.$el.remove(),I.delete(D),l.log("list",`${A} removed item:`,D))};if(f){const z=f(R.$el);z instanceof Promise?z.then(K,K):K()}else K()},Ue=(D,R)=>{m.delete(D),I.add(D),$(D,R)};let zt;zt=H(()=>{const D=e.value,R=D.length;x(()=>{if(P&&R>0&&(P.remove(),P=null),R===0){if(g&&!P){const a=typeof g=="string"?Ft(g):g;P=c(a).appendTo(T)}m.forEach((a,u)=>{I.has(u)||Ue(u,a)}),j=[];return}l.log("list",`${A} updating with ${R} items`);const K=new Map;for(let a=0;a<j.length;a++)K.set(j[a],a);const z=new Array(R),Vt=new Set,Ct=new Int32Array(R),bt=[],qt=[],Qt=[];for(let a=0;a<R;a++){const u=D[a],_=S(u,a);if(z[a]=_,Vt.has(_)){l.warn(d.LIST,b.DUPLICATE_KEY(_,a)),Ct[a]=-1;continue}Vt.add(_);const C=m.get(_);if(C){const h=C.item;!r&&h!==u&&!ms(h,u)&&(bt.push(_),qt.push(u),Qt.push(a)),Ct[a]=I.has(_)?-1:K.get(_)??-1}else bt.push(_),qt.push(u),Qt.push(a),Ct[a]=-1}const Le="<!--sep-->",St=bt.length,we=new Array(St),Xt=[];for(let a=0;a<St;a++){const u=n(qt[a],Qt[a]);we[a]=u,typeof u=="string"&&Xt.push(u)}let Tt=null;if(Xt.length>0){const a=Xt.join(Le);Tt=Ft(a).split(Le)}let ke=0;for(let a=0;a<St;a++){const u=we[a],_=c(typeof u=="string"?Tt[ke++]:u),C=bt[a],h=m.get(C);if(h){const U=h.$el[0];U&&p.cleanupTree(U),h.$el.replaceWith(_),h.$el=_,h.state="replaced"}else m.set(C,{$el:_,item:null,state:"new"})}for(const[a,u]of m)!Vt.has(a)&&!I.has(a)&&Ue(a,u);const Pe=gs(Ct);let $t=Pe.length-1,xe=null;const Kt=j.length===0;if(Kt&&Tt!==null&&ke===St&&!i&&!o&&!f&&I.size===0){this.innerHTML=Tt.join("");let a=0;for(let u=0;u<R;u++){const _=z[u],C=D[u],h=m.get(_);if(!h)continue;const U=this.children[a++];U&&(h.$el=c(U),h.item=C,h.state=void 0,I.delete(_),l.domUpdated(h.$el,"list.add",C))}}else{const a=Kt?document.createDocumentFragment():null;if(Kt&&a){for(let u=R-1;u>=0;u--){const _=z[u],C=D[u],h=m.get(_);if(!h)continue;const U=h.state,M=U==="new",ct=U==="replaced";h.item=C,h.state=void 0,h.$el[0]&&(!M&&!ct&&r?r(h.$el,C,u):(M||ct)&&i&&i(h.$el,C,u));for(let Yt=h.$el.length-1;Yt>=0;Yt--)a.insertBefore(h.$el[Yt],a.firstChild);o&&M&&o(h.$el),M&&(I.delete(_),l.domUpdated(h.$el,"list.add",C))}this.appendChild(a)}else for(let u=R-1;u>=0;u--){const _=z[u],C=D[u],h=m.get(_);if(!h)continue;const U=h.state,M=U==="new",ct=U==="replaced";h.item=C,h.state=void 0,h.$el[0]&&(!M&&!ct&&r?r(h.$el,C,u):(M||ct)&&i&&i(h.$el,C,u)),$t>=0&&Pe[$t]===u?$t--:Fs(h.$el,xe,T),o&&M&&o(h.$el),xe=h.$el[0]??null,M&&(I.delete(_),l.domUpdated(h.$el,"list.add",C))}}j=z})}),p.trackEffect(this,zt),p.trackCleanup(this,()=>{m.clear(),I.clear(),j=[],P?.remove()})})};const Bs=Object.freeze({});c.fn.atomMount=function(e,t){const s=t??Bs;return this.each(function(){p.cleanupTree(this);const n=c(this);let i;try{i=x(()=>e(n,s))}catch(r){l.error(d.MOUNT,b.MOUNT_ERROR(),r);return}typeof i=="function"&&p.setComponentCleanup(this,i)})},c.fn.atomUnmount=function(){return this.each(function(){Ae(this)})};function De(e,t){try{return history.pushState(e,"",t),!0}catch(s){return l.warn(d.ROUTE,"PushState failed (likely file:// protocol or security restriction). UI will update, but URL will not.",s),!1}}class Hs{constructor(t){this.isDestroyed=!1,this.previousRoute="",this.cleanups=[],this.templateCache=new Map,this.config={...t,mode:t.mode??mt.mode,basePath:t.basePath??mt.basePath,autoBindLinks:t.autoBindLinks??mt.autoBindLinks,activeClass:t.activeClass??mt.activeClass},this.isHistoryMode=this.config.mode==="history",this.$target=c(this.config.target),this.normalizedBasePath=this.config.basePath?.replace(/\/$/,"")||"",this.previousUrl=this.isHistoryMode?window.location.pathname+window.location.search:window.location.hash,this.currentRouteAtom=ft(this.getRouteName()),this.currentRoute=this.currentRouteAtom,this.queryParamsAtom=ft(this.getQueryParams()),this.queryParams=rt(()=>this.queryParamsAtom.value),this.handleUrlChange=this.handleUrlChange.bind(this),this.destroy=this.destroy.bind(this),this.init()}init(){const t=this.isHistoryMode?"popstate":"hashchange";window.addEventListener(t,this.handleUrlChange),this.cleanups.push(()=>window.removeEventListener(t,this.handleUrlChange));const s=H(()=>{const n=this.currentRouteAtom.value;x(()=>this.renderRoute(n))});this.cleanups.push(()=>s.dispose()),this.setupAutoBindLinks(),this.$target[0]&&p.trackCleanup(this.$target[0],this.destroy)}getRouteName(){const{default:t}=this.config;if(this.isHistoryMode){let r=window.location.pathname;return this.normalizedBasePath&&r.startsWith(this.normalizedBasePath)&&(r=r.substring(this.normalizedBasePath.length)),r.charCodeAt(0)===47&&(r=r.slice(1)),r||t}const s=window.location.hash,n=s.indexOf("?");return(n===-1?s.substring(1):s.substring(1,n))||t}getQueryParams(){let t;if(this.isHistoryMode){if(t=window.location.search.substring(1),!t)return{}}else{const i=window.location.hash,r=i.indexOf("?");if(r===-1)return{};t=i.substring(r+1)}const s=new URLSearchParams(t),n=Object.fromEntries(s);if(t.includes("%"))try{decodeURIComponent(t)}catch{l.warn(d.ROUTE,b.MALFORMED_URI(t))}return n}setUrl(t){if(this.isHistoryMode){const s=`${this.normalizedBasePath}/${t}`;De(null,s),this.previousUrl=s}else{const s=`#${t}`;window.location.hash=s,this.previousUrl=s}}restoreUrl(){this.isHistoryMode?De(null,this.previousUrl):window.location.hash=this.previousUrl}getCurrentUrl(){return this.isHistoryMode?window.location.pathname+window.location.search:window.location.hash}getRouteConfig(t){const{routes:s,notFound:n}=this.config;let i=s[t];return!i&&n&&(i=s[n]),i||(l.warn(d.ROUTE,b.ROUTE_NOT_FOUND(t)),null)}renderTemplate(t){let s=this.templateCache.get(t);if(!s){const i=document.querySelector(t);if(!i||!(i instanceof HTMLTemplateElement))return l.warn(d.ROUTE,b.TEMPLATE_NOT_FOUND(t)),!1;s=i,this.templateCache.set(t,s)}const n=s.content.cloneNode(!0);return this.$target.append(n),!0}renderRoute(t){if(this.isDestroyed)return;const s=this.$target[0];if(!s){l.warn(d.ROUTE,b.TARGET_NOT_FOUND(this.config.target));return}const n=this.getRouteConfig(t);if(!n)return;const i=this.getQueryParams(),r=this.previousRoute;this.config.beforeTransition&&this.config.beforeTransition(r,t),this.$target.empty();let o=i;if(n.onEnter){const f=n.onEnter(i);f!==void 0&&(o={...i,...f})}n.render?n.render(s,t,o):n.template&&this.renderTemplate(n.template)&&n.onMount&&n.onMount(this.$target.children()),this.config.afterTransition&&this.config.afterTransition(r,t),this.previousRoute=t}handleUrlChange(){if(this.isDestroyed)return;const t=this.getCurrentUrl();if(t===this.previousUrl)return;const s=this.getRouteName(),n=this.currentRouteAtom.peek(),i=this.getQueryParams();if(n!==s){const r=this.config.routes[n];if(r?.onLeave&&r.onLeave()===!1){this.restoreUrl();return}this.currentRouteAtom.value=s,this.queryParamsAtom.value=i}else{this.queryParamsAtom.value=i;const r=this.config.routes[n];r?.onParamsChange?r.onParamsChange(i):this.renderRoute(s)}this.previousUrl=t}setupAutoBindLinks(){if(!this.config.autoBindLinks)return;const t=i=>{i.preventDefault();const r=i.currentTarget.dataset.route;r!=null&&this.navigate(r)};c(document).on("click","[data-route]",t),this.cleanups.push(()=>{c(document).off("click","[data-route]",t)});const{activeClass:s}=this.config,n=H(()=>{const i=this.currentRouteAtom.value;x(()=>{const r=document.querySelectorAll("[data-route]");for(const o of r){const f=o.dataset.route,g=i===f;o.classList.toggle(s,g),g?o.setAttribute("aria-current","page"):o.removeAttribute("aria-current")}})});this.cleanups.push(()=>n.dispose())}navigate(t){if(this.isDestroyed)return;const s=this.currentRouteAtom.peek(),n=this.config.routes[s];if(n?.onLeave&&n.onLeave()===!1)return;const i=t||this.config.default;if(!i){l.warn(d.ROUTE,"navigate() called with empty routeName and no default configured.");return}this.setUrl(i),this.queryParamsAtom.value={},this.currentRouteAtom.value=i}destroy(){this.isDestroyed||(this.isDestroyed=!0,this.cleanups.forEach(t=>{try{t()}catch(s){l.warn(d.ROUTE,"Cleanup error during destroy:",s)}}),this.cleanups.length=0,this.templateCache.clear())}}function Gs(e){return new Hs(e)}c.extend({route:Gs});const js=new Promise(()=>{});c.extend({atomFetch(e,t){const{defaultValue:s,transform:n,method:i,headers:r,ajaxOptions:o,onError:f,eager:g}=t,S=typeof e=="function"?e:null,T=typeof e=="string"?e:void 0,A={...o,...i!==void 0&&{method:i},...r!==void 0&&{headers:r}};let m=null;return rt(async()=>{m?.abort(),m=new AbortController;const I=m.signal,j=T?{...A,url:T}:{...A,url:S()},P=c.ajax(j);I.onabort=()=>P.abort(),I.aborted&&P.abort();try{const $=await P;return n?n($):$}catch($){if(I.aborted)return js;try{f?.($)}catch{}throw $}finally{I.onabort=null,m.signal===I&&(m=null)}},{defaultValue:s,lazy:!(g??!0)})}}),c(()=>{Ie(),me(document.body)}),E.default=c,E.atom=ft,E.batch=Pt,E.computed=rt,E.disableAutoCleanup=vs,E.disablejQueryOverrides=Ds,E.effect=H,E.enableAutoCleanup=me,E.enablejQueryOverrides=Ie,E.isAtom=dt,E.isComputed=ae,E.isReactive=xt,E.nextTick=pe,E.registry=p,E.untracked=x,Object.defineProperties(E,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}));
1
+ (function(y,c){typeof exports=="object"&&typeof module<"u"?c(exports,require("jquery")):typeof define=="function"&&define.amd?define(["exports","jquery"],c):(y=typeof globalThis<"u"?globalThis:y||self,c(y.AtomEffectJQuery={},y.jQuery))})(this,(function(y,c){"use strict";const lt={IDLE:"idle",PENDING:"pending",RESOLVED:"resolved",REJECTED:"rejected"},P={DISPOSED:1,EXECUTING:8},Wt={DISPOSED:1,IS_COMPUTED:2,DIRTY:8,IDLE:16,PENDING:32,RESOLVED:64,REJECTED:128,RECOMPUTING:256,HAS_ERROR:512},B={DISPOSED:1,SYNC:8,NOTIFICATION_SCHEDULED:16},V={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},Fe={WARN_INFINITE_LOOP:!0},Jt={MAX_ASYNC_RETRIES:3,MAX_PROMISE_ID:Number.MAX_SAFE_INTEGER-1},ht=1073741823,Be=typeof process<"u"&&process.env&&!1||!1,He=Object.freeze([]);class K extends Error{constructor(t,e=null,n=!0){super(t),this.cause=e,this.recoverable=n,this.name="AtomError"}}class q extends K{constructor(t,e=null){super(t,e,!0),this.name="ComputedError"}}class W extends K{constructor(t,e=null){super(t,e,!1),this.name="EffectError"}}class Nt extends K{constructor(t,e=null){super(t,e,!1),this.name="SchedulerError"}}const Ge=Symbol("AtomEffect.DebugName"),je=Symbol("AtomEffect.Type"),Ot=Symbol("AtomEffect.NoDefaultValue"),ut={enabled:Be,warnInfiniteLoop:Fe.WARN_INFINITE_LOOP,warn(s,t){},checkCircular(s,t){if(s===t)throw new q("Direct circular dependency detected")},attachDebugInfo(s,t,e){},getDebugName:s=>s?.[Ge],getDebugType:s=>s?.[je]};let ze=1;const Ve=()=>ze++;function Zt(s,t,e){if(typeof t=="function"){const i=t;if(e.some(o=>o&&o.fn===i))return;e.push(new Dt(i,void 0));return}if("addDependency"in t){t.addDependency(s);return}const n=t;e.some(i=>i&&i.sub===n)||e.push(new Dt(void 0,n))}function te(s,t,e){const n=new Map;t.forEach(i=>{i?.unsub&&n.set(i.node,i.unsub)}),s.forEach(i=>{if(!i)return;const o=i.node,r=n.get(o);r!==void 0?(i.unsub=r,n.delete(o)):(ut.checkCircular(o,e),i.unsub=o.subscribe(e))}),n.forEach(i=>i())}class vt{constructor(t,e,n=void 0){this.node=t,this.version=e,this.unsub=n}}class Dt{constructor(t,e){this.fn=t,this.sub=e}}const b={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:(s,t)=>`Maximum flush iterations (${s}) exceeded. ${t} 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."};function J(s,t,e){if(s instanceof K)return s;const n=s instanceof Error,i=n?s.message:String(s),o=n?s:void 0,r=`${n?s.constructor.name:"Unexpected error"} (${e}): ${i}`;return new t(r,o)}class ee{constructor(){this.flags=0,this.version=0,this._lastSeenEpoch=-1,this.id=Ve()&ht}}class se extends ee{subscribe(t){const e=typeof t=="function";if(!e&&(!t||typeof t.execute!="function"))throw J(new TypeError("Invalid subscriber"),K,b.ATOM_SUBSCRIBER_MUST_BE_FUNCTION);if(this._subscribers.some(i=>i?e?i.fn===t:i.sub===t:!1))return()=>{};const n=new Dt(e?t:void 0,e?void 0:t);return this._subscribers.push(n),()=>this._unsubscribe(n)}_unsubscribe(t){const e=this._subscribers,n=e.indexOf(t);if(n===-1)return;const i=e.pop();n<e.length&&i&&(e[n]=i)}subscriberCount(){return this._subscribers.length}_notifySubscribers(t,e){this._subscribers.length!==0&&this._subscribers.slice(0).forEach(n=>{if(n)try{n.fn?n.fn(t,e):n.sub&&n.sub.execute()}catch(i){this._handleNotifyError(i)}})}_handleNotifyError(t){console.error(J(t,K,b.ATOM_INDIVIDUAL_SUBSCRIBER_FAILED))}}let At=0;const Lt=()=>(At=At+1&ht||1,At),Ut=s=>s+1&ht;let wt=0,ft=!1,ne=0;const ie=()=>ne;function oe(){return ft?!1:(ft=!0,ne=Lt(),wt=0,!0)}const re=()=>{ft=!1},qe=()=>ft?++wt:0;class Qe{constructor(){this._queueBuffer=[[],[]],this._bufferIndex=0,this._size=0,this._epoch=0,this._isProcessing=!1,this._isBatching=!1,this._isFlushingSync=!1,this._batchDepth=0,this._batchQueue=[],this._batchQueueSize=0,this._maxFlushIterations=V.MAX_FLUSH_ITERATIONS,this.onOverflow=null,this._boundRunLoop=this._runLoop.bind(this)}get phase(){return this._isProcessing||this._isFlushingSync?2:this._isBatching?1:0}get queueSize(){return this._size}get isBatching(){return this._isBatching}schedule(t){if(t._nextEpoch!==this._epoch){if(t._nextEpoch=this._epoch,this._isBatching||this._isFlushingSync){this._batchQueue[this._batchQueueSize++]=t;return}this._queueBuffer[this._bufferIndex][this._size++]=t,this._isProcessing||this._flush()}}_flush(){this._isProcessing||this._size===0||(this._isProcessing=!0,queueMicrotask(this._boundRunLoop))}_runLoop(){try{if(this._size===0)return;const t=oe();this._drainQueue(),t&&re()}finally{this._isProcessing=!1,this._size>0&&!this._isBatching&&this._flush()}}_flushSync(){this._isFlushingSync=!0;const t=oe();try{this._mergeBatchQueue(),this._drainQueue()}finally{this._isFlushingSync=!1,t&&re()}}_mergeBatchQueue(){if(this._batchQueueSize===0)return;const t=++this._epoch,e=this._batchQueue,n=this._queueBuffer[this._bufferIndex];let i=this._size;e.slice(0,this._batchQueueSize).forEach(o=>{o._nextEpoch!==t&&(o._nextEpoch=t,n[i++]=o)}),this._size=i,this._batchQueueSize=0,e.length>V.BATCH_QUEUE_SHRINK_THRESHOLD&&(e.length=0)}_drainQueue(){let t=0;for(;this._size>0;){if(++t>this._maxFlushIterations){this._handleFlushOverflow();return}this._processQueue(),this._mergeBatchQueue()}}_processQueue(){const t=this._bufferIndex,e=this._queueBuffer[t],n=this._size;this._bufferIndex=t^1,this._size=0,this._epoch++;for(let i=0;i<n;i++)try{e[i]()}catch(o){console.error(new Nt("Error occurred during scheduler execution",o))}e.length=0}_handleFlushOverflow(){const t=this._size+this._batchQueueSize;if(console.error(new Nt(b.SCHEDULER_FLUSH_OVERFLOW(this._maxFlushIterations,t))),this._size=0,this._queueBuffer[this._bufferIndex].length=0,this._batchQueueSize=0,this.onOverflow)try{this.onOverflow(t)}catch{}}startBatch(){this._batchDepth++,this._isBatching=!0}endBatch(){this._batchDepth!==0&&--this._batchDepth===0&&(this._flushSync(),this._isBatching=!1)}setMaxFlushIterations(t){if(t<V.MIN_FLUSH_ITERATIONS)throw new Nt(`Max flush iterations must be at least ${V.MIN_FLUSH_ITERATIONS}`);this._maxFlushIterations=t}}const nt=new Qe,kt=Symbol.for("atom-effect/atom"),ce=Symbol.for("atom-effect/computed"),Xe=Symbol.for("atom-effect/effect"),x={current:null,run(s,t){const e=this.current;this.current=s;try{return t()}finally{this.current=e}}};function F(s){const t=x.current;if(t===null)return s();x.current=null;try{return s()}finally{x.current=t}}var ae;class $e extends se{constructor(t,e){super(),this._pendingOldValue=void 0,this._notifyTask=()=>this._flushNotifications(),this._subscribers=[],this[ae]=!0,this._value=t,e&&(this.flags|=B.SYNC),ut.attachDebugInfo(this,"atom",this.id)}get value(){const t=x.current;return t&&Zt(this,t,this._subscribers),this._value}set value(t){const e=this._value;if(Object.is(e,t))return;this._value=t,this.version=Ut(this.version);const n=this.flags;if(!(this._subscribers.length===0||n&B.NOTIFICATION_SCHEDULED)){if(this._pendingOldValue=e,this.flags=n|B.NOTIFICATION_SCHEDULED,n&B.SYNC&&!nt.isBatching){this._flushNotifications();return}nt.schedule(this._notifyTask)}}_flushNotifications(){const t=this.flags;if(!(t&B.NOTIFICATION_SCHEDULED)||t&B.DISPOSED)return;const e=this._pendingOldValue;this._pendingOldValue=void 0,this.flags&=-17,this._notifySubscribers(this._value,e)}peek(){return this._value}dispose(){this.flags&B.DISPOSED||(this._subscribers.length=0,this.flags|=B.DISPOSED,this._value=void 0,this._pendingOldValue=void 0)}[(ae=kt,Symbol.dispose)](){this.dispose()}}function dt(s,t={}){return new $e(s,t.sync??!1)}class Ye{constructor(t=50,e=256,n=!1){this.limit=t,this.capacity=e,this.pool=[],this.stats=null,this.stats=n?{acquired:0,released:0,rejected:{frozen:0,tooLarge:0,poolFull:0}}:null}acquire(){return this.stats&&this.stats.acquired++,this.pool.pop()??[]}release(t,e){if(!(e&&t===e)){if(t.length>this.capacity){this.stats&&this.stats.rejected.tooLarge++;return}if(this.pool.length>=this.limit){this.stats&&this.stats.rejected.poolFull++;return}if(Object.isFrozen(t)){this.stats&&this.stats.rejected.frozen++;return}t.length=0,this.pool.push(t),this.stats&&this.stats.released++}}getStats(){if(!this.stats)return null;const{acquired:t,released:e,rejected:n}=this.stats,i=t-e-(n.frozen+n.tooLarge+n.poolFull);return{acquired:t,released:e,rejected:{...n},leaked:i,poolSize:this.pool.length}}reset(){this.pool.length=0,this.stats&&(this.stats={acquired:0,released:0,rejected:{frozen:0,tooLarge:0,poolFull:0}})}}const A=Object.freeze([]),H=new Ye;function _t(s){return s!==null&&typeof s=="object"&&kt in s}function le(s){return s!==null&&typeof s=="object"&&ce in s}function he(s){return s!==null&&typeof s=="object"&&typeof s.then=="function"}var ue,fe;const{IDLE:Et,DIRTY:Z,PENDING:pt,RESOLVED:Q,REJECTED:it,HAS_ERROR:gt,RECOMPUTING:ot,DISPOSED:Pt,IS_COMPUTED:Ke}=Wt;function We(s){return s&Q?lt.RESOLVED:s&pt?lt.PENDING:s&it?lt.REJECTED:lt.IDLE}class Je extends se{constructor(t,e={}){if(typeof t!="function")throw new q(b.COMPUTED_MUST_BE_FUNCTION);super(),this[fe]=!0,this[ue]=!0,this._error=null,this._promiseId=0,this._subscribers=[],this._links=A,this._asyncStartAggregateVersion=0,this._asyncRetryCount=0,this._lastDriftEpoch=-1,this._trackEpoch=-1,this._trackLinks=A,this._trackCount=0,this._value=void 0,this.flags=Ke|Z|Et,this._equal=e.equal??Object.is,this._fn=t,this._defaultValue="defaultValue"in e?e.defaultValue:Ot,this._onError=e.onError??null;const n=e.maxAsyncRetries;if(this._maxAsyncRetries=(n??Jt.MAX_ASYNC_RETRIES)&ht,ut.attachDebugInfo(this,"computed",this.id),e.lazy===!1)try{this._recompute()}catch{}}_track(){const t=x.current;t&&Zt(this,t,this._subscribers)}get value(){this._track();const t=this.flags;if((t&(Q|Z|Et))===Q)return this._value;if(t&Pt)throw new q(b.COMPUTED_DISPOSED);if(t&ot){if(this._defaultValue!==Ot)return this._defaultValue;throw new q(b.COMPUTED_CIRCULAR_DEPENDENCY)}if(t&(Z|Et)&&(this._recompute(),this.flags&Q))return this._value;const e=this._defaultValue,n=e!==Ot;if(this.flags&pt){if(n)return e;throw new q(b.COMPUTED_ASYNC_PENDING_NO_DEFAULT)}if(this.flags&it){if(n)return e;throw this._error}return this._value}peek(){return this._value}get state(){return this._track(),We(this.flags)}get hasError(){return this._track(),this.flags&(it|gt)?!0:this._links.some(t=>t?.node?.flags&gt)}get isValid(){return!this.hasError}get errors(){if(this._track(),!this.hasError)return He;const t=[];return this._error&&t.push(this._error),this._links.forEach(e=>{const n=e.node;n.flags&gt&&n.errors.forEach(i=>{i&&!t.includes(i)&&t.push(i)})}),Object.freeze(t)}get lastError(){return this._track(),this._error}get isPending(){return this._track(),(this.flags&pt)!==0}get isResolved(){return this._track(),(this.flags&Q)!==0}invalidate(){this._markDirty()}dispose(){if(this.flags&Pt)return;const t=this._links;t!==A&&(t.forEach(e=>e.unsub?.()),H.release(t),this._links=A),this._subscribers.length=0,this.flags=Pt|Z|Et,this._error=null,this._value=void 0}[(fe=kt,ue=ce,Symbol.dispose)](){this.dispose()}addDependency(t){if(t._lastSeenEpoch!==this._trackEpoch){if(t._lastSeenEpoch=this._trackEpoch,this._trackCount<this._trackLinks.length){const e=this._trackLinks[this._trackCount];e.node=t,e.version=t.version}else this._trackLinks.push(new vt(t,t.version));this._trackCount++}}_recompute(){if(this.flags&ot)return;this.flags|=ot;const t=this._links;this._trackEpoch=Lt(),this._trackLinks=H.acquire(),this._trackCount=0;let e=!1;try{const n=x.run(this,this._fn);this._trackLinks.length=this._trackCount,te(this._trackLinks,t,this),this._links=this._trackLinks,e=!0,he(n)?this._handleAsyncComputation(n):this._finalizeResolution(n)}catch(n){if(!e)try{this._trackLinks.length=this._trackCount,te(this._trackLinks,t,this),this._links=this._trackLinks,e=!0}catch{}this._handleError(n,b.COMPUTED_COMPUTATION_FAILED,!0)}finally{e&&t!==A?H.release(t):e||H.release(this._trackLinks),this._trackEpoch=-1,this._trackLinks=A,this._trackCount=0,this.flags&=~ot}}_handleAsyncComputation(t){this.flags=(this.flags|pt)&-217,this._notifySubscribers(void 0,void 0),this._asyncStartAggregateVersion=this._captureVersionSnapshot(),this._asyncRetryCount=0,this._promiseId=(this._promiseId+1)%Jt.MAX_PROMISE_ID;const e=this._promiseId;t.then(n=>{if(e===this._promiseId){if(this._captureVersionSnapshot()!==this._asyncStartAggregateVersion){const i=ie();return this._lastDriftEpoch!==i&&(this._lastDriftEpoch=i,this._asyncRetryCount=0),this._asyncRetryCount++<this._maxAsyncRetries?this._markDirty():this._handleError(new q(`Async drift threshold exceeded after ${this._maxAsyncRetries} retries.`),b.COMPUTED_ASYNC_COMPUTATION_FAILED)}this._finalizeResolution(n),this._notifySubscribers(n,void 0)}},n=>e===this._promiseId&&this._handleError(n,b.COMPUTED_ASYNC_COMPUTATION_FAILED))}_captureVersionSnapshot(){let t=0;const e=this._links;for(let n=0,i=e.length;n<i;n++)t=(t<<5)-t+e[n].node.version|0;return t}_handleError(t,e,n=!1){const i=J(t,q,e);if(!n&&!(this.flags&it)&&(this.version=Ut(this.version)),this._error=i,this.flags=this.flags&-121|it|gt,this._onError)try{this._onError(i)}catch(o){console.error(b.CALLBACK_ERROR_IN_ERROR_HANDLER,o)}if(n)throw i;this._notifySubscribers(void 0,void 0)}_finalizeResolution(t){(!(this.flags&Q)||!this._equal(this._value,t))&&(this.version=Ut(this.version)),this._value=t,this._error=null,this.flags=(this.flags|Q)&-697}execute(){this._markDirty()}_markDirty(){this.flags&(ot|Z)||(this.flags|=Z,this._notifySubscribers(void 0,void 0))}}function rt(s,t={}){return new Je(s,t)}var de;class Ze extends ee{constructor(t,e={}){super(),this[de]=!0,this._cleanup=null,this._links=A,this._nextLinks=null,this._prevLinks=A,this._currentEpoch=-1,this._lastFlushEpoch=-1,this._executionsInEpoch=0,this._executionCount=0,this._windowStart=0,this._windowCount=0,this._execId=0,this._fn=t,this._onError=e.onError??null,this._sync=e.sync??!1,this._maxExecutions=e.maxExecutionsPerSecond??V.MAX_EXECUTIONS_PER_SECOND,this._maxExecutionsPerFlush=e.maxExecutionsPerFlush??V.MAX_EXECUTIONS_PER_EFFECT,this._sync?(this._executeTask=void 0,this._notifyCallback=()=>this.execute()):(this._executeTask=()=>this.execute(),this._notifyCallback=()=>nt.schedule(this._executeTask)),ut.attachDebugInfo(this,"effect",this.id)}run(){if(this.flags&P.DISPOSED)throw new W(b.EFFECT_DISPOSED);this.execute(!0)}dispose(){this.flags&P.DISPOSED||(this.flags|=P.DISPOSED,this._execCleanup(),this._unsubLinks(this._links),this._links!==A&&H.release(this._links),this._links=A,this._prevLinks=A)}[(de=Xe,Symbol.dispose)](){this.dispose()}addDependency(t){if(!(this.flags&P.EXECUTING))return;const e=this._currentEpoch;if(t._lastSeenEpoch===e)return;t._lastSeenEpoch=e;const n=this._nextLinks,i=this._prevLinks,o=i.findIndex(r=>r&&r.node===t&&r.unsub);if(o!==-1){const r=i[o];r.version=t.version,n.push(r),i[o]=null;return}try{const r=t.subscribe(this._notifyCallback);n.push(new vt(t,t.version,r))}catch(r){const a=J(r,W,b.EFFECT_EXECUTION_FAILED);if(console.error(a),this._onError)try{this._onError(a)}catch{}n.push(new vt(t,t.version,void 0))}}execute(t=!1){if(this.flags&(P.DISPOSED|P.EXECUTING)||!t&&this._links.length>0&&!this._isDirty())return;this._checkInfiniteLoops(),this.flags|=P.EXECUTING,this._execCleanup(),this._prevLinks=this._links;const e=H.acquire();this._nextLinks=e,this._currentEpoch=Lt();let n=!1;try{const i=x.run(this,this._fn);this._links=e,n=!0,he(i)?this._handleAsyncResult(i):this._cleanup=typeof i=="function"?i:null}catch(i){this._links=e,n=!0,this._handleExecutionError(i),this._cleanup=null}finally{this._finalizeDependencies(n,this._prevLinks,e),this.flags&=-9}}_handleAsyncResult(t){const e=++this._execId;t.then(n=>{if(e!==this._execId||this.flags&P.DISPOSED){if(typeof n=="function")try{n()}catch(i){this._handleExecutionError(i,b.EFFECT_CLEANUP_FAILED)}return}typeof n=="function"&&(this._cleanup=n)},n=>e===this._execId&&this._handleExecutionError(n))}_finalizeDependencies(t,e,n){this._nextLinks=null,this._prevLinks=A,t?(e.forEach(i=>i?.unsub?.()),e!==A&&H.release(e)):(this._unsubLinks(n),H.release(n))}_unsubLinks(t){t.forEach(e=>e?.unsub?.())}_isDirty(){const t=this._links,e=x.current;x.current=null;try{return t.some(n=>{const i=n.node;if(i.flags&Wt.IS_COMPUTED)try{i.value}catch{return!0}return i.version!==n.version})}finally{x.current=e}}_execCleanup(){if(this._cleanup){try{this._cleanup()}catch(t){this._handleExecutionError(t,b.EFFECT_CLEANUP_FAILED)}this._cleanup=null}}_checkInfiniteLoops(){const t=ie();this._lastFlushEpoch!==t&&(this._lastFlushEpoch=t,this._executionsInEpoch=0),++this._executionsInEpoch>this._maxExecutionsPerFlush&&this._throwInfiniteLoopError("per-effect"),qe()>V.MAX_EXECUTIONS_PER_FLUSH&&this._throwInfiniteLoopError("global"),this._executionCount++}get isDisposed(){return(this.flags&P.DISPOSED)!==0}get executionCount(){return this._executionCount}get isExecuting(){return(this.flags&P.EXECUTING)!==0}_throwInfiniteLoopError(t){const e=new W(`Infinite loop detected (${t}): effect executed ${this._executionsInEpoch} times in current flush. Total executions in flush: ${wt}`);throw this.dispose(),console.error(e),e}_handleExecutionError(t,e=b.EFFECT_EXECUTION_FAILED){const n=J(t,W,e);if(console.error(n),this._onError)try{this._onError(n)}catch(i){console.error(J(i,W,b.CALLBACK_ERROR_IN_ERROR_HANDLER))}}}function G(s,t={}){if(typeof s!="function")throw new W(b.EFFECT_MUST_BE_FUNCTION);const e=new Ze(s,t);return e.execute(),e}function xt(s){if(typeof s!="function")throw new TypeError("Batch callback must be a function");nt.startBatch();try{return s()}finally{nt.endBatch()}}const E={ROUTE:"[atom-route]",BINDING:"[atom-binding]",LIST:"[atom-list]",MOUNT:"[atom-mount]"},mt=Object.freeze({mode:"hash",basePath:"",autoBindLinks:!1,activeClass:"active"}),ts={EVENT:"input"},es=new Set(["input","select","textarea"]),ss=new Set(["innerHTML","outerHTML","srcdoc","__proto__","constructor","prototype"]),R={ROUTE_NOT_FOUND:s=>`Route "${s}" not found and no notFound route configured`,TEMPLATE_NOT_FOUND:s=>`Template "${s}" not found`,TARGET_NOT_FOUND:s=>`Target element "${s}" not found`,MALFORMED_URI:s=>`Malformed URI component: ${s}`,UNSAFE_CONTENT:()=>"Unsafe content neutralized during sanitization.",BLOCKED_DANGEROUS_CSS_VALUE:s=>`Blocked dangerous value in CSS style property "${s}".`,BLOCKED_EVENT_HANDLER:s=>`Blocked setting dangerous event handler attribute "${s}".`,BLOCKED_PROTOCOL:s=>`Blocked dangerous protocol in "${s}" attribute.`,BLOCKED_DANGEROUS_PROP:s=>`Blocked setting dangerous property "${s}". Use html binding for sanitized HTML.`,INVALID_INPUT_ELEMENT:s=>`Val binding used on non-input element <${s}>.`,MISSING_SOURCE:s=>`[${s}] source is required when prop/name is a string.`,MISSING_CONDITION:s=>`[${s}] condition is required when className is a string.`,DUPLICATE_KEY:(s,t)=>`Duplicate key "${s}" at index ${t}.`,UPDATER_ERROR:s=>`Updater threw in binding "${s}"`,EFFECT_DISPOSE_ERROR:()=>"Effect dispose error",BINDING_CLEANUP_ERROR:()=>"Binding cleanup error",PARSE_ERROR:()=>"parse() threw during DOM→Atom sync",MOUNT_ERROR:()=>"Mount error",MOUNT_CLEANUP_ERROR:()=>"Cleanup error"};function Mt(s){return _t(s)}function Ft(s){const t=s.tagName.toLowerCase();if(s.id)return`${t}#${s.id}`;const e=s.classList,n=e.length;if(n===0)return t;let i=t;for(let o=0;o<n;o++)i+=`.${e[o]}`;return i}const ns=new Set(["href","src","action","formaction","xlink:href","data","poster","srcset","background","cite","longdesc","profile","usemap","classid","codebase"]),ct=Object.prototype.hasOwnProperty,is=/^\s*(?:javascript|vbscript)\s*:/i,os=/(?:expression\s*\(|behavior\s*:|-moz-binding\s*:|(?:\\[0-9a-f]{1,6}\s*|[\s\x00-\x20/'"])*(?:j\s*a\s*v\s*a\s*s\s*c\s*r\s*i\s*p\s*t|v\s*b\s*s\s*c\s*r\s*i\s*p\s*t|d\s*a\s*t\s*a)\s*:(?!image\/))/i,rs=/url\s*\(\s*(?:["']?\s*)?(?:javascript|vbscript)\s*:/i,cs=/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g,as=/&#x([0-9a-f]+);?|&#([0-9]+);?/gi,ls={colon:":",Tab:" ",NewLine:`
2
+ `},hs=/&(colon|Tab|NewLine);/g,us=/<\?[\s\S]*?\?>/g,fs=/(<(script|iframe|object|embed|base|meta|applet|noscript|form|style|link)\b[^>]*>([\s\S]*?)<\/\2>|<(script|iframe|object|embed|base|meta|applet|noscript|form|style|link)\b[^>]*\/?>)/gi,ds=/(j\s*a\s*v\s*a\s*s\s*c\s*r\s*i\s*p\s*t|v\s*b\s*s\s*c\s*r\s*i\s*p\s*t)\s*:/gi,_s=/data\s*:\s*(?:text\/(?:html|javascript|vbscript|xml)|application\/(?:javascript|xhtml\+xml|xml|x-shockwave-flash)|image\/svg\+xml)/gi,Es=/\bon\w+\s*=/gim,ps=new RegExp(os.source,"gim");function Bt(s){let t=String(s??"");t=t.replace(cs,""),t=t.replace(as,(n,i,o)=>String.fromCodePoint(i?parseInt(i,16):parseInt(o,10))),t=t.replace(hs,(n,i)=>ls[i]??""),t=t.replace(us,"");let e;do e=t,t=t.replace(fs,"");while(t!==e);return t=t.replace(ds,"data-unsafe-protocol:"),t=t.replace(_s,"data-unsafe-protocol:"),t=t.replace(Es,"data-unsafe-attr="),t=t.replace(ps,"data-unsafe-css:"),t}function gs(s,t){return ns.has(s.toLowerCase())?is.test(t):!1}function ms(s){return s.toLowerCase().includes("url(")?rs.test(s):!1}function Is(s,t){if(s===t)return!0;if(s===null||t===null||typeof s!="object"||typeof t!="object")return!1;const e=Object.keys(s),n=Object.keys(t);if(e.length!==n.length)return!1;const i=s,o=t;for(let r=0;r<e.length;r++){const a=e[r];if(!ct.call(o,a)||i[a]!==o[a])return!1}return!0}function ys(s){const t=s.length;if(t===0)return new Int32Array(0);const e=new Int32Array(t).fill(-1),n=new Int32Array(t);let i=0;for(let r=0;r<t;r++){const a=s[r];if(a===void 0||a===-1)continue;const p=i>0?n[i-1]:void 0;if(i===0||p!==void 0&&(s[p]??-1)<a){e[r]=p??-1,n[i++]=r;continue}let d=0,m=i-1;for(;d<m;){const g=d+m>>>1,v=n[g];v!==void 0&&(s[v]??-1)<a?d=g+1:m=g}const O=n[d];O!==void 0&&a<(s[O]??Number.MAX_SAFE_INTEGER)&&(d>0&&(e[r]=n[d-1]??-1),n[d]=r)}const o=new Int32Array(i);if(i>0){let r=n[i-1];for(let a=i-1;a>=0&&r!==void 0&&r!==-1;a--)o[a]=r,r=e[r]}return o}const Cs={},_e=600,bs=`${_e/1e3}s`;function Ss(){if(typeof window<"u"){const s=window.__ATOM_DEBUG__;if(typeof s=="boolean")return s}return Cs?.VITE_ATOM_DEBUG==="true"}let tt=Ss();const f={get enabled(){return tt},set enabled(s){tt=s},log(s,...t){tt&&console.log(`${E.MOUNT} ${s}:`,...t)},atomChanged(s,t,e){tt&&console.log(`${E.MOUNT} Atom "${s??"anonymous"}" changed:`,t,"→",e)},domUpdated(s,t,e){if(!tt)return;const n=s instanceof Element?s:s[0];n instanceof HTMLElement&&(console.log(`${E.MOUNT} DOM updated: ${Ft(n)}.${t} =`,e),Ns(n))},cleanup(s){tt&&console.log(`${E.MOUNT} Cleanup: ${s}`)},warn(s,t,...e){console.warn(`${s} ${t}`,...e)},error(s,t,e){console.error(`${s} ${t}`,e)}},Ht="atom-debug-highlight",Ts="data-atom-debug";let Ee;function Rs(){if(Ee?.deref()?.isConnected)return;const s=document.createElement("style");s.setAttribute(Ts,""),s.textContent=`.${Ht}{outline:2px solid rgba(255,68,68,0.8);outline-offset:1px;transition:outline ${bs} ease-out}`,document.head.appendChild(s),Ee=new WeakRef(s)}const Gt=new WeakMap,jt=new WeakMap;function Ns(s){if(!s.isConnected)return;Rs();const t=jt.get(s);t!==void 0&&cancelAnimationFrame(t);const e=Gt.get(s);e!==void 0&&clearTimeout(e);const n=requestAnimationFrame(()=>{jt.delete(s),s.classList.add(Ht),Gt.set(s,setTimeout(()=>{s.classList.remove(Ht),Gt.delete(s)},_e))});jt.set(s,n)}function pe(s,t){return dt(s,t)}Object.defineProperty(pe,"debug",{enumerable:!0,configurable:!0,get(){return f.enabled},set(s){f.enabled=s}});function ge(){return new Promise(s=>setTimeout(s,0))}const Os={atom:pe,computed:rt,effect:G,batch:xt,untracked:F,isAtom:_t,isComputed:le,isReactive:Mt,nextTick:ge};c.extend(Os);const et="_aes-bound";class vs{constructor(){this.records=new WeakMap,this.preservedNodes=new WeakSet,this.ignoredNodes=new WeakSet}keep(t){this.preservedNodes.add(t)}isKept(t){return this.preservedNodes.has(t)}markIgnored(t){this.ignoredNodes.add(t)}isIgnored(t){return this.ignoredNodes.has(t)}getOrCreateRecord(t){let e=this.records.get(t);return e||(e={},this.records.set(t,e),t.classList.add(et)),e}trackEffect(t,e){const n=this.getOrCreateRecord(t);n.effects??=[],n.effects.push(e)}trackCleanup(t,e){const n=this.getOrCreateRecord(t);n.cleanups??=[],n.cleanups.push(e)}setComponentCleanup(t,e){const n=this.getOrCreateRecord(t);n.componentCleanup=e}hasBind(t){return this.records.has(t)}cleanup(t){const e=this.records.get(t);if(!e){t.isConnected&&t.classList.remove(et),this.preservedNodes.delete(t),this.ignoredNodes.delete(t);return}if(this.records.delete(t),this.preservedNodes.delete(t),this.ignoredNodes.delete(t),t.isConnected&&t.classList.remove(et),f.enabled&&f.cleanup(Ft(t)),e.componentCleanup)try{e.componentCleanup()}catch(n){f.error(E.MOUNT,R.MOUNT_CLEANUP_ERROR(),n)}if(e.effects){const n=e.effects;for(let i=0,o=n.length;i<o;i++)try{n[i].dispose()}catch(r){f.error(E.BINDING,R.EFFECT_DISPOSE_ERROR(),r)}}if(e.cleanups){const n=e.cleanups;for(let i=0,o=n.length;i<o;i++)try{n[i]()}catch(r){f.error(E.BINDING,R.BINDING_CLEANUP_ERROR(),r)}}}cleanupDescendants(t){const e=t.getElementsByClassName(et);for(let n=e.length-1;n>=0;n--){const i=e[n];i&&(this.records.has(i)?this.cleanup(i):(i.classList.remove(et),f.enabled&&f.warn(E.BINDING,`${et} class found on unregistered element:`,i)))}}cleanupTree(t){this.cleanupDescendants(t),this.cleanup(t)}}const C=new vs;let at=null,It=null;function me(s){if(at!==null){It!==s&&f.warn(E.BINDING,"enableAutoCleanup() called with a different root while already active. Observation was NOT switched — call disableAutoCleanup() first.",{current:It,requested:s});return}It=s,at=new MutationObserver(t=>{for(let e=0,n=t.length;e<n;e++){const i=t[e].removedNodes;for(let o=0,r=i.length;o<r;o++){const a=i[o];a.nodeType===1&&(a.isConnected||C.isKept(a)||C.isIgnored(a)||C.cleanupTree(a))}}}),at.observe(s,{childList:!0,subtree:!0})}function Ds(){at?.disconnect(),at=null,It=null}function X(s,t,e,n){if(Mt(t)){const i=t;C.trackEffect(s,G(()=>{const o=i.value;F(()=>{try{e(o)}catch(r){f.error(E.BINDING,`${R.UPDATER_ERROR(n)}:`,r);return}f.enabled&&f.domUpdated(s,n,o)})}))}else{try{e(t)}catch(i){f.error(E.BINDING,`${R.UPDATER_ERROR(n)} (static):`,i);return}f.enabled&&f.domUpdated(s,n,t)}}const j=Symbol("atom-effect-internal"),yt=new WeakMap;let M=null;const Ie=s=>{if(s[j])return s;let t=yt.get(s);return t||(t=function(...e){return xt(()=>s.apply(this,e))},t[j]=!0,yt.set(s,t)),t};function As(s){const t={};return Object.keys(s).forEach(e=>{const n=s[e];n&&(t[e]=Ie(n))}),t}function Ls(s){const t={};return Object.keys(s).forEach(e=>{const n=s[e];t[e]=n?yt.get(n)??n:void 0}),t}function ye(){if(M!==null)return;M={on:c.fn.on,off:c.fn.off,remove:c.fn.remove,empty:c.fn.empty,detach:c.fn.detach};const s=M;c.fn.remove=function(t){const e=t?this.filter(t):this;for(let n=0,i=e.length;n<i;n++){const o=e[n];o&&(C.markIgnored(o),C.cleanupTree(o))}return s.remove.call(this,t)},c.fn.empty=function(){for(let t=0,e=this.length;t<e;t++){const n=this[t];n&&C.cleanupDescendants(n)}return s.empty.call(this)},c.fn.detach=function(t){const e=t?this.filter(t):this;for(let n=0,i=e.length;n<i;n++){const o=e[n];o&&C.keep(o)}return s.detach.call(this,t)},c.fn.on=function(...t){const e=t[0];if(e&&typeof e=="object")t[0]=As(e);else for(let n=t.length-1;n>=0;n--)if(typeof t[n]=="function"){t[n]=Ie(t[n]);break}return s.on.apply(this,t)},c.fn.off=function(...t){const e=t[0];if(e&&typeof e=="object")t[0]=Ls(e);else for(let n=t.length-1;n>=0;n--)if(typeof t[n]=="function"){const i=t[n];t[n]=yt.get(i)??i;break}return s.off.apply(this,t)}}function Us(){M!==null&&(c.fn.on=M.on,c.fn.off=M.off,c.fn.remove=M.remove,c.fn.empty=M.empty,c.fn.detach=M.detach,M=null)}var L=(s=>(s[s.None=0]="None",s[s.Focused=1]="Focused",s[s.Composing=2]="Composing",s[s.SyncingToAtom=4]="SyncingToAtom",s[s.SyncingToDom=8]="SyncingToDom",s[s.Busy=14]="Busy",s))(L||{});let ws=0;class ks{constructor(t,e,n){this.flags=0,this.timeoutId=void 0,this.handleCompositionStart=()=>{this.flags|=L.Composing},this.handleCompositionEnd=()=>{this.flags&=~L.Composing,this.handleInput()},this.handleFocus=()=>{this.flags|=L.Focused},this.handleBlur=()=>{this.flags&=~L.Focused,this.timeoutId!==void 0&&(clearTimeout(this.timeoutId),this.timeoutId=void 0,this.syncAtomFromDom());const r=this.format(this.atom.peek());this.el.value!==r&&(this.el.value=r)},this.syncDomFromAtom=()=>{const r=this.atom.value;F(()=>{const a=this.format(r),p=this.el.value;if(p===a)return;const d=!!(this.flags&L.Focused);if(d)try{if(this.equal(this.parse(p),r))return}catch{}this.flags|=L.SyncingToDom;try{if(d&&(this.el instanceof HTMLInputElement||this.el instanceof HTMLTextAreaElement)){const m=this.el.selectionStart,O=this.el.selectionEnd;this.el.value=a;const g=a.length;m!==null&&O!==null&&this.el.setSelectionRange(m<g?m:g,O<g?O:g)}else this.el.value=a;f.domUpdated(this.$el,"val",a)}finally{this.flags&=~L.SyncingToDom}})},this.cleanup=()=>{this.$el.off(this.ns),clearTimeout(this.timeoutId),this.timeoutId=void 0},this.$el=t,this.el=t[0],this.atom=e,this.ns=`.atomBind-${++ws}`;const i=n.debounce??0,o=n.event??ts.EVENT;this.parse=n.parse??(r=>r),this.format=n.format??(r=>String(r??"")),this.equal=n.equal??Object.is,i>0?this.handleInput=()=>{this.flags&L.Composing||(clearTimeout(this.timeoutId),this.timeoutId=setTimeout(()=>this.syncAtomFromDom(),i))}:this.handleInput=()=>{this.flags&L.Composing||this.syncAtomFromDom()},this.handleFocus[j]=!0,this.handleBlur[j]=!0,this.handleCompositionStart[j]=!0,this.handleCompositionEnd[j]=!0,this.handleInput[j]=!0,this.bindEvents(o)}syncAtomFromDom(){if(!(this.flags&L.Busy)){this.flags|=L.SyncingToAtom;try{const t=this.parse(this.el.value);this.equal(this.atom.peek(),t)||(this.atom.value=t)}catch(t){f.warn(E.BINDING,`${R.PARSE_ERROR()}:`,t)}finally{this.flags&=~L.SyncingToAtom}}}bindEvents(t){const e=this.ns;this.$el.on(`focus${e}`,this.handleFocus).on(`blur${e}`,this.handleBlur).on(`compositionstart${e}`,this.handleCompositionStart).on(`compositionend${e}`,this.handleCompositionEnd).on(`${t}${e}`,this.handleInput)}}function Ps(s,t,e){const n=new ks(s,t,e);return{fx:G(n.syncDomFromAtom),cleanup:n.cleanup}}const Ce=new Map;function xs(s){let t=Ce.get(s);return t!==void 0||(t=s.includes("-")?s.replace(/-./g,e=>e[1].toUpperCase()):s,Ce.set(s,t)),t}const be=new WeakMap;function Ms(s){let t=be.get(s);return t||(t=rt(()=>Bt(s.value)),be.set(s,t)),t}function U(s){return{$el:c(s),el:s,trackCleanup:t=>C.trackCleanup(s,t)}}function Se(s,t,e){const n=s.el;X(n,t,i=>{const o=e?e(i):typeof i=="string"?i:String(i??"");n.textContent!==o&&(n.textContent=o)},"text")}function Te(s,t){const e=s.el,n=_t(t)?Ms(t):t;X(e,n,i=>{e.innerHTML!==i&&(C.cleanupDescendants(e),e.innerHTML=i)},"html")}function Re(s,t){for(const e in t)if(ct.call(t,e)){const n=t[e];X(s.el,n,i=>{s.el.classList.toggle(e,!!i)},`class.${e}`)}}function Ne(s,t){const e=s.el,n=e.style;for(const i in t)if(ct.call(t,i)){const o=t[i],r=xs(i),[a,p]=Array.isArray(o)?o:[o,""];X(e,a,d=>{const m=p?`${d}${p}`:String(d);ms(m)||(n[r]=m)},`css.${i}`)}}function Oe(s,t){const e=s.el;for(const n in t)if(ct.call(t,n)){if(n.toLowerCase().startsWith("on"))continue;X(e,t[n],i=>{if(i==null||i===!1){e.removeAttribute(n);return}const o=i===!0?n:String(i);gs(n,o)||e.getAttribute(n)!==o&&e.setAttribute(n,o)},`attr.${n}`)}}function ve(s,t){const e=s.el;for(const n in t)if(ct.call(t,n)){if(ss.has(n))continue;X(s.el,t[n],i=>{e[n]!==i&&(e[n]=i)},`prop.${n}`)}}function Ct(s,t,e){const n=s.el;X(n,t,o=>{const r=e!==!!o;n.style.display=r?"":"none"},e?"hide":"show")}function De(s,t,e={}){const n=s.el.tagName.toLowerCase();if(!es.has(n)){console.warn(`${E.BINDING} ${R.INVALID_INPUT_ELEMENT(n)}`);return}const{fx:i,cleanup:o}=Ps(s.$el,t,e);C.trackEffect(s.el,i),s.trackCleanup(o)}function Ae(s,t){const e=s.el,n=s.$el,i=()=>{const r=e.checked;t.value!==r&&(t.value=r)};i[j]=!0,n.on("change",i),s.trackCleanup(()=>n.off("change",i));const o=G(()=>{const r=!!t.value;F(()=>{e.checked!==r&&(e.checked=r,f.domUpdated(n,"checked",r))})});C.trackEffect(e,o)}function Fs(s,t){const e=s.$el;e.on(t),s.trackCleanup(()=>e.off(t))}function Bs(s,t,e){const n=s.$el;n.on(t,e),s.trackCleanup(()=>n.off(t,e))}function Le(s){C.cleanupTree(s)}c.fn.atomText=function(s,t){for(let e=0,n=this.length;e<n;e++)Se(U(this[e]),s,t);return this},c.fn.atomHtml=function(s){for(let t=0,e=this.length;t<e;t++)Te(U(this[t]),s);return this},c.fn.atomClass=function(s,t){if(typeof s=="string"&&t===void 0)return console.warn(`${E.BINDING} ${R.MISSING_CONDITION("atomClass")}`),this;const e=typeof s=="string"?{[s]:t}:s;for(let n=0,i=this.length;n<i;n++)Re(U(this[n]),e);return this},c.fn.atomCss=function(s,t,e){if(typeof s=="string"&&t===void 0)return console.warn(`${E.BINDING} ${R.MISSING_SOURCE("atomCss")}`),this;const n=typeof s=="string"?{[s]:e?[t,e]:t}:s;for(let i=0,o=this.length;i<o;i++)Ne(U(this[i]),n);return this},c.fn.atomAttr=function(s,t){if(typeof s=="string"&&t===void 0)return console.warn(`${E.BINDING} ${R.MISSING_SOURCE("atomAttr")}`),this;const e=typeof s=="string"?{[s]:t}:s;for(let n=0,i=this.length;n<i;n++)Oe(U(this[n]),e);return this},c.fn.atomProp=function(s,t){if(typeof s=="string"&&t===void 0)return console.warn(`${E.BINDING} ${R.MISSING_SOURCE("atomProp")}`),this;const e=typeof s=="string"?{[s]:t}:s;for(let n=0,i=this.length;n<i;n++)ve(U(this[n]),e);return this},c.fn.atomShow=function(s){for(let t=0,e=this.length;t<e;t++)Ct(U(this[t]),s,!1);return this},c.fn.atomHide=function(s){for(let t=0,e=this.length;t<e;t++)Ct(U(this[t]),s,!0);return this},c.fn.atomVal=function(s,t={}){for(let e=0,n=this.length;e<n;e++)De(U(this[e]),s,t);return this},c.fn.atomChecked=function(s){for(let t=0,e=this.length;t<e;t++)Ae(U(this[t]),s);return this},c.fn.atomOn=function(s,t){for(let e=0,n=this.length;e<n;e++)Bs(U(this[e]),s,t);return this},c.fn.atomBind=function(s){const{text:t,html:e,class:n,css:i,attr:o,prop:r,show:a,hide:p,val:d,checked:m,on:O}=s;let g,v;d!==void 0&&(Array.isArray(d)?(g=d[0],v=d[1]):g=d);for(let $=0,S=this.length;$<S;$++){const I=U(this[$]);t!==void 0&&Se(I,t),e!==void 0&&Te(I,e),n!==void 0&&Re(I,n),i!==void 0&&Ne(I,i),o!==void 0&&Oe(I,o),r!==void 0&&ve(I,r),a!==void 0&&Ct(I,a,!1),p!==void 0&&Ct(I,p,!0),d!==void 0&&De(I,g,v),m!==void 0&&Ae(I,m),O!==void 0&&Fs(I,O)}return this},c.fn.atomUnbind=function(){for(let s=0,t=this.length;s<t;s++)Le(this[s]);return this};function Hs(s,t,e){t?.isConnected?s.insertBefore(t):s.appendTo(e)}c.fn.atomList=function(s,t){const{key:e,render:n,bind:i,update:o,onAdd:r,onRemove:a,empty:p}=t,d=typeof e=="function"?e:(m,O)=>m[e];for(let m=0,O=this.length;m<O;m++){const g=this[m],v=c(g),$=Ft(g),S=new Map,I=new Set;let N=[],st=null;const qs=(w,D)=>{const Y=()=>{zt?.isDisposed||(D.$el.remove(),I.delete(w),f.log("list",`${$} removed item:`,w))};if(!a){Y();return}const z=a(D.$el);z instanceof Promise?z.then(Y,Y):Y()},we=(w,D)=>{S.delete(w),I.add(w),qs(w,D)};let zt;zt=G(()=>{const w=s.value,D=w.length;F(()=>{if(st&&D>0&&(st.remove(),st=null),D===0){if(p&&!st){const l=typeof p=="string"?Bt(p):p;st=c(l).appendTo(v)}for(let l=0;l<N.length;l++){const h=N[l],_=S.get(h);_&&we(h,_)}N.length=0;return}f.log("list",`${$} updating with ${D} items`);const Y=new Map;for(let l=0;l<N.length;l++)Y.set(N[l],l);const z=new Array(D),Vt=new Set,bt=new Int32Array(D),St=[],qt=[],Qt=[];for(let l=0;l<D;l++){const h=w[l],_=d(h,l);if(z[l]=_,Vt.has(_)){f.warn(E.LIST,R.DUPLICATE_KEY(_,l)),bt[l]=-1;continue}Vt.add(_);const T=S.get(_);if(T){const u=T.item;!o&&u!==h&&!Is(u,h)&&(St.push(_),qt.push(h),Qt.push(l)),bt[l]=I.has(_)?-1:Y.get(_)??-1}else St.push(_),qt.push(h),Qt.push(l),bt[l]=-1}const Tt=St.length,ke=new Array(Tt),Xt=[];for(let l=0;l<Tt;l++){const h=n(qt[l],Qt[l]);ke[l]=h,typeof h=="string"&&Xt.push(h)}let Rt=null;if(Xt.length>0){const l=`<!--sep-${Math.random().toString(36).substring(2)}-${Date.now().toString(36)}-->`;Rt=Bt(Xt.join(l)).split(l)}let Pe=0;for(let l=0;l<Tt;l++){const h=ke[l],_=c(typeof h=="string"?Rt[Pe++]:h),T=St[l],u=S.get(T);if(u){const k=u.$el[0];k&&C.cleanupTree(k),u.$el.replaceWith(_),u.$el=_,u.state="replaced"}else S.set(T,{$el:_,item:null,state:"new"})}for(let l=0;l<N.length;l++){const h=N[l];if(!Vt.has(h)){const _=S.get(h);_&&we(h,_)}}const xe=ys(bt);let $t=xe.length-1,Me=null;const Yt=N.length===0;if(Yt&&Rt!==null&&Pe===Tt&&!i&&!r&&!a&&I.size===0){g.innerHTML=Rt.join("");let l=0;for(let h=0;h<D;h++){const _=z[h],T=w[h],u=S.get(_);if(!u)continue;const k=g.children[l++];k&&(u.$el=c(k),u.item=T,u.state=void 0,I.delete(_),f.domUpdated(u.$el,"list.add",T))}}else{const l=Yt?document.createDocumentFragment():null;if(Yt&&l){for(let h=D-1;h>=0;h--){const _=z[h],T=w[h],u=S.get(_);if(!u)continue;const k=u.state;u.item=T,u.state=void 0,u.$el[0]&&(k===void 0?o&&o(u.$el,T,h):i&&i(u.$el,T,h));for(let Kt=u.$el.length-1;Kt>=0;Kt--)l.insertBefore(u.$el[Kt],l.firstChild);k==="new"&&(r&&r(u.$el),I.delete(_),f.domUpdated(u.$el,"list.add",T))}g.appendChild(l)}else for(let h=D-1;h>=0;h--){const _=z[h],T=w[h],u=S.get(_);if(!u)continue;const k=u.state;u.item=T,u.state=void 0,u.$el[0]&&(k===void 0?o&&o(u.$el,T,h):i&&i(u.$el,T,h)),$t>=0&&xe[$t]===h?$t--:Hs(u.$el,Me,v),Me=u.$el[0]??null,k==="new"&&(r&&r(u.$el),I.delete(_),f.domUpdated(u.$el,"list.add",T))}}N=z})}),C.trackEffect(g,zt),C.trackCleanup(g,()=>{S.clear(),I.clear(),N.length=0,st?.remove()})}return this};const Gs=Object.freeze({});c.fn.atomMount=function(s,t){const e=t??Gs;for(let n=0,i=this.length;n<i;n++){const o=this[n];if(!o)continue;C.cleanupTree(o);const r=c(o);let a;try{a=F(()=>s(r,e))}catch(p){f.error(E.MOUNT,R.MOUNT_ERROR(),p);continue}typeof a=="function"&&C.setComponentCleanup(o,a)}return this},c.fn.atomUnmount=function(){for(let s=0,t=this.length;s<t;s++){const e=this[s];e&&Le(e)}return this};function Ue(s,t){try{return history.pushState(s,"",t),!0}catch(e){return f.warn(E.ROUTE,"PushState failed (likely file:// protocol or security restriction). UI will update, but URL will not.",e),!1}}class js{constructor(t){this.isDestroyed=!1,this.previousRoute="",this.cleanups=[],this.templateCache=new Map,this.config={...t,mode:t.mode??mt.mode,basePath:t.basePath??mt.basePath,autoBindLinks:t.autoBindLinks??mt.autoBindLinks,activeClass:t.activeClass??mt.activeClass},this.isHistoryMode=this.config.mode==="history",this.$target=c(this.config.target),this.normalizedBasePath=this.config.basePath?.replace(/\/$/,"")||"",this.previousUrl=this.isHistoryMode?window.location.pathname+window.location.search:window.location.hash,this.currentRouteAtom=dt(this.getRouteName()),this.currentRoute=this.currentRouteAtom,this.queryParamsAtom=dt(this.getQueryParams()),this.queryParams=rt(()=>this.queryParamsAtom.value),this.handleUrlChange=this.handleUrlChange.bind(this),this.destroy=this.destroy.bind(this),this.init()}init(){const t=this.isHistoryMode?"popstate":"hashchange";window.addEventListener(t,this.handleUrlChange),this.cleanups.push(()=>window.removeEventListener(t,this.handleUrlChange));const e=G(()=>{const n=this.currentRouteAtom.value;F(()=>this.renderRoute(n))});this.cleanups.push(()=>e.dispose()),this.setupAutoBindLinks(),this.$target[0]&&C.trackCleanup(this.$target[0],this.destroy)}getRouteName(){const{default:t}=this.config;if(this.isHistoryMode){let o=window.location.pathname;return this.normalizedBasePath&&o.startsWith(this.normalizedBasePath)&&(o=o.substring(this.normalizedBasePath.length)),o.charCodeAt(0)===47&&(o=o.slice(1)),o||t}const e=window.location.hash,n=e.indexOf("?");return(n===-1?e.substring(1):e.substring(1,n))||t}getQueryParams(){let t;if(this.isHistoryMode){if(t=window.location.search.substring(1),!t)return{}}else{const i=window.location.hash,o=i.indexOf("?");if(o===-1)return{};t=i.substring(o+1)}const e=new URLSearchParams(t),n=Object.fromEntries(e);if(t.includes("%"))try{decodeURIComponent(t)}catch{f.warn(E.ROUTE,R.MALFORMED_URI(t))}return n}setUrl(t){if(this.isHistoryMode){const e=`${this.normalizedBasePath}/${t}`;Ue(null,e),this.previousUrl=e}else{const e=`#${t}`;window.location.hash=e,this.previousUrl=e}}restoreUrl(){this.isHistoryMode?Ue(null,this.previousUrl):window.location.hash=this.previousUrl}getCurrentUrl(){return this.isHistoryMode?window.location.pathname+window.location.search:window.location.hash}getRouteConfig(t){const{routes:e,notFound:n}=this.config;let i=e[t];return!i&&n&&(i=e[n]),i||(f.warn(E.ROUTE,R.ROUTE_NOT_FOUND(t)),null)}renderTemplate(t){let e=this.templateCache.get(t);if(!e){const i=document.querySelector(t);if(!i||!(i instanceof HTMLTemplateElement))return f.warn(E.ROUTE,R.TEMPLATE_NOT_FOUND(t)),!1;e=i,this.templateCache.set(t,e)}const n=e.content.cloneNode(!0);return this.$target.append(n),!0}renderRoute(t){if(this.isDestroyed)return;const e=this.$target[0];if(!e){f.warn(E.ROUTE,R.TARGET_NOT_FOUND(this.config.target));return}const n=this.getRouteConfig(t);if(!n)return;const i=this.getQueryParams(),o=this.previousRoute;this.config.beforeTransition&&this.config.beforeTransition(o,t),this.$target.empty();let r=i;if(n.onEnter){const a=n.onEnter(i);a!==void 0&&(r={...i,...a})}n.render?n.render(e,t,r):n.template&&this.renderTemplate(n.template)&&n.onMount&&n.onMount(this.$target.children()),this.config.afterTransition&&this.config.afterTransition(o,t),this.previousRoute=t}handleUrlChange(){if(this.isDestroyed)return;const t=this.getCurrentUrl();if(t===this.previousUrl)return;const e=this.getRouteName(),n=this.currentRouteAtom.peek(),i=this.getQueryParams();if(n!==e){const o=this.config.routes[n];if(o?.onLeave&&o.onLeave()===!1){this.restoreUrl();return}this.currentRouteAtom.value=e,this.queryParamsAtom.value=i}else{this.queryParamsAtom.value=i;const o=this.config.routes[n];o?.onParamsChange?o.onParamsChange(i):this.renderRoute(e)}this.previousUrl=t}setupAutoBindLinks(){if(!this.config.autoBindLinks)return;const t=i=>{i.preventDefault();const o=i.currentTarget.dataset.route;o!=null&&this.navigate(o)};c(document).on("click","[data-route]",t),this.cleanups.push(()=>{c(document).off("click","[data-route]",t)});const{activeClass:e}=this.config,n=G(()=>{const i=this.currentRouteAtom.value;F(()=>{const o=document.querySelectorAll("[data-route]");for(let r=0,a=o.length;r<a;r++){const p=o[r],d=p.dataset.route,m=i===d;p.classList.toggle(e,m),m?p.setAttribute("aria-current","page"):p.removeAttribute("aria-current")}})});this.cleanups.push(()=>n.dispose())}navigate(t){if(this.isDestroyed)return;const e=this.currentRouteAtom.peek(),n=this.config.routes[e];if(n?.onLeave&&n.onLeave()===!1)return;const i=t||this.config.default;if(!i){f.warn(E.ROUTE,"navigate() called with empty routeName and no default configured.");return}this.setUrl(i),this.queryParamsAtom.value={},this.currentRouteAtom.value=i}destroy(){if(this.isDestroyed)return;this.isDestroyed=!0;const t=this.cleanups;for(let e=0,n=t.length;e<n;e++)try{t[e]()}catch(i){f.warn(E.ROUTE,"Cleanup error during destroy:",i)}this.cleanups.length=0,this.templateCache.clear()}}function zs(s){return new js(s)}c.extend({route:zs});const Vs=new Promise(()=>{});c.extend({atomFetch(s,t){const{defaultValue:e,transform:n,method:i,headers:o,ajaxOptions:r,onError:a,eager:p}=t,d=typeof s=="string",m=d?s:void 0,O=d?null:s,g=Object.assign({},r);i!==void 0&&(g.method=i),o!==void 0&&(g.headers=o),d&&(g.url=m);let v=null;return rt(async()=>{v?.abort(),v=new AbortController;const S=v.signal;d||(g.url=O());const I=c.ajax(g);S.onabort=()=>I.abort(),S.aborted&&I.abort();try{const N=await I;return n?n(N):N}catch(N){if(S.aborted)return Vs;try{a?.(N)}catch{}throw N}finally{S.onabort=null,v.signal===S&&(v=null)}},{defaultValue:e,lazy:!(p??!0)})}}),c(()=>{ye(),me(document.body)}),y.default=c,y.atom=dt,y.batch=xt,y.computed=rt,y.disableAutoCleanup=Ds,y.disablejQueryOverrides=Us,y.effect=G,y.enableAutoCleanup=me,y.enablejQueryOverrides=ye,y.isAtom=_t,y.isComputed=le,y.isReactive=Mt,y.nextTick=ge,y.registry=C,y.untracked=F,Object.defineProperties(y,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}));
2
3
  //# sourceMappingURL=atom-effect-jquery.min.js.map