zero-query 1.0.9 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -21
- package/README.md +2 -0
- package/cli/args.js +33 -33
- package/cli/commands/build-api.js +443 -0
- package/cli/commands/build.js +254 -216
- package/cli/commands/bundle.js +1228 -1183
- package/cli/commands/create.js +137 -121
- package/cli/commands/dev/devtools/index.js +56 -56
- package/cli/commands/dev/devtools/js/components.js +49 -49
- package/cli/commands/dev/devtools/js/core.js +423 -423
- package/cli/commands/dev/devtools/js/elements.js +421 -421
- package/cli/commands/dev/devtools/js/network.js +166 -166
- package/cli/commands/dev/devtools/js/performance.js +73 -73
- package/cli/commands/dev/devtools/js/router.js +105 -105
- package/cli/commands/dev/devtools/js/source.js +132 -132
- package/cli/commands/dev/devtools/js/stats.js +35 -35
- package/cli/commands/dev/devtools/js/tabs.js +79 -79
- package/cli/commands/dev/devtools/panel.html +95 -95
- package/cli/commands/dev/devtools/styles.css +244 -244
- package/cli/commands/dev/index.js +107 -107
- package/cli/commands/dev/logger.js +75 -75
- package/cli/commands/dev/overlay.js +858 -858
- package/cli/commands/dev/server.js +220 -167
- package/cli/commands/dev/validator.js +94 -94
- package/cli/commands/dev/watcher.js +172 -172
- package/cli/help.js +114 -112
- package/cli/index.js +52 -52
- package/cli/scaffold/default/LICENSE +21 -21
- package/cli/scaffold/default/app/app.js +207 -207
- package/cli/scaffold/default/app/components/about.js +201 -201
- package/cli/scaffold/default/app/components/api-demo.js +143 -143
- package/cli/scaffold/default/app/components/contact-card.js +231 -231
- package/cli/scaffold/default/app/components/contacts/contacts.css +706 -706
- package/cli/scaffold/default/app/components/contacts/contacts.html +200 -200
- package/cli/scaffold/default/app/components/contacts/contacts.js +196 -196
- package/cli/scaffold/default/app/components/counter.js +127 -127
- package/cli/scaffold/default/app/components/home.js +249 -249
- package/cli/scaffold/default/app/components/not-found.js +16 -16
- package/cli/scaffold/default/app/components/playground/playground.css +115 -115
- package/cli/scaffold/default/app/components/playground/playground.html +161 -161
- package/cli/scaffold/default/app/components/playground/playground.js +116 -116
- package/cli/scaffold/default/app/components/todos.js +225 -225
- package/cli/scaffold/default/app/components/toolkit/toolkit.css +97 -97
- package/cli/scaffold/default/app/components/toolkit/toolkit.html +146 -146
- package/cli/scaffold/default/app/components/toolkit/toolkit.js +280 -280
- package/cli/scaffold/default/app/routes.js +15 -15
- package/cli/scaffold/default/app/store.js +101 -101
- package/cli/scaffold/default/global.css +552 -552
- package/cli/scaffold/default/index.html +99 -99
- package/cli/scaffold/minimal/app/app.js +85 -85
- package/cli/scaffold/minimal/app/components/about.js +68 -68
- package/cli/scaffold/minimal/app/components/counter.js +122 -122
- package/cli/scaffold/minimal/app/components/home.js +68 -68
- package/cli/scaffold/minimal/app/components/not-found.js +16 -16
- package/cli/scaffold/minimal/app/routes.js +9 -9
- package/cli/scaffold/minimal/app/store.js +36 -36
- package/cli/scaffold/minimal/global.css +300 -300
- package/cli/scaffold/minimal/index.html +44 -44
- package/cli/scaffold/ssr/app/app.js +41 -41
- package/cli/scaffold/ssr/app/components/about.js +55 -55
- package/cli/scaffold/ssr/app/components/blog/index.js +65 -65
- package/cli/scaffold/ssr/app/components/blog/post.js +86 -86
- package/cli/scaffold/ssr/app/components/home.js +37 -37
- package/cli/scaffold/ssr/app/components/not-found.js +15 -15
- package/cli/scaffold/ssr/app/routes.js +8 -8
- package/cli/scaffold/ssr/global.css +228 -228
- package/cli/scaffold/ssr/index.html +37 -37
- package/cli/scaffold/ssr/package.json +8 -8
- package/cli/scaffold/ssr/server/data/posts.js +144 -144
- package/cli/scaffold/ssr/server/index.js +213 -213
- package/cli/scaffold/webrtc/app/app.js +11 -0
- package/cli/scaffold/webrtc/app/components/video-room.js +295 -0
- package/cli/scaffold/webrtc/app/lib/room.js +252 -0
- package/cli/scaffold/webrtc/assets/.gitkeep +0 -0
- package/cli/scaffold/webrtc/global.css +250 -0
- package/cli/scaffold/webrtc/index.html +21 -0
- package/cli/utils.js +305 -287
- package/dist/API.md +7264 -0
- package/dist/zquery.dist.zip +0 -0
- package/dist/zquery.js +10313 -6252
- package/dist/zquery.min.js +8 -601
- package/index.d.ts +570 -365
- package/index.js +311 -232
- package/package.json +76 -69
- package/src/component.js +1709 -1454
- package/src/core.js +921 -921
- package/src/diff.js +497 -497
- package/src/errors.js +209 -209
- package/src/expression.js +922 -922
- package/src/http.js +242 -242
- package/src/package.json +1 -1
- package/src/reactive.js +255 -254
- package/src/router.js +843 -773
- package/src/ssr.js +418 -418
- package/src/store.js +318 -272
- package/src/utils.js +515 -515
- package/src/webrtc/e2ee.js +351 -0
- package/src/webrtc/errors.js +116 -0
- package/src/webrtc/ice.js +301 -0
- package/src/webrtc/index.js +131 -0
- package/src/webrtc/joinToken.js +119 -0
- package/src/webrtc/observe.js +172 -0
- package/src/webrtc/peer.js +351 -0
- package/src/webrtc/reactive.js +268 -0
- package/src/webrtc/room.js +625 -0
- package/src/webrtc/sdp.js +302 -0
- package/src/webrtc/sfu/index.js +43 -0
- package/src/webrtc/sfu/livekit.js +131 -0
- package/src/webrtc/sfu/mediasoup.js +150 -0
- package/src/webrtc/signaling.js +373 -0
- package/src/webrtc/turn.js +237 -0
- package/tests/_helpers/webrtcFakes.js +289 -0
- package/tests/audit.test.js +4158 -4158
- package/tests/cli.test.js +1136 -1023
- package/tests/compare.test.js +497 -0
- package/tests/component.test.js +3969 -3938
- package/tests/core.test.js +1910 -1910
- package/tests/dev-server.test.js +489 -0
- package/tests/diff.test.js +1416 -1416
- package/tests/docs.test.js +1664 -0
- package/tests/electron-features.test.js +864 -0
- package/tests/errors.test.js +619 -619
- package/tests/expression.test.js +1056 -1056
- package/tests/http.test.js +648 -648
- package/tests/reactive.test.js +819 -819
- package/tests/router.test.js +2327 -2327
- package/tests/ssr.test.js +870 -870
- package/tests/store.test.js +830 -830
- package/tests/test-minifier.js +153 -153
- package/tests/test-ssr.js +27 -27
- package/tests/utils.test.js +1377 -1377
- package/tests/webrtc/e2ee.test.js +283 -0
- package/tests/webrtc/ice.test.js +202 -0
- package/tests/webrtc/joinToken.test.js +89 -0
- package/tests/webrtc/observe.test.js +111 -0
- package/tests/webrtc/peer.test.js +373 -0
- package/tests/webrtc/reactive.test.js +235 -0
- package/tests/webrtc/room.test.js +406 -0
- package/tests/webrtc/sdp.test.js +151 -0
- package/tests/webrtc/sfu-livekit.test.js +119 -0
- package/tests/webrtc/sfu.test.js +160 -0
- package/tests/webrtc/signaling.test.js +251 -0
- package/tests/webrtc/turn.test.js +256 -0
- package/types/collection.d.ts +383 -383
- package/types/component.d.ts +186 -186
- package/types/errors.d.ts +135 -135
- package/types/http.d.ts +92 -92
- package/types/misc.d.ts +201 -201
- package/types/reactive.d.ts +98 -98
- package/types/router.d.ts +190 -190
- package/types/ssr.d.ts +102 -102
- package/types/store.d.ts +146 -145
- package/types/utils.d.ts +245 -245
- package/types/webrtc.d.ts +653 -0
package/dist/zquery.min.js
CHANGED
|
@@ -1,606 +1,13 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* zQuery (zeroQuery) v1.0
|
|
2
|
+
* zQuery (zeroQuery) v1.2.0
|
|
3
3
|
* Lightweight Frontend Library
|
|
4
4
|
* https://github.com/tonywied17/zero-query
|
|
5
5
|
* (c) 2026 Anthony Wiedman - MIT License
|
|
6
6
|
*/
|
|
7
|
-
(function(
|
|
8
|
-
|
|
9
|
-
if(typeof handler!=='function')return()=>{};_errorHandlers.push(handler);return()=>{const idx=_errorHandlers.indexOf(handler);if(idx!==-1)_errorHandlers.splice(idx,1);};}
|
|
10
|
-
|
|
11
|
-
console.error(`[zQuery ${code}] ${message}`,context,cause||'');}
|
|
12
|
-
|
|
13
|
-
function validate(value,name,expectedType){if(value===undefined||value===null){throw new ZQueryError(ErrorCode.INVALID_ARGUMENT,`"${name}" is required but got ${value}`);}
|
|
14
|
-
if(expectedType&&typeof value!==expectedType){throw new ZQueryError(ErrorCode.INVALID_ARGUMENT,`"${name}" must be a ${expectedType}, got ${typeof value}`);}}
|
|
15
|
-
function formatError(err){const isZQ=err instanceof ZQueryError;return{code:isZQ?err.code:'',type:isZQ?'ZQueryError':(err.name||'Error'),message:err.message||'Unknown error',context:isZQ?err.context:{},stack:err.stack||'',cause:err.cause?formatError(err.cause):null,};}
|
|
16
|
-
function guardAsync(fn,code,context={}){return async(...args)=>{try{return await fn(...args);}catch(err){reportError(code,err.message||'Async callback error',context,err);}};}
|
|
17
|
-
function reactive(target,onChange,_path=''){if(typeof target!=='object'||target===null)return target;if(typeof onChange!=='function'){reportError(ErrorCode.REACTIVE_CALLBACK,'reactive() onChange must be a function',{received:typeof onChange});onChange=()=>{};}
|
|
18
|
-
const proxyCache=new WeakMap();const handler={get(obj,key){if(key==='__isReactive')return true;if(key==='__raw')return obj;const value=obj[key];if(typeof value==='object'&&value!==null){if(proxyCache.has(value))return proxyCache.get(value);const childProxy=new Proxy(value,handler);proxyCache.set(value,childProxy);return childProxy;}
|
|
19
|
-
return value;},set(obj,key,value){const old=obj[key];if(old===value)return true;obj[key]=value;if(old&&typeof old==='object')proxyCache.delete(old);try{onChange(key,value,old);}catch(err){reportError(ErrorCode.REACTIVE_CALLBACK,`Reactive onChange threw for key "${String(key)}"`,{key,value,old},err);}
|
|
20
|
-
return true;},deleteProperty(obj,key){const old=obj[key];delete obj[key];if(old&&typeof old==='object')proxyCache.delete(old);try{onChange(key,undefined,old);}catch(err){reportError(ErrorCode.REACTIVE_CALLBACK,`Reactive onChange threw for key "${String(key)}"`,{key,old},err);}
|
|
21
|
-
return true;}};return new Proxy(target,handler);}
|
|
22
|
-
class Signal{constructor(value){this._value=value;this._subscribers=new Set();}
|
|
23
|
-
get value(){if(Signal._activeEffect){this._subscribers.add(Signal._activeEffect);if(Signal._activeEffect._deps){Signal._activeEffect._deps.add(this);}}
|
|
24
|
-
return this._value;}
|
|
25
|
-
set value(newVal){if(this._value===newVal)return;this._value=newVal;this._notify();}
|
|
26
|
-
peek(){return this._value;}
|
|
27
|
-
_notify(){if(Signal._batching){Signal._batchQueue.add(this);return;}
|
|
28
|
-
const subs=[...this._subscribers];for(let i=0;i<subs.length;i++){try{subs[i]();}
|
|
29
|
-
catch(err){reportError(ErrorCode.SIGNAL_CALLBACK,'Signal subscriber threw',{signal:this},err);}}}
|
|
30
|
-
subscribe(fn){this._subscribers.add(fn);return()=>this._subscribers.delete(fn);}
|
|
31
|
-
toString(){return String(this._value);}}
|
|
32
|
-
Signal._activeEffect=null;Signal._batching=false;Signal._batchQueue=new Set();function signal(initial){return new Signal(initial);}
|
|
33
|
-
function computed(fn){const s=new Signal(undefined);effect(()=>{const v=fn();if(v!==s._value){s._value=v;s._notify();}});return s;}
|
|
34
|
-
function effect(fn){const execute=()=>{if(execute._deps){for(const sig of execute._deps){sig._subscribers.delete(execute);}
|
|
35
|
-
execute._deps.clear();}
|
|
36
|
-
Signal._activeEffect=execute;try{fn();}
|
|
37
|
-
catch(err){reportError(ErrorCode.EFFECT_EXEC,'Effect function threw',{},err);}
|
|
38
|
-
finally{Signal._activeEffect=null;}};execute._deps=new Set();execute();return()=>{if(execute._deps){for(const sig of execute._deps){sig._subscribers.delete(execute);}
|
|
39
|
-
execute._deps.clear();}};}
|
|
40
|
-
function batch(fn){if(Signal._batching){fn();return;}
|
|
41
|
-
Signal._batching=true;Signal._batchQueue.clear();try{fn();}finally{Signal._batching=false;const subs=new Set();for(const sig of Signal._batchQueue){for(const sub of sig._subscribers){subs.add(sub);}}
|
|
42
|
-
Signal._batchQueue.clear();for(const sub of subs){try{sub();}
|
|
43
|
-
catch(err){reportError(ErrorCode.SIGNAL_CALLBACK,'Signal subscriber threw',{},err);}}}}
|
|
44
|
-
function untracked(fn){const prev=Signal._activeEffect;Signal._activeEffect=null;try{return fn();}finally{Signal._activeEffect=prev;}}
|
|
45
|
-
let _tpl=null;function _getTemplate(){if(!_tpl)_tpl=document.createElement('template');return _tpl;}
|
|
46
|
-
function morph(rootEl,newHTML){const start=typeof window!=='undefined'&&window.__zqMorphHook?performance.now():0;const tpl=_getTemplate();tpl.innerHTML=newHTML;const newRoot=tpl.content;const tempDiv=document.createElement('div');while(newRoot.firstChild)tempDiv.appendChild(newRoot.firstChild);_morphChildren(rootEl,tempDiv);if(start)window.__zqMorphHook(rootEl,performance.now()-start);}
|
|
47
|
-
function morphElement(oldEl,newHTML){const start=typeof window!=='undefined'&&window.__zqMorphHook?performance.now():0;const tpl=_getTemplate();tpl.innerHTML=newHTML;const newEl=tpl.content.firstElementChild;if(!newEl)return oldEl;if(oldEl.nodeName===newEl.nodeName){_morphAttributes(oldEl,newEl);_morphChildren(oldEl,newEl);if(start)window.__zqMorphHook(oldEl,performance.now()-start);return oldEl;}
|
|
48
|
-
const clone=newEl.cloneNode(true);oldEl.parentNode.replaceChild(clone,oldEl);if(start)window.__zqMorphHook(clone,performance.now()-start);return clone;}
|
|
49
|
-
const _morph=morph;const _morphElement=morphElement;function _morphChildren(oldParent,newParent){const oldCN=oldParent.childNodes;const newCN=newParent.childNodes;const oldLen=oldCN.length;const newLen=newCN.length;const oldChildren=new Array(oldLen);const newChildren=new Array(newLen);for(let i=0;i<oldLen;i++)oldChildren[i]=oldCN[i];for(let i=0;i<newLen;i++)newChildren[i]=newCN[i];let hasKeys=false;let oldKeyMap,newKeyMap;for(let i=0;i<oldLen;i++){if(_getKey(oldChildren[i])!=null){hasKeys=true;break;}}
|
|
50
|
-
if(!hasKeys){for(let i=0;i<newLen;i++){if(_getKey(newChildren[i])!=null){hasKeys=true;break;}}}
|
|
51
|
-
if(hasKeys){oldKeyMap=new Map();newKeyMap=new Map();for(let i=0;i<oldLen;i++){const key=_getKey(oldChildren[i]);if(key!=null)oldKeyMap.set(key,i);}
|
|
52
|
-
for(let i=0;i<newLen;i++){const key=_getKey(newChildren[i]);if(key!=null)newKeyMap.set(key,i);}
|
|
53
|
-
_morphChildrenKeyed(oldParent,oldChildren,newChildren,oldKeyMap,newKeyMap);}else{_morphChildrenUnkeyed(oldParent,oldChildren,newChildren);}}
|
|
54
|
-
function _morphChildrenUnkeyed(oldParent,oldChildren,newChildren){const oldLen=oldChildren.length;const newLen=newChildren.length;const minLen=oldLen<newLen?oldLen:newLen;for(let i=0;i<minLen;i++){_morphNode(oldParent,oldChildren[i],newChildren[i]);}
|
|
55
|
-
if(newLen>oldLen){for(let i=oldLen;i<newLen;i++){oldParent.appendChild(newChildren[i].cloneNode(true));}}
|
|
56
|
-
if(oldLen>newLen){for(let i=oldLen-1;i>=newLen;i--){oldParent.removeChild(oldChildren[i]);}}}
|
|
57
|
-
function _morphChildrenKeyed(oldParent,oldChildren,newChildren,oldKeyMap,newKeyMap){const consumed=new Set();const newLen=newChildren.length;const matched=new Array(newLen);for(let i=0;i<newLen;i++){const key=_getKey(newChildren[i]);if(key!=null&&oldKeyMap.has(key)){const oldIdx=oldKeyMap.get(key);matched[i]=oldChildren[oldIdx];consumed.add(oldIdx);}else{matched[i]=null;}}
|
|
58
|
-
for(let i=oldChildren.length-1;i>=0;i--){if(!consumed.has(i)){const key=_getKey(oldChildren[i]);if(key!=null&&!newKeyMap.has(key)){oldParent.removeChild(oldChildren[i]);}}}
|
|
59
|
-
const oldIndices=[];for(let i=0;i<newLen;i++){if(matched[i]){const key=_getKey(newChildren[i]);oldIndices.push(oldKeyMap.get(key));}else{oldIndices.push(-1);}}
|
|
60
|
-
const lisSet=_lis(oldIndices);let cursor=oldParent.firstChild;const unkeyedOld=[];for(let i=0;i<oldChildren.length;i++){if(!consumed.has(i)&&_getKey(oldChildren[i])==null){unkeyedOld.push(oldChildren[i]);}}
|
|
61
|
-
let unkeyedIdx=0;for(let i=0;i<newLen;i++){const newNode=newChildren[i];const newKey=_getKey(newNode);let oldNode=matched[i];if(!oldNode&&newKey==null){oldNode=unkeyedOld[unkeyedIdx++]||null;}
|
|
62
|
-
if(oldNode){if(!lisSet.has(i)){oldParent.insertBefore(oldNode,cursor);}
|
|
63
|
-
const nextSib=oldNode.nextSibling;_morphNode(oldParent,oldNode,newNode);cursor=nextSib;}else{const clone=newNode.cloneNode(true);if(cursor){oldParent.insertBefore(clone,cursor);}else{oldParent.appendChild(clone);}}}
|
|
64
|
-
while(unkeyedIdx<unkeyedOld.length){const leftover=unkeyedOld[unkeyedIdx++];if(leftover.parentNode===oldParent){oldParent.removeChild(leftover);}}
|
|
65
|
-
for(let i=0;i<oldChildren.length;i++){if(!consumed.has(i)){const node=oldChildren[i];if(node.parentNode===oldParent&&_getKey(node)!=null&&!newKeyMap.has(_getKey(node))){oldParent.removeChild(node);}}}}
|
|
66
|
-
function _lis(arr){const len=arr.length;const result=new Set();if(len===0)return result;const tails=[];const prev=new Array(len).fill(-1);const tailIndices=[];for(let i=0;i<len;i++){if(arr[i]===-1)continue;const val=arr[i];let lo=0,hi=tails.length;while(lo<hi){const mid=(lo+hi)>>1;if(tails[mid]<val)lo=mid+1;else hi=mid;}
|
|
67
|
-
tails[lo]=val;tailIndices[lo]=i;prev[i]=lo>0?tailIndices[lo-1]:-1;}
|
|
68
|
-
let k=tailIndices[tails.length-1];for(let i=tails.length-1;i>=0;i--){result.add(k);k=prev[k];}
|
|
69
|
-
return result;}
|
|
70
|
-
function _morphNode(parent,oldNode,newNode){if(oldNode.nodeType===3||oldNode.nodeType===8){if(newNode.nodeType===oldNode.nodeType){if(oldNode.nodeValue!==newNode.nodeValue){oldNode.nodeValue=newNode.nodeValue;}
|
|
71
|
-
return;}
|
|
72
|
-
parent.replaceChild(newNode.cloneNode(true),oldNode);return;}
|
|
73
|
-
if(oldNode.nodeType!==newNode.nodeType||oldNode.nodeName!==newNode.nodeName){parent.replaceChild(newNode.cloneNode(true),oldNode);return;}
|
|
74
|
-
if(oldNode.nodeType===1){if(oldNode.hasAttribute('z-skip'))return;if(oldNode.isEqualNode(newNode))return;_morphAttributes(oldNode,newNode);const tag=oldNode.nodeName;if(tag==='INPUT'){_syncInputValue(oldNode,newNode);return;}
|
|
75
|
-
if(tag==='TEXTAREA'){if(oldNode.value!==newNode.textContent){oldNode.value=newNode.textContent||'';}
|
|
76
|
-
return;}
|
|
77
|
-
if(tag==='SELECT'){_morphChildren(oldNode,newNode);if(oldNode.value!==newNode.value){oldNode.value=newNode.value;}
|
|
78
|
-
return;}
|
|
79
|
-
_morphChildren(oldNode,newNode);}}
|
|
80
|
-
function _morphAttributes(oldEl,newEl){const newAttrs=newEl.attributes;const oldAttrs=oldEl.attributes;const newLen=newAttrs.length;const oldLen=oldAttrs.length;if(newLen===oldLen){let same=true;for(let i=0;i<newLen;i++){const na=newAttrs[i];if(oldEl.getAttribute(na.name)!==na.value){same=false;break;}}
|
|
81
|
-
if(same){for(let i=0;i<oldLen;i++){if(!newEl.hasAttribute(oldAttrs[i].name)){same=false;break;}}}
|
|
82
|
-
if(same)return;}
|
|
83
|
-
const newNames=new Set();for(let i=0;i<newLen;i++){const attr=newAttrs[i];newNames.add(attr.name);if(oldEl.getAttribute(attr.name)!==attr.value){oldEl.setAttribute(attr.name,attr.value);}}
|
|
84
|
-
const oldNames=new Array(oldLen);for(let i=0;i<oldLen;i++)oldNames[i]=oldAttrs[i].name;for(let i=oldNames.length-1;i>=0;i--){if(!newNames.has(oldNames[i])){oldEl.removeAttribute(oldNames[i]);}}}
|
|
85
|
-
function _syncInputValue(oldEl,newEl){const type=(oldEl.type||'').toLowerCase();if(type==='checkbox'||type==='radio'){if(oldEl.checked!==newEl.checked)oldEl.checked=newEl.checked;}else{const newVal=newEl.getAttribute('value');if(newVal!==null&&oldEl.value!==newVal){oldEl.value=newVal;}}
|
|
86
|
-
if(oldEl.disabled!==newEl.disabled)oldEl.disabled=newEl.disabled;}
|
|
87
|
-
function _getKey(node){if(node.nodeType!==1)return null;const zk=node.getAttribute('z-key');if(zk)return zk;if(node.id)return'\0id:'+node.id;const ds=node.dataset;if(ds){if(ds.id)return'\0data-id:'+ds.id;if(ds.key)return'\0data-key:'+ds.key;}
|
|
88
|
-
return null;}
|
|
89
|
-
class ZQueryCollection{constructor(elements){this.elements=Array.isArray(elements)?elements:(elements?[elements]:[]);this.length=this.elements.length;this.elements.forEach((el,i)=>{this[i]=el;});}
|
|
90
|
-
each(fn){this.elements.forEach((el,i)=>fn.call(el,i,el));return this;}
|
|
91
|
-
map(fn){return this.elements.map((el,i)=>fn.call(el,i,el));}
|
|
92
|
-
forEach(fn){this.elements.forEach((el,i)=>fn(el,i,this.elements));return this;}
|
|
93
|
-
first(){return this.elements[0]||null;}
|
|
94
|
-
last(){return this.elements[this.length-1]||null;}
|
|
95
|
-
eq(i){return new ZQueryCollection(this.elements[i]?[this.elements[i]]:[]);}
|
|
96
|
-
toArray(){return[...this.elements];}[Symbol.iterator](){return this.elements[Symbol.iterator]();}
|
|
97
|
-
find(selector){const found=[];this.elements.forEach(el=>found.push(...el.querySelectorAll(selector)));return new ZQueryCollection(found);}
|
|
98
|
-
parent(){const parents=[...new Set(this.elements.map(el=>el.parentElement).filter(Boolean))];return new ZQueryCollection(parents);}
|
|
99
|
-
closest(selector){return new ZQueryCollection(this.elements.map(el=>el.closest(selector)).filter(Boolean));}
|
|
100
|
-
children(selector){const kids=[];this.elements.forEach(el=>{kids.push(...(selector?el.querySelectorAll(`:scope > ${selector}`):el.children));});return new ZQueryCollection([...kids]);}
|
|
101
|
-
siblings(selector){const sibs=[];this.elements.forEach(el=>{if(!el.parentElement)return;const all=[...el.parentElement.children].filter(c=>c!==el);sibs.push(...(selector?all.filter(c=>c.matches(selector)):all));});return new ZQueryCollection(sibs);}
|
|
102
|
-
next(selector){const els=this.elements.map(el=>el.nextElementSibling).filter(Boolean);return new ZQueryCollection(selector?els.filter(el=>el.matches(selector)):els);}
|
|
103
|
-
prev(selector){const els=this.elements.map(el=>el.previousElementSibling).filter(Boolean);return new ZQueryCollection(selector?els.filter(el=>el.matches(selector)):els);}
|
|
104
|
-
nextAll(selector){const result=[];this.elements.forEach(el=>{let sib=el.nextElementSibling;while(sib){if(!selector||sib.matches(selector))result.push(sib);sib=sib.nextElementSibling;}});return new ZQueryCollection(result);}
|
|
105
|
-
nextUntil(selector,filter){const result=[];this.elements.forEach(el=>{let sib=el.nextElementSibling;while(sib){if(selector&&sib.matches(selector))break;if(!filter||sib.matches(filter))result.push(sib);sib=sib.nextElementSibling;}});return new ZQueryCollection(result);}
|
|
106
|
-
prevAll(selector){const result=[];this.elements.forEach(el=>{let sib=el.previousElementSibling;while(sib){if(!selector||sib.matches(selector))result.push(sib);sib=sib.previousElementSibling;}});return new ZQueryCollection(result);}
|
|
107
|
-
prevUntil(selector,filter){const result=[];this.elements.forEach(el=>{let sib=el.previousElementSibling;while(sib){if(selector&&sib.matches(selector))break;if(!filter||sib.matches(filter))result.push(sib);sib=sib.previousElementSibling;}});return new ZQueryCollection(result);}
|
|
108
|
-
parents(selector){const result=[];this.elements.forEach(el=>{let parent=el.parentElement;while(parent){if(!selector||parent.matches(selector))result.push(parent);parent=parent.parentElement;}});return new ZQueryCollection([...new Set(result)]);}
|
|
109
|
-
parentsUntil(selector,filter){const result=[];this.elements.forEach(el=>{let parent=el.parentElement;while(parent){if(selector&&parent.matches(selector))break;if(!filter||parent.matches(filter))result.push(parent);parent=parent.parentElement;}});return new ZQueryCollection([...new Set(result)]);}
|
|
110
|
-
contents(){const result=[];this.elements.forEach(el=>result.push(...el.childNodes));return new ZQueryCollection(result);}
|
|
111
|
-
filter(selector){if(typeof selector==='function'){return new ZQueryCollection(this.elements.filter(selector));}
|
|
112
|
-
return new ZQueryCollection(this.elements.filter(el=>el.matches(selector)));}
|
|
113
|
-
not(selector){if(typeof selector==='function'){return new ZQueryCollection(this.elements.filter((el,i)=>!selector.call(el,i,el)));}
|
|
114
|
-
return new ZQueryCollection(this.elements.filter(el=>!el.matches(selector)));}
|
|
115
|
-
has(selector){return new ZQueryCollection(this.elements.filter(el=>el.querySelector(selector)));}
|
|
116
|
-
is(selector){if(typeof selector==='function'){return this.elements.some((el,i)=>selector.call(el,i,el));}
|
|
117
|
-
return this.elements.some(el=>el.matches(selector));}
|
|
118
|
-
slice(start,end){return new ZQueryCollection(this.elements.slice(start,end));}
|
|
119
|
-
add(selector,context){const toAdd=(selector instanceof ZQueryCollection)?selector.elements:(selector instanceof Node)?[selector]:Array.from((context||document).querySelectorAll(selector));return new ZQueryCollection([...this.elements,...toAdd]);}
|
|
120
|
-
get(index){if(index===undefined)return[...this.elements];return index<0?this.elements[this.length+index]:this.elements[index];}
|
|
121
|
-
index(selector){if(selector===undefined){const el=this.first();if(!el||!el.parentElement)return-1;return Array.from(el.parentElement.children).indexOf(el);}
|
|
122
|
-
const target=(typeof selector==='string')?document.querySelector(selector):selector;return this.elements.indexOf(target);}
|
|
123
|
-
addClass(...names){if(names.length===1&&names[0].indexOf(' ')===-1){const c=names[0];for(let i=0;i<this.elements.length;i++)this.elements[i].classList.add(c);return this;}
|
|
124
|
-
const classes=names.flatMap(n=>n.split(/\s+/));for(let i=0;i<this.elements.length;i++)this.elements[i].classList.add(...classes);return this;}
|
|
125
|
-
removeClass(...names){if(names.length===1&&names[0].indexOf(' ')===-1){const c=names[0];for(let i=0;i<this.elements.length;i++)this.elements[i].classList.remove(c);return this;}
|
|
126
|
-
const classes=names.flatMap(n=>n.split(/\s+/));for(let i=0;i<this.elements.length;i++)this.elements[i].classList.remove(...classes);return this;}
|
|
127
|
-
toggleClass(...args){const force=typeof args[args.length-1]==='boolean'?args.pop():undefined;if(args.length===1&&args[0].indexOf(' ')===-1){const c=args[0];for(let i=0;i<this.elements.length;i++){force!==undefined?this.elements[i].classList.toggle(c,force):this.elements[i].classList.toggle(c);}
|
|
128
|
-
return this;}
|
|
129
|
-
const classes=args.flatMap(n=>n.split(/\s+/));for(let i=0;i<this.elements.length;i++){const el=this.elements[i];for(let j=0;j<classes.length;j++){force!==undefined?el.classList.toggle(classes[j],force):el.classList.toggle(classes[j]);}}
|
|
130
|
-
return this;}
|
|
131
|
-
hasClass(name){return this.first()?.classList.contains(name)||false;}
|
|
132
|
-
attr(name,value){if(typeof name==='object'&&name!==null){return this.each((_,el)=>{for(const[k,v]of Object.entries(name))el.setAttribute(k,v);});}
|
|
133
|
-
if(value===undefined)return this.first()?.getAttribute(name);return this.each((_,el)=>el.setAttribute(name,value));}
|
|
134
|
-
removeAttr(name){return this.each((_,el)=>el.removeAttribute(name));}
|
|
135
|
-
prop(name,value){if(value===undefined)return this.first()?.[name];return this.each((_,el)=>{el[name]=value;});}
|
|
136
|
-
data(key,value){if(value===undefined){if(key===undefined)return this.first()?.dataset;const raw=this.first()?.dataset[key];try{return JSON.parse(raw);}catch{return raw;}}
|
|
137
|
-
return this.each((_,el)=>{el.dataset[key]=typeof value==='object'?JSON.stringify(value):value;});}
|
|
138
|
-
css(props,value){if(typeof props==='string'&&value!==undefined){return this.each((_,el)=>{el.style[props]=value;});}
|
|
139
|
-
if(typeof props==='string'){const el=this.first();return el?getComputedStyle(el)[props]:undefined;}
|
|
140
|
-
return this.each((_,el)=>Object.assign(el.style,props));}
|
|
141
|
-
width(){return this.first()?.getBoundingClientRect().width;}
|
|
142
|
-
height(){return this.first()?.getBoundingClientRect().height;}
|
|
143
|
-
offset(){const r=this.first()?.getBoundingClientRect();return r?{top:r.top+window.scrollY,left:r.left+window.scrollX,width:r.width,height:r.height}:null;}
|
|
144
|
-
position(){const el=this.first();return el?{top:el.offsetTop,left:el.offsetLeft}:null;}
|
|
145
|
-
scrollTop(value){if(value===undefined){const el=this.first();return el===window?window.scrollY:el?.scrollTop;}
|
|
146
|
-
return this.each((_,el)=>{if(el===window)window.scrollTo(window.scrollX,value);else el.scrollTop=value;});}
|
|
147
|
-
scrollLeft(value){if(value===undefined){const el=this.first();return el===window?window.scrollX:el?.scrollLeft;}
|
|
148
|
-
return this.each((_,el)=>{if(el===window)window.scrollTo(value,window.scrollY);else el.scrollLeft=value;});}
|
|
149
|
-
innerWidth(){const el=this.first();return el?.clientWidth;}
|
|
150
|
-
innerHeight(){const el=this.first();return el?.clientHeight;}
|
|
151
|
-
outerWidth(includeMargin=false){const el=this.first();if(!el)return undefined;let w=el.offsetWidth;if(includeMargin){const style=getComputedStyle(el);w+=parseFloat(style.marginLeft)+parseFloat(style.marginRight);}
|
|
152
|
-
return w;}
|
|
153
|
-
outerHeight(includeMargin=false){const el=this.first();if(!el)return undefined;let h=el.offsetHeight;if(includeMargin){const style=getComputedStyle(el);h+=parseFloat(style.marginTop)+parseFloat(style.marginBottom);}
|
|
154
|
-
return h;}
|
|
155
|
-
html(content){if(content===undefined)return this.first()?.innerHTML;return this.each((_,el)=>{if(el.childNodes.length>0){_morph(el,content);}else{el.innerHTML=content;}});}
|
|
156
|
-
morph(content){return this.each((_,el)=>{_morph(el,content);});}
|
|
157
|
-
text(content){if(content===undefined)return this.first()?.textContent;return this.each((_,el)=>{el.textContent=content;});}
|
|
158
|
-
val(value){if(value===undefined)return this.first()?.value;return this.each((_,el)=>{el.value=value;});}
|
|
159
|
-
append(content){return this.each((_,el)=>{if(typeof content==='string')el.insertAdjacentHTML('beforeend',content);else if(content instanceof ZQueryCollection)content.each((__,c)=>el.appendChild(c));else if(content instanceof Node)el.appendChild(content);});}
|
|
160
|
-
prepend(content){return this.each((_,el)=>{if(typeof content==='string')el.insertAdjacentHTML('afterbegin',content);else if(content instanceof Node)el.insertBefore(content,el.firstChild);});}
|
|
161
|
-
after(content){return this.each((_,el)=>{if(typeof content==='string')el.insertAdjacentHTML('afterend',content);else if(content instanceof Node)el.parentNode.insertBefore(content,el.nextSibling);});}
|
|
162
|
-
before(content){return this.each((_,el)=>{if(typeof content==='string')el.insertAdjacentHTML('beforebegin',content);else if(content instanceof Node)el.parentNode.insertBefore(content,el);});}
|
|
163
|
-
wrap(wrapper){return this.each((_,el)=>{const w=typeof wrapper==='string'?createFragment(wrapper).firstElementChild:wrapper.cloneNode(true);if(!w||!el.parentNode)return;el.parentNode.insertBefore(w,el);w.appendChild(el);});}
|
|
164
|
-
remove(){return this.each((_,el)=>el.remove());}
|
|
165
|
-
empty(){return this.each((_,el)=>{el.textContent='';});}
|
|
166
|
-
clone(deep=true){return new ZQueryCollection(this.elements.map(el=>el.cloneNode(deep)));}
|
|
167
|
-
replaceWith(content){return this.each((_,el)=>{if(typeof content==='string'){_morphElement(el,content);}else if(content instanceof Node){el.parentNode.replaceChild(content,el);}});}
|
|
168
|
-
appendTo(target){const dest=typeof target==='string'?document.querySelector(target):target instanceof ZQueryCollection?target.first():target;if(dest)this.each((_,el)=>dest.appendChild(el));return this;}
|
|
169
|
-
prependTo(target){const dest=typeof target==='string'?document.querySelector(target):target instanceof ZQueryCollection?target.first():target;if(dest)this.each((_,el)=>dest.insertBefore(el,dest.firstChild));return this;}
|
|
170
|
-
insertAfter(target){const ref=typeof target==='string'?document.querySelector(target):target instanceof ZQueryCollection?target.first():target;if(ref&&ref.parentNode)this.each((_,el)=>ref.parentNode.insertBefore(el,ref.nextSibling));return this;}
|
|
171
|
-
insertBefore(target){const ref=typeof target==='string'?document.querySelector(target):target instanceof ZQueryCollection?target.first():target;if(ref&&ref.parentNode)this.each((_,el)=>ref.parentNode.insertBefore(el,ref));return this;}
|
|
172
|
-
replaceAll(target){const targets=typeof target==='string'?Array.from(document.querySelectorAll(target)):target instanceof ZQueryCollection?target.elements:[target];targets.forEach((t,i)=>{const nodes=i===0?this.elements:this.elements.map(el=>el.cloneNode(true));nodes.forEach(el=>t.parentNode.insertBefore(el,t));t.remove();});return this;}
|
|
173
|
-
unwrap(selector){this.elements.forEach(el=>{const parent=el.parentElement;if(!parent||parent===document.body)return;if(selector&&!parent.matches(selector))return;parent.replaceWith(...parent.childNodes);});return this;}
|
|
174
|
-
wrapAll(wrapper){const w=typeof wrapper==='string'?createFragment(wrapper).firstElementChild:wrapper.cloneNode(true);const first=this.first();if(!first)return this;first.parentNode.insertBefore(w,first);this.each((_,el)=>w.appendChild(el));return this;}
|
|
175
|
-
wrapInner(wrapper){return this.each((_,el)=>{const w=typeof wrapper==='string'?createFragment(wrapper).firstElementChild:wrapper.cloneNode(true);while(el.firstChild)w.appendChild(el.firstChild);el.appendChild(w);});}
|
|
176
|
-
detach(){return this.each((_,el)=>el.remove());}
|
|
177
|
-
show(display=''){return this.each((_,el)=>{el.style.display=display;});}
|
|
178
|
-
hide(){return this.each((_,el)=>{el.style.display='none';});}
|
|
179
|
-
toggle(display=''){return this.each((_,el)=>{const hidden=el.style.display==='none'||(el.style.display!==''?false:getComputedStyle(el).display==='none');el.style.display=hidden?display:'none';});}
|
|
180
|
-
on(event,selectorOrHandler,handler){const events=event.split(/\s+/);return this.each((_,el)=>{events.forEach(evt=>{if(typeof selectorOrHandler==='function'){el.addEventListener(evt,selectorOrHandler);}else if(typeof selectorOrHandler==='string'){const wrapper=(e)=>{if(!e.target||typeof e.target.closest!=='function')return;const target=e.target.closest(selectorOrHandler);if(target&&el.contains(target))handler.call(target,e);};wrapper._zqOriginal=handler;wrapper._zqSelector=selectorOrHandler;el.addEventListener(evt,wrapper);if(!el._zqDelegated)el._zqDelegated=[];el._zqDelegated.push({evt,wrapper});}});});}
|
|
181
|
-
off(event,handler){const events=event.split(/\s+/);return this.each((_,el)=>{events.forEach(evt=>{el.removeEventListener(evt,handler);if(el._zqDelegated){el._zqDelegated=el._zqDelegated.filter(d=>{if(d.evt===evt&&d.wrapper._zqOriginal===handler){el.removeEventListener(evt,d.wrapper);return false;}
|
|
182
|
-
return true;});}});});}
|
|
183
|
-
one(event,handler){return this.each((_,el)=>{el.addEventListener(event,handler,{once:true});});}
|
|
184
|
-
trigger(event,detail){return this.each((_,el)=>{el.dispatchEvent(new CustomEvent(event,{detail,bubbles:true,cancelable:true}));});}
|
|
185
|
-
click(fn){return fn?this.on('click',fn):this.trigger('click');}
|
|
186
|
-
submit(fn){return fn?this.on('submit',fn):this.trigger('submit');}
|
|
187
|
-
focus(){this.first()?.focus();return this;}
|
|
188
|
-
blur(){this.first()?.blur();return this;}
|
|
189
|
-
hover(enterFn,leaveFn){this.on('mouseenter',enterFn);return this.on('mouseleave',leaveFn||enterFn);}
|
|
190
|
-
animate(props,duration=300,easing='ease'){if(this.length===0)return Promise.resolve(this);return new Promise(resolve=>{let resolved=false;const count={done:0};const listeners=[];this.each((_,el)=>{el.style.transition=`all ${duration}ms ${easing}`;requestAnimationFrame(()=>{Object.assign(el.style,props);const onEnd=()=>{el.removeEventListener('transitionend',onEnd);el.style.transition='';if(!resolved&&++count.done>=this.length){resolved=true;resolve(this);}};el.addEventListener('transitionend',onEnd);listeners.push({el,onEnd});});});setTimeout(()=>{if(!resolved){resolved=true;for(const{el,onEnd}of listeners){el.removeEventListener('transitionend',onEnd);el.style.transition='';}
|
|
191
|
-
resolve(this);}},duration+50);});}
|
|
192
|
-
fadeIn(duration=300){return this.css({opacity:'0',display:''}).animate({opacity:'1'},duration);}
|
|
193
|
-
fadeOut(duration=300){return this.animate({opacity:'0'},duration).then(col=>col.hide());}
|
|
194
|
-
fadeToggle(duration=300){return Promise.all(this.elements.map(el=>{const cs=getComputedStyle(el);const visible=cs.opacity!=='0'&&cs.display!=='none';const col=new ZQueryCollection([el]);return visible?col.fadeOut(duration):col.fadeIn(duration);})).then(()=>this);}
|
|
195
|
-
fadeTo(duration,opacity){return this.animate({opacity:String(opacity)},duration);}
|
|
196
|
-
slideDown(duration=300){return this.each((_,el)=>{el.style.display='';el.style.overflow='hidden';const h=el.scrollHeight+'px';el.style.maxHeight='0';el.style.transition=`max-height ${duration}ms ease`;requestAnimationFrame(()=>{el.style.maxHeight=h;});setTimeout(()=>{el.style.maxHeight='';el.style.overflow='';el.style.transition='';},duration);});}
|
|
197
|
-
slideUp(duration=300){return this.each((_,el)=>{el.style.overflow='hidden';el.style.maxHeight=el.scrollHeight+'px';el.style.transition=`max-height ${duration}ms ease`;requestAnimationFrame(()=>{el.style.maxHeight='0';});setTimeout(()=>{el.style.display='none';el.style.maxHeight='';el.style.overflow='';el.style.transition='';},duration);});}
|
|
198
|
-
slideToggle(duration=300){return this.each((_,el)=>{if(el.style.display==='none'||getComputedStyle(el).display==='none'){el.style.display='';el.style.overflow='hidden';const h=el.scrollHeight+'px';el.style.maxHeight='0';el.style.transition=`max-height ${duration}ms ease`;requestAnimationFrame(()=>{el.style.maxHeight=h;});setTimeout(()=>{el.style.maxHeight='';el.style.overflow='';el.style.transition='';},duration);}else{el.style.overflow='hidden';el.style.maxHeight=el.scrollHeight+'px';el.style.transition=`max-height ${duration}ms ease`;requestAnimationFrame(()=>{el.style.maxHeight='0';});setTimeout(()=>{el.style.display='none';el.style.maxHeight='';el.style.overflow='';el.style.transition='';},duration);}});}
|
|
199
|
-
serialize(){const form=this.first();if(!form||form.tagName!=='FORM')return'';return new URLSearchParams(new FormData(form)).toString();}
|
|
200
|
-
serializeObject(){const form=this.first();if(!form||form.tagName!=='FORM')return{};const obj={};new FormData(form).forEach((v,k)=>{if(obj[k]!==undefined){if(!Array.isArray(obj[k]))obj[k]=[obj[k]];obj[k].push(v);}else{obj[k]=v;}});return obj;}}
|
|
201
|
-
function createFragment(html){const tpl=document.createElement('template');tpl.innerHTML=html.trim();return tpl.content;}
|
|
202
|
-
function query(selector,context){if(!selector)return new ZQueryCollection([]);if(selector instanceof ZQueryCollection)return selector;if(selector instanceof Node||selector===window){return new ZQueryCollection([selector]);}
|
|
203
|
-
if(selector instanceof NodeList||selector instanceof HTMLCollection||Array.isArray(selector)){return new ZQueryCollection(Array.from(selector));}
|
|
204
|
-
if(typeof selector==='string'&&selector.trim().startsWith('<')){const fragment=createFragment(selector);return new ZQueryCollection([...fragment.childNodes].filter(n=>n.nodeType===1));}
|
|
205
|
-
if(typeof selector==='string'){const root=context?(typeof context==='string'?document.querySelector(context):context):document;return new ZQueryCollection([...root.querySelectorAll(selector)]);}
|
|
206
|
-
return new ZQueryCollection([]);}
|
|
207
|
-
function queryAll(selector,context){if(!selector)return new ZQueryCollection([]);if(selector instanceof ZQueryCollection)return selector;if(selector instanceof Node||selector===window){return new ZQueryCollection([selector]);}
|
|
208
|
-
if(selector instanceof NodeList||selector instanceof HTMLCollection||Array.isArray(selector)){return new ZQueryCollection(Array.from(selector));}
|
|
209
|
-
if(typeof selector==='string'&&selector.trim().startsWith('<')){const fragment=createFragment(selector);return new ZQueryCollection([...fragment.childNodes].filter(n=>n.nodeType===1));}
|
|
210
|
-
if(typeof selector==='string'){const root=context?(typeof context==='string'?document.querySelector(context):context):document;return new ZQueryCollection([...root.querySelectorAll(selector)]);}
|
|
211
|
-
return new ZQueryCollection([]);}
|
|
212
|
-
query.id=(id)=>document.getElementById(id);query.class=(name)=>document.querySelector(`.${name}`);query.classes=(name)=>new ZQueryCollection(Array.from(document.getElementsByClassName(name)));query.tag=(name)=>new ZQueryCollection(Array.from(document.getElementsByTagName(name)));Object.defineProperty(query,'name',{value:(name)=>new ZQueryCollection(Array.from(document.getElementsByName(name))),writable:true,configurable:true});query.children=(parentId)=>{const p=document.getElementById(parentId);return new ZQueryCollection(p?Array.from(p.children):[]);};query.qs=(sel,ctx=document)=>ctx.querySelector(sel);query.qsa=(sel,ctx=document)=>Array.from(ctx.querySelectorAll(sel));query.create=(tag,attrs={},...children)=>{const el=document.createElement(tag);for(const[k,v]of Object.entries(attrs)){if(k==='class')el.className=v;else if(k==='style'&&typeof v==='object')Object.assign(el.style,v);else if(k.startsWith('on')&&typeof v==='function')el.addEventListener(k.slice(2).toLowerCase(),v);else if(k==='data'&&typeof v==='object')Object.entries(v).forEach(([dk,dv])=>{el.dataset[dk]=dv;});else el.setAttribute(k,v);}
|
|
213
|
-
children.flat().forEach(child=>{if(typeof child==='string')el.appendChild(document.createTextNode(child));else if(child instanceof Node)el.appendChild(child);});return new ZQueryCollection(el);};query.ready=(fn)=>{if(document.readyState!=='loading')fn();else document.addEventListener('DOMContentLoaded',fn);};query.on=(event,selectorOrHandler,handler)=>{if(typeof selectorOrHandler==='function'){document.addEventListener(event,selectorOrHandler);return;}
|
|
214
|
-
if(typeof selectorOrHandler==='object'&&typeof selectorOrHandler.addEventListener==='function'){selectorOrHandler.addEventListener(event,handler);return;}
|
|
215
|
-
document.addEventListener(event,(e)=>{if(!e.target||typeof e.target.closest!=='function')return;const target=e.target.closest(selectorOrHandler);if(target)handler.call(target,e);});};query.off=(event,handler)=>{document.removeEventListener(event,handler);};query.fn=ZQueryCollection.prototype;const T={NUM:1,STR:2,IDENT:3,OP:4,PUNC:5,TMPL:6,EOF:7};const PREC={'??':2,'||':3,'&&':4,'==':8,'!=':8,'===':8,'!==':8,'<':9,'>':9,'<=':9,'>=':9,'instanceof':9,'in':9,'+':11,'-':11,'*':12,'/':12,'%':12,};const KEYWORDS=new Set(['true','false','null','undefined','typeof','instanceof','in','new','void']);function tokenize(expr){const tokens=[];let i=0;const len=expr.length;while(i<len){const ch=expr[i];if(ch===' '||ch==='\t'||ch==='\n'||ch==='\r'){i++;continue;}
|
|
216
|
-
if((ch>='0'&&ch<='9')||(ch==='.'&&i+1<len&&expr[i+1]>='0'&&expr[i+1]<='9')){let num='';if(ch==='0'&&i+1<len&&(expr[i+1]==='x'||expr[i+1]==='X')){num='0x';i+=2;while(i<len&&/[0-9a-fA-F]/.test(expr[i]))num+=expr[i++];}else{while(i<len&&((expr[i]>='0'&&expr[i]<='9')||expr[i]==='.'))num+=expr[i++];if(i<len&&(expr[i]==='e'||expr[i]==='E')){num+=expr[i++];if(i<len&&(expr[i]==='+'||expr[i]==='-'))num+=expr[i++];while(i<len&&expr[i]>='0'&&expr[i]<='9')num+=expr[i++];}}
|
|
217
|
-
tokens.push({t:T.NUM,v:Number(num)});continue;}
|
|
218
|
-
if(ch==="'"||ch==='"'){const quote=ch;let str='';i++;while(i<len&&expr[i]!==quote){if(expr[i]==='\\'&&i+1<len){const esc=expr[++i];if(esc==='n')str+='\n';else if(esc==='t')str+='\t';else if(esc==='r')str+='\r';else if(esc==='\\')str+='\\';else if(esc===quote)str+=quote;else str+=esc;}else{str+=expr[i];}
|
|
219
|
-
i++;}
|
|
220
|
-
i++;tokens.push({t:T.STR,v:str});continue;}
|
|
221
|
-
if(ch==='`'){const parts=[];let str='';i++;while(i<len&&expr[i]!=='`'){if(expr[i]==='$'&&i+1<len&&expr[i+1]==='{'){parts.push(str);str='';i+=2;let depth=1;let inner='';while(i<len&&depth>0){if(expr[i]==='{')depth++;else if(expr[i]==='}'){depth--;if(depth===0)break;}
|
|
222
|
-
inner+=expr[i++];}
|
|
223
|
-
i++;parts.push({expr:inner});}else{if(expr[i]==='\\'&&i+1<len){str+=expr[++i];}
|
|
224
|
-
else str+=expr[i];i++;}}
|
|
225
|
-
i++;parts.push(str);tokens.push({t:T.TMPL,v:parts});continue;}
|
|
226
|
-
if((ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z')||ch==='_'||ch==='$'){let ident='';while(i<len&&/[\w$]/.test(expr[i]))ident+=expr[i++];tokens.push({t:T.IDENT,v:ident});continue;}
|
|
227
|
-
const two=expr.slice(i,i+3);if(two==='==='||two==='!=='||two==='?.'){if(two==='?.'){tokens.push({t:T.OP,v:'?.'});i+=2;}else{tokens.push({t:T.OP,v:two});i+=3;}
|
|
228
|
-
continue;}
|
|
229
|
-
const pair=expr.slice(i,i+2);if(pair==='=='||pair==='!='||pair==='<='||pair==='>='||pair==='&&'||pair==='||'||pair==='??'||pair==='?.'||pair==='=>'){tokens.push({t:T.OP,v:pair});i+=2;continue;}
|
|
230
|
-
if('+-*/%'.includes(ch)){tokens.push({t:T.OP,v:ch});i++;continue;}
|
|
231
|
-
if('<>=!'.includes(ch)){tokens.push({t:T.OP,v:ch});i++;continue;}
|
|
232
|
-
if(ch==='.'&&i+2<len&&expr[i+1]==='.'&&expr[i+2]==='.'){tokens.push({t:T.OP,v:'...'});i+=3;continue;}
|
|
233
|
-
if('()[]{},.?:'.includes(ch)){tokens.push({t:T.PUNC,v:ch});i++;continue;}
|
|
234
|
-
i++;}
|
|
235
|
-
tokens.push({t:T.EOF,v:null});return tokens;}
|
|
236
|
-
class Parser{constructor(tokens,scope){this.tokens=tokens;this.pos=0;this.scope=scope;}
|
|
237
|
-
peek(){return this.tokens[this.pos];}
|
|
238
|
-
next(){return this.tokens[this.pos++];}
|
|
239
|
-
expect(type,val){const t=this.next();if(t.t!==type||(val!==undefined&&t.v!==val)){throw new Error(`Expected ${val || type} but got ${t.v}`);}
|
|
240
|
-
return t;}
|
|
241
|
-
match(type,val){const t=this.peek();if(t.t===type&&(val===undefined||t.v===val)){return this.next();}
|
|
242
|
-
return null;}
|
|
243
|
-
parse(){const result=this.parseExpression(0);return result;}
|
|
244
|
-
parseExpression(minPrec){let left=this.parseUnary();while(true){const tok=this.peek();if(tok.t===T.PUNC&&tok.v==='?'){if(this.tokens[this.pos+1]?.v!=='.'){if(1<=minPrec)break;this.next();const truthy=this.parseExpression(0);this.expect(T.PUNC,':');const falsy=this.parseExpression(0);left={type:'ternary',cond:left,truthy,falsy};continue;}}
|
|
245
|
-
if(tok.t===T.OP&&tok.v in PREC){const prec=PREC[tok.v];if(prec<=minPrec)break;this.next();const right=this.parseExpression(prec);left={type:'binary',op:tok.v,left,right};continue;}
|
|
246
|
-
if(tok.t===T.IDENT&&(tok.v==='instanceof'||tok.v==='in')&&PREC[tok.v]>minPrec){const prec=PREC[tok.v];this.next();const right=this.parseExpression(prec);left={type:'binary',op:tok.v,left,right};continue;}
|
|
247
|
-
break;}
|
|
248
|
-
return left;}
|
|
249
|
-
parseUnary(){const tok=this.peek();if(tok.t===T.IDENT&&tok.v==='typeof'){this.next();const arg=this.parseUnary();return{type:'typeof',arg};}
|
|
250
|
-
if(tok.t===T.IDENT&&tok.v==='void'){this.next();this.parseUnary();return{type:'literal',value:undefined};}
|
|
251
|
-
if(tok.t===T.OP&&tok.v==='!'){this.next();const arg=this.parseUnary();return{type:'not',arg};}
|
|
252
|
-
if(tok.t===T.OP&&(tok.v==='-'||tok.v==='+')){this.next();const arg=this.parseUnary();return{type:'unary',op:tok.v,arg};}
|
|
253
|
-
return this.parsePostfix();}
|
|
254
|
-
parsePostfix(){let left=this.parsePrimary();while(true){const tok=this.peek();if(tok.t===T.PUNC&&tok.v==='.'){this.next();const prop=this.next();left={type:'member',obj:left,prop:prop.v,computed:false};if(this.peek().t===T.PUNC&&this.peek().v==='('){left=this._parseCall(left);}
|
|
255
|
-
continue;}
|
|
256
|
-
if(tok.t===T.OP&&tok.v==='?.'){this.next();const next=this.peek();if(next.t===T.PUNC&&next.v==='['){this.next();const prop=this.parseExpression(0);this.expect(T.PUNC,']');left={type:'optional_member',obj:left,prop,computed:true};}else if(next.t===T.PUNC&&next.v==='('){left={type:'optional_call',callee:left,args:this._parseArgs()};}else{const prop=this.next();left={type:'optional_member',obj:left,prop:prop.v,computed:false};if(this.peek().t===T.PUNC&&this.peek().v==='('){left=this._parseCall(left);}}
|
|
257
|
-
continue;}
|
|
258
|
-
if(tok.t===T.PUNC&&tok.v==='['){this.next();const prop=this.parseExpression(0);this.expect(T.PUNC,']');left={type:'member',obj:left,prop,computed:true};if(this.peek().t===T.PUNC&&this.peek().v==='('){left=this._parseCall(left);}
|
|
259
|
-
continue;}
|
|
260
|
-
if(tok.t===T.PUNC&&tok.v==='('){left=this._parseCall(left);continue;}
|
|
261
|
-
break;}
|
|
262
|
-
return left;}
|
|
263
|
-
_parseCall(callee){const args=this._parseArgs();return{type:'call',callee,args};}
|
|
264
|
-
_parseArgs(){this.expect(T.PUNC,'(');const args=[];while(!(this.peek().t===T.PUNC&&this.peek().v===')')&&this.peek().t!==T.EOF){if(this.peek().t===T.OP&&this.peek().v==='...'){this.next();args.push({type:'spread',arg:this.parseExpression(0)});}else{args.push(this.parseExpression(0));}
|
|
265
|
-
if(this.peek().t===T.PUNC&&this.peek().v===',')this.next();}
|
|
266
|
-
this.expect(T.PUNC,')');return args;}
|
|
267
|
-
parsePrimary(){const tok=this.peek();if(tok.t===T.NUM){this.next();return{type:'literal',value:tok.v};}
|
|
268
|
-
if(tok.t===T.STR){this.next();return{type:'literal',value:tok.v};}
|
|
269
|
-
if(tok.t===T.TMPL){this.next();return{type:'template',parts:tok.v};}
|
|
270
|
-
if(tok.t===T.PUNC&&tok.v==='('){const savedPos=this.pos;this.next();const params=[];let couldBeArrow=true;if(this.peek().t===T.PUNC&&this.peek().v===')'){}else{while(couldBeArrow){const p=this.peek();if(p.t===T.IDENT&&!KEYWORDS.has(p.v)){params.push(this.next().v);if(this.peek().t===T.PUNC&&this.peek().v===','){this.next();}else{break;}}else{couldBeArrow=false;}}}
|
|
271
|
-
if(couldBeArrow&&this.peek().t===T.PUNC&&this.peek().v===')'){this.next();if(this.peek().t===T.OP&&this.peek().v==='=>'){this.next();const body=this.parseExpression(0);return{type:'arrow',params,body};}}
|
|
272
|
-
this.pos=savedPos;this.next();const expr=this.parseExpression(0);this.expect(T.PUNC,')');return expr;}
|
|
273
|
-
if(tok.t===T.PUNC&&tok.v==='['){this.next();const elements=[];while(!(this.peek().t===T.PUNC&&this.peek().v===']')&&this.peek().t!==T.EOF){if(this.peek().t===T.OP&&this.peek().v==='...'){this.next();elements.push({type:'spread',arg:this.parseExpression(0)});}else{elements.push(this.parseExpression(0));}
|
|
274
|
-
if(this.peek().t===T.PUNC&&this.peek().v===',')this.next();}
|
|
275
|
-
this.expect(T.PUNC,']');return{type:'array',elements};}
|
|
276
|
-
if(tok.t===T.PUNC&&tok.v==='{'){this.next();const properties=[];while(!(this.peek().t===T.PUNC&&this.peek().v==='}')&&this.peek().t!==T.EOF){if(this.peek().t===T.OP&&this.peek().v==='...'){this.next();properties.push({spread:true,value:this.parseExpression(0)});if(this.peek().t===T.PUNC&&this.peek().v===',')this.next();continue;}
|
|
277
|
-
const keyTok=this.next();let key;if(keyTok.t===T.IDENT||keyTok.t===T.STR)key=keyTok.v;else if(keyTok.t===T.NUM)key=String(keyTok.v);else throw new Error('Invalid object key: '+keyTok.v);if(this.peek().t===T.PUNC&&(this.peek().v===','||this.peek().v==='}')){properties.push({key,value:{type:'ident',name:key}});}else{this.expect(T.PUNC,':');properties.push({key,value:this.parseExpression(0)});}
|
|
278
|
-
if(this.peek().t===T.PUNC&&this.peek().v===',')this.next();}
|
|
279
|
-
this.expect(T.PUNC,'}');return{type:'object',properties};}
|
|
280
|
-
if(tok.t===T.IDENT){this.next();if(tok.v==='true')return{type:'literal',value:true};if(tok.v==='false')return{type:'literal',value:false};if(tok.v==='null')return{type:'literal',value:null};if(tok.v==='undefined')return{type:'literal',value:undefined};if(tok.v==='new'){let classExpr=this.parsePrimary();while(this.peek().t===T.PUNC&&this.peek().v==='.'){this.next();const prop=this.next();classExpr={type:'member',obj:classExpr,prop:prop.v,computed:false};}
|
|
281
|
-
let args=[];if(this.peek().t===T.PUNC&&this.peek().v==='('){args=this._parseArgs();}
|
|
282
|
-
return{type:'new',callee:classExpr,args};}
|
|
283
|
-
if(this.peek().t===T.OP&&this.peek().v==='=>'){this.next();const body=this.parseExpression(0);return{type:'arrow',params:[tok.v],body};}
|
|
284
|
-
return{type:'ident',name:tok.v};}
|
|
285
|
-
this.next();return{type:'literal',value:undefined};}}
|
|
286
|
-
const SAFE_ARRAY_METHODS=new Set(['length','map','filter','find','findIndex','some','every','reduce','reduceRight','forEach','includes','indexOf','lastIndexOf','join','slice','concat','flat','flatMap','reverse','sort','fill','keys','values','entries','at','toString',]);const SAFE_STRING_METHODS=new Set(['length','charAt','charCodeAt','includes','indexOf','lastIndexOf','slice','substring','trim','trimStart','trimEnd','toLowerCase','toUpperCase','split','replace','replaceAll','match','search','startsWith','endsWith','padStart','padEnd','repeat','at','toString','valueOf',]);const SAFE_NUMBER_METHODS=new Set(['toFixed','toPrecision','toString','valueOf',]);const SAFE_OBJECT_METHODS=new Set(['hasOwnProperty','toString','valueOf',]);const SAFE_MATH_PROPS=new Set(['PI','E','LN2','LN10','LOG2E','LOG10E','SQRT2','SQRT1_2','abs','ceil','floor','round','trunc','max','min','pow','sqrt','sign','random','log','log2','log10',]);const SAFE_JSON_PROPS=new Set(['parse','stringify']);function _isSafeAccess(obj,prop){const BLOCKED=new Set(['constructor','__proto__','prototype','__defineGetter__','__defineSetter__','__lookupGetter__','__lookupSetter__','call','apply','bind',]);if(typeof prop==='string'&&BLOCKED.has(prop))return false;if(obj!==null&&obj!==undefined&&(typeof obj==='object'||typeof obj==='function'))return true;if(typeof obj==='string')return SAFE_STRING_METHODS.has(prop);if(typeof obj==='number')return SAFE_NUMBER_METHODS.has(prop);return false;}
|
|
287
|
-
function evaluate(node,scope){if(!node)return undefined;switch(node.type){case'literal':return node.value;case'ident':{const name=node.name;for(const layer of scope){if(layer&&typeof layer==='object'&&name in layer){return layer[name];}}
|
|
288
|
-
if(name==='Math')return Math;if(name==='JSON')return JSON;if(name==='Date')return Date;if(name==='Array')return Array;if(name==='Object')return Object;if(name==='String')return String;if(name==='Number')return Number;if(name==='Boolean')return Boolean;if(name==='parseInt')return parseInt;if(name==='parseFloat')return parseFloat;if(name==='isNaN')return isNaN;if(name==='isFinite')return isFinite;if(name==='Infinity')return Infinity;if(name==='NaN')return NaN;if(name==='encodeURIComponent')return encodeURIComponent;if(name==='decodeURIComponent')return decodeURIComponent;if(name==='console')return console;if(name==='Map')return Map;if(name==='Set')return Set;if(name==='URL')return URL;if(name==='URLSearchParams')return URLSearchParams;return undefined;}
|
|
289
|
-
case'template':{let result='';for(const part of node.parts){if(typeof part==='string'){result+=part;}else if(part&&part.expr){result+=String(safeEval(part.expr,scope)??'');}}
|
|
290
|
-
return result;}
|
|
291
|
-
case'member':{const obj=evaluate(node.obj,scope);if(obj==null)return undefined;const prop=node.computed?evaluate(node.prop,scope):node.prop;if(!_isSafeAccess(obj,prop))return undefined;return obj[prop];}
|
|
292
|
-
case'optional_member':{const obj=evaluate(node.obj,scope);if(obj==null)return undefined;const prop=node.computed?evaluate(node.prop,scope):node.prop;if(!_isSafeAccess(obj,prop))return undefined;return obj[prop];}
|
|
293
|
-
case'call':{const result=_resolveCall(node,scope,false);return result;}
|
|
294
|
-
case'optional_call':{const calleeNode=node.callee;const args=_evalArgs(node.args,scope);if(calleeNode.type==='member'||calleeNode.type==='optional_member'){const obj=evaluate(calleeNode.obj,scope);if(obj==null)return undefined;const prop=calleeNode.computed?evaluate(calleeNode.prop,scope):calleeNode.prop;if(!_isSafeAccess(obj,prop))return undefined;const fn=obj[prop];if(typeof fn!=='function')return undefined;return fn.apply(obj,args);}
|
|
295
|
-
const callee=evaluate(calleeNode,scope);if(callee==null)return undefined;if(typeof callee!=='function')return undefined;return callee(...args);}
|
|
296
|
-
case'new':{const Ctor=evaluate(node.callee,scope);if(typeof Ctor!=='function')return undefined;if(Ctor===Date||Ctor===Array||Ctor===Map||Ctor===Set||Ctor===URL||Ctor===URLSearchParams){const args=_evalArgs(node.args,scope);return new Ctor(...args);}
|
|
297
|
-
return undefined;}
|
|
298
|
-
case'binary':return _evalBinary(node,scope);case'unary':{const val=evaluate(node.arg,scope);return node.op==='-'?-val:+val;}
|
|
299
|
-
case'not':return!evaluate(node.arg,scope);case'typeof':{try{return typeof evaluate(node.arg,scope);}catch{return'undefined';}}
|
|
300
|
-
case'ternary':{const cond=evaluate(node.cond,scope);return cond?evaluate(node.truthy,scope):evaluate(node.falsy,scope);}
|
|
301
|
-
case'array':{const arr=[];for(const e of node.elements){if(e.type==='spread'){const iterable=evaluate(e.arg,scope);if(iterable!=null&&typeof iterable[Symbol.iterator]==='function'){for(const v of iterable)arr.push(v);}}else{arr.push(evaluate(e,scope));}}
|
|
302
|
-
return arr;}
|
|
303
|
-
case'object':{const obj={};for(const prop of node.properties){if(prop.spread){const source=evaluate(prop.value,scope);if(source!=null&&typeof source==='object'){Object.assign(obj,source);}}else{obj[prop.key]=evaluate(prop.value,scope);}}
|
|
304
|
-
return obj;}
|
|
305
|
-
case'arrow':{const paramNames=node.params;const bodyNode=node.body;const closedScope=scope;return function(...args){const arrowScope={};paramNames.forEach((name,i)=>{arrowScope[name]=args[i];});return evaluate(bodyNode,[arrowScope,...closedScope]);};}
|
|
306
|
-
default:return undefined;}}
|
|
307
|
-
function _evalArgs(argNodes,scope){const result=[];for(const a of argNodes){if(a.type==='spread'){const iterable=evaluate(a.arg,scope);if(iterable!=null&&typeof iterable[Symbol.iterator]==='function'){for(const v of iterable)result.push(v);}}else{result.push(evaluate(a,scope));}}
|
|
308
|
-
return result;}
|
|
309
|
-
function _resolveCall(node,scope){const callee=node.callee;const args=_evalArgs(node.args,scope);if(callee.type==='member'||callee.type==='optional_member'){const obj=evaluate(callee.obj,scope);if(obj==null)return undefined;const prop=callee.computed?evaluate(callee.prop,scope):callee.prop;if(!_isSafeAccess(obj,prop))return undefined;const fn=obj[prop];if(typeof fn!=='function')return undefined;return fn.apply(obj,args);}
|
|
310
|
-
const fn=evaluate(callee,scope);if(typeof fn!=='function')return undefined;return fn(...args);}
|
|
311
|
-
function _evalBinary(node,scope){if(node.op==='&&'){const left=evaluate(node.left,scope);return left?evaluate(node.right,scope):left;}
|
|
312
|
-
if(node.op==='||'){const left=evaluate(node.left,scope);return left?left:evaluate(node.right,scope);}
|
|
313
|
-
if(node.op==='??'){const left=evaluate(node.left,scope);return left!=null?left:evaluate(node.right,scope);}
|
|
314
|
-
const left=evaluate(node.left,scope);const right=evaluate(node.right,scope);switch(node.op){case'+':return left+right;case'-':return left-right;case'*':return left*right;case'/':return left/right;case'%':return left%right;case'==':return left==right;case'!=':return left!=right;case'===':return left===right;case'!==':return left!==right;case'<':return left<right;case'>':return left>right;case'<=':return left<=right;case'>=':return left>=right;case'instanceof':return left instanceof right;case'in':return left in right;default:return undefined;}}
|
|
315
|
-
const _astCache=new Map();const _AST_CACHE_MAX=512;function safeEval(expr,scope){try{const trimmed=expr.trim();if(!trimmed)return undefined;if(/^[a-zA-Z_$][\w$]*$/.test(trimmed)){for(const layer of scope){if(layer&&typeof layer==='object'&&trimmed in layer){return layer[trimmed];}}}
|
|
316
|
-
let ast=_astCache.get(trimmed);if(ast){_astCache.delete(trimmed);_astCache.set(trimmed,ast);}else{const tokens=tokenize(trimmed);const parser=new Parser(tokens,scope);ast=parser.parse();if(_astCache.size>=_AST_CACHE_MAX){const first=_astCache.keys().next().value;_astCache.delete(first);}
|
|
317
|
-
_astCache.set(trimmed,ast);}
|
|
318
|
-
return evaluate(ast,scope);}catch(err){if(typeof console!=='undefined'&&console.debug){console.debug(`[zQuery EXPR_EVAL] Failed to evaluate: "${expr}"`,err.message);}
|
|
319
|
-
return undefined;}}
|
|
320
|
-
const _registry=new Map();const _instances=new Map();const _resourceCache=new Map();let _uid=0;if(typeof document!=='undefined'&&!document.querySelector('[data-zq-cloak]')){const _s=document.createElement('style');_s.textContent='[z-cloak]{display:none!important}*,*::before,*::after{-webkit-tap-highlight-color:transparent}';_s.setAttribute('data-zq-cloak','');document.head.appendChild(_s);}
|
|
321
|
-
const _debounceTimers=new WeakMap();const _throttleTimers=new WeakMap();function _fetchResource(url){if(_resourceCache.has(url))return _resourceCache.get(url);if(typeof window!=='undefined'&&window.__zqInline){for(const[path,content]of Object.entries(window.__zqInline)){if(url===path||url.endsWith('/'+path)||url.endsWith('\\'+path)){const resolved=Promise.resolve(content);_resourceCache.set(url,resolved);return resolved;}}}
|
|
322
|
-
let resolvedUrl=url;if(typeof url==='string'&&!url.startsWith('/')&&!url.includes(':')&&!url.startsWith('//')){try{const baseEl=document.querySelector('base');const root=baseEl?baseEl.href:(window.location.origin+'/');resolvedUrl=new URL(url,root).href;}catch{}}
|
|
323
|
-
const promise=fetch(resolvedUrl).then(res=>{if(!res.ok)throw new Error(`zQuery: Failed to load resource "${url}" (${res.status})`);return res.text();});_resourceCache.set(url,promise);return promise;}
|
|
324
|
-
function _resolveUrl(url,base){if(!base||!url||typeof url!=='string')return url;if(url.startsWith('/')||url.includes('://')||url.startsWith('//'))return url;try{if(base.includes('://')){return new URL(url,base).href;}
|
|
325
|
-
const baseEl=document.querySelector('base');const root=baseEl?baseEl.href:(window.location.origin+'/');const absBase=new URL(base.endsWith('/')?base:base+'/',root).href;return new URL(url,absBase).href;}catch{return url;}}
|
|
326
|
-
let _ownScriptUrl;try{if(typeof document!=='undefined'&&document.currentScript&&document.currentScript.src){_ownScriptUrl=document.currentScript.src.replace(/[?#].*$/,'');}}catch{}
|
|
327
|
-
function _detectCallerBase(){try{const stack=new Error().stack||'';const urls=stack.match(/(?:https?|file):\/\/[^\s\)]+/g)||[];for(const raw of urls){const url=raw.replace(/:\d+:\d+$/,'').replace(/:\d+$/,'');if(/zquery(\.min)?\.js$/i.test(url))continue;if(_ownScriptUrl&&url.replace(/[?#].*$/,'')===_ownScriptUrl)continue;return url.replace(/\/[^/]*$/,'/');}}catch{}
|
|
328
|
-
return undefined;}
|
|
329
|
-
function _getPath(obj,path){return path.split('.').reduce((o,k)=>o?.[k],obj);}
|
|
330
|
-
function _setPath(obj,path,value){const keys=path.split('.');const last=keys.pop();const target=keys.reduce((o,k)=>(o&&typeof o==='object')?o[k]:undefined,obj);if(target&&typeof target==='object')target[last]=value;}
|
|
331
|
-
class Component{constructor(el,definition,props={}){this._uid=++_uid;this._el=el;this._def=definition;this._mounted=false;this._destroyed=false;this._updateQueued=false;this._listeners=[];this._watchCleanups=[];this.refs={};this._slotContent={};const defaultSlotNodes=[];[...el.childNodes].forEach(node=>{if(node.nodeType===1&&node.hasAttribute('slot')){const slotName=node.getAttribute('slot')||'default';if(!this._slotContent[slotName])this._slotContent[slotName]='';this._slotContent[slotName]+=node.outerHTML;}else if(node.nodeType===1||(node.nodeType===3&&node.textContent.trim())){defaultSlotNodes.push(node.nodeType===1?node.outerHTML:node.textContent);}});if(defaultSlotNodes.length){this._slotContent['default']=defaultSlotNodes.join('');}
|
|
332
|
-
this.props=Object.freeze({...props});const initialState=typeof definition.state==='function'?definition.state():{...(definition.state||{})};this.state=reactive(initialState,(key,value,old)=>{if(!this._destroyed){this._runWatchers(key,value,old);this._scheduleUpdate();}});this.computed={};if(definition.computed){for(const[name,fn]of Object.entries(definition.computed)){Object.defineProperty(this.computed,name,{get:()=>fn.call(this,this.state.__raw||this.state),enumerable:true});}}
|
|
333
|
-
for(const[key,val]of Object.entries(definition)){if(typeof val==='function'&&!_reservedKeys.has(key)){this[key]=val.bind(this);}}
|
|
334
|
-
if(definition.init){try{definition.init.call(this);}
|
|
335
|
-
catch(err){reportError(ErrorCode.COMP_LIFECYCLE,`Component "${definition._name}" init() threw`,{component:definition._name},err);}}
|
|
336
|
-
if(definition.watch){this._prevWatchValues={};for(const key of Object.keys(definition.watch)){this._prevWatchValues[key]=_getPath(this.state.__raw||this.state,key);}}}
|
|
337
|
-
_runWatchers(changedKey,value,old){const watchers=this._def.watch;if(!watchers)return;for(const[key,handler]of Object.entries(watchers)){if(changedKey===key||key.startsWith(changedKey+'.')||changedKey.startsWith(key+'.')){const currentVal=_getPath(this.state.__raw||this.state,key);const prevVal=this._prevWatchValues?.[key];if(currentVal!==prevVal){const fn=typeof handler==='function'?handler:handler.handler;if(typeof fn==='function')fn.call(this,currentVal,prevVal);if(this._prevWatchValues)this._prevWatchValues[key]=currentVal;}}}}
|
|
338
|
-
_scheduleUpdate(){if(this._updateQueued)return;this._updateQueued=true;queueMicrotask(()=>{try{if(!this._destroyed)this._render();}finally{this._updateQueued=false;}});}
|
|
339
|
-
async _loadExternals(){const def=this._def;const base=def._base;if(def.templateUrl&&!def._templateLoaded){const tu=def.templateUrl;if(typeof tu==='string'){def._externalTemplate=await _fetchResource(_resolveUrl(tu,base));}else if(Array.isArray(tu)){const urls=tu.map(u=>_resolveUrl(u,base));const results=await Promise.all(urls.map(u=>_fetchResource(u)));def._externalTemplates={};results.forEach((html,i)=>{def._externalTemplates[i]=html;});}else if(typeof tu==='object'){const entries=Object.entries(tu);const results=await Promise.all(entries.map(([,url])=>_fetchResource(_resolveUrl(url,base))));def._externalTemplates={};entries.forEach(([key],i)=>{def._externalTemplates[key]=results[i];});}
|
|
340
|
-
def._templateLoaded=true;}
|
|
341
|
-
if(def.styleUrl&&!def._styleLoaded){const su=def.styleUrl;if(typeof su==='string'){const resolved=_resolveUrl(su,base);def._externalStyles=await _fetchResource(resolved);def._resolvedStyleUrls=[resolved];}else if(Array.isArray(su)){const urls=su.map(u=>_resolveUrl(u,base));const results=await Promise.all(urls.map(u=>_fetchResource(u)));def._externalStyles=results.join('\n');def._resolvedStyleUrls=urls;}
|
|
342
|
-
def._styleLoaded=true;}}
|
|
343
|
-
_render(){if((this._def.templateUrl&&!this._def._templateLoaded)||(this._def.styleUrl&&!this._def._styleLoaded)){this._loadExternals().then(()=>{if(!this._destroyed)this._render();});return;}
|
|
344
|
-
if(this._def._externalTemplates){this.templates=this._def._externalTemplates;}
|
|
345
|
-
let html;if(this._def.render){html=this._def.render.call(this);html=this._expandZFor(html);}else if(this._def._externalTemplate){html=this._expandZFor(this._def._externalTemplate);html=html.replace(/\{\{(.+?)\}\}/g,(_,expr)=>{try{const result=safeEval(expr.trim(),[this.state.__raw||this.state,{props:this.props,computed:this.computed,$:typeof window!=='undefined'?window.$:undefined}]);return result!=null?escapeHtml(String(result)):'';}catch{return'';}});}else{html='';}
|
|
346
|
-
html=this._expandContentDirectives(html);if(html.includes('<slot')){html=html.replace(/<slot(?:\s+name="([^"]*)")?\s*(?:\/>|>([\s\S]*?)<\/slot>)/g,(_,name,fallback)=>{const slotName=name||'default';return this._slotContent[slotName]||fallback||'';});}
|
|
347
|
-
const combinedStyles=[this._def.styles||'',this._def._externalStyles||''].filter(Boolean).join('\n');if(!this._mounted&&combinedStyles){const scopeAttr=`z-s${this._uid}`;this._el.setAttribute(scopeAttr,'');let noScopeDepth=0;let braceDepth=0;const scoped=combinedStyles.replace(/([^{}]+)\{|\}/g,(match,selector)=>{if(match==='}'){if(noScopeDepth>0&&braceDepth<=noScopeDepth)noScopeDepth=0;braceDepth--;return match;}
|
|
348
|
-
braceDepth++;const trimmed=selector.trim();if(trimmed.startsWith('@')){if(/^@(keyframes|font-face)\b/.test(trimmed)){noScopeDepth=braceDepth;}
|
|
349
|
-
return match;}
|
|
350
|
-
if(noScopeDepth>0&&braceDepth>noScopeDepth){return match;}
|
|
351
|
-
return selector.split(',').map(s=>`[${scopeAttr}] ${s.trim()}`).join(', ')+' {';});const styleEl=document.createElement('style');styleEl.textContent=scoped;styleEl.setAttribute('data-zq-component',this._def._name||'');styleEl.setAttribute('data-zq-scope',scopeAttr);if(this._def._resolvedStyleUrls){styleEl.setAttribute('data-zq-style-urls',this._def._resolvedStyleUrls.join(' '));if(this._def.styles){styleEl.setAttribute('data-zq-inline',this._def.styles);}}
|
|
352
|
-
document.head.appendChild(styleEl);this._styleEl=styleEl;}
|
|
353
|
-
let _focusInfo=null;const _active=document.activeElement;if(_active&&this._el.contains(_active)){const modelKey=_active.getAttribute?.('z-model');const refKey=_active.getAttribute?.('z-ref');let selector=null;if(modelKey){selector=`[z-model="${modelKey}"]`;}else if(refKey){selector=`[z-ref="${refKey}"]`;}else{const tag=_active.tagName.toLowerCase();if(tag==='input'||tag==='textarea'||tag==='select'){let s=tag;if(_active.type)s+=`[type="${_active.type}"]`;if(_active.name)s+=`[name="${_active.name}"]`;if(_active.placeholder)s+=`[placeholder="${CSS.escape(_active.placeholder)}"]`;selector=s;}}
|
|
354
|
-
if(selector){_focusInfo={selector,start:_active.selectionStart,end:_active.selectionEnd,dir:_active.selectionDirection,};}}
|
|
355
|
-
const _renderStart=typeof window!=='undefined'&&(window.__zqMorphHook||window.__zqRenderHook)?performance.now():0;if(!this._mounted){this._el.innerHTML=html;if(_renderStart&&window.__zqRenderHook)window.__zqRenderHook(this._el,performance.now()-_renderStart,'mount',this._def._name);}else{morph(this._el,html);}
|
|
356
|
-
this._processDirectives();this._bindEvents();this._bindRefs();this._bindModels();if(_focusInfo){const el=this._el.querySelector(_focusInfo.selector);if(el){if(el!==document.activeElement)el.focus();try{if(_focusInfo.start!==null&&_focusInfo.start!==undefined){el.setSelectionRange(_focusInfo.start,_focusInfo.end,_focusInfo.dir);}}catch(_){}}}
|
|
357
|
-
mountAll(this._el);if(!this._mounted){this._mounted=true;if(this._def.mounted){try{this._def.mounted.call(this);}
|
|
358
|
-
catch(err){reportError(ErrorCode.COMP_LIFECYCLE,`Component "${this._def._name}" mounted() threw`,{component:this._def._name},err);}}}else{if(this._def.updated){try{this._def.updated.call(this);}
|
|
359
|
-
catch(err){reportError(ErrorCode.COMP_LIFECYCLE,`Component "${this._def._name}" updated() threw`,{component:this._def._name},err);}}}}
|
|
360
|
-
_bindEvents(){const eventMap=new Map();const allEls=this._el.querySelectorAll('*');allEls.forEach(child=>{if(child.closest('[z-pre]'))return;const attrs=child.attributes;for(let a=0;a<attrs.length;a++){const attr=attrs[a];let raw;if(attr.name.charCodeAt(0)===64){raw=attr.name.slice(1);}else if(attr.name.startsWith('z-on:')){raw=attr.name.slice(5);}else{continue;}
|
|
361
|
-
const parts=raw.split('.');const event=parts[0];const modifiers=parts.slice(1);const methodExpr=attr.value;if(!child.dataset.zqEid){child.dataset.zqEid=String(++_uid);}
|
|
362
|
-
const selector=`[data-zq-eid="${child.dataset.zqEid}"]`;if(!eventMap.has(event))eventMap.set(event,[]);eventMap.get(event).push({selector,methodExpr,modifiers,el:child});}});this._eventBindings=eventMap;if(this._delegatedEvents){for(const event of eventMap.keys()){if(!this._delegatedEvents.has(event)){this._attachDelegatedEvent(event,eventMap.get(event));}}
|
|
363
|
-
for(const event of this._delegatedEvents.keys()){if(!eventMap.has(event)){const{handler,opts}=this._delegatedEvents.get(event);this._el.removeEventListener(event,handler,opts);this._delegatedEvents.delete(event);this._listeners=this._listeners.filter(l=>l.event!==event);}}
|
|
364
|
-
return;}
|
|
365
|
-
this._delegatedEvents=new Map();for(const[event,bindings]of eventMap){this._attachDelegatedEvent(event,bindings);}
|
|
366
|
-
this._outsideListeners=this._outsideListeners||[];for(const[event,bindings]of eventMap){for(const binding of bindings){if(!binding.modifiers.includes('outside'))continue;const outsideHandler=(e)=>{if(binding.el.contains(e.target))return;const match=binding.methodExpr.match(/^(\w+)(?:\(([^)]*)\))?$/);if(!match)return;const fn=this[match[1]];if(typeof fn==='function')fn.call(this,e);};document.addEventListener(event,outsideHandler,true);this._outsideListeners.push({event,handler:outsideHandler});}}}
|
|
367
|
-
_attachDelegatedEvent(event,bindings){const needsCapture=bindings.some(b=>b.modifiers.includes('capture'));const needsPassive=bindings.some(b=>b.modifiers.includes('passive'));const listenerOpts=(needsCapture||needsPassive)?{capture:needsCapture,passive:needsPassive}:false;const handler=(e)=>{const currentBindings=this._eventBindings?.get(event)||[];const hits=[];for(const binding of currentBindings){const matched=e.target.closest(binding.selector);if(!matched)continue;hits.push({...binding,matched});}
|
|
368
|
-
hits.sort((a,b)=>{if(a.matched===b.matched)return 0;return a.matched.contains(b.matched)?1:-1;});let stoppedAt=null;for(const{selector,methodExpr,modifiers,el,matched}of hits){if(stoppedAt){let blocked=false;for(const stopped of stoppedAt){if(matched.contains(stopped)&&matched!==stopped){blocked=true;break;}}
|
|
369
|
-
if(blocked)continue;}
|
|
370
|
-
if(modifiers.includes('self')&&e.target!==el)continue;if(modifiers.includes('outside')){if(el.contains(e.target))continue;}
|
|
371
|
-
const _keyMap={enter:'Enter',escape:'Escape',tab:'Tab',space:' ',delete:'Delete|Backspace',up:'ArrowUp',down:'ArrowDown',left:'ArrowLeft',right:'ArrowRight'};const _nonKeyMods=new Set(['prevent','stop','self','once','outside','capture','passive','debounce','throttle','ctrl','shift','alt','meta']);let keyFiltered=false;for(let mi=0;mi<modifiers.length;mi++){const mod=modifiers[mi];if(_keyMap[mod]){const keys=_keyMap[mod].split('|');if(!e.key||!keys.includes(e.key)){keyFiltered=true;break;}}else if(_nonKeyMods.has(mod)){continue;}else if(/^\d+$/.test(mod)&&mi>0&&(modifiers[mi-1]==='debounce'||modifiers[mi-1]==='throttle')){continue;}else{if(!e.key||e.key.toLowerCase()!==mod.toLowerCase()){keyFiltered=true;break;}}}
|
|
372
|
-
if(keyFiltered)continue;if(modifiers.includes('ctrl')&&!e.ctrlKey)continue;if(modifiers.includes('shift')&&!e.shiftKey)continue;if(modifiers.includes('alt')&&!e.altKey)continue;if(modifiers.includes('meta')&&!e.metaKey)continue;if(modifiers.includes('prevent'))e.preventDefault();if(modifiers.includes('stop')){e.stopPropagation();if(!stoppedAt)stoppedAt=[];stoppedAt.push(matched);}
|
|
373
|
-
const invoke=(evt)=>{const match=methodExpr.match(/^(\w+)(?:\(([^)]*)\))?$/);if(!match)return;const methodName=match[1];const fn=this[methodName];if(typeof fn!=='function')return;if(match[2]!==undefined){const args=match[2].split(',').map(a=>{a=a.trim();if(a==='')return undefined;if(a==='$event')return evt;if(a==='true')return true;if(a==='false')return false;if(a==='null')return null;if(/^-?\d+(\.\d+)?$/.test(a))return Number(a);if((a.startsWith("'")&&a.endsWith("'"))||(a.startsWith('"')&&a.endsWith('"')))return a.slice(1,-1);if(a.startsWith('state.'))return _getPath(this.state,a.slice(6));return a;}).filter(a=>a!==undefined);fn(...args);}else{fn(evt);}};const debounceIdx=modifiers.indexOf('debounce');if(debounceIdx!==-1){const ms=parseInt(modifiers[debounceIdx+1],10)||250;const timers=_debounceTimers.get(el)||{};clearTimeout(timers[event]);timers[event]=setTimeout(()=>invoke(e),ms);_debounceTimers.set(el,timers);continue;}
|
|
374
|
-
const throttleIdx=modifiers.indexOf('throttle');if(throttleIdx!==-1){const ms=parseInt(modifiers[throttleIdx+1],10)||250;const timers=_throttleTimers.get(el)||{};if(timers[event])continue;invoke(e);timers[event]=setTimeout(()=>{timers[event]=null;},ms);_throttleTimers.set(el,timers);continue;}
|
|
375
|
-
if(modifiers.includes('once')){if(el.dataset.zqOnce===event)continue;el.dataset.zqOnce=event;}
|
|
376
|
-
invoke(e);}};this._el.addEventListener(event,handler,listenerOpts);this._listeners.push({event,handler});this._delegatedEvents.set(event,{handler,opts:listenerOpts});}
|
|
377
|
-
_bindRefs(){this.refs={};this._el.querySelectorAll('[z-ref]').forEach(el=>{this.refs[el.getAttribute('z-ref')]=el;});}
|
|
378
|
-
_bindModels(){this._el.querySelectorAll('[z-model]').forEach(el=>{const key=el.getAttribute('z-model');const tag=el.tagName.toLowerCase();const type=(el.type||'').toLowerCase();const isEditable=el.hasAttribute('contenteditable');const isLazy=el.hasAttribute('z-lazy');const isTrim=el.hasAttribute('z-trim');const isNum=el.hasAttribute('z-number');const isUpper=el.hasAttribute('z-uppercase');const isLower=el.hasAttribute('z-lowercase');const hasDebounce=el.hasAttribute('z-debounce');const debounceMs=hasDebounce?(parseInt(el.getAttribute('z-debounce'),10)||250):0;const currentVal=_getPath(this.state,key);if(tag==='input'&&type==='checkbox'){el.checked=!!currentVal;}else if(tag==='input'&&type==='radio'){el.checked=el.value===String(currentVal);}else if(tag==='select'&&el.multiple){const vals=Array.isArray(currentVal)?currentVal.map(String):[];[...el.options].forEach(opt=>{opt.selected=vals.includes(opt.value);});}else if(isEditable){if(el.textContent!==String(currentVal??'')){el.textContent=currentVal??'';}}else{el.value=currentVal??'';}
|
|
379
|
-
const event=isLazy||tag==='select'||type==='checkbox'||type==='radio'?'change':isEditable?'input':'input';if(el._zqModelBound)return;el._zqModelBound=true;const handler=()=>{let val;if(type==='checkbox')val=el.checked;else if(tag==='select'&&el.multiple)val=[...el.selectedOptions].map(o=>o.value);else if(isEditable)val=el.textContent;else val=el.value;if(isTrim&&typeof val==='string')val=val.trim();if(isUpper&&typeof val==='string')val=val.toUpperCase();if(isLower&&typeof val==='string')val=val.toLowerCase();if(isNum||type==='number'||type==='range')val=Number(val);_setPath(this.state,key,val);};if(hasDebounce){let timer=null;el.addEventListener(event,()=>{clearTimeout(timer);timer=setTimeout(handler,debounceMs);});}else{el.addEventListener(event,handler);}});}
|
|
380
|
-
_evalExpr(expr){return safeEval(expr,[this.state.__raw||this.state,{props:this.props,refs:this.refs,computed:this.computed,$:typeof window!=='undefined'?window.$:undefined}]);}
|
|
381
|
-
_expandZFor(html){if(!html.includes('z-for'))return html;const temp=document.createElement('div');temp.innerHTML=html;const _recurse=(root)=>{let forEls=[...root.querySelectorAll('[z-for]')].filter(el=>!el.querySelector('[z-for]'));if(!forEls.length)return;for(const el of forEls){if(!el.parentNode)continue;const expr=el.getAttribute('z-for');const m=expr.match(/^\s*(?:\(\s*(\w+)(?:\s*,\s*(\w+))?\s*\)|(\w+))\s+in\s+(.+)\s*$/);if(!m){el.removeAttribute('z-for');continue;}
|
|
382
|
-
const itemVar=m[1]||m[3];const indexVar=m[2]||'$index';const listExpr=m[4].trim();let list=this._evalExpr(listExpr);if(list==null){el.remove();continue;}
|
|
383
|
-
if(typeof list==='number'){list=Array.from({length:list},(_,i)=>i+1);}
|
|
384
|
-
if(!Array.isArray(list)&&typeof list==='object'&&typeof list[Symbol.iterator]!=='function'){list=Object.entries(list).map(([k,v])=>({key:k,value:v}));}
|
|
385
|
-
if(!Array.isArray(list)&&typeof list[Symbol.iterator]==='function'){list=[...list];}
|
|
386
|
-
if(!Array.isArray(list)){el.remove();continue;}
|
|
387
|
-
const parent=el.parentNode;const tplEl=el.cloneNode(true);tplEl.removeAttribute('z-for');const tplOuter=tplEl.outerHTML;const fragment=document.createDocumentFragment();const evalReplace=(str,item,index)=>str.replace(/\{\{(.+?)\}\}/g,(_,inner)=>{try{const loopScope={};loopScope[itemVar]=item;loopScope[indexVar]=index;const result=safeEval(inner.trim(),[loopScope,this.state.__raw||this.state,{props:this.props,computed:this.computed,$:typeof window!=='undefined'?window.$:undefined}]);return result!=null?escapeHtml(String(result)):'';}catch{return'';}});for(let i=0;i<list.length;i++){const processed=evalReplace(tplOuter,list[i],i);const wrapper=document.createElement('div');wrapper.innerHTML=processed;while(wrapper.firstChild)fragment.appendChild(wrapper.firstChild);}
|
|
388
|
-
parent.replaceChild(fragment,el);}
|
|
389
|
-
if(root.querySelector('[z-for]'))_recurse(root);};_recurse(temp);return temp.innerHTML;}
|
|
390
|
-
_expandContentDirectives(html){if(!html.includes('z-html')&&!html.includes('z-text'))return html;const temp=document.createElement('div');temp.innerHTML=html;temp.querySelectorAll('[z-html]').forEach(el=>{if(el.closest('[z-pre]'))return;const val=this._evalExpr(el.getAttribute('z-html'));el.innerHTML=val!=null?String(val):'';el.removeAttribute('z-html');});temp.querySelectorAll('[z-text]').forEach(el=>{if(el.closest('[z-pre]'))return;const val=this._evalExpr(el.getAttribute('z-text'));el.textContent=val!=null?String(val):'';el.removeAttribute('z-text');});return temp.innerHTML;}
|
|
391
|
-
_processDirectives(){const ifEls=[...this._el.querySelectorAll('[z-if]')];for(const el of ifEls){if(!el.parentNode||el.closest('[z-pre]'))continue;const show=!!this._evalExpr(el.getAttribute('z-if'));const chain=[{el,show}];let sib=el.nextElementSibling;while(sib){if(sib.hasAttribute('z-else-if')){chain.push({el:sib,show:!!this._evalExpr(sib.getAttribute('z-else-if'))});sib=sib.nextElementSibling;}else if(sib.hasAttribute('z-else')){chain.push({el:sib,show:true});break;}else{break;}}
|
|
392
|
-
let found=false;for(const item of chain){if(!found&&item.show){found=true;item.el.removeAttribute('z-if');item.el.removeAttribute('z-else-if');item.el.removeAttribute('z-else');}else{item.el.remove();}}}
|
|
393
|
-
this._el.querySelectorAll('[z-show]').forEach(el=>{if(el.closest('[z-pre]'))return;const show=!!this._evalExpr(el.getAttribute('z-show'));el.style.display=show?'':'none';el.removeAttribute('z-show');});const walker=document.createTreeWalker(this._el,NodeFilter.SHOW_ELEMENT,{acceptNode(n){return n.hasAttribute('z-pre')?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT;}});let node;while((node=walker.nextNode())){const attrs=node.attributes;for(let i=attrs.length-1;i>=0;i--){const attr=attrs[i];let attrName;if(attr.name.startsWith('z-bind:'))attrName=attr.name.slice(7);else if(attr.name.charCodeAt(0)===58&&attr.name.charCodeAt(1)!==58)attrName=attr.name.slice(1);else continue;const val=this._evalExpr(attr.value);node.removeAttribute(attr.name);if(val===false||val===null||val===undefined){node.removeAttribute(attrName);}else if(val===true){node.setAttribute(attrName,'');}else{node.setAttribute(attrName,String(val));}}}
|
|
394
|
-
this._el.querySelectorAll('[z-class]').forEach(el=>{if(el.closest('[z-pre]'))return;const val=this._evalExpr(el.getAttribute('z-class'));if(typeof val==='string'){val.split(/\s+/).filter(Boolean).forEach(c=>el.classList.add(c));}else if(Array.isArray(val)){val.filter(Boolean).forEach(c=>el.classList.add(String(c)));}else if(val&&typeof val==='object'){for(const[cls,active]of Object.entries(val)){el.classList.toggle(cls,!!active);}}
|
|
395
|
-
el.removeAttribute('z-class');});this._el.querySelectorAll('[z-style]').forEach(el=>{if(el.closest('[z-pre]'))return;const val=this._evalExpr(el.getAttribute('z-style'));if(typeof val==='string'){el.style.cssText+=';'+val;}else if(val&&typeof val==='object'){for(const[prop,v]of Object.entries(val)){el.style[prop]=v;}}
|
|
396
|
-
el.removeAttribute('z-style');});this._el.querySelectorAll('[z-cloak]').forEach(el=>{el.removeAttribute('z-cloak');});}
|
|
397
|
-
setState(partial){if(partial&&Object.keys(partial).length>0){Object.assign(this.state,partial);}else{this._scheduleUpdate();}}
|
|
398
|
-
emit(name,detail){this._el.dispatchEvent(new CustomEvent(name,{detail,bubbles:true,cancelable:true}));}
|
|
399
|
-
destroy(){if(this._destroyed)return;this._destroyed=true;if(this._def.destroyed){try{this._def.destroyed.call(this);}
|
|
400
|
-
catch(err){reportError(ErrorCode.COMP_LIFECYCLE,`Component "${this._def._name}" destroyed() threw`,{component:this._def._name},err);}}
|
|
401
|
-
this._listeners.forEach(({event,handler})=>this._el.removeEventListener(event,handler));this._listeners=[];if(this._outsideListeners){this._outsideListeners.forEach(({event,handler})=>document.removeEventListener(event,handler,true));this._outsideListeners=[];}
|
|
402
|
-
this._delegatedEvents=null;this._eventBindings=null;const allEls=this._el.querySelectorAll('*');allEls.forEach(child=>{const dTimers=_debounceTimers.get(child);if(dTimers){for(const key in dTimers)clearTimeout(dTimers[key]);_debounceTimers.delete(child);}
|
|
403
|
-
const tTimers=_throttleTimers.get(child);if(tTimers){for(const key in tTimers)clearTimeout(tTimers[key]);_throttleTimers.delete(child);}});if(this._styleEl)this._styleEl.remove();_instances.delete(this._el);this._el.innerHTML='';}}
|
|
404
|
-
const _reservedKeys=new Set(['state','render','styles','init','mounted','updated','destroyed','props','templateUrl','styleUrl','templates','base','computed','watch']);function component(name,definition){if(!name||typeof name!=='string'){throw new ZQueryError(ErrorCode.COMP_INVALID_NAME,'Component name must be a non-empty string');}
|
|
405
|
-
if(!name.includes('-')){throw new ZQueryError(ErrorCode.COMP_INVALID_NAME,`Component name "${name}" must contain a hyphen (Web Component convention)`);}
|
|
406
|
-
definition._name=name;if(definition.base!==undefined){definition._base=definition.base;}else{definition._base=_detectCallerBase();}
|
|
407
|
-
_registry.set(name,definition);}
|
|
408
|
-
function mount(target,componentName,props={}){const el=typeof target==='string'?document.querySelector(target):target;if(!el)throw new ZQueryError(ErrorCode.COMP_MOUNT_TARGET,`Mount target "${target}" not found`,{target});const def=_registry.get(componentName);if(!def)throw new ZQueryError(ErrorCode.COMP_NOT_FOUND,`Component "${componentName}" not registered`,{component:componentName});if(_instances.has(el))_instances.get(el).destroy();const instance=new Component(el,def,props);_instances.set(el,instance);instance._render();return instance;}
|
|
409
|
-
function mountAll(root=document.body){for(const[name,def]of _registry){const tags=root.querySelectorAll(name);tags.forEach(tag=>{if(_instances.has(tag))return;const props={};let parentInstance=null;let ancestor=tag.parentElement;while(ancestor){if(_instances.has(ancestor)){parentInstance=_instances.get(ancestor);break;}
|
|
410
|
-
ancestor=ancestor.parentElement;}[...tag.attributes].forEach(attr=>{if(attr.name.startsWith('@')||attr.name.startsWith('z-'))return;if(attr.name.startsWith(':')){const propName=attr.name.slice(1);if(parentInstance){props[propName]=safeEval(attr.value,[parentInstance.state.__raw||parentInstance.state,{props:parentInstance.props,refs:parentInstance.refs,computed:parentInstance.computed,$:typeof window!=='undefined'?window.$:undefined}]);}else{try{props[propName]=JSON.parse(attr.value);}
|
|
411
|
-
catch{props[propName]=attr.value;}}
|
|
412
|
-
return;}
|
|
413
|
-
try{props[attr.name]=JSON.parse(attr.value);}
|
|
414
|
-
catch{props[attr.name]=attr.value;}});const instance=new Component(tag,def,props);_instances.set(tag,instance);instance._render();});}}
|
|
415
|
-
function getInstance(target){const el=typeof target==='string'?document.querySelector(target):target;return _instances.get(el)||null;}
|
|
416
|
-
function destroy(target){const el=typeof target==='string'?document.querySelector(target):target;const inst=_instances.get(el);if(inst)inst.destroy();}
|
|
417
|
-
function getRegistry(){return Object.fromEntries(_registry);}
|
|
418
|
-
async function prefetch(name){const def=_registry.get(name);if(!def)return;if((def.templateUrl&&!def._templateLoaded)||(def.styleUrl&&!def._styleLoaded)){await Component.prototype._loadExternals.call({_def:def});}}
|
|
419
|
-
const _globalStyles=new Map();function style(urls,opts={}){const callerBase=_detectCallerBase();const list=Array.isArray(urls)?urls:[urls];const elements=[];const loadPromises=[];let _criticalStyle=null;if(opts.critical!==false){_criticalStyle=document.createElement('style');_criticalStyle.setAttribute('data-zq-critical','');_criticalStyle.textContent=`html{visibility:hidden!important;background:${opts.bg || '#0d1117'}}`;document.head.insertBefore(_criticalStyle,document.head.firstChild);}
|
|
420
|
-
for(let url of list){if(typeof url==='string'&&!url.startsWith('/')&&!url.includes(':')&&!url.startsWith('//')){url=_resolveUrl(url,callerBase);}
|
|
421
|
-
if(_globalStyles.has(url)){elements.push(_globalStyles.get(url));continue;}
|
|
422
|
-
const link=document.createElement('link');link.rel='stylesheet';link.href=url;link.setAttribute('data-zq-style','');const p=new Promise(resolve=>{link.onload=resolve;link.onerror=resolve;});loadPromises.push(p);document.head.appendChild(link);_globalStyles.set(url,link);elements.push(link);}
|
|
423
|
-
const ready=Promise.all(loadPromises).then(()=>{if(_criticalStyle){_criticalStyle.remove();}});return{ready,remove(){for(const el of elements){el.remove();for(const[k,v]of _globalStyles){if(v===el){_globalStyles.delete(k);break;}}}}};}
|
|
424
|
-
const _ZQ_STATE_KEY='__zq';function _shallowEqual(a,b){if(a===b)return true;if(!a||!b)return false;const keysA=Object.keys(a);const keysB=Object.keys(b);if(keysA.length!==keysB.length)return false;for(let i=0;i<keysA.length;i++){const k=keysA[i];if(a[k]!==b[k])return false;}
|
|
425
|
-
return true;}
|
|
426
|
-
class Router{constructor(config={}){this._el=null;const isFile=typeof location!=='undefined'&&location.protocol==='file:';this._mode=isFile?'hash':(config.mode||'history');let rawBase=config.base;if(rawBase==null){rawBase=(typeof window!=='undefined'&&window.__ZQ_BASE)||'';if(!rawBase&&typeof document!=='undefined'){const baseEl=document.querySelector('base');if(baseEl){try{rawBase=new URL(baseEl.href).pathname;}
|
|
427
|
-
catch{rawBase=baseEl.getAttribute('href')||'';}
|
|
428
|
-
if(rawBase==='/')rawBase='';}}}
|
|
429
|
-
this._base=String(rawBase).replace(/\/+$/,'');if(this._base&&!this._base.startsWith('/'))this._base='/'+this._base;this._routes=[];this._fallback=config.fallback||null;this._current=null;this._guards={before:[],after:[]};this._listeners=new Set();this._instance=null;this._resolving=false;this._substateListeners=[];this._inSubstate=false;if(config.el){this._el=typeof config.el==='string'?document.querySelector(config.el):config.el;}else if(typeof document!=='undefined'){const outlet=document.querySelector('z-outlet');if(outlet){this._el=outlet;if(!config.fallback&&outlet.getAttribute('fallback')){this._fallback=outlet.getAttribute('fallback');}
|
|
430
|
-
if(!config.mode&&outlet.getAttribute('mode')){const attrMode=outlet.getAttribute('mode');if(attrMode==='hash'||attrMode==='history'){this._mode=isFile?'hash':attrMode;}}
|
|
431
|
-
if(config.base==null&&outlet.getAttribute('base')){let ob=outlet.getAttribute('base');ob=String(ob).replace(/\/+$/,'');if(ob&&!ob.startsWith('/'))ob='/'+ob;this._base=ob;}}}
|
|
432
|
-
if(config.routes){config.routes.forEach(r=>this.add(r));}
|
|
433
|
-
if(this._mode==='hash'){this._onNavEvent=()=>this._resolve();window.addEventListener('hashchange',this._onNavEvent);this._onPopState=(e)=>{const st=e.state;if(st&&st[_ZQ_STATE_KEY]==='substate'){const handled=this._fireSubstate(st.key,st.data,'pop');if(handled)return;this._resolve().then(()=>{this._fireSubstate(st.key,st.data,'pop');});return;}else if(this._inSubstate){this._inSubstate=false;this._fireSubstate(null,null,'reset');}};window.addEventListener('popstate',this._onPopState);}else{this._onNavEvent=(e)=>{const st=e.state;if(st&&st[_ZQ_STATE_KEY]==='substate'){const handled=this._fireSubstate(st.key,st.data,'pop');if(handled)return;this._resolve().then(()=>{this._fireSubstate(st.key,st.data,'pop');});return;}else if(this._inSubstate){this._inSubstate=false;this._fireSubstate(null,null,'reset');}
|
|
434
|
-
this._resolve();};window.addEventListener('popstate',this._onNavEvent);}
|
|
435
|
-
this._onLinkClick=(e)=>{if(e.metaKey||e.ctrlKey||e.shiftKey||e.altKey)return;const link=e.target.closest('[z-link]');if(!link)return;if(link.getAttribute('target')==='_blank')return;e.preventDefault();let href=link.getAttribute('z-link');if(href&&/^[a-z][a-z0-9+.-]*:/i.test(href))return;const paramsAttr=link.getAttribute('z-link-params');if(paramsAttr){try{const params=JSON.parse(paramsAttr);href=this._interpolateParams(href,params);}catch(err){reportError(ErrorCode.ROUTER_RESOLVE,'Malformed JSON in z-link-params',{href,paramsAttr},err);}}
|
|
436
|
-
this.navigate(href);if(link.hasAttribute('z-to-top')){const scrollBehavior=link.getAttribute('z-to-top')||'instant';window.scrollTo({top:0,behavior:scrollBehavior});}};document.addEventListener('click',this._onLinkClick);if(this._el){queueMicrotask(()=>this._resolve());}}
|
|
437
|
-
add(route){const{regex,keys}=compilePath(route.path);this._routes.push({...route,_regex:regex,_keys:keys});if(route.fallback){const fb=compilePath(route.fallback);this._routes.push({...route,path:route.fallback,_regex:fb.regex,_keys:fb.keys});}
|
|
438
|
-
return this;}
|
|
439
|
-
remove(path){this._routes=this._routes.filter(r=>r.path!==path);return this;}
|
|
440
|
-
_interpolateParams(path,params){if(!params||typeof params!=='object')return path;return path.replace(/:([\w]+)/g,(_,key)=>{const val=params[key];return val!=null?encodeURIComponent(String(val)):':'+key;});}
|
|
441
|
-
_currentURL(){if(this._mode==='hash'){return window.location.hash.slice(1)||'/';}
|
|
442
|
-
const pathname=window.location.pathname||'/';const hash=window.location.hash||'';return pathname+hash;}
|
|
443
|
-
navigate(path,options={}){if(options.params)path=this._interpolateParams(path,options.params);const[cleanPath,fragment]=(path||'').split('#');let normalized=this._normalizePath(cleanPath);const hash=fragment?'#'+fragment:'';if(this._mode==='hash'){if(fragment)window.__zqScrollTarget=fragment;const targetHash='#'+normalized;if(window.location.hash===targetHash&&!options.force)return this;window.location.hash=targetHash;}else{const targetURL=this._base+normalized+hash;const currentURL=(window.location.pathname||'/')+(window.location.hash||'');if(targetURL===currentURL&&!options.force){if(fragment){const el=document.getElementById(fragment);if(el)el.scrollIntoView({behavior:'smooth',block:'start'});}
|
|
444
|
-
return this;}
|
|
445
|
-
const targetPathOnly=this._base+normalized;const currentPathOnly=window.location.pathname||'/';if(targetPathOnly===currentPathOnly&&hash&&!options.force){window.history.replaceState({...options.state,[_ZQ_STATE_KEY]:'route'},'',targetURL);if(fragment){const el=document.getElementById(fragment);if(el)el.scrollIntoView({behavior:'smooth',block:'start'});}
|
|
446
|
-
return this;}
|
|
447
|
-
window.history.pushState({...options.state,[_ZQ_STATE_KEY]:'route'},'',targetURL);this._resolve();}
|
|
448
|
-
return this;}
|
|
449
|
-
replace(path,options={}){if(options.params)path=this._interpolateParams(path,options.params);const[cleanPath,fragment]=(path||'').split('#');let normalized=this._normalizePath(cleanPath);const hash=fragment?'#'+fragment:'';if(this._mode==='hash'){if(fragment)window.__zqScrollTarget=fragment;window.location.replace('#'+normalized);}else{window.history.replaceState({...options.state,[_ZQ_STATE_KEY]:'route'},'',this._base+normalized+hash);this._resolve();}
|
|
450
|
-
return this;}
|
|
451
|
-
_normalizePath(path){let p=path&&path.startsWith('/')?path:(path?`/${path}`:'/');if(this._base){if(p===this._base)return'/';if(p.startsWith(this._base+'/'))p=p.slice(this._base.length)||'/';}
|
|
452
|
-
return p;}
|
|
453
|
-
resolve(path){const normalized=path&&path.startsWith('/')?path:(path?`/${path}`:'/');return this._base+normalized;}
|
|
454
|
-
back(){window.history.back();return this;}
|
|
455
|
-
forward(){window.history.forward();return this;}
|
|
456
|
-
go(n){window.history.go(n);return this;}
|
|
457
|
-
beforeEach(fn){this._guards.before.push(fn);return this;}
|
|
458
|
-
afterEach(fn){this._guards.after.push(fn);return this;}
|
|
459
|
-
onChange(fn){this._listeners.add(fn);return()=>this._listeners.delete(fn);}
|
|
460
|
-
pushSubstate(key,data){this._inSubstate=true;if(this._mode==='hash'){const current=window.location.hash||'#/';window.history.pushState({[_ZQ_STATE_KEY]:'substate',key,data},'',window.location.href);}else{window.history.pushState({[_ZQ_STATE_KEY]:'substate',key,data},'',window.location.href);}
|
|
461
|
-
return this;}
|
|
462
|
-
onSubstate(fn){this._substateListeners.push(fn);return()=>{this._substateListeners=this._substateListeners.filter(f=>f!==fn);};}
|
|
463
|
-
_fireSubstate(key,data,action){for(const fn of this._substateListeners){try{if(fn(key,data,action)===true)return true;}catch(err){reportError(ErrorCode.ROUTER_GUARD,'onSubstate listener threw',{key,data},err);}}
|
|
464
|
-
return false;}
|
|
465
|
-
get current(){return this._current;}
|
|
466
|
-
get base(){return this._base;}
|
|
467
|
-
get path(){if(this._mode==='hash'){const raw=window.location.hash.slice(1)||'/';if(raw&&!raw.startsWith('/')){window.__zqScrollTarget=raw;const fallbackPath=(this._current&&this._current.path)||'/';window.location.replace('#'+fallbackPath);return fallbackPath;}
|
|
468
|
-
return raw;}
|
|
469
|
-
let pathname=window.location.pathname||'/';if(pathname.length>1&&pathname.endsWith('/')){pathname=pathname.slice(0,-1);}
|
|
470
|
-
if(this._base){if(pathname===this._base)return'/';if(pathname.startsWith(this._base+'/')){return pathname.slice(this._base.length)||'/';}}
|
|
471
|
-
return pathname;}
|
|
472
|
-
get query(){const search=this._mode==='hash'?(window.location.hash.split('?')[1]||''):window.location.search.slice(1);return Object.fromEntries(new URLSearchParams(search));}
|
|
473
|
-
async _resolve(){if(this._resolving)return;this._resolving=true;this._redirectCount=0;try{await this.__resolve();}finally{this._resolving=false;}}
|
|
474
|
-
async __resolve(){const histState=window.history.state;if(histState&&histState[_ZQ_STATE_KEY]==='substate'){const handled=this._fireSubstate(histState.key,histState.data,'resolve');if(handled)return;}
|
|
475
|
-
const fullPath=this.path;const[pathPart,queryString]=fullPath.split('?');const path=pathPart||'/';const query=Object.fromEntries(new URLSearchParams(queryString||''));let matched=null;let params={};for(const route of this._routes){const m=path.match(route._regex);if(m){matched=route;route._keys.forEach((key,i)=>{params[key]=m[i+1];});break;}}
|
|
476
|
-
if(!matched&&this._fallback){matched={component:this._fallback,path:'*',_keys:[],_regex:/.*/};}
|
|
477
|
-
if(!matched)return;const to={route:matched,params,query,path};const from=this._current;if(from&&this._instance&&matched.component===from.route.component){const sameParams=_shallowEqual(params,from.params);const sameQuery=_shallowEqual(query,from.query);if(sameParams&&sameQuery){return;}}
|
|
478
|
-
for(const guard of this._guards.before){try{const result=await guard(to,from);if(result===false)return;if(typeof result==='string'){if(++this._redirectCount>10){reportError(ErrorCode.ROUTER_GUARD,'Too many guard redirects (possible loop)',{to},null);return;}
|
|
479
|
-
const[rPath,rFrag]=result.split('#');const rNorm=this._normalizePath(rPath||'/');const rHash=rFrag?'#'+rFrag:'';if(this._mode==='hash'){if(rFrag)window.__zqScrollTarget=rFrag;window.location.replace('#'+rNorm);}else{window.history.replaceState({[_ZQ_STATE_KEY]:'route'},'',this._base+rNorm+rHash);}
|
|
480
|
-
return this.__resolve();}}catch(err){reportError(ErrorCode.ROUTER_GUARD,'Before-guard threw',{to,from},err);return;}}
|
|
481
|
-
if(matched.load){try{await matched.load();}
|
|
482
|
-
catch(err){reportError(ErrorCode.ROUTER_LOAD,`Failed to load module for route "${matched.path}"`,{path:matched.path},err);return;}}
|
|
483
|
-
this._current=to;if(this._el&&matched.component){if(typeof matched.component==='string'){await prefetch(matched.component);}
|
|
484
|
-
if(this._instance){this._instance.destroy();this._instance=null;}
|
|
485
|
-
const _routeStart=typeof window!=='undefined'&&window.__zqRenderHook?performance.now():0;this._el.innerHTML='';const props={...params,$route:to,$query:query,$params:params};if(typeof matched.component==='string'){const container=document.createElement(matched.component);this._el.appendChild(container);try{this._instance=mount(container,matched.component,props);}catch(err){reportError(ErrorCode.COMP_NOT_FOUND,`Failed to mount component for route "${matched.path}"`,{component:matched.component,path:matched.path},err);return;}
|
|
486
|
-
if(_routeStart)window.__zqRenderHook(this._el,performance.now()-_routeStart,'route',matched.component);}
|
|
487
|
-
else if(typeof matched.component==='function'){this._el.innerHTML=matched.component(to);if(_routeStart)window.__zqRenderHook(this._el,performance.now()-_routeStart,'route',to);}}
|
|
488
|
-
this._updateActiveRoutes(path);for(const guard of this._guards.after){await guard(to,from);}
|
|
489
|
-
this._listeners.forEach(fn=>fn(to,from));}
|
|
490
|
-
_updateActiveRoutes(currentPath){if(typeof document==='undefined')return;const els=document.querySelectorAll('[z-active-route]');for(let i=0;i<els.length;i++){const el=els[i];const route=el.getAttribute('z-active-route');const cls=el.getAttribute('z-active-class')||'active';const exact=el.hasAttribute('z-active-exact');const isActive=exact?currentPath===route:(route==='/'?currentPath==='/':currentPath.startsWith(route));el.classList.toggle(cls,isActive);}}
|
|
491
|
-
destroy(){if(this._onNavEvent){window.removeEventListener(this._mode==='hash'?'hashchange':'popstate',this._onNavEvent);this._onNavEvent=null;}
|
|
492
|
-
if(this._onPopState){window.removeEventListener('popstate',this._onPopState);this._onPopState=null;}
|
|
493
|
-
if(this._onLinkClick){document.removeEventListener('click',this._onLinkClick);this._onLinkClick=null;}
|
|
494
|
-
if(this._instance)this._instance.destroy();this._listeners.clear();this._substateListeners=[];this._inSubstate=false;this._routes=[];this._guards={before:[],after:[]};}}
|
|
495
|
-
function compilePath(path){const keys=[];const pattern=path.replace(/:(\w+)/g,(_,key)=>{keys.push(key);return'([^/]+)';}).replace(/\*/g,'(.*)');return{regex:new RegExp(`^${pattern}$`),keys};}
|
|
496
|
-
function matchRoute(routes,pathname,fallback='not-found'){for(const route of routes){const{regex,keys}=compilePath(route.path);const m=pathname.match(regex);if(m){const params={};keys.forEach((key,i)=>{params[key]=m[i+1];});return{component:route.component,params};}
|
|
497
|
-
if(route.fallback){const fb=compilePath(route.fallback);const fbm=pathname.match(fb.regex);if(fbm){const params={};fb.keys.forEach((key,i)=>{params[key]=fbm[i+1];});return{component:route.component,params};}}}
|
|
498
|
-
return{component:fallback,params:{}};}
|
|
499
|
-
let _activeRouter=null;function createRouter(config){_activeRouter=new Router(config);return _activeRouter;}
|
|
500
|
-
function getRouter(){return _activeRouter;}
|
|
501
|
-
class Store{constructor(config={}){this._subscribers=new Map();this._wildcards=new Set();this._actions=config.actions||{};this._getters=config.getters||{};this._middleware=[];this._history=[];this._maxHistory=config.maxHistory||1000;this._debug=config.debug||false;this._batching=false;this._batchQueue=[];this._undoStack=[];this._redoStack=[];this._maxUndo=config.maxUndo||50;const initial=typeof config.state==='function'?config.state():{...(config.state||{})};this._initialState=JSON.parse(JSON.stringify(initial));this.state=reactive(initial,(key,value,old)=>{if(this._batching){this._batchQueue.push({key,value,old});return;}
|
|
502
|
-
this._notifySubscribers(key,value,old);});this.getters={};for(const[name,fn]of Object.entries(this._getters)){Object.defineProperty(this.getters,name,{get:()=>fn(this.state.__raw||this.state),enumerable:true});}}
|
|
503
|
-
_notifySubscribers(key,value,old){const subs=this._subscribers.get(key);if(subs)subs.forEach(fn=>{try{fn(key,value,old);}
|
|
504
|
-
catch(err){reportError(ErrorCode.STORE_SUBSCRIBE,`Subscriber for "${key}" threw`,{key},err);}});this._wildcards.forEach(fn=>{try{fn(key,value,old);}
|
|
505
|
-
catch(err){reportError(ErrorCode.STORE_SUBSCRIBE,'Wildcard subscriber threw',{key},err);}});}
|
|
506
|
-
batch(fn){this._batching=true;this._batchQueue=[];try{fn(this.state);}finally{this._batching=false;const last=new Map();for(const entry of this._batchQueue){last.set(entry.key,entry);}
|
|
507
|
-
this._batchQueue=[];for(const{key,value,old}of last.values()){this._notifySubscribers(key,value,old);}}}
|
|
508
|
-
checkpoint(){const snap=JSON.parse(JSON.stringify(this.state.__raw||this.state));this._undoStack.push(snap);if(this._undoStack.length>this._maxUndo){this._undoStack.splice(0,this._undoStack.length-this._maxUndo);}
|
|
509
|
-
this._redoStack=[];}
|
|
510
|
-
undo(){if(this._undoStack.length===0)return false;const current=JSON.parse(JSON.stringify(this.state.__raw||this.state));this._redoStack.push(current);const prev=this._undoStack.pop();this.replaceState(prev);return true;}
|
|
511
|
-
redo(){if(this._redoStack.length===0)return false;const current=JSON.parse(JSON.stringify(this.state.__raw||this.state));this._undoStack.push(current);const next=this._redoStack.pop();this.replaceState(next);return true;}
|
|
512
|
-
get canUndo(){return this._undoStack.length>0;}
|
|
513
|
-
get canRedo(){return this._redoStack.length>0;}
|
|
514
|
-
dispatch(name,...args){const action=this._actions[name];if(!action){reportError(ErrorCode.STORE_ACTION,`Unknown action "${name}"`,{action:name,args});return;}
|
|
515
|
-
for(const mw of this._middleware){try{const result=mw(name,args,this.state);if(result===false)return;}catch(err){reportError(ErrorCode.STORE_MIDDLEWARE,`Middleware threw during "${name}"`,{action:name},err);return;}}
|
|
516
|
-
if(this._debug){console.log(`%c[Store] ${name}`,'color: #4CAF50; font-weight: bold;',...args);}
|
|
517
|
-
try{const result=action(this.state,...args);this._history.push({action:name,args,timestamp:Date.now()});if(this._history.length>this._maxHistory){this._history.splice(0,this._history.length-this._maxHistory);}
|
|
518
|
-
return result;}catch(err){reportError(ErrorCode.STORE_ACTION,`Action "${name}" threw`,{action:name,args},err);}}
|
|
519
|
-
subscribe(keyOrFn,fn){if(typeof keyOrFn==='function'){this._wildcards.add(keyOrFn);return()=>this._wildcards.delete(keyOrFn);}
|
|
520
|
-
if(!this._subscribers.has(keyOrFn)){this._subscribers.set(keyOrFn,new Set());}
|
|
521
|
-
this._subscribers.get(keyOrFn).add(fn);return()=>this._subscribers.get(keyOrFn)?.delete(fn);}
|
|
522
|
-
snapshot(){return JSON.parse(JSON.stringify(this.state.__raw||this.state));}
|
|
523
|
-
replaceState(newState){const raw=this.state.__raw||this.state;for(const key of Object.keys(raw)){delete this.state[key];}
|
|
524
|
-
Object.assign(this.state,newState);}
|
|
525
|
-
use(fn){this._middleware.push(fn);return this;}
|
|
526
|
-
get history(){return[...this._history];}
|
|
527
|
-
reset(initialState){this.replaceState(initialState||JSON.parse(JSON.stringify(this._initialState)));this._history=[];this._undoStack=[];this._redoStack=[];}}
|
|
528
|
-
let _stores=new Map();function createStore(name,config){if(typeof name==='object'){config=name;name='default';}
|
|
529
|
-
const store=new Store(config);_stores.set(name,store);return store;}
|
|
530
|
-
function getStore(name='default'){return _stores.get(name)||null;}
|
|
531
|
-
const _config={baseURL:'',headers:{'Content-Type':'application/json'},timeout:30000,};const _interceptors={request:[],response:[],};async function request(method,url,data,options={}){if(!url||typeof url!=='string'){throw new Error(`HTTP request requires a URL string, got ${typeof url}`);}
|
|
532
|
-
let fullURL=url.startsWith('http')?url:_config.baseURL+url;let headers={..._config.headers,...options.headers};let body=undefined;const fetchOpts={method:method.toUpperCase(),headers,...options,};if(data!==undefined&&method!=='GET'&&method!=='HEAD'){if(data instanceof FormData){body=data;delete fetchOpts.headers['Content-Type'];}else if(typeof data==='object'){body=JSON.stringify(data);}else{body=data;}
|
|
533
|
-
fetchOpts.body=body;}
|
|
534
|
-
if(data&&(method==='GET'||method==='HEAD')&&typeof data==='object'){const params=new URLSearchParams(data).toString();fullURL+=(fullURL.includes('?')?'&':'?')+params;}
|
|
535
|
-
const controller=new AbortController();const timeout=options.timeout??_config.timeout;let timer;if(options.signal){if(typeof AbortSignal.any==='function'){fetchOpts.signal=AbortSignal.any([options.signal,controller.signal]);}else{fetchOpts.signal=controller.signal;if(options.signal.aborted){controller.abort(options.signal.reason);}else{options.signal.addEventListener('abort',()=>controller.abort(options.signal.reason),{once:true});}}}else{fetchOpts.signal=controller.signal;}
|
|
536
|
-
let _timedOut=false;if(timeout>0){timer=setTimeout(()=>{_timedOut=true;controller.abort();},timeout);}
|
|
537
|
-
for(const interceptor of _interceptors.request){const result=await interceptor(fetchOpts,fullURL);if(result===false)throw new Error('Request blocked by interceptor');if(result?.url)fullURL=result.url;if(result?.options)Object.assign(fetchOpts,result.options);}
|
|
538
|
-
try{const response=await fetch(fullURL,fetchOpts);if(timer)clearTimeout(timer);const contentType=response.headers.get('Content-Type')||'';let responseData;try{if(contentType.includes('application/json')){responseData=await response.json();}else if(contentType.includes('text/')){responseData=await response.text();}else if(contentType.includes('application/octet-stream')||contentType.includes('image/')){responseData=await response.blob();}else{const text=await response.text();try{responseData=JSON.parse(text);}catch{responseData=text;}}}catch(parseErr){responseData=null;console.warn(`[zQuery HTTP] Failed to parse response body from ${method} ${fullURL}:`,parseErr.message);}
|
|
539
|
-
const result={ok:response.ok,status:response.status,statusText:response.statusText,headers:Object.fromEntries(response.headers.entries()),data:responseData,response,};for(const interceptor of _interceptors.response){await interceptor(result);}
|
|
540
|
-
if(!response.ok){const err=new Error(`HTTP ${response.status}: ${response.statusText}`);err.response=result;throw err;}
|
|
541
|
-
return result;}catch(err){if(timer)clearTimeout(timer);if(err.name==='AbortError'){if(_timedOut){throw new Error(`Request timeout after ${timeout}ms: ${method} ${fullURL}`);}
|
|
542
|
-
throw new Error(`Request aborted: ${method} ${fullURL}`);}
|
|
543
|
-
throw err;}}
|
|
544
|
-
const http={get:(url,params,opts)=>request('GET',url,params,opts),post:(url,data,opts)=>request('POST',url,data,opts),put:(url,data,opts)=>request('PUT',url,data,opts),patch:(url,data,opts)=>request('PATCH',url,data,opts),delete:(url,data,opts)=>request('DELETE',url,data,opts),head:(url,opts)=>request('HEAD',url,undefined,opts),configure(opts){if(opts.baseURL!==undefined)_config.baseURL=opts.baseURL;if(opts.headers)Object.assign(_config.headers,opts.headers);if(opts.timeout!==undefined)_config.timeout=opts.timeout;},getConfig(){return{baseURL:_config.baseURL,headers:{..._config.headers},timeout:_config.timeout,};},onRequest(fn){_interceptors.request.push(fn);return()=>{const idx=_interceptors.request.indexOf(fn);if(idx!==-1)_interceptors.request.splice(idx,1);};},onResponse(fn){_interceptors.response.push(fn);return()=>{const idx=_interceptors.response.indexOf(fn);if(idx!==-1)_interceptors.response.splice(idx,1);};},clearInterceptors(type){if(!type||type==='request')_interceptors.request.length=0;if(!type||type==='response')_interceptors.response.length=0;},all(requests){return Promise.all(requests);},createAbort(){return new AbortController();},raw:(url,opts)=>fetch(url,opts),};function debounce(fn,ms=250){let timer;const debounced=(...args)=>{clearTimeout(timer);timer=setTimeout(()=>fn(...args),ms);};debounced.cancel=()=>clearTimeout(timer);return debounced;}
|
|
545
|
-
function throttle(fn,ms=250){let last=0;let timer;return(...args)=>{const now=Date.now();const remaining=ms-(now-last);clearTimeout(timer);if(remaining<=0){last=now;fn(...args);}else{timer=setTimeout(()=>{last=Date.now();fn(...args);},remaining);}};}
|
|
546
|
-
function pipe(...fns){return(input)=>fns.reduce((val,fn)=>fn(val),input);}
|
|
547
|
-
function once(fn){let called=false,result;return(...args)=>{if(!called){called=true;result=fn(...args);}
|
|
548
|
-
return result;};}
|
|
549
|
-
function sleep(ms){return new Promise(resolve=>setTimeout(resolve,ms));}
|
|
550
|
-
function escapeHtml(str){const map={'&':'&','<':'<','>':'>','"':'"',"'":'''};return String(str).replace(/[&<>"']/g,c=>map[c]);}
|
|
551
|
-
function stripHtml(str){return String(str).replace(/<[^>]*>/g,'');}
|
|
552
|
-
function html(strings,...values){return strings.reduce((result,str,i)=>{const val=values[i-1];const escaped=(val instanceof TrustedHTML)?val.toString():escapeHtml(val??'');return result+escaped+str;});}
|
|
553
|
-
class TrustedHTML{constructor(html){this._html=html;}
|
|
554
|
-
toString(){return this._html;}}
|
|
555
|
-
function trust(htmlStr){return new TrustedHTML(htmlStr);}
|
|
556
|
-
function uuid(){if(crypto?.randomUUID)return crypto.randomUUID();return'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g,c=>{const buf=new Uint8Array(1);crypto.getRandomValues(buf);const r=buf[0]&15;return(c==='x'?r:(r&0x3|0x8)).toString(16);});}
|
|
557
|
-
function camelCase(str){return str.replace(/-([a-z])/g,(_,c)=>c.toUpperCase());}
|
|
558
|
-
function kebabCase(str){return str.replace(/([A-Z]+)([A-Z][a-z])/g,'$1-$2').replace(/([a-z\d])([A-Z])/g,'$1-$2').toLowerCase();}
|
|
559
|
-
function deepClone(obj){if(typeof structuredClone==='function')return structuredClone(obj);const seen=new Map();function clone(val){if(val===null||typeof val!=='object')return val;if(seen.has(val))return seen.get(val);if(val instanceof Date)return new Date(val.getTime());if(val instanceof RegExp)return new RegExp(val.source,val.flags);if(val instanceof Map){const m=new Map();seen.set(val,m);val.forEach((v,k)=>m.set(clone(k),clone(v)));return m;}
|
|
560
|
-
if(val instanceof Set){const s=new Set();seen.set(val,s);val.forEach(v=>s.add(clone(v)));return s;}
|
|
561
|
-
if(ArrayBuffer.isView(val))return new val.constructor(val.buffer.slice(0));if(val instanceof ArrayBuffer)return val.slice(0);if(Array.isArray(val)){const arr=[];seen.set(val,arr);for(let i=0;i<val.length;i++)arr[i]=clone(val[i]);return arr;}
|
|
562
|
-
const result=Object.create(Object.getPrototypeOf(val));seen.set(val,result);for(const key of Object.keys(val))result[key]=clone(val[key]);return result;}
|
|
563
|
-
return clone(obj);}
|
|
564
|
-
const _UNSAFE_KEYS=new Set(['__proto__','constructor','prototype']);function deepMerge(target,...sources){const seen=new WeakSet();function merge(tgt,src){if(seen.has(src))return tgt;seen.add(src);for(const key of Object.keys(src)){if(_UNSAFE_KEYS.has(key))continue;if(src[key]&&typeof src[key]==='object'&&!Array.isArray(src[key])){if(!tgt[key]||typeof tgt[key]!=='object')tgt[key]={};merge(tgt[key],src[key]);}else{tgt[key]=src[key];}}
|
|
565
|
-
return tgt;}
|
|
566
|
-
for(const source of sources)merge(target,source);return target;}
|
|
567
|
-
function isEqual(a,b,_seen){if(a===b)return true;if(typeof a!==typeof b)return false;if(typeof a!=='object'||a===null||b===null)return false;if(Array.isArray(a)!==Array.isArray(b))return false;if(!_seen)_seen=new Set();if(_seen.has(a))return true;_seen.add(a);const keysA=Object.keys(a);const keysB=Object.keys(b);if(keysA.length!==keysB.length)return false;return keysA.every(k=>isEqual(a[k],b[k],_seen));}
|
|
568
|
-
function param(obj){return new URLSearchParams(obj).toString();}
|
|
569
|
-
function parseQuery(str){return Object.fromEntries(new URLSearchParams(str));}
|
|
570
|
-
const storage={get(key,fallback=null){try{const raw=localStorage.getItem(key);return raw!==null?JSON.parse(raw):fallback;}catch{return fallback;}},set(key,value){localStorage.setItem(key,JSON.stringify(value));},remove(key){localStorage.removeItem(key);},clear(){localStorage.clear();},};const session={get(key,fallback=null){try{const raw=sessionStorage.getItem(key);return raw!==null?JSON.parse(raw):fallback;}catch{return fallback;}},set(key,value){sessionStorage.setItem(key,JSON.stringify(value));},remove(key){sessionStorage.removeItem(key);},clear(){sessionStorage.clear();},};class EventBus{constructor(){this._handlers=new Map();}
|
|
571
|
-
on(event,fn){if(!this._handlers.has(event))this._handlers.set(event,new Set());this._handlers.get(event).add(fn);return()=>this.off(event,fn);}
|
|
572
|
-
off(event,fn){this._handlers.get(event)?.delete(fn);}
|
|
573
|
-
emit(event,...args){this._handlers.get(event)?.forEach(fn=>fn(...args));}
|
|
574
|
-
once(event,fn){const wrapper=(...args)=>{fn(...args);this.off(event,wrapper);};return this.on(event,wrapper);}
|
|
575
|
-
clear(){this._handlers.clear();}}
|
|
576
|
-
const bus=new EventBus();function range(startOrEnd,end,step){let s,e,st;if(end===undefined){s=0;e=startOrEnd;st=1;}
|
|
577
|
-
else{s=startOrEnd;e=end;st=step!==undefined?step:1;}
|
|
578
|
-
if(st===0)return[];const result=[];if(st>0){for(let i=s;i<e;i+=st)result.push(i);}
|
|
579
|
-
else{for(let i=s;i>e;i+=st)result.push(i);}
|
|
580
|
-
return result;}
|
|
581
|
-
function unique(arr,keyFn){if(!keyFn)return[...new Set(arr)];const seen=new Set();return arr.filter(item=>{const k=keyFn(item);if(seen.has(k))return false;seen.add(k);return true;});}
|
|
582
|
-
function chunk(arr,size){const result=[];for(let i=0;i<arr.length;i+=size)result.push(arr.slice(i,i+size));return result;}
|
|
583
|
-
function groupBy(arr,keyFn){const result={};for(const item of arr){const k=keyFn(item);(result[k]??=[]).push(item);}
|
|
584
|
-
return result;}
|
|
585
|
-
function pick(obj,keys){const result={};for(const k of keys){if(k in obj)result[k]=obj[k];}
|
|
586
|
-
return result;}
|
|
587
|
-
function omit(obj,keys){const exclude=new Set(keys);const result={};for(const k of Object.keys(obj)){if(!exclude.has(k))result[k]=obj[k];}
|
|
588
|
-
return result;}
|
|
589
|
-
function getPath(obj,path,fallback){const keys=path.split('.');let cur=obj;for(const k of keys){if(cur==null||typeof cur!=='object')return fallback;cur=cur[k];}
|
|
590
|
-
return cur===undefined?fallback:cur;}
|
|
591
|
-
function setPath(obj,path,value){const keys=path.split('.');let cur=obj;for(let i=0;i<keys.length-1;i++){const k=keys[i];if(_UNSAFE_KEYS.has(k))return obj;if(cur[k]==null||typeof cur[k]!=='object')cur[k]={};cur=cur[k];}
|
|
592
|
-
const lastKey=keys[keys.length-1];if(_UNSAFE_KEYS.has(lastKey))return obj;cur[lastKey]=value;return obj;}
|
|
593
|
-
function isEmpty(val){if(val==null)return true;if(typeof val==='string'||Array.isArray(val))return val.length===0;if(val instanceof Map||val instanceof Set)return val.size===0;if(typeof val==='object')return Object.keys(val).length===0;return false;}
|
|
594
|
-
function capitalize(str){if(!str)return'';return str[0].toUpperCase()+str.slice(1).toLowerCase();}
|
|
595
|
-
function truncate(str,maxLen,suffix='…'){if(str.length<=maxLen)return str;const end=Math.max(0,maxLen-suffix.length);return str.slice(0,end)+suffix;}
|
|
596
|
-
function clamp(val,min,max){return val<min?min:val>max?max:val;}
|
|
597
|
-
function memoize(fn,keyFnOrOpts){let keyFn,maxSize=0;if(typeof keyFnOrOpts==='function')keyFn=keyFnOrOpts;else if(keyFnOrOpts&&typeof keyFnOrOpts==='object')maxSize=keyFnOrOpts.maxSize||0;const cache=new Map();const memoized=(...args)=>{const key=keyFn?keyFn(...args):args[0];if(cache.has(key)){const value=cache.get(key);cache.delete(key);cache.set(key,value);return value;}
|
|
598
|
-
const result=fn(...args);cache.set(key,result);if(maxSize>0&&cache.size>maxSize){cache.delete(cache.keys().next().value);}
|
|
599
|
-
return result;};memoized.clear=()=>cache.clear();return memoized;}
|
|
600
|
-
function retry(fn,opts={}){const{attempts=3,delay=1000,backoff=1}=opts;return new Promise((resolve,reject)=>{let attempt=0,currentDelay=delay;const tryOnce=()=>{attempt++;fn(attempt).then(resolve,(err)=>{if(attempt>=attempts)return reject(err);const d=currentDelay;currentDelay*=backoff;setTimeout(tryOnce,d);});};tryOnce();});}
|
|
601
|
-
function timeout(promise,ms,message){let timer;const race=Promise.race([promise,new Promise((_,reject)=>{timer=setTimeout(()=>reject(new Error(message||`Timed out after ${ms}ms`)),ms);})]);return race.finally(()=>clearTimeout(timer));}
|
|
602
|
-
function $(selector,context){if(typeof selector==='function'){query.ready(selector);return;}
|
|
603
|
-
return query(selector,context);}
|
|
604
|
-
$.id=query.id;$.class=query.class;$.classes=query.classes;$.tag=query.tag;Object.defineProperty($,'name',{value:query.name,writable:true,configurable:true});$.children=query.children;$.qs=query.qs;$.qsa=query.qsa;$.all=function(selector,context){return queryAll(selector,context);};$.create=query.create;$.ready=query.ready;$.on=query.on;$.off=query.off;$.fn=query.fn;$.reactive=reactive;$.Signal=Signal;$.signal=signal;$.computed=computed;$.effect=effect;$.batch=batch;$.untracked=untracked;$.component=component;$.mount=mount;$.mountAll=mountAll;$.getInstance=getInstance;$.destroy=destroy;$.components=getRegistry;$.prefetch=prefetch;$.style=style;$.morph=morph;$.morphElement=morphElement;$.safeEval=safeEval;$.router=createRouter;$.getRouter=getRouter;$.matchRoute=matchRoute;$.store=createStore;$.getStore=getStore;$.http=http;$.get=http.get;$.post=http.post;$.put=http.put;$.patch=http.patch;$.delete=http.delete;$.head=http.head;$.debounce=debounce;$.throttle=throttle;$.pipe=pipe;$.once=once;$.sleep=sleep;$.escapeHtml=escapeHtml;$.stripHtml=stripHtml;$.html=html;$.trust=trust;$.TrustedHTML=TrustedHTML;$.uuid=uuid;$.camelCase=camelCase;$.kebabCase=kebabCase;$.deepClone=deepClone;$.deepMerge=deepMerge;$.isEqual=isEqual;$.param=param;$.parseQuery=parseQuery;$.storage=storage;$.session=session;$.EventBus=EventBus;$.bus=bus;$.range=range;$.unique=unique;$.chunk=chunk;$.groupBy=groupBy;$.pick=pick;$.omit=omit;$.getPath=getPath;$.setPath=setPath;$.isEmpty=isEmpty;$.capitalize=capitalize;$.truncate=truncate;$.clamp=clamp;$.memoize=memoize;$.retry=retry;$.timeout=timeout;$.onError=onError;$.ZQueryError=ZQueryError;$.ErrorCode=ErrorCode;$.guardCallback=guardCallback;$.guardAsync=guardAsync;$.validate=validate;$.formatError=formatError;$.version='1.0.9';$.libSize='~108 KB';$.unitTests={"passed":1965,"failed":0,"total":1965,"suites":525,"duration":3752,"ok":true};$.meta={};$.noConflict=()=>{if(typeof window!=='undefined'&&window.$===$){delete window.$;}
|
|
605
|
-
return $;};if(typeof window!=='undefined'){window.$=$;window.zQuery=$;}
|
|
606
|
-
$;})(typeof window!=='undefined'?window:globalThis);
|
|
7
|
+
(function(bs){"use strict";const S=Object.freeze({REACTIVE_CALLBACK:"ZQ_REACTIVE_CALLBACK",SIGNAL_CALLBACK:"ZQ_SIGNAL_CALLBACK",EFFECT_EXEC:"ZQ_EFFECT_EXEC",EXPR_PARSE:"ZQ_EXPR_PARSE",EXPR_EVAL:"ZQ_EXPR_EVAL",EXPR_UNSAFE_ACCESS:"ZQ_EXPR_UNSAFE_ACCESS",COMP_INVALID_NAME:"ZQ_COMP_INVALID_NAME",COMP_NOT_FOUND:"ZQ_COMP_NOT_FOUND",COMP_MOUNT_TARGET:"ZQ_COMP_MOUNT_TARGET",COMP_RENDER:"ZQ_COMP_RENDER",COMP_LIFECYCLE:"ZQ_COMP_LIFECYCLE",COMP_RESOURCE:"ZQ_COMP_RESOURCE",COMP_DIRECTIVE:"ZQ_COMP_DIRECTIVE",ROUTER_LOAD:"ZQ_ROUTER_LOAD",ROUTER_GUARD:"ZQ_ROUTER_GUARD",ROUTER_RESOLVE:"ZQ_ROUTER_RESOLVE",STORE_ACTION:"ZQ_STORE_ACTION",STORE_MIDDLEWARE:"ZQ_STORE_MIDDLEWARE",STORE_SUBSCRIBE:"ZQ_STORE_SUBSCRIBE",HTTP_REQUEST:"ZQ_HTTP_REQUEST",HTTP_TIMEOUT:"ZQ_HTTP_TIMEOUT",HTTP_INTERCEPTOR:"ZQ_HTTP_INTERCEPTOR",HTTP_PARSE:"ZQ_HTTP_PARSE",SSR_RENDER:"ZQ_SSR_RENDER",SSR_COMPONENT:"ZQ_SSR_COMPONENT",SSR_HYDRATION:"ZQ_SSR_HYDRATION",SSR_PAGE:"ZQ_SSR_PAGE",INVALID_ARGUMENT:"ZQ_INVALID_ARGUMENT"});class I extends Error{constructor(e,t,n={},r){super(t),this.name="ZQueryError",this.code=e,this.context=n,r&&(this.cause=r)}}let Y=[];function Nt(s){return s===null?(Y=[],()=>{}):typeof s!="function"?()=>{}:(Y.push(s),()=>{const e=Y.indexOf(s);e!==-1&&Y.splice(e,1)})}function C(s,e,t={},n){const r=n instanceof I?n:new I(s,e,t,n);for(const i of Y)try{i(r)}catch{}console.error(`[zQuery ${s}] ${e}`,t,n||"")}function Pt(s,e,t={}){return(...n)=>{try{return s(...n)}catch(r){C(e,r.message||"Callback error",t,r)}}}function Bt(s,e,t){if(s==null)throw new I(S.INVALID_ARGUMENT,`"${e}" is required but got ${s}`);if(t&&typeof s!==t)throw new I(S.INVALID_ARGUMENT,`"${e}" must be a ${t}, got ${typeof s}`)}function Qe(s){const e=s instanceof I;return{code:e?s.code:"",type:e?"ZQueryError":s.name||"Error",message:s.message||"Unknown error",context:e?s.context:{},stack:s.stack||"",cause:s.cause?Qe(s.cause):null}}function Ut(s,e,t={}){return async(...n)=>{try{return await s(...n)}catch(r){C(e,r.message||"Async callback error",t,r)}}}class E extends I{constructor(e,t={}){const n=t.code||"ZQ_WEBRTC",r=t.context||{};super(n,e,r,t.cause),this.name="WebRtcError"}}class P extends E{constructor(e,t={}){super(e,{code:t.code||"ZQ_WEBRTC_SIGNALING",context:t.context,cause:t.cause}),this.name="SignalingError"}}class U extends E{constructor(e,t={}){super(e,{code:t.code||"ZQ_WEBRTC_ICE",context:t.context,cause:t.cause}),this.name="IceError"}}class B extends E{constructor(e,t={}){super(e,{code:t.code||"ZQ_WEBRTC_SDP",context:t.context,cause:t.cause}),this.name="SdpError"}}class M extends E{constructor(e,t={}){super(e,{code:t.code||"ZQ_WEBRTC_TURN",context:t.context,cause:t.cause}),this.name="TurnError"}}class L extends E{constructor(e,t={}){super(e,{code:t.code||"ZQ_WEBRTC_E2EE",context:t.context,cause:t.cause}),this.name="E2eeError"}}class O extends E{constructor(e,t={}){super(e,{code:t.code||"ZQ_WEBRTC_SFU",context:t.context,cause:t.cause}),this.name="SfuError"}}const Mt=65536,$e="UDP/TLS/RTP/SAVPF",Ss=Object.freeze(["sendrecv","sendonly","recvonly","inactive"]);function ge(s,e={}){if(typeof s!="string")throw new B("parseSdp: input must be a string",{code:"ZQ_WEBRTC_SDP_PARSE"});const t=typeof e.maxBytes=="number"?e.maxBytes:Mt;if(s.length>t)throw new B(`parseSdp: payload exceeds ${t} bytes`,{code:"ZQ_WEBRTC_SDP_TOO_LARGE"});if(s.length===0)throw new B("parseSdp: empty input",{code:"ZQ_WEBRTC_SDP_PARSE"});const n=s.replace(/\r\n/g,`
|
|
8
|
+
`).split(`
|
|
9
|
+
`).filter(a=>a.length>0);if(n.length===0)throw new B("parseSdp: no non-empty lines",{code:"ZQ_WEBRTC_SDP_PARSE"});const r={version:0,origin:null,sessionName:"",attributes:[],media:[]};let i=r,o=null;for(let a=0;a<n.length;a++){const c=n[a],u=c.indexOf("=");if(u<1)throw new B(`parseSdp: malformed line ${a+1}`,{code:"ZQ_WEBRTC_SDP_PARSE",context:{line:a+1}});const l=c.slice(0,u),p=c.slice(u+1);if(a===0&&l!=="v")throw new B("parseSdp: SDP must start with v=",{code:"ZQ_WEBRTC_SDP_PARSE",context:{line:1}});switch(l){case"v":r.version=Number(p);break;case"o":r.origin=It(p);break;case"s":r.sessionName=p;break;case"m":{o=Dt(p),r.media.push(o),i=o;break}case"a":Wt(i,p);break;default:break}}return r}function Ze(s){const e=ge(s);if(e.media.length===0)throw new B("validateSdp: SDP has no m-lines",{code:"ZQ_WEBRTC_SDP_NO_MEDIA"});const t=Ee(e.attributes,"ice-ufrag"),n=Ee(e.attributes,"ice-pwd"),r=Ee(e.attributes,"fingerprint");for(let i=0;i<e.media.length;i++){const o=e.media[i];if(o.port===0)continue;if(o.proto!==$e)throw new B(`validateSdp: m-line ${i} proto "${o.proto}" must be "${$e}"`,{code:"ZQ_WEBRTC_SDP_BAD_PROTO",context:{index:i,proto:o.proto}});const a=o.iceUfrag||t,c=o.icePwd||n,u=o.fingerprint||r;if(!a)throw new B(`validateSdp: m-line ${i} missing ice-ufrag`,{code:"ZQ_WEBRTC_SDP_NO_ICE_UFRAG",context:{index:i}});if(!c)throw new B(`validateSdp: m-line ${i} missing ice-pwd`,{code:"ZQ_WEBRTC_SDP_NO_ICE_PWD",context:{index:i}});if(!u)throw new B(`validateSdp: m-line ${i} missing fingerprint`,{code:"ZQ_WEBRTC_SDP_NO_FINGERPRINT",context:{index:i}})}return e}function It(s){const e=s.split(/\s+/);return e.length<6?null:{username:e[0],sessionId:e[1],sessionVersion:Number(e[2]),netType:e[3],addrType:e[4],address:e[5]}}function Dt(s){const e=s.split(/\s+/);return{kind:e[0]||"",port:Number(e[1])||0,proto:e[2]||"",fmts:e.slice(3),mid:void 0,iceUfrag:void 0,icePwd:void 0,fingerprint:void 0,setup:void 0,direction:void 0,rtcpMux:!1,candidates:[],rtpmaps:[],attributes:[]}}function Wt(s,e){const t=e.indexOf(":"),n=t===-1?e:e.slice(0,t),r=t===-1?"":e.slice(t+1);switch(s.attributes.push({key:n,value:r}),n){case"mid":"mid"in s&&(s.mid=r);break;case"ice-ufrag":"iceUfrag"in s&&(s.iceUfrag=r);break;case"ice-pwd":"icePwd"in s&&(s.icePwd=r);break;case"setup":"setup"in s&&(s.setup=r);break;case"rtcp-mux":"rtcpMux"in s&&(s.rtcpMux=!0);break;case"fingerprint":{const i=r.indexOf(" "),o=i===-1?{algorithm:r,value:""}:{algorithm:r.slice(0,i),value:r.slice(i+1)};"fingerprint"in s&&(s.fingerprint=o);break}case"candidate":"candidates"in s&&s.candidates.push(`candidate:${r}`);break;case"rtpmap":{if(!("rtpmaps"in s))break;const i=r.indexOf(" ");if(i===-1)break;const o=Number(r.slice(0,i)),a=r.slice(i+1).split("/");s.rtpmaps.push({payload:o,codec:a[0]||"",clockRate:Number(a[1])||0,channels:a[2]?Number(a[2]):void 0});break}case"sendrecv":case"sendonly":case"recvonly":case"inactive":"direction"in s&&(s.direction=n);break;default:break}}function Ee(s,e){for(let t=0;t<s.length;t++)if(s[t].key===e)return s[t].value||!0}const zt=Object.freeze(["host","srflx","prflx","relay"]),vs=Object.freeze(["active","passive","so"]);function be(s){if(typeof s!="string")throw new U("parseCandidate: input must be a string",{code:"ZQ_WEBRTC_ICE_PARSE"});let e=s.trim();if(e.indexOf("a=")===0&&(e=e.slice(2)),e.indexOf("candidate:")!==0)throw new U('parseCandidate: missing "candidate:" prefix',{code:"ZQ_WEBRTC_ICE_PARSE",context:{candidate:s}});e=e.slice(10);const t=e.split(/\s+/);if(t.length<8)throw new U("parseCandidate: too few tokens",{code:"ZQ_WEBRTC_ICE_PARSE",context:{candidate:s}});const n=t[0],r=t[1],i=t[2],o=t[3],a=t[4],c=t[5],u=t[6],l=t[7],p=t.slice(8);if(u!=="typ")throw new U('parseCandidate: expected "typ" keyword',{code:"ZQ_WEBRTC_ICE_PARSE",context:{candidate:s}});if(zt.indexOf(l)===-1)throw new U(`parseCandidate: unknown type "${l}"`,{code:"ZQ_WEBRTC_ICE_PARSE",context:{candidate:s}});const h=Number(r),d=Number(o),_=Number(c);if(!Number.isInteger(h)||h<0)throw new U("parseCandidate: invalid component",{code:"ZQ_WEBRTC_ICE_PARSE",context:{candidate:s}});if(!Number.isFinite(d))throw new U("parseCandidate: invalid priority",{code:"ZQ_WEBRTC_ICE_PARSE",context:{candidate:s}});if(!Number.isInteger(_)||_<0||_>65535)throw new U("parseCandidate: invalid port",{code:"ZQ_WEBRTC_ICE_PARSE",context:{candidate:s}});const w={foundation:n,component:h,transport:i.toLowerCase(),priority:d,address:a,port:_,type:l,extensions:{}};for(let m=0;m<p.length-1;m+=2){const v=p[m],N=p[m+1];v==="raddr"?w.relatedAddress=N:v==="rport"?w.relatedPort=Number(N):v==="tcptype"?w.tcpType=N:w.extensions[v]=N}return w}function He(s){if(!s||typeof s!="object")throw new U("stringifyCandidate: input must be an object",{code:"ZQ_WEBRTC_ICE_SERIALIZE"});const e=["foundation","component","transport","priority","address","port","type"];for(const n of e)if(s[n]===void 0||s[n]===null)throw new U(`stringifyCandidate: missing "${n}"`,{code:"ZQ_WEBRTC_ICE_SERIALIZE"});let t=`candidate:${s.foundation} ${s.component} ${s.transport} ${s.priority} ${s.address} ${s.port} typ ${s.type}`;if(s.relatedAddress!==void 0&&(t+=` raddr ${s.relatedAddress}`),s.relatedPort!==void 0&&(t+=` rport ${s.relatedPort}`),s.tcpType!==void 0&&(t+=` tcptype ${s.tcpType}`),s.extensions)for(const n of Object.keys(s.extensions))t+=` ${n} ${s.extensions[n]}`;return t}function ie(s){if(typeof s!="string")return!1;const e=s.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);if(!e)return!1;for(let t=1;t<=4;t++)if(Number(e[t])>255)return!1;return!0}function oe(s){return typeof s!="string"?!1:s.indexOf(":")!==-1&&/^[0-9a-fA-F:]+$/.test(s)}function Se(s){if(ie(s)){const e=s.split(".").map(Number),t=e[0],n=e[1];return t===10||t===172&&n>=16&&n<=31||t===192&&n===168||t===100&&n>=64&&n<=127}if(oe(s)){const e=s.toLowerCase().split(":")[0];return e.length===0?!1:(parseInt(e,16)&65024)===64512}return!1}function ve(s){return ie(s)?s.indexOf("127.")===0:oe(s)?s==="::1"||/^0*:0*:0*:0*:0*:0*:0*:0*1$/.test(s):!1}function Te(s){if(ie(s))return s.indexOf("169.254.")===0;if(oe(s)){const e=s.toLowerCase().split(":")[0];return e.length===0?!1:(parseInt(e,16)&65472)===65152}return!1}function Ce(s){return typeof s!="string"||ie(s)||oe(s)?!1:s.toLowerCase().endsWith(".local")}function Ke(s,e={}){if(!Array.isArray(s))return[];const t=!!e.blockPrivate,n=!!e.blockLoopback,r=!!e.blockLinkLocal,i=!!e.blockMdns,o=!!e.blockTcp,a=e.allowedTypes||null,c=typeof e.maxCandidates=="number"?e.maxCandidates:1/0,u=typeof e.predicate=="function"?e.predicate:null,l=[];for(const p of s){if(l.length>=c)break;const h=typeof p=="string";let d;if(h)try{d=be(p)}catch{continue}else d=p;d&&(a&&a.indexOf(d.type)===-1||o&&d.transport==="tcp"||i&&Ce(d.address)||t&&Se(d.address)||n&&ve(d.address)||r&&Te(d.address)||u&&!u(d)||l.push(p))}return l}const qt=250,Ft=8e3,jt=10,Qt=200,$t=10,Ge=1e3;class Ae{constructor(e,t={}){if(typeof e!="string"||e.length===0)throw new P("SignalingClient requires a non-empty url",{code:"ZQ_WEBRTC_SIGNALING_BAD_URL"});const n=t.reconnect===!1?null:Object.assign({baseMs:qt,capMs:Ft,maxRetries:jt},t.reconnect||{});this.url=e,this.options={reconnect:n,iceFlushMs:t.iceFlushMs||Qt,iceBatch:t.iceBatch||$t,WebSocket:t.WebSocket||null},this.peerId=null,this.ws=null,this.connected=!1,this.closed=!1,this._attempts=0,this._listeners=new Map,this._iceQueue=[],this._iceTimer=null,this._reconnectTimer=null,this._helloReceived=!1}on(e,t){if(typeof t!="function")return()=>{};let n=this._listeners.get(e);return n||(n=new Set,this._listeners.set(e,n)),n.add(t),()=>this.off(e,t)}off(e,t){const n=this._listeners.get(e);n&&n.delete(t)}_emit(e,t){const n=this._listeners.get(e);if(!(!n||n.size===0))for(const r of[...n])try{r(t)}catch{}}connect(){return this.connected?Promise.resolve():(this.closed=!1,new Promise((e,t)=>{const n=()=>{this.off("open",n),this.off("error",r),e()},r=i=>{this._attempts===0&&(this.off("open",n),this.off("error",r),t(i))};this.on("open",n),this.on("error",r),this._open()}))}send(e,t={}){if(typeof e!="string"||e.length===0)throw new P("SignalingClient.send requires a frame type",{code:"ZQ_WEBRTC_SIGNALING_BAD_FRAME"});const n=Object.assign({type:e},t);if(e==="ice"){this._iceQueue.push(n),this._scheduleIceFlush();return}this._sendRaw(n)}close(){if(this.closed=!0,this._reconnectTimer&&(clearTimeout(this._reconnectTimer),this._reconnectTimer=null),this._iceTimer&&(clearTimeout(this._iceTimer),this._iceTimer=null),this._iceQueue.length=0,this.ws){try{this._sendRaw({type:"bye"})}catch{}try{this.ws.close(Ge,"client-bye")}catch{}}}_open(){const e=this.options.WebSocket||(typeof WebSocket!="undefined"?WebSocket:null);if(!e){const n=new P("No WebSocket implementation available (SSR? pass options.WebSocket)",{code:"ZQ_WEBRTC_SIGNALING_NO_WS"});this._emit("error",n);return}this._helloReceived=!1;let t;try{t=new e(this.url)}catch(n){const r=new P("Failed to construct WebSocket",{code:"ZQ_WEBRTC_SIGNALING_OPEN",cause:n});this._emit("error",r),this._scheduleReconnect();return}this.ws=t,t.onopen=()=>{this.connected=!0,this._attempts=0,this._emit("open",{url:this.url})},t.onmessage=n=>this._onMessage(n),t.onerror=n=>{const r=new P("WebSocket error",{code:"ZQ_WEBRTC_SIGNALING_WS_ERROR",context:{event:n}});this._emit("error",r)},t.onclose=n=>{this.connected=!1,this.ws=null;const r={code:n&&n.code,reason:n&&n.reason,wasClean:n&&n.wasClean};this._emit("close",r),!this.closed&&r.code!==Ge&&this._scheduleReconnect()}}_onMessage(e){let t;try{t=JSON.parse(e.data)}catch(n){this._emit("error",new P("Malformed JSON from server",{code:"ZQ_WEBRTC_SIGNALING_BAD_JSON",cause:n}));return}if(!t||typeof t!="object"||typeof t.type!="string"){this._emit("error",new P('Frame missing required "type" field',{code:"ZQ_WEBRTC_SIGNALING_BAD_FRAME",context:{frame:t}}));return}if(!this._helloReceived){if(t.type!=="hello"||typeof t.peerId!="string"){this._emit("error",new P("First frame must be a hello with peerId",{code:"ZQ_WEBRTC_SIGNALING_NO_HELLO",context:{frame:t}}));return}this._helloReceived=!0,this.peerId=t.peerId}this._emit(t.type,t)}_sendRaw(e){if(!this.ws||!this.connected){this._emit("error",new P("Cannot send frame: socket not open",{code:"ZQ_WEBRTC_SIGNALING_NOT_OPEN",context:{type:e&&e.type}}));return}try{this.ws.send(JSON.stringify(e))}catch(t){this._emit("error",new P("socket.send threw",{code:"ZQ_WEBRTC_SIGNALING_SEND_FAIL",cause:t}))}}_scheduleIceFlush(){this._iceTimer||(this._iceTimer=setTimeout(()=>{this._iceTimer=null,this._flushIce(),this._iceQueue.length>0&&this._scheduleIceFlush()},this.options.iceFlushMs))}_flushIce(){const e=this._iceQueue.splice(0,this.options.iceBatch);for(const t of e)this._sendRaw(t)}_scheduleReconnect(){const e=this.options.reconnect;if(!e)return;if(this._attempts>=e.maxRetries){this._emit("error",new P("Max reconnect attempts exceeded",{code:"ZQ_WEBRTC_SIGNALING_GIVEUP",context:{attempts:this._attempts}})),this.closed=!0;return}const t=this._attempts++,n=Math.min(e.capMs,e.baseMs*Math.pow(2,t));this._emit("reconnect",{attempt:t+1,delayMs:n}),this._reconnectTimer=setTimeout(()=>{this._reconnectTimer=null,this.closed||this._open()},n)}}const Zt=30;class Re{constructor(e,t,n={}){if(typeof e!="string"||e.length===0)throw new E("Peer requires a non-empty peerId",{code:"ZQ_WEBRTC_PEER_BAD_ID"});if(!t||typeof t.send!="function"||typeof t.on!="function")throw new E("Peer requires a SignalingClient-like object",{code:"ZQ_WEBRTC_PEER_BAD_SIGNALING"});const r=n.RTCPeerConnection||typeof globalThis!="undefined"&&globalThis.RTCPeerConnection||null;if(!r)throw new E("RTCPeerConnection is not available in this environment",{code:"ZQ_WEBRTC_NO_RTC"});const i=Object.assign({iceServers:n.iceServers||[]},n.rtcConfig||{});this.id=e,this.signaling=t,this.polite=!!n.polite,this.pc=new r(i),this.closed=!1,this.makingOffer=!1,this.ignoreOffer=!1,this.srdAnswerPending=!1,this._listeners=new Map,this._maxIceCandidates=n.maxIceCandidates||Zt,this._sentCandidates=0,this._sigUnsub=[],this._attachPc(),this._attachSignaling()}on(e,t){if(typeof t!="function")return()=>{};let n=this._listeners.get(e);return n||(n=new Set,this._listeners.set(e,n)),n.add(t),()=>this.off(e,t)}off(e,t){const n=this._listeners.get(e);n&&n.delete(t)}_emit(e,t){const n=this._listeners.get(e);if(!(!n||n.size===0))for(const r of[...n])try{r(t)}catch{}}addTrack(e,...t){return this.pc.addTrack(e,...t)}removeTrack(e){return this.pc.removeTrack(e)}createDataChannel(e,t){return this.pc.createDataChannel(e,t)}restartIce(){if(!this.closed)try{this.pc.restartIce()}catch(e){this._emit("error",new U(e.message||"restartIce failed",{code:"ZQ_WEBRTC_ICE_RESTART_FAILED",cause:e}))}}close(){if(!this.closed){this.closed=!0;for(const e of this._sigUnsub)try{e()}catch{}this._sigUnsub.length=0;try{this.pc.close()}catch{}this._emit("close")}}_attachPc(){this.pc.onnegotiationneeded=async()=>{if(!this.closed)try{this.makingOffer=!0,await this.pc.setLocalDescription();const e=this.pc.localDescription;if(!e||!e.sdp)return;this.signaling.send("offer",{to:this.id,sdp:e.sdp})}catch(e){this._emit("error",new B(e.message||"offer failed",{code:"ZQ_WEBRTC_SDP_OFFER_FAILED",cause:e}))}finally{this.makingOffer=!1}},this.pc.onicecandidate=e=>{if(this.closed)return;const t=e&&e.candidate;if(!t){this.signaling.send("ice",{to:this.id,candidate:null});return}const n=typeof t=="string"?t:t.candidate;n&&n.indexOf(".local")===-1&&(this._sentCandidates>=this._maxIceCandidates||(this._sentCandidates++,this.signaling.send("ice",{to:this.id,candidate:n})))},this.pc.ontrack=e=>{this.closed||this._emit("track",e)},this.pc.ondatachannel=e=>{this.closed||this._emit("datachannel",e)},this.pc.onconnectionstatechange=()=>{if(this.closed)return;const e=this.pc.connectionState;if(this._emit("connectionstatechange",e),e==="failed")try{this.pc.restartIce()}catch{}}}_attachSignaling(){const e=t=>n=>{this.closed||!n||n.from!==this.id||t(n)};this._sigUnsub.push(this.signaling.on("offer",e(t=>this._onRemoteDescription("offer",t.sdp))),this.signaling.on("answer",e(t=>this._onRemoteDescription("answer",t.sdp))),this.signaling.on("ice",e(t=>this._onRemoteCandidate(t.candidate))))}async _onRemoteDescription(e,t){const n=typeof t=="string"?{type:e,sdp:t}:t;try{const r=!this.makingOffer&&(this.pc.signalingState==="stable"||this.srdAnswerPending),i=n.type==="offer"&&!r;if(this.ignoreOffer=!this.polite&&i,this.ignoreOffer)return;if(this.srdAnswerPending=n.type==="answer",await this.pc.setRemoteDescription(n),this.srdAnswerPending=!1,n.type==="offer"){await this.pc.setLocalDescription();const o=this.pc.localDescription;o&&o.sdp&&this.signaling.send("answer",{to:this.id,sdp:o.sdp})}}catch(r){this._emit("error",new B(r.message||"setRemoteDescription failed",{code:"ZQ_WEBRTC_SDP_APPLY_FAILED",cause:r}))}}async _onRemoteCandidate(e){try{if(e==null){await this.pc.addIceCandidate(null);return}await this.pc.addIceCandidate({candidate:e})}catch(t){if(this.ignoreOffer)return;this._emit("error",new U(t.message||"addIceCandidate failed",{code:"ZQ_WEBRTC_ICE_ADD_FAILED",cause:t}))}}}class K{constructor({id:e,self:t,signaling:n,peerOptions:r={}}){if(typeof e!="string"||e.length===0)throw new E("Room: id must be a non-empty string",{code:"ZQ_WEBRTC_ROOM_BAD_ID"});if(typeof t!="string"||t.length===0)throw new E("Room: self must be a non-empty string",{code:"ZQ_WEBRTC_ROOM_BAD_SELF"});if(!n||typeof n.send!="function")throw new E("Room: signaling must be a SignalingClient",{code:"ZQ_WEBRTC_ROOM_BAD_SIGNALING"});this.id=e,this.self=t,this.signaling=n,this.peerOptions=r,this.closed=!1,this.peers=$(new Map),this.localTracks=$([]),this._listeners=new Map,this._publishedTracks=[],this._peerSenders=new Map,this._channels=new Map,this._signalingUnsubs=[],this._attachSignaling()}_addPeer(e){if(this.closed||e===this.self)return;const t=this.peers.peek();if(t.has(e))return;const n=this.self>e,r=new Re(e,this.signaling,Object.assign({polite:n},this.peerOptions)),i={id:e,peer:r,pc:r.pc,stream:Kt(),audio:!1,video:!1,connection:"new"};r.on("track",a=>{const c=a&&a.streams&&a.streams[0];c&&c!==i.stream?i.stream=c:a&&a.track&&typeof i.stream.addTrack=="function"&&i.stream.addTrack(a.track),a&&a.track&&(a.track.kind==="audio"&&(i.audio=!0),a.track.kind==="video"&&(i.video=!0)),this._touchPeer(e)}),r.on("connectionstatechange",a=>{i.connection=a,this._touchPeer(e),a==="failed"&&this._emit("error",new E(`Room: peer "${e}" connection failed`,{code:"ZQ_WEBRTC_PEER_FAILED",context:{peerId:e}}))}),r.on("datachannel",a=>{const c=a&&a.channel;if(!c)return;const u=this._channels.get(c.label);u&&u._adoptIncoming(e,c)}),r.on("error",a=>this._emit("error",a));const o=new Map(t);if(o.set(e,i),this.peers.value=o,this._publishedTracks.length>0){const a=new Map;for(const{track:c,stream:u}of this._publishedTracks)try{const l=r.addTrack(c,u);a.set(c,l)}catch(l){this._emit("error",l)}this._peerSenders.set(e,a)}for(const a of this._channels.values())try{a._openOnPeer(e,r)}catch(c){this._emit("error",c)}this._emit("peer-joined",i)}_removePeer(e){const t=this.peers.peek(),n=t.get(e);if(!n)return;try{n.peer.close()}catch{}for(const i of this._channels.values())i._dropPeer(e);this._peerSenders.delete(e);const r=new Map(t);r.delete(e),this.peers.value=r,this._emit("peer-left",n)}_touchPeer(e){const t=this.peers.peek();t.has(e)&&(this.peers.value=new Map(t))}async publish(e){if(this.closed)throw new E("Room.publish: room is closed",{code:"ZQ_WEBRTC_ROOM_CLOSED"});if(!e||typeof e.getTracks!="function")throw new E("Room.publish: stream must be a MediaStream",{code:"ZQ_WEBRTC_ROOM_BAD_STREAM"});const t=e.getTracks();for(const n of t)if(!this._publishedTracks.some(r=>r.track===n)){this._publishedTracks.push({track:n,stream:e});for(const[r,i]of this.peers.peek()){const o=this._peerSenders.get(r)||new Map;try{const a=i.peer.addTrack(n,e);o.set(n,a)}catch(a){this._emit("error",a)}this._peerSenders.set(r,o)}}this.localTracks.value=this._publishedTracks.map(n=>n.track)}async unpublish(e){if(this.closed)return;if(!e||typeof e.getTracks!="function")throw new E("Room.unpublish: stream must be a MediaStream",{code:"ZQ_WEBRTC_ROOM_BAD_STREAM"});const t=e.getTracks();for(const n of t){const r=this._publishedTracks.findIndex(i=>i.track===n);if(r!==-1){this._publishedTracks.splice(r,1);for(const[i,o]of this.peers.peek()){const a=this._peerSenders.get(i);if(!a)continue;const c=a.get(n);if(c){try{o.peer.removeTrack(c)}catch(u){this._emit("error",u)}a.delete(n)}}}}this.localTracks.value=this._publishedTracks.map(n=>n.track)}dataChannel(e,t){if(this.closed)throw new E("Room.dataChannel: room is closed",{code:"ZQ_WEBRTC_ROOM_CLOSED"});if(typeof e!="string"||e.length===0)throw new E("Room.dataChannel: label must be a non-empty string",{code:"ZQ_WEBRTC_ROOM_BAD_LABEL"});const n=this._channels.get(e);if(n)return n;const r=new Ht(e,t||{});this._channels.set(e,r);for(const[i,o]of this.peers.peek())try{r._openOnPeer(i,o.peer)}catch(a){this._emit("error",a)}return r}async leave(){if(!this.closed){this.closed=!0;for(const e of this._signalingUnsubs)try{e()}catch{}this._signalingUnsubs=[];for(const e of this._channels.values())e._closeAll();this._channels.clear();for(const[,e]of this.peers.peek())try{e.peer.close()}catch{}this.peers.value=new Map;try{this.signaling.send("leave",{})}catch{}this._listeners.clear()}}on(e,t){if(typeof t!="function")return()=>{};let n=this._listeners.get(e);return n||(n=new Set,this._listeners.set(e,n)),n.add(t),()=>this.off(e,t)}off(e,t){const n=this._listeners.get(e);n&&n.delete(t)}_emit(e,t){const n=this._listeners.get(e);if(n)for(const r of[...n])try{r(t)}catch{}}_attachSignaling(){this._signalingUnsubs.push(this.signaling.on("peer-joined",e=>{e&&typeof e.id=="string"&&this._addPeer(e.id)})),this._signalingUnsubs.push(this.signaling.on("peer-left",e=>{e&&typeof e.id=="string"&&this._removePeer(e.id)})),this._signalingUnsubs.push(this.signaling.on("mute",e=>{this._emit("mute",e)})),this._signalingUnsubs.push(this.signaling.on("unmute",e=>{this._emit("unmute",e)}))}}class Ht{constructor(e,t){this.label=e,this.opts=t,this.closed=!1,this._byPeer=new Map,this._onMessage=new Set,this._onOpen=new Set}_openOnPeer(e,t){if(this.closed||this._byPeer.has(e))return;const n=t.createDataChannel(this.label,this.opts);this._attach(e,n)}_adoptIncoming(e,t){this.closed||this._byPeer.has(e)||this._attach(e,t)}_attach(e,t){this._byPeer.set(e,t);const n=()=>{for(const i of[...this._onOpen])try{i(e)}catch{}},r=i=>{const o=i&&"data"in i?i.data:i;for(const a of[...this._onMessage])try{a(o,e)}catch{}};typeof t.addEventListener=="function"?(t.addEventListener("open",n),t.addEventListener("message",r)):(t.onopen=n,t.onmessage=r)}_dropPeer(e){const t=this._byPeer.get(e);if(t)try{t.close()}catch{}this._byPeer.delete(e)}_closeAll(){this.closed=!0;for(const e of this._byPeer.values())try{e.close()}catch{}this._byPeer.clear(),this._onMessage.clear(),this._onOpen.clear()}send(e){if(!this.closed)for(const t of this._byPeer.values())try{t.send(e)}catch{}}on(e,t){if(typeof t!="function")return()=>{};const n=e==="open"?this._onOpen:this._onMessage;return n.add(t),()=>n.delete(t)}close(){this._closeAll()}}async function Je(s,e){if(typeof s!="string"||s.length===0)throw new E("webrtc.join: url must be a non-empty string",{code:"ZQ_WEBRTC_JOIN_BAD_URL"});if(!e||typeof e.room!="string"||e.room.length===0)throw new E("webrtc.join: opts.room must be a non-empty string",{code:"ZQ_WEBRTC_JOIN_BAD_ROOM"});const t={};e.reconnect!==void 0&&(t.reconnect=e.reconnect),e.WebSocket&&(t.WebSocket=e.WebSocket);const n=new Ae(s,t),r={};e.iceServers&&(r.iceServers=e.iceServers),e.RTCPeerConnection&&(r.RTCPeerConnection=e.RTCPeerConnection),e.polite!==void 0&&e.polite!=="auto"&&(r.polite=!!e.polite);const i=typeof e.signalingTimeoutMs=="number"?e.signalingTimeoutMs:15e3,o=Ve(n,"hello",i),a=Ve(n,"joined",i);a.catch(()=>{});try{await n.connect();const c=await o,u=c&&c.peerId;if(typeof u!="string"||u.length===0)throw new P("webrtc.join: hello frame missing peerId",{code:"ZQ_WEBRTC_JOIN_NO_PEER_ID"});n.send("join",{room:e.room,token:e.token});const l=await a,p=l&&Array.isArray(l.peers)?l.peers:[],h=new K({id:e.room,self:u,signaling:n,peerOptions:r});for(const d of p)h._addPeer(d);if(e.media){const d=e.media===!0?{audio:!0,video:!0}:e.media,_=e.navigator||(typeof navigator!="undefined"?navigator:null),w=_&&_.mediaDevices;if(!w||typeof w.getUserMedia!="function")throw new E("webrtc.join: navigator.mediaDevices.getUserMedia is unavailable",{code:"ZQ_WEBRTC_JOIN_NO_MEDIA_DEVICES"});const m=await w.getUserMedia(d);await h.publish(m)}return h}catch(c){try{n.close()}catch{}throw c instanceof E?c:new E(`webrtc.join: ${c&&c.message?c.message:"failed"}`,{code:"ZQ_WEBRTC_JOIN_FAILED",cause:c})}}function Ve(s,e,t){return new Promise((n,r)=>{let i=!1;const o=s.on(e,c=>{if(!i){i=!0;try{o()}catch{}clearTimeout(a),n(c)}}),a=setTimeout(()=>{if(!i){i=!0;try{o()}catch{}r(new P(`webrtc.join: timed out waiting for "${e}" after ${t}ms`,{code:"ZQ_WEBRTC_JOIN_TIMEOUT",context:{type:e,timeoutMs:t}}))}},t)})}function Kt(){if(typeof MediaStream=="function")try{return new MediaStream}catch{}const s=[];return{id:`stream_${Math.random().toString(36).slice(2,10)}`,getTracks:()=>s.slice(),addTrack:e=>{s.push(e)},removeTrack:e=>{const t=s.indexOf(e);t>=0&&s.splice(t,1)}}}function Ye(s,e){return s instanceof K?Promise.resolve(s):typeof s!="string"?Promise.reject(new E("useRoom: first argument must be a signaling URL or a Room",{code:"ZQ_WEBRTC_USE_ROOM_BAD_ARG"})):Je(s,e||{})}function Xe(s,e){if(!(s instanceof K))throw new E("usePeer: room must be a Room instance",{code:"ZQ_WEBRTC_USE_PEER_BAD_ROOM"});if(typeof e!="string"||e.length===0)throw new E("usePeer: peerId must be a non-empty string",{code:"ZQ_WEBRTC_USE_PEER_BAD_ID"});const t=$(null),n=()=>{const o=s.peers.peek().get(e)||null;o!==t.peek()&&(t.value=o)};n();const r=s.peers.subscribe(n);return{get value(){return t.value},peek(){return t.peek()},subscribe(i){return t.subscribe(i)},dispose(){try{r()}catch{}}}}function et(s){if(!s||!s.stream)throw new E("useTracks: peerInfo.stream is required",{code:"ZQ_WEBRTC_USE_TRACKS_BAD_PEER"});const e=$(st(s.stream)),t=()=>{const i=st(s.stream);e.value=i};let n=null;const r=s.stream;return typeof r.addEventListener=="function"&&(r.addEventListener("addtrack",t),r.addEventListener("removetrack",t),n=()=>{try{r.removeEventListener("addtrack",t)}catch{}try{r.removeEventListener("removetrack",t)}catch{}}),{get value(){return e.value},peek(){return e.peek()},subscribe(i){return e.subscribe(i)},refresh:t,dispose(){n&&n()}}}function tt(s,e,t){if(!(s instanceof K))throw new E("useDataChannel: room must be a Room instance",{code:"ZQ_WEBRTC_USE_DC_BAD_ROOM"});if(typeof e!="string"||e.length===0)throw new E("useDataChannel: label must be a non-empty string",{code:"ZQ_WEBRTC_USE_DC_BAD_LABEL"});const n=t&&typeof t.history=="number"?t.history:100,r=s.dataChannel(e,t&&t.opts),i=$([]),o=r.on("message",(a,c)=>{const u={data:a,from:c,at:Date.now()},l=i.peek().slice();l.push(u),l.length>n&&l.splice(0,l.length-n),i.value=l});return{messages:{get value(){return i.value},peek(){return i.peek()},subscribe(a){return i.subscribe(a)}},send(a){r.send(a)},close(){try{o()}catch{}try{r.close()}catch{}},dispose(){try{o()}catch{}}}}function nt(s,e){if(!s||!s.pc)throw new E("useConnectionQuality: peerInfo.pc is required",{code:"ZQ_WEBRTC_USE_CQ_BAD_PEER"});const t=e&&typeof e.intervalMs=="number"?e.intervalMs:2e3,n=e&&typeof e.getStats=="function"?e.getStats:()=>s.pc.getStats(),r=$("good");let i=!1;const o=async()=>{if(!i)try{const c=await n(),u=Gt(c);u!==r.peek()&&(r.value=u)}catch{}};o();const a=setInterval(o,t);return{get value(){return r.value},peek(){return r.peek()},subscribe(c){return r.subscribe(c)},dispose(){i=!0,clearInterval(a)}}}function st(s){if(s&&typeof s.getTracks=="function")try{return s.getTracks()}catch{return[]}return[]}function Gt(s){const e=[];if(s&&typeof s.forEach=="function")s.forEach(o=>e.push(o));else if(s&&typeof s=="object")for(const o of Object.keys(s))e.push(s[o]);let t=null,n=null;for(const o of e)!o||typeof o!="object"||(o.type==="inbound-rtp"&&!t&&(t=o),o.type==="candidate-pair"&&(o.state==="succeeded"||o.nominated)&&(n=o));let r=0;if(t&&typeof t.packetsLost=="number"&&typeof t.packetsReceived=="number"){const o=t.packetsLost+t.packetsReceived;r=o>0?t.packetsLost/o*100:0}const i=n&&typeof n.currentRoundTripTime=="number"?n.currentRoundTripTime*1e3:0;return r<2&&i<200?"good":r<10&&i<500?"fair":"poor"}async function ke(s,e){if(typeof s!="string"||!s)throw new M("fetchTurnCredentials: url must be a non-empty string",{code:"ZQ_WEBRTC_TURN_BAD_URL"});const t=e&&e.fetch||(typeof fetch!="undefined"?fetch:null);if(!t)throw new M("fetchTurnCredentials: no fetch implementation available",{code:"ZQ_WEBRTC_TURN_NO_FETCH"});const n={...e||{}};delete n.fetch;let r;try{r=await t(s,n)}catch(o){throw new M(`fetchTurnCredentials: network error - ${o&&o.message?o.message:o}`,{code:"ZQ_WEBRTC_TURN_NETWORK",cause:o instanceof Error?o:void 0,context:{url:s}})}if(!r||!r.ok){const o=r?r.status:0;throw new M(`fetchTurnCredentials: HTTP ${o}`,{code:"ZQ_WEBRTC_TURN_HTTP",context:{url:s,status:o}})}let i;try{i=await r.json()}catch(o){throw new M("fetchTurnCredentials: response is not valid JSON",{code:"ZQ_WEBRTC_TURN_BAD_JSON",cause:o instanceof Error?o:void 0,context:{url:s}})}return Jt(i,s)}function rt(s,e){const t=[],n=new Set,r=i=>{if(!i||!i.urls)return;const a=(Array.isArray(i.urls)?i.urls:[i.urls]).filter(u=>typeof u!="string"||!u||n.has(u)?!1:(n.add(u),!0));if(a.length===0)return;const c={...i,urls:a};t.push(c)};if(Array.isArray(s))for(const i of s)r(i);return e&&Array.isArray(e.urls)&&e.urls.length>0&&r({urls:e.urls,username:e.username,credential:e.credential}),t}function it(s){if(!s||typeof s.url!="string"||!s.url)throw new M("createTurnRefresher: opts.url is required",{code:"ZQ_WEBRTC_TURN_REFRESHER_BAD_URL"});const e=s.url,t=s.fetch||null,n=Number.isFinite(s.leadMs)?s.leadMs:3e4,r=Number.isFinite(s.minIntervalMs)?s.minIntervalMs:5e3,i=typeof s.onRefresh=="function"?s.onRefresh:null,o=typeof s.onError=="function"?s.onError:null,a=s.requestInit||void 0;let c=null,u=!1,l=null;const p={get value(){return l},peek(){return l},async refresh(){if(u)return null;try{const d=t?{...a||{},fetch:t}:a,_=await ke(e,d);return u||(l=_,h(_.ttl),i&&i(_)),_}catch(d){throw!u&&o&&o(d),u||h(60),d}},async start(){return u?null:p.refresh()},stop(){u=!0,c&&(clearTimeout(c),c=null)}};function h(d){c&&(clearTimeout(c),c=null);const _=Math.max(r,d*1e3-n);c=setTimeout(()=>{c=null,p.refresh().catch(()=>{})},_),c&&typeof c.unref=="function"&&c.unref()}return p}function Jt(s,e){if(!s||typeof s!="object")throw new M("fetchTurnCredentials: response is not an object",{code:"ZQ_WEBRTC_TURN_BAD_BODY",context:{url:e}});const{username:t,credential:n,urls:r,ttl:i}=s;if(typeof t!="string"||!t)throw new M("fetchTurnCredentials: response.username missing",{code:"ZQ_WEBRTC_TURN_BAD_BODY",context:{url:e,field:"username"}});if(typeof n!="string"||!n)throw new M("fetchTurnCredentials: response.credential missing",{code:"ZQ_WEBRTC_TURN_BAD_BODY",context:{url:e,field:"credential"}});if(!Array.isArray(r)||r.length===0||!r.every(a=>typeof a=="string"&&a))throw new M("fetchTurnCredentials: response.urls must be a non-empty string array",{code:"ZQ_WEBRTC_TURN_BAD_BODY",context:{url:e,field:"urls"}});const o=Number(i);if(!Number.isFinite(o)||o<=0)throw new M("fetchTurnCredentials: response.ttl must be a positive number",{code:"ZQ_WEBRTC_TURN_BAD_BODY",context:{url:e,field:"ttl"}});return{username:t,credential:n,urls:r.slice(),ttl:o}}const ot=128,at=12,X=1+at,Vt=1e5,Yt=new TextEncoder().encode("zquery-sframe-v1");function ae(){const s=typeof crypto!="undefined"&&crypto.subtle?crypto.subtle:null;if(!s)throw new L("WebCrypto SubtleCrypto is not available in this environment",{code:"ZQ_WEBRTC_E2EE_NO_WEBCRYPTO"});return s}function Xt(s){const e=new Uint8Array(s);if(typeof crypto=="undefined"||typeof crypto.getRandomValues!="function")throw new L("crypto.getRandomValues is not available in this environment",{code:"ZQ_WEBRTC_E2EE_NO_RANDOM"});return crypto.getRandomValues(e),e}function ce(s){if(s instanceof Uint8Array)return s;if(s instanceof ArrayBuffer)return new Uint8Array(s);if(ArrayBuffer.isView(s))return new Uint8Array(s.buffer,s.byteOffset,s.byteLength);if(s&&typeof s=="object"&&typeof s.byteLength=="number"&&Object.prototype.toString.call(s)==="[object ArrayBuffer]")return new Uint8Array(s);throw new L("expected a BufferSource (Uint8Array | ArrayBuffer | typed array)",{code:"ZQ_WEBRTC_E2EE_BAD_INPUT"})}async function ct(s,e){if(typeof s!="string"||!s)throw new L("deriveSFrameKey: passphrase must be a non-empty string",{code:"ZQ_WEBRTC_E2EE_BAD_PASSPHRASE"});if(typeof e!="string"||!e)throw new L("deriveSFrameKey: salt must be a non-empty string",{code:"ZQ_WEBRTC_E2EE_BAD_SALT"});const t=ae(),n=new TextEncoder,r=await t.importKey("raw",n.encode(s),{name:"PBKDF2"},!1,["deriveBits"]),i=await t.deriveBits({name:"PBKDF2",hash:"SHA-256",salt:n.encode(e),iterations:Vt},r,256),o=await t.importKey("raw",i,{name:"HKDF"},!1,["deriveKey"]);return t.deriveKey({name:"HKDF",hash:"SHA-256",salt:n.encode(e),info:Yt},o,{name:"AES-GCM",length:ot},!1,["encrypt","decrypt"])}async function ut(){return ae().generateKey({name:"AES-GCM",length:ot},!0,["encrypt","decrypt"])}class ee{constructor(e){const t=e&&Number.isFinite(e.maxEpochs)?e.maxEpochs:4;this._keys=new Map,this._maxEpochs=Math.max(1,t),this.currentEpoch=0}setKey(e,t){if(!Number.isInteger(e)||e<0||e>255)throw new L("SFrameContext.setKey: epoch must be an integer in [0, 255]",{code:"ZQ_WEBRTC_E2EE_BAD_EPOCH"});if(!t)throw new L("SFrameContext.setKey: key required",{code:"ZQ_WEBRTC_E2EE_BAD_KEY"});for(this._keys.set(e,t),this.currentEpoch=e;this._keys.size>this._maxEpochs;){const n=this._keys.keys().next().value;this._keys.delete(n)}}removeEpoch(e){this._keys.delete(e)}getKey(e){return this._keys.get(e)||null}get epochCount(){return this._keys.size}}async function Oe(s,e){if(!(s instanceof ee))throw new L("encryptFrame: ctx must be an SFrameContext",{code:"ZQ_WEBRTC_E2EE_BAD_CTX"});const t=s.getKey(s.currentEpoch);if(!t)throw new L(`encryptFrame: no key installed for epoch ${s.currentEpoch}`,{code:"ZQ_WEBRTC_E2EE_NO_KEY",context:{epoch:s.currentEpoch}});const n=ce(e),r=Xt(at),i=new Uint8Array(await ae().encrypt({name:"AES-GCM",iv:r},t,n)),o=new Uint8Array(X+i.byteLength);return o[0]=s.currentEpoch&255,o.set(r,1),o.set(i,X),o}async function xe(s,e){if(!(s instanceof ee))throw new L("decryptFrame: ctx must be an SFrameContext",{code:"ZQ_WEBRTC_E2EE_BAD_CTX"});const t=ce(e);if(t.byteLength<=X)throw new L("decryptFrame: frame too short for SFrame header",{code:"ZQ_WEBRTC_E2EE_SHORT_FRAME"});const n=t[0],r=s.getKey(n);if(!r)throw new L(`decryptFrame: no key for epoch ${n}`,{code:"ZQ_WEBRTC_E2EE_UNKNOWN_EPOCH",context:{epoch:n}});const i=t.subarray(1,X),o=t.subarray(X);let a;try{a=new Uint8Array(await ae().decrypt({name:"AES-GCM",iv:i},r,o))}catch(c){throw new L("decryptFrame: AES-GCM authentication failed",{code:"ZQ_WEBRTC_E2EE_AUTH_FAILED",cause:c instanceof Error?c:void 0,context:{epoch:n}})}return a}function lt(s,e){if(!s||typeof s.getSenders!="function"||typeof s.getReceivers!="function")throw new L("attachE2ee: pc must look like an RTCPeerConnection",{code:"ZQ_WEBRTC_E2EE_BAD_PC"});if(!(e instanceof ee))throw new L("attachE2ee: ctx must be an SFrameContext",{code:"ZQ_WEBRTC_E2EE_BAD_CTX"});const t=new WeakSet;let n=!1;function r(a){if(n||t.has(a))return;t.add(a);const c=ft(a);if(!c)return;const u=new TransformStream({async transform(l,p){try{const h=ce(l.data),d=await Oe(e,h);l.data=d.buffer,p.enqueue(l)}catch{}}});c.readable.pipeThrough(u).pipeTo(c.writable).catch(()=>{})}function i(a){if(n||t.has(a))return;t.add(a);const c=ft(a);if(!c)return;const u=new TransformStream({async transform(l,p){try{const h=ce(l.data),d=await xe(e,h);l.data=d.buffer,p.enqueue(l)}catch{}}});c.readable.pipeThrough(u).pipeTo(c.writable).catch(()=>{})}function o(){if(!n){for(const a of s.getSenders())r(a);for(const a of s.getReceivers())i(a)}}return o(),{refresh:o,detach(){n=!0}}}function ft(s){if(typeof s.createEncodedStreams=="function")try{return s.createEncodedStreams()}catch{return null}return null}function ht(s){if(typeof s!="string"||!s)throw new E("decodeJoinToken(token): token must be a non-empty string",{code:"ZQ_WEBRTC_TOKEN_BAD_INPUT"});const e=s.split(".");if(e.length<1||e.length>3)throw new E(`decodeJoinToken(token): expected 1-3 base64url segments, got ${e.length}`,{code:"ZQ_WEBRTC_TOKEN_BAD_SHAPE",context:{segments:e.length}});const t=e.length===3?e[1]:e[0];let n;try{const r=tn(t);n=JSON.parse(r)}catch(r){throw new E("decodeJoinToken(token): payload is not valid base64url-encoded JSON",{code:"ZQ_WEBRTC_TOKEN_BAD_PAYLOAD",cause:r})}if(!n||typeof n!="object")throw new E("decodeJoinToken(token): payload must be a JSON object",{code:"ZQ_WEBRTC_TOKEN_BAD_PAYLOAD"});return{user:en(n),room:typeof n.room=="string"?n.room:null,exp:typeof n.exp=="number"?n.exp:null,raw:n}}function dt(s,e={}){if(!s||typeof s!="object"||typeof s.exp!="number")return!1;const t=typeof e.nowMs=="number"?e.nowMs:Date.now(),n=typeof e.skewMs=="number"?e.skewMs:0;return s.exp*1e3<=t-n}function en(s){const e=s.user;return e&&typeof e=="object"&&typeof e.id=="string"?{id:e.id,...e}:typeof s.sub=="string"?{id:s.sub}:null}function tn(s){let e=s.replace(/-/g,"+").replace(/_/g,"/");const t=e.length%4;if(t===2)e+="==";else if(t===3)e+="=";else if(t===1)throw new Error("invalid base64url length");if(typeof atob=="function"){const n=atob(e),r=new Uint8Array(n.length);for(let i=0;i<n.length;i++)r[i]=n.charCodeAt(i);return new TextDecoder().decode(r)}return Buffer.from(e,"base64").toString("utf8")}async function Le(s){if(!s||typeof s.getStats!="function")throw new E("samplePeerStats(pc): RTCPeerConnection required",{code:"ZQ_WEBRTC_OBSERVE_BAD_PC"});let e;try{e=await s.getStats()}catch(t){throw new E("samplePeerStats(pc): getStats() failed",{code:"ZQ_WEBRTC_OBSERVE_GETSTATS_FAILED",cause:t})}return nn(e)}function pt(s,e={}){if(!s||typeof s.getStats!="function")throw new E("createStatsSampler(pc): RTCPeerConnection required",{code:"ZQ_WEBRTC_OBSERVE_BAD_PC"});const t=typeof e.intervalMs=="number"&&e.intervalMs>0?e.intervalMs:2e3,n=e.immediate!==!1,r=typeof e.onSample=="function"?e.onSample:null,i=typeof e.onError=="function"?e.onError:null;let o=null,a=!1;const c=async()=>{if(!a)try{const l=await Le(s);if(a)return;if(o=l,r)try{r(l)}catch{}}catch(l){if(i)try{i(l)}catch{}}};n&&c();const u=setInterval(c,t);return{stop(){a||(a=!0,clearInterval(u))},getLatest(){return o}}}function _t(s){if(!s||!s.summary)return"unknown";const{rttMs:e,lossPct:t}=s.summary;return e==null&&t===0?"unknown":t>5||e!=null&&e>400?"poor":t>1||e!=null&&e>200?"fair":"good"}function nn(s){const e=[],t=[];let n=null;const r=h=>{!h||typeof h!="object"||(h.type==="inbound-rtp"&&e.push(h),h.type==="outbound-rtp"&&t.push(h),h.type==="candidate-pair"&&(h.nominated||h.state==="succeeded")&&(n||(n=h)))};if(s&&typeof s.forEach=="function")s.forEach(r);else if(s&&typeof s=="object")for(const h of Object.keys(s))r(s[h]);let i=0,o=0,a=0,c=0;for(const h of t)typeof h.bytesSent=="number"&&(i+=h.bytesSent);for(const h of e)typeof h.bytesReceived=="number"&&(o+=h.bytesReceived),typeof h.packetsLost=="number"&&(a+=h.packetsLost),typeof h.packetsReceived=="number"&&(c+=h.packetsReceived);const u=a+c,l=u>0?a/u*100:0;let p=null;return n&&typeof n.currentRoundTripTime=="number"&&(p=n.currentRoundTripTime*1e3),{report:s,inboundRtp:e,outboundRtp:t,candidatePair:n,summary:{rttMs:p,lossPct:l,bytesSent:i,bytesReceived:o}}}async function sn(){try{return await import(["mediasoup","client"].join("-"))}catch(s){throw new O("mediasoup-client peer dependency is not installed; run `npm install mediasoup-client`",{code:"ZQ_WEBRTC_SFU_PEER_MISSING",cause:s})}}async function rn(s={}){const e=s.client||await sn(),t=e.Device||e.default&&e.default.Device;if(typeof t!="function")throw new O("mediasoup-client module did not expose a Device constructor",{code:"ZQ_WEBRTC_SFU_BAD_MODULE"});let n;try{n=new t(s.deviceOptions||{})}catch(r){throw new O("failed to construct mediasoup-client Device",{code:"ZQ_WEBRTC_SFU_DEVICE_FAILED",cause:r})}return{name:"mediasoup",device:n,get loaded(){return!!n.loaded},async load(r){if(!r||typeof r!="object")throw new O("load(routerRtpCapabilities): routerRtpCapabilities required",{code:"ZQ_WEBRTC_SFU_BAD_RTP_CAPS"});if(!n.loaded)try{await n.load({routerRtpCapabilities:r})}catch(i){throw new O("device.load() failed",{code:"ZQ_WEBRTC_SFU_LOAD_FAILED",cause:i})}},canProduce(r){if(!n.loaded)throw new O("canProduce(): device not loaded yet",{code:"ZQ_WEBRTC_SFU_NOT_LOADED"});return!!n.canProduce(r)},createSendTransport(r){if(!n.loaded)throw new O("createSendTransport(): device not loaded yet",{code:"ZQ_WEBRTC_SFU_NOT_LOADED"});return n.createSendTransport(r)},createRecvTransport(r){if(!n.loaded)throw new O("createRecvTransport(): device not loaded yet",{code:"ZQ_WEBRTC_SFU_NOT_LOADED"});return n.createRecvTransport(r)},async join(r){throw new O("mediasoup adapter.join() not implemented; use device + createSendTransport/createRecvTransport with your SFU signaling layer",{code:"ZQ_WEBRTC_SFU_JOIN_UNAVAILABLE"})}}}async function on(){try{return await import(["livekit","client"].join("-"))}catch(s){throw new O("livekit-client peer dependency is not installed; run `npm install livekit-client`",{code:"ZQ_WEBRTC_SFU_PEER_MISSING",cause:s})}}async function an(s={}){const e=s.client||await on(),t=e.Room||e.default&&e.default.Room;if(typeof t!="function")throw new O("livekit-client module did not expose a Room constructor",{code:"ZQ_WEBRTC_SFU_BAD_MODULE"});let n;try{n=new t(s.roomOptions||{})}catch(i){throw new O("failed to construct livekit-client Room",{code:"ZQ_WEBRTC_SFU_ROOM_FAILED",cause:i})}let r=!1;return{name:"livekit",room:n,get connected(){return r},async connect(i,o,a){if(typeof i!="string"||!i)throw new O("connect(url, token): url required",{code:"ZQ_WEBRTC_SFU_BAD_URL"});if(typeof o!="string"||!o)throw new O("connect(url, token): token required",{code:"ZQ_WEBRTC_SFU_BAD_TOKEN"});try{await n.connect(i,o,a),r=!0}catch(c){throw new O("livekit-client Room.connect() failed",{code:"ZQ_WEBRTC_SFU_CONNECT_FAILED",cause:c})}},async disconnect(){if(r)try{await n.disconnect()}finally{r=!1}},async join(i){throw new O("livekit adapter.join() not implemented; use connect(url, token) and the underlying livekit-client Room directly",{code:"ZQ_WEBRTC_SFU_JOIN_UNAVAILABLE"})}}}async function mt(s,e={}){if(s==="mediasoup")return rn(e);if(s==="livekit")return an(e);throw new O(`unknown SFU adapter: ${s}`,{code:"ZQ_WEBRTC_SFU_UNKNOWN",context:{name:s}})}const cn={SignalingClient:Ae,Peer:Re,Room:K,join:Je,useRoom:Ye,usePeer:Xe,useTracks:et,useDataChannel:tt,useConnectionQuality:nt,fetchTurnCredentials:ke,mergeIceServers:rt,createTurnRefresher:it,deriveSFrameKey:ct,generateSFrameKey:ut,SFrameContext:ee,encryptFrame:Oe,decryptFrame:xe,attachE2ee:lt,loadSfuAdapter:mt,decodeJoinToken:ht,isJoinTokenExpired:dt,samplePeerStats:Le,createStatsSampler:pt,classifyStats:_t,parseSdp:ge,validateSdp:Ze,parseCandidate:be,stringifyCandidate:He,filterCandidates:Ke,isPrivateIp:Se,isLoopbackIp:ve,isLinkLocalIp:Te,isMdnsHostname:Ce,WebRtcError:E,SignalingError:P,IceError:U,SdpError:B,TurnError:M,E2eeError:L,SfuError:O};function Ne(s,e,t=""){if(typeof s!="object"||s===null)return s;typeof e!="function"&&(C(S.REACTIVE_CALLBACK,"reactive() onChange must be a function",{received:typeof e}),e=()=>{});const n=new WeakMap,r={get(i,o){if(o==="__isReactive")return!0;if(o==="__raw")return i;const a=i[o];if(typeof a=="object"&&a!==null){if(n.has(a))return n.get(a);const c=new Proxy(a,r);return n.set(a,c),c}return a},set(i,o,a){const c=i[o];if(c===a)return!0;i[o]=a,c&&typeof c=="object"&&n.delete(c);try{e(o,a,c)}catch(u){C(S.REACTIVE_CALLBACK,`Reactive onChange threw for key "${String(o)}"`,{key:o,value:a,old:c},u)}return!0},deleteProperty(i,o){const a=i[o];delete i[o],a&&typeof a=="object"&&n.delete(a);try{e(o,void 0,a)}catch(c){C(S.REACTIVE_CALLBACK,`Reactive onChange threw for key "${String(o)}"`,{key:o,old:a},c)}return!0}};return new Proxy(s,r)}class R{constructor(e){this._value=e,this._subscribers=new Set}get value(){return R._activeEffect&&(this._subscribers.add(R._activeEffect),R._activeEffect._deps&&R._activeEffect._deps.add(this)),this._value}set value(e){this._value!==e&&(this._value=e,this._notify())}peek(){return this._value}_notify(){if(R._batching){R._batchQueue.add(this);return}const e=[...this._subscribers];for(let t=0;t<e.length;t++)try{e[t]()}catch(n){C(S.SIGNAL_CALLBACK,"Signal subscriber threw",{signal:this},n)}}subscribe(e){return this._subscribers.add(e),()=>this._subscribers.delete(e)}toString(){return String(this._value)}}R._activeEffect=null,R._batching=!1,R._batchQueue=new Set;function $(s){return new R(s)}function un(s){const e=new R(void 0);return yt(()=>{const t=s();t!==e._value&&(e._value=t,e._notify())}),e}function yt(s){const e=()=>{if(e._deps){for(const t of e._deps)t._subscribers.delete(e);e._deps.clear()}R._activeEffect=e;try{s()}catch(t){C(S.EFFECT_EXEC,"Effect function threw",{},t)}finally{R._activeEffect=null}};return e._deps=new Set,e(),()=>{if(e._deps){for(const t of e._deps)t._subscribers.delete(e);e._deps.clear()}}}function ln(s){if(R._batching)return s();R._batching=!0,R._batchQueue.clear();let e;try{e=s()}finally{R._batching=!1;const t=new Set;for(const n of R._batchQueue)for(const r of n._subscribers)t.add(r);R._batchQueue.clear();for(const n of t)try{n()}catch(r){C(S.SIGNAL_CALLBACK,"Signal subscriber threw",{},r)}}return e}function fn(s){const e=R._activeEffect;R._activeEffect=null;try{return s()}finally{R._activeEffect=e}}let Pe=null;function wt(){return Pe||(Pe=document.createElement("template")),Pe}function Be(s,e){const t=typeof window!="undefined"&&window.__zqMorphHook?performance.now():0,n=wt();n.innerHTML=e;const r=n.content,i=document.createElement("div");for(;r.firstChild;)i.appendChild(r.firstChild);ue(s,i),t&&window.__zqMorphHook(s,performance.now()-t)}function gt(s,e){const t=typeof window!="undefined"&&window.__zqMorphHook?performance.now():0,n=wt();n.innerHTML=e;const r=n.content.firstElementChild;if(!r)return s;if(s.nodeName===r.nodeName)return St(s,r),ue(s,r),t&&window.__zqMorphHook(s,performance.now()-t),s;const i=r.cloneNode(!0);return s.parentNode.replaceChild(i,s),t&&window.__zqMorphHook(i,performance.now()-t),i}const Et=Be,hn=gt;function ue(s,e){const t=s.childNodes,n=e.childNodes,r=t.length,i=n.length,o=new Array(r),a=new Array(i);for(let p=0;p<r;p++)o[p]=t[p];for(let p=0;p<i;p++)a[p]=n[p];let c=!1,u,l;for(let p=0;p<r;p++)if(D(o[p])!=null){c=!0;break}if(!c){for(let p=0;p<i;p++)if(D(a[p])!=null){c=!0;break}}if(c){u=new Map,l=new Map;for(let p=0;p<r;p++){const h=D(o[p]);h!=null&&u.set(h,p)}for(let p=0;p<i;p++){const h=D(a[p]);h!=null&&l.set(h,p)}pn(s,o,a,u,l)}else dn(s,o,a)}function dn(s,e,t){const n=e.length,r=t.length,i=n<r?n:r;for(let o=0;o<i;o++)bt(s,e[o],t[o]);if(r>n)for(let o=n;o<r;o++)s.appendChild(t[o].cloneNode(!0));if(n>r)for(let o=n-1;o>=r;o--)s.removeChild(e[o])}function pn(s,e,t,n,r){const i=new Set,o=t.length,a=new Array(o);for(let d=0;d<o;d++){const _=D(t[d]);if(_!=null&&n.has(_)){const w=n.get(_);a[d]=e[w],i.add(w)}else a[d]=null}for(let d=e.length-1;d>=0;d--)if(!i.has(d)){const _=D(e[d]);_!=null&&!r.has(_)&&s.removeChild(e[d])}const c=[];for(let d=0;d<o;d++)if(a[d]){const _=D(t[d]);c.push(n.get(_))}else c.push(-1);const u=_n(c);let l=s.firstChild;const p=[];for(let d=0;d<e.length;d++)!i.has(d)&&D(e[d])==null&&p.push(e[d]);let h=0;for(let d=0;d<o;d++){const _=t[d],w=D(_);let m=a[d];if(!m&&w==null&&(m=p[h++]||null),m){u.has(d)||s.insertBefore(m,l);const v=m.nextSibling;bt(s,m,_),l=v}else{const v=_.cloneNode(!0);l?s.insertBefore(v,l):s.appendChild(v)}}for(;h<p.length;){const d=p[h++];d.parentNode===s&&s.removeChild(d)}for(let d=0;d<e.length;d++)if(!i.has(d)){const _=e[d];_.parentNode===s&&D(_)!=null&&!r.has(D(_))&&s.removeChild(_)}}function _n(s){const e=s.length,t=new Set;if(e===0)return t;const n=[],r=new Array(e).fill(-1),i=[];for(let a=0;a<e;a++){if(s[a]===-1)continue;const c=s[a];let u=0,l=n.length;for(;u<l;){const p=u+l>>1;n[p]<c?u=p+1:l=p}n[u]=c,i[u]=a,r[a]=u>0?i[u-1]:-1}let o=i[n.length-1];for(let a=n.length-1;a>=0;a--)t.add(o),o=r[o];return t}function bt(s,e,t){if(e.nodeType===3||e.nodeType===8){if(t.nodeType===e.nodeType){e.nodeValue!==t.nodeValue&&(e.nodeValue=t.nodeValue);return}s.replaceChild(t.cloneNode(!0),e);return}if(e.nodeType!==t.nodeType||e.nodeName!==t.nodeName){s.replaceChild(t.cloneNode(!0),e);return}if(e.nodeType===1){if(e.hasAttribute("z-skip")||e.isEqualNode(t))return;St(e,t);const n=e.nodeName;if(n==="INPUT"){mn(e,t);return}if(n==="TEXTAREA"){e.value!==t.textContent&&(e.value=t.textContent||"");return}if(n==="SELECT"){ue(e,t),e.value!==t.value&&(e.value=t.value);return}ue(e,t)}}function St(s,e){const t=e.attributes,n=s.attributes,r=t.length,i=n.length;if(r===i){let c=!0;for(let u=0;u<r;u++){const l=t[u];if(s.getAttribute(l.name)!==l.value){c=!1;break}}if(c){for(let u=0;u<i;u++)if(!e.hasAttribute(n[u].name)){c=!1;break}}if(c)return}const o=new Set;for(let c=0;c<r;c++){const u=t[c];o.add(u.name),s.getAttribute(u.name)!==u.value&&s.setAttribute(u.name,u.value)}const a=new Array(i);for(let c=0;c<i;c++)a[c]=n[c].name;for(let c=a.length-1;c>=0;c--)o.has(a[c])||s.removeAttribute(a[c])}function mn(s,e){const t=(s.type||"").toLowerCase();if(t==="checkbox"||t==="radio")s.checked!==e.checked&&(s.checked=e.checked);else{const n=e.getAttribute("value");n!==null&&s.value!==n&&(s.value=n)}s.disabled!==e.disabled&&(s.disabled=e.disabled)}function D(s){if(s.nodeType!==1)return null;const e=s.getAttribute("z-key");if(e)return e;if(s.id)return"\0id:"+s.id;const t=s.dataset;if(t){if(t.id)return"\0data-id:"+t.id;if(t.key)return"\0data-key:"+t.key}return null}class g{constructor(e){this.elements=Array.isArray(e)?e:e?[e]:[],this.length=this.elements.length,this.elements.forEach((t,n)=>{this[n]=t})}each(e){return this.elements.forEach((t,n)=>e.call(t,n,t)),this}map(e){return this.elements.map((t,n)=>e.call(t,n,t))}forEach(e){return this.elements.forEach((t,n)=>e(t,n,this.elements)),this}first(){return this.elements[0]||null}last(){return this.elements[this.length-1]||null}eq(e){return new g(this.elements[e]?[this.elements[e]]:[])}toArray(){return[...this.elements]}[Symbol.iterator](){return this.elements[Symbol.iterator]()}find(e){const t=[];return this.elements.forEach(n=>t.push(...n.querySelectorAll(e))),new g(t)}parent(){const e=[...new Set(this.elements.map(t=>t.parentElement).filter(Boolean))];return new g(e)}closest(e){return new g(this.elements.map(t=>t.closest(e)).filter(Boolean))}children(e){const t=[];return this.elements.forEach(n=>{t.push(...e?n.querySelectorAll(`:scope > ${e}`):n.children)}),new g([...t])}siblings(e){const t=[];return this.elements.forEach(n=>{if(!n.parentElement)return;const r=[...n.parentElement.children].filter(i=>i!==n);t.push(...e?r.filter(i=>i.matches(e)):r)}),new g(t)}next(e){const t=this.elements.map(n=>n.nextElementSibling).filter(Boolean);return new g(e?t.filter(n=>n.matches(e)):t)}prev(e){const t=this.elements.map(n=>n.previousElementSibling).filter(Boolean);return new g(e?t.filter(n=>n.matches(e)):t)}nextAll(e){const t=[];return this.elements.forEach(n=>{let r=n.nextElementSibling;for(;r;)(!e||r.matches(e))&&t.push(r),r=r.nextElementSibling}),new g(t)}nextUntil(e,t){const n=[];return this.elements.forEach(r=>{let i=r.nextElementSibling;for(;i&&!(e&&i.matches(e));)(!t||i.matches(t))&&n.push(i),i=i.nextElementSibling}),new g(n)}prevAll(e){const t=[];return this.elements.forEach(n=>{let r=n.previousElementSibling;for(;r;)(!e||r.matches(e))&&t.push(r),r=r.previousElementSibling}),new g(t)}prevUntil(e,t){const n=[];return this.elements.forEach(r=>{let i=r.previousElementSibling;for(;i&&!(e&&i.matches(e));)(!t||i.matches(t))&&n.push(i),i=i.previousElementSibling}),new g(n)}parents(e){const t=[];return this.elements.forEach(n=>{let r=n.parentElement;for(;r;)(!e||r.matches(e))&&t.push(r),r=r.parentElement}),new g([...new Set(t)])}parentsUntil(e,t){const n=[];return this.elements.forEach(r=>{let i=r.parentElement;for(;i&&!(e&&i.matches(e));)(!t||i.matches(t))&&n.push(i),i=i.parentElement}),new g([...new Set(n)])}contents(){const e=[];return this.elements.forEach(t=>e.push(...t.childNodes)),new g(e)}filter(e){return typeof e=="function"?new g(this.elements.filter(e)):new g(this.elements.filter(t=>t.matches(e)))}not(e){return typeof e=="function"?new g(this.elements.filter((t,n)=>!e.call(t,n,t))):new g(this.elements.filter(t=>!t.matches(e)))}has(e){return new g(this.elements.filter(t=>t.querySelector(e)))}is(e){return typeof e=="function"?this.elements.some((t,n)=>e.call(t,n,t)):this.elements.some(t=>t.matches(e))}slice(e,t){return new g(this.elements.slice(e,t))}add(e,t){const n=e instanceof g?e.elements:e instanceof Node?[e]:Array.from((t||document).querySelectorAll(e));return new g([...this.elements,...n])}get(e){return e===void 0?[...this.elements]:e<0?this.elements[this.length+e]:this.elements[e]}index(e){if(e===void 0){const n=this.first();return!n||!n.parentElement?-1:Array.from(n.parentElement.children).indexOf(n)}const t=typeof e=="string"?document.querySelector(e):e;return this.elements.indexOf(t)}addClass(...e){if(e.length===1&&e[0].indexOf(" ")===-1){const n=e[0];for(let r=0;r<this.elements.length;r++)this.elements[r].classList.add(n);return this}const t=e.flatMap(n=>n.split(/\s+/));for(let n=0;n<this.elements.length;n++)this.elements[n].classList.add(...t);return this}removeClass(...e){if(e.length===1&&e[0].indexOf(" ")===-1){const n=e[0];for(let r=0;r<this.elements.length;r++)this.elements[r].classList.remove(n);return this}const t=e.flatMap(n=>n.split(/\s+/));for(let n=0;n<this.elements.length;n++)this.elements[n].classList.remove(...t);return this}toggleClass(...e){const t=typeof e[e.length-1]=="boolean"?e.pop():void 0;if(e.length===1&&e[0].indexOf(" ")===-1){const r=e[0];for(let i=0;i<this.elements.length;i++)t!==void 0?this.elements[i].classList.toggle(r,t):this.elements[i].classList.toggle(r);return this}const n=e.flatMap(r=>r.split(/\s+/));for(let r=0;r<this.elements.length;r++){const i=this.elements[r];for(let o=0;o<n.length;o++)t!==void 0?i.classList.toggle(n[o],t):i.classList.toggle(n[o])}return this}hasClass(e){var t;return((t=this.first())==null?void 0:t.classList.contains(e))||!1}attr(e,t){var n;return typeof e=="object"&&e!==null?this.each((r,i)=>{for(const[o,a]of Object.entries(e))i.setAttribute(o,a)}):t===void 0?(n=this.first())==null?void 0:n.getAttribute(e):this.each((r,i)=>i.setAttribute(e,t))}removeAttr(e){return this.each((t,n)=>n.removeAttribute(e))}prop(e,t){var n;return t===void 0?(n=this.first())==null?void 0:n[e]:this.each((r,i)=>{i[e]=t})}data(e,t){var n,r;if(t===void 0){if(e===void 0)return(n=this.first())==null?void 0:n.dataset;const i=(r=this.first())==null?void 0:r.dataset[e];try{return JSON.parse(i)}catch{return i}}return this.each((i,o)=>{o.dataset[e]=typeof t=="object"?JSON.stringify(t):t})}css(e,t){if(typeof e=="string"&&t!==void 0)return this.each((n,r)=>{r.style[e]=t});if(typeof e=="string"){const n=this.first();return n?getComputedStyle(n)[e]:void 0}return this.each((n,r)=>Object.assign(r.style,e))}width(){var e;return(e=this.first())==null?void 0:e.getBoundingClientRect().width}height(){var e;return(e=this.first())==null?void 0:e.getBoundingClientRect().height}offset(){var t;const e=(t=this.first())==null?void 0:t.getBoundingClientRect();return e?{top:e.top+window.scrollY,left:e.left+window.scrollX,width:e.width,height:e.height}:null}position(){const e=this.first();return e?{top:e.offsetTop,left:e.offsetLeft}:null}scrollTop(e){if(e===void 0){const t=this.first();return t===window?window.scrollY:t==null?void 0:t.scrollTop}return this.each((t,n)=>{n===window?window.scrollTo(window.scrollX,e):n.scrollTop=e})}scrollLeft(e){if(e===void 0){const t=this.first();return t===window?window.scrollX:t==null?void 0:t.scrollLeft}return this.each((t,n)=>{n===window?window.scrollTo(e,window.scrollY):n.scrollLeft=e})}innerWidth(){const e=this.first();return e==null?void 0:e.clientWidth}innerHeight(){const e=this.first();return e==null?void 0:e.clientHeight}outerWidth(e=!1){const t=this.first();if(!t)return;let n=t.offsetWidth;if(e){const r=getComputedStyle(t);n+=parseFloat(r.marginLeft)+parseFloat(r.marginRight)}return n}outerHeight(e=!1){const t=this.first();if(!t)return;let n=t.offsetHeight;if(e){const r=getComputedStyle(t);n+=parseFloat(r.marginTop)+parseFloat(r.marginBottom)}return n}html(e){var t;return e===void 0?(t=this.first())==null?void 0:t.innerHTML:this.each((n,r)=>{r.childNodes.length>0?Et(r,e):r.innerHTML=e})}morph(e){return this.each((t,n)=>{Et(n,e)})}text(e){var t;return e===void 0?(t=this.first())==null?void 0:t.textContent:this.each((n,r)=>{r.textContent=e})}val(e){var t;return e===void 0?(t=this.first())==null?void 0:t.value:this.each((n,r)=>{r.value=e})}append(e){return this.each((t,n)=>{typeof e=="string"?n.insertAdjacentHTML("beforeend",e):e instanceof g?e.each((r,i)=>n.appendChild(i)):e instanceof Node&&n.appendChild(e)})}prepend(e){return this.each((t,n)=>{typeof e=="string"?n.insertAdjacentHTML("afterbegin",e):e instanceof Node&&n.insertBefore(e,n.firstChild)})}after(e){return this.each((t,n)=>{typeof e=="string"?n.insertAdjacentHTML("afterend",e):e instanceof Node&&n.parentNode.insertBefore(e,n.nextSibling)})}before(e){return this.each((t,n)=>{typeof e=="string"?n.insertAdjacentHTML("beforebegin",e):e instanceof Node&&n.parentNode.insertBefore(e,n)})}wrap(e){return this.each((t,n)=>{const r=typeof e=="string"?te(e).firstElementChild:e.cloneNode(!0);!r||!n.parentNode||(n.parentNode.insertBefore(r,n),r.appendChild(n))})}remove(){return this.each((e,t)=>t.remove())}empty(){return this.each((e,t)=>{t.textContent=""})}clone(e=!0){return new g(this.elements.map(t=>t.cloneNode(e)))}replaceWith(e){return this.each((t,n)=>{typeof e=="string"?hn(n,e):e instanceof Node&&n.parentNode.replaceChild(e,n)})}appendTo(e){const t=typeof e=="string"?document.querySelector(e):e instanceof g?e.first():e;return t&&this.each((n,r)=>t.appendChild(r)),this}prependTo(e){const t=typeof e=="string"?document.querySelector(e):e instanceof g?e.first():e;return t&&this.each((n,r)=>t.insertBefore(r,t.firstChild)),this}insertAfter(e){const t=typeof e=="string"?document.querySelector(e):e instanceof g?e.first():e;return t&&t.parentNode&&this.each((n,r)=>t.parentNode.insertBefore(r,t.nextSibling)),this}insertBefore(e){const t=typeof e=="string"?document.querySelector(e):e instanceof g?e.first():e;return t&&t.parentNode&&this.each((n,r)=>t.parentNode.insertBefore(r,t)),this}replaceAll(e){return(typeof e=="string"?Array.from(document.querySelectorAll(e)):e instanceof g?e.elements:[e]).forEach((n,r)=>{(r===0?this.elements:this.elements.map(o=>o.cloneNode(!0))).forEach(o=>n.parentNode.insertBefore(o,n)),n.remove()}),this}unwrap(e){return this.elements.forEach(t=>{const n=t.parentElement;!n||n===document.body||e&&!n.matches(e)||n.replaceWith(...n.childNodes)}),this}wrapAll(e){const t=typeof e=="string"?te(e).firstElementChild:e.cloneNode(!0),n=this.first();return n?(n.parentNode.insertBefore(t,n),this.each((r,i)=>t.appendChild(i)),this):this}wrapInner(e){return this.each((t,n)=>{const r=typeof e=="string"?te(e).firstElementChild:e.cloneNode(!0);for(;n.firstChild;)r.appendChild(n.firstChild);n.appendChild(r)})}detach(){return this.each((e,t)=>t.remove())}show(e=""){return this.each((t,n)=>{n.style.display=e})}hide(){return this.each((e,t)=>{t.style.display="none"})}toggle(e=""){return this.each((t,n)=>{const r=n.style.display==="none"||(n.style.display!==""?!1:getComputedStyle(n).display==="none");n.style.display=r?e:"none"})}on(e,t,n){const r=e.split(/\s+/);return this.each((i,o)=>{r.forEach(a=>{if(typeof t=="function")o.addEventListener(a,t);else if(typeof t=="string"){const c=u=>{if(!u.target||typeof u.target.closest!="function")return;const l=u.target.closest(t);l&&o.contains(l)&&n.call(l,u)};c._zqOriginal=n,c._zqSelector=t,o.addEventListener(a,c),o._zqDelegated||(o._zqDelegated=[]),o._zqDelegated.push({evt:a,wrapper:c})}})})}off(e,t){const n=e.split(/\s+/);return this.each((r,i)=>{n.forEach(o=>{i.removeEventListener(o,t),i._zqDelegated&&(i._zqDelegated=i._zqDelegated.filter(a=>a.evt===o&&a.wrapper._zqOriginal===t?(i.removeEventListener(o,a.wrapper),!1):!0))})})}one(e,t){return this.each((n,r)=>{r.addEventListener(e,t,{once:!0})})}trigger(e,t){return this.each((n,r)=>{r.dispatchEvent(new CustomEvent(e,{detail:t,bubbles:!0,cancelable:!0}))})}click(e){return e?this.on("click",e):this.trigger("click")}submit(e){return e?this.on("submit",e):this.trigger("submit")}focus(){var e;return(e=this.first())==null||e.focus(),this}blur(){var e;return(e=this.first())==null||e.blur(),this}hover(e,t){return this.on("mouseenter",e),this.on("mouseleave",t||e)}animate(e,t=300,n="ease"){return this.length===0?Promise.resolve(this):new Promise(r=>{let i=!1;const o={done:0},a=[];this.each((c,u)=>{u.style.transition=`all ${t}ms ${n}`,requestAnimationFrame(()=>{Object.assign(u.style,e);const l=()=>{u.removeEventListener("transitionend",l),u.style.transition="",!i&&++o.done>=this.length&&(i=!0,r(this))};u.addEventListener("transitionend",l),a.push({el:u,onEnd:l})})}),setTimeout(()=>{if(!i){i=!0;for(const{el:c,onEnd:u}of a)c.removeEventListener("transitionend",u),c.style.transition="";r(this)}},t+50)})}fadeIn(e=300){return this.css({opacity:"0",display:""}).animate({opacity:"1"},e)}fadeOut(e=300){return this.animate({opacity:"0"},e).then(t=>t.hide())}fadeToggle(e=300){return Promise.all(this.elements.map(t=>{const n=getComputedStyle(t),r=n.opacity!=="0"&&n.display!=="none",i=new g([t]);return r?i.fadeOut(e):i.fadeIn(e)})).then(()=>this)}fadeTo(e,t){return this.animate({opacity:String(t)},e)}slideDown(e=300){return this.each((t,n)=>{n.style.display="",n.style.overflow="hidden";const r=n.scrollHeight+"px";n.style.maxHeight="0",n.style.transition=`max-height ${e}ms ease`,requestAnimationFrame(()=>{n.style.maxHeight=r}),setTimeout(()=>{n.style.maxHeight="",n.style.overflow="",n.style.transition=""},e)})}slideUp(e=300){return this.each((t,n)=>{n.style.overflow="hidden",n.style.maxHeight=n.scrollHeight+"px",n.style.transition=`max-height ${e}ms ease`,requestAnimationFrame(()=>{n.style.maxHeight="0"}),setTimeout(()=>{n.style.display="none",n.style.maxHeight="",n.style.overflow="",n.style.transition=""},e)})}slideToggle(e=300){return this.each((t,n)=>{if(n.style.display==="none"||getComputedStyle(n).display==="none"){n.style.display="",n.style.overflow="hidden";const r=n.scrollHeight+"px";n.style.maxHeight="0",n.style.transition=`max-height ${e}ms ease`,requestAnimationFrame(()=>{n.style.maxHeight=r}),setTimeout(()=>{n.style.maxHeight="",n.style.overflow="",n.style.transition=""},e)}else n.style.overflow="hidden",n.style.maxHeight=n.scrollHeight+"px",n.style.transition=`max-height ${e}ms ease`,requestAnimationFrame(()=>{n.style.maxHeight="0"}),setTimeout(()=>{n.style.display="none",n.style.maxHeight="",n.style.overflow="",n.style.transition=""},e)})}serialize(){const e=this.first();return!e||e.tagName!=="FORM"?"":new URLSearchParams(new FormData(e)).toString()}serializeObject(){const e=this.first();if(!e||e.tagName!=="FORM")return{};const t={};return new FormData(e).forEach((n,r)=>{t[r]!==void 0?(Array.isArray(t[r])||(t[r]=[t[r]]),t[r].push(n)):t[r]=n}),t}}function te(s){const e=document.createElement("template");return e.innerHTML=s.trim(),e.content}function T(s,e){if(!s)return new g([]);if(s instanceof g)return s;if(s instanceof Node||s===window)return new g([s]);if(s instanceof NodeList||s instanceof HTMLCollection||Array.isArray(s))return new g(Array.from(s));if(typeof s=="string"&&s.trim().startsWith("<")){const t=te(s);return new g([...t.childNodes].filter(n=>n.nodeType===1))}if(typeof s=="string"){const t=e?typeof e=="string"?document.querySelector(e):e:document;return new g([...t.querySelectorAll(s)])}return new g([])}function yn(s,e){if(!s)return new g([]);if(s instanceof g)return s;if(s instanceof Node||s===window)return new g([s]);if(s instanceof NodeList||s instanceof HTMLCollection||Array.isArray(s))return new g(Array.from(s));if(typeof s=="string"&&s.trim().startsWith("<")){const t=te(s);return new g([...t.childNodes].filter(n=>n.nodeType===1))}if(typeof s=="string"){const t=e?typeof e=="string"?document.querySelector(e):e:document;return new g([...t.querySelectorAll(s)])}return new g([])}T.id=s=>document.getElementById(s),T.class=s=>document.querySelector(`.${s}`),T.classes=s=>new g(Array.from(document.getElementsByClassName(s))),T.tag=s=>new g(Array.from(document.getElementsByTagName(s))),Object.defineProperty(T,"name",{value:s=>new g(Array.from(document.getElementsByName(s))),writable:!0,configurable:!0}),T.children=s=>{const e=document.getElementById(s);return new g(e?Array.from(e.children):[])},T.qs=(s,e=document)=>e.querySelector(s),T.qsa=(s,e=document)=>Array.from(e.querySelectorAll(s)),T.create=(s,e={},...t)=>{const n=document.createElement(s);for(const[r,i]of Object.entries(e))r==="class"?n.className=i:r==="style"&&typeof i=="object"?Object.assign(n.style,i):r.startsWith("on")&&typeof i=="function"?n.addEventListener(r.slice(2).toLowerCase(),i):r==="data"&&typeof i=="object"?Object.entries(i).forEach(([o,a])=>{n.dataset[o]=a}):n.setAttribute(r,i);return t.flat().forEach(r=>{typeof r=="string"?n.appendChild(document.createTextNode(r)):r instanceof Node&&n.appendChild(r)}),new g(n)},T.ready=s=>{document.readyState!=="loading"?s():document.addEventListener("DOMContentLoaded",s)},T.on=(s,e,t)=>{if(typeof e=="function"){document.addEventListener(s,e);return}if(typeof e=="object"&&typeof e.addEventListener=="function"){e.addEventListener(s,t);return}document.addEventListener(s,n=>{if(!n.target||typeof n.target.closest!="function")return;const r=n.target.closest(e);r&&t.call(r,n)})},T.off=(s,e)=>{document.removeEventListener(s,e)},T.fn=g.prototype;const y={NUM:1,STR:2,IDENT:3,OP:4,PUNC:5,TMPL:6,EOF:7},le={"??":2,"||":3,"&&":4,"==":8,"!=":8,"===":8,"!==":8,"<":9,">":9,"<=":9,">=":9,instanceof:9,in:9,"+":11,"-":11,"*":12,"/":12,"%":12},wn=new Set(["true","false","null","undefined","typeof","instanceof","in","new","void"]);function gn(s){const e=[];let t=0;const n=s.length;for(;t<n;){const r=s[t];if(r===" "||r===" "||r===`
|
|
10
|
+
`||r==="\r"){t++;continue}if(r>="0"&&r<="9"||r==="."&&t+1<n&&s[t+1]>="0"&&s[t+1]<="9"){let a="";if(r==="0"&&t+1<n&&(s[t+1]==="x"||s[t+1]==="X"))for(a="0x",t+=2;t<n&&/[0-9a-fA-F]/.test(s[t]);)a+=s[t++];else{for(;t<n&&(s[t]>="0"&&s[t]<="9"||s[t]===".");)a+=s[t++];if(t<n&&(s[t]==="e"||s[t]==="E"))for(a+=s[t++],t<n&&(s[t]==="+"||s[t]==="-")&&(a+=s[t++]);t<n&&s[t]>="0"&&s[t]<="9";)a+=s[t++]}e.push({t:y.NUM,v:Number(a)});continue}if(r==="'"||r==='"'){const a=r;let c="";for(t++;t<n&&s[t]!==a;){if(s[t]==="\\"&&t+1<n){const u=s[++t];u==="n"?c+=`
|
|
11
|
+
`:u==="t"?c+=" ":u==="r"?c+="\r":u==="\\"?c+="\\":u===a?c+=a:c+=u}else c+=s[t];t++}t++,e.push({t:y.STR,v:c});continue}if(r==="`"){const a=[];let c="";for(t++;t<n&&s[t]!=="`";)if(s[t]==="$"&&t+1<n&&s[t+1]==="{"){a.push(c),c="",t+=2;let u=1,l="";for(;t<n&&u>0;){if(s[t]==="{")u++;else if(s[t]==="}"&&(u--,u===0))break;l+=s[t++]}t++,a.push({expr:l})}else s[t]==="\\"&&t+1<n?c+=s[++t]:c+=s[t],t++;t++,a.push(c),e.push({t:y.TMPL,v:a});continue}if(r>="a"&&r<="z"||r>="A"&&r<="Z"||r==="_"||r==="$"){let a="";for(;t<n&&/[\w$]/.test(s[t]);)a+=s[t++];e.push({t:y.IDENT,v:a});continue}const i=s.slice(t,t+3);if(i==="==="||i==="!=="||i==="?."){i==="?."?(e.push({t:y.OP,v:"?."}),t+=2):(e.push({t:y.OP,v:i}),t+=3);continue}const o=s.slice(t,t+2);if(o==="=="||o==="!="||o==="<="||o===">="||o==="&&"||o==="||"||o==="??"||o==="?."||o==="=>"){e.push({t:y.OP,v:o}),t+=2;continue}if("+-*/%".includes(r)){e.push({t:y.OP,v:r}),t++;continue}if("<>=!".includes(r)){e.push({t:y.OP,v:r}),t++;continue}if(r==="."&&t+2<n&&s[t+1]==="."&&s[t+2]==="."){e.push({t:y.OP,v:"..."}),t+=3;continue}if("()[]{},.?:".includes(r)){e.push({t:y.PUNC,v:r}),t++;continue}t++}return e.push({t:y.EOF,v:null}),e}class En{constructor(e,t){this.tokens=e,this.pos=0,this.scope=t}peek(){return this.tokens[this.pos]}next(){return this.tokens[this.pos++]}expect(e,t){const n=this.next();if(n.t!==e||t!==void 0&&n.v!==t)throw new Error(`Expected ${t||e} but got ${n.v}`);return n}match(e,t){const n=this.peek();return n.t===e&&(t===void 0||n.v===t)?this.next():null}parse(){return this.parseExpression(0)}parseExpression(e){var n;let t=this.parseUnary();for(;;){const r=this.peek();if(r.t===y.PUNC&&r.v==="?"&&((n=this.tokens[this.pos+1])==null?void 0:n.v)!=="."){if(1<=e)break;this.next();const i=this.parseExpression(0);this.expect(y.PUNC,":");const o=this.parseExpression(0);t={type:"ternary",cond:t,truthy:i,falsy:o};continue}if(r.t===y.OP&&r.v in le){const i=le[r.v];if(i<=e)break;this.next();const o=this.parseExpression(i);t={type:"binary",op:r.v,left:t,right:o};continue}if(r.t===y.IDENT&&(r.v==="instanceof"||r.v==="in")&&le[r.v]>e){const i=le[r.v];this.next();const o=this.parseExpression(i);t={type:"binary",op:r.v,left:t,right:o};continue}break}return t}parseUnary(){const e=this.peek();if(e.t===y.IDENT&&e.v==="typeof")return this.next(),{type:"typeof",arg:this.parseUnary()};if(e.t===y.IDENT&&e.v==="void")return this.next(),this.parseUnary(),{type:"literal",value:void 0};if(e.t===y.OP&&e.v==="!")return this.next(),{type:"not",arg:this.parseUnary()};if(e.t===y.OP&&(e.v==="-"||e.v==="+")){this.next();const t=this.parseUnary();return{type:"unary",op:e.v,arg:t}}return this.parsePostfix()}parsePostfix(){let e=this.parsePrimary();for(;;){const t=this.peek();if(t.t===y.PUNC&&t.v==="."){this.next();const n=this.next();e={type:"member",obj:e,prop:n.v,computed:!1},this.peek().t===y.PUNC&&this.peek().v==="("&&(e=this._parseCall(e));continue}if(t.t===y.OP&&t.v==="?."){this.next();const n=this.peek();if(n.t===y.PUNC&&n.v==="["){this.next();const r=this.parseExpression(0);this.expect(y.PUNC,"]"),e={type:"optional_member",obj:e,prop:r,computed:!0}}else if(n.t===y.PUNC&&n.v==="(")e={type:"optional_call",callee:e,args:this._parseArgs()};else{const r=this.next();e={type:"optional_member",obj:e,prop:r.v,computed:!1},this.peek().t===y.PUNC&&this.peek().v==="("&&(e=this._parseCall(e))}continue}if(t.t===y.PUNC&&t.v==="["){this.next();const n=this.parseExpression(0);this.expect(y.PUNC,"]"),e={type:"member",obj:e,prop:n,computed:!0},this.peek().t===y.PUNC&&this.peek().v==="("&&(e=this._parseCall(e));continue}if(t.t===y.PUNC&&t.v==="("){e=this._parseCall(e);continue}break}return e}_parseCall(e){const t=this._parseArgs();return{type:"call",callee:e,args:t}}_parseArgs(){this.expect(y.PUNC,"(");const e=[];for(;!(this.peek().t===y.PUNC&&this.peek().v===")")&&this.peek().t!==y.EOF;)this.peek().t===y.OP&&this.peek().v==="..."?(this.next(),e.push({type:"spread",arg:this.parseExpression(0)})):e.push(this.parseExpression(0)),this.peek().t===y.PUNC&&this.peek().v===","&&this.next();return this.expect(y.PUNC,")"),e}parsePrimary(){const e=this.peek();if(e.t===y.NUM)return this.next(),{type:"literal",value:e.v};if(e.t===y.STR)return this.next(),{type:"literal",value:e.v};if(e.t===y.TMPL)return this.next(),{type:"template",parts:e.v};if(e.t===y.PUNC&&e.v==="("){const t=this.pos;this.next();const n=[];let r=!0;if(!(this.peek().t===y.PUNC&&this.peek().v===")"))for(;r;){const o=this.peek();if(o.t===y.IDENT&&!wn.has(o.v))if(n.push(this.next().v),this.peek().t===y.PUNC&&this.peek().v===",")this.next();else break;else r=!1}if(r&&this.peek().t===y.PUNC&&this.peek().v===")"&&(this.next(),this.peek().t===y.OP&&this.peek().v==="=>")){this.next();const o=this.parseExpression(0);return{type:"arrow",params:n,body:o}}this.pos=t,this.next();const i=this.parseExpression(0);return this.expect(y.PUNC,")"),i}if(e.t===y.PUNC&&e.v==="["){this.next();const t=[];for(;!(this.peek().t===y.PUNC&&this.peek().v==="]")&&this.peek().t!==y.EOF;)this.peek().t===y.OP&&this.peek().v==="..."?(this.next(),t.push({type:"spread",arg:this.parseExpression(0)})):t.push(this.parseExpression(0)),this.peek().t===y.PUNC&&this.peek().v===","&&this.next();return this.expect(y.PUNC,"]"),{type:"array",elements:t}}if(e.t===y.PUNC&&e.v==="{"){this.next();const t=[];for(;!(this.peek().t===y.PUNC&&this.peek().v==="}")&&this.peek().t!==y.EOF;){if(this.peek().t===y.OP&&this.peek().v==="..."){this.next(),t.push({spread:!0,value:this.parseExpression(0)}),this.peek().t===y.PUNC&&this.peek().v===","&&this.next();continue}const n=this.next();let r;if(n.t===y.IDENT||n.t===y.STR)r=n.v;else if(n.t===y.NUM)r=String(n.v);else throw new Error("Invalid object key: "+n.v);this.peek().t===y.PUNC&&(this.peek().v===","||this.peek().v==="}")?t.push({key:r,value:{type:"ident",name:r}}):(this.expect(y.PUNC,":"),t.push({key:r,value:this.parseExpression(0)})),this.peek().t===y.PUNC&&this.peek().v===","&&this.next()}return this.expect(y.PUNC,"}"),{type:"object",properties:t}}if(e.t===y.IDENT){if(this.next(),e.v==="true")return{type:"literal",value:!0};if(e.v==="false")return{type:"literal",value:!1};if(e.v==="null")return{type:"literal",value:null};if(e.v==="undefined")return{type:"literal",value:void 0};if(e.v==="new"){let t=this.parsePrimary();for(;this.peek().t===y.PUNC&&this.peek().v===".";){this.next();const r=this.next();t={type:"member",obj:t,prop:r.v,computed:!1}}let n=[];return this.peek().t===y.PUNC&&this.peek().v==="("&&(n=this._parseArgs()),{type:"new",callee:t,args:n}}if(this.peek().t===y.OP&&this.peek().v==="=>"){this.next();const t=this.parseExpression(0);return{type:"arrow",params:[e.v],body:t}}return{type:"ident",name:e.v}}return this.next(),{type:"literal",value:void 0}}}const Ts=new Set(["length","map","filter","find","findIndex","some","every","reduce","reduceRight","forEach","includes","indexOf","lastIndexOf","join","slice","concat","flat","flatMap","reverse","sort","fill","keys","values","entries","at","toString"]),bn=new Set(["length","charAt","charCodeAt","includes","indexOf","lastIndexOf","slice","substring","trim","trimStart","trimEnd","toLowerCase","toUpperCase","split","replace","replaceAll","match","search","startsWith","endsWith","padStart","padEnd","repeat","at","toString","valueOf"]),Sn=new Set(["toFixed","toPrecision","toString","valueOf"]),Cs=new Set(["hasOwnProperty","toString","valueOf"]),As=new Set(["PI","E","LN2","LN10","LOG2E","LOG10E","SQRT2","SQRT1_2","abs","ceil","floor","round","trunc","max","min","pow","sqrt","sign","random","log","log2","log10"]),Rs=new Set(["parse","stringify"]);function fe(s,e){return typeof e=="string"&&new Set(["constructor","__proto__","prototype","__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__","call","apply","bind"]).has(e)?!1:s!=null&&(typeof s=="object"||typeof s=="function")?!0:typeof s=="string"?bn.has(e):typeof s=="number"?Sn.has(e):!1}function b(s,e){var t;if(s)switch(s.type){case"literal":return s.value;case"ident":{const n=s.name;for(const r of e)if(r&&typeof r=="object"&&n in r)return r[n];return n==="Math"?Math:n==="JSON"?JSON:n==="Date"?Date:n==="Array"?Array:n==="Object"?Object:n==="String"?String:n==="Number"?Number:n==="Boolean"?Boolean:n==="parseInt"?parseInt:n==="parseFloat"?parseFloat:n==="isNaN"?isNaN:n==="isFinite"?isFinite:n==="Infinity"?1/0:n==="NaN"?NaN:n==="encodeURIComponent"?encodeURIComponent:n==="decodeURIComponent"?decodeURIComponent:n==="console"?console:n==="Map"?Map:n==="Set"?Set:n==="URL"?URL:n==="URLSearchParams"?URLSearchParams:void 0}case"template":{let n="";for(const r of s.parts)typeof r=="string"?n+=r:r&&r.expr&&(n+=String((t=G(r.expr,e))!=null?t:""));return n}case"member":{const n=b(s.obj,e);if(n==null)return;const r=s.computed?b(s.prop,e):s.prop;return fe(n,r)?n[r]:void 0}case"optional_member":{const n=b(s.obj,e);if(n==null)return;const r=s.computed?b(s.prop,e):s.prop;return fe(n,r)?n[r]:void 0}case"call":return vn(s,e,!1);case"optional_call":{const n=s.callee,r=Ue(s.args,e);if(n.type==="member"||n.type==="optional_member"){const o=b(n.obj,e);if(o==null)return;const a=n.computed?b(n.prop,e):n.prop;if(!fe(o,a))return;const c=o[a];return typeof c!="function"?void 0:c.apply(o,r)}const i=b(n,e);return i==null||typeof i!="function"?void 0:i(...r)}case"new":{const n=b(s.callee,e);if(typeof n!="function")return;if(n===Date||n===Array||n===Map||n===Set||n===URL||n===URLSearchParams){const r=Ue(s.args,e);return new n(...r)}return}case"binary":return Tn(s,e);case"unary":{const n=b(s.arg,e);return s.op==="-"?-n:+n}case"not":return!b(s.arg,e);case"typeof":try{return typeof b(s.arg,e)}catch{return"undefined"}case"ternary":{const n=b(s.cond,e);return b(n?s.truthy:s.falsy,e)}case"array":{const n=[];for(const r of s.elements)if(r.type==="spread"){const i=b(r.arg,e);if(i!=null&&typeof i[Symbol.iterator]=="function")for(const o of i)n.push(o)}else n.push(b(r,e));return n}case"object":{const n={};for(const r of s.properties)if(r.spread){const i=b(r.value,e);i!=null&&typeof i=="object"&&Object.assign(n,i)}else n[r.key]=b(r.value,e);return n}case"arrow":{const n=s.params,r=s.body,i=e;return function(...o){const a={};return n.forEach((c,u)=>{a[c]=o[u]}),b(r,[a,...i])}}default:return}}function Ue(s,e){const t=[];for(const n of s)if(n.type==="spread"){const r=b(n.arg,e);if(r!=null&&typeof r[Symbol.iterator]=="function")for(const i of r)t.push(i)}else t.push(b(n,e));return t}function vn(s,e){const t=s.callee,n=Ue(s.args,e);if(t.type==="member"||t.type==="optional_member"){const i=b(t.obj,e);if(i==null)return;const o=t.computed?b(t.prop,e):t.prop;if(!fe(i,o))return;const a=i[o];return typeof a!="function"?void 0:a.apply(i,n)}const r=b(t,e);if(typeof r=="function")return r(...n)}function Tn(s,e){if(s.op==="&&"){const r=b(s.left,e);return r&&b(s.right,e)}if(s.op==="||"){const r=b(s.left,e);return r||b(s.right,e)}if(s.op==="??"){const r=b(s.left,e);return r!=null?r:b(s.right,e)}const t=b(s.left,e),n=b(s.right,e);switch(s.op){case"+":return t+n;case"-":return t-n;case"*":return t*n;case"/":return t/n;case"%":return t%n;case"==":return t==n;case"!=":return t!=n;case"===":return t===n;case"!==":return t!==n;case"<":return t<n;case">":return t>n;case"<=":return t<=n;case">=":return t>=n;case"instanceof":return t instanceof n;case"in":return t in n;default:return}}const Z=new Map,Cn=512;function G(s,e){try{const t=s.trim();if(!t)return;if(/^[a-zA-Z_$][\w$]*$/.test(t)){for(const r of e)if(r&&typeof r=="object"&&t in r)return r[t]}let n=Z.get(t);if(n)Z.delete(t),Z.set(t,n);else{const r=gn(t);if(n=new En(r,e).parse(),Z.size>=Cn){const o=Z.keys().next().value;Z.delete(o)}Z.set(t,n)}return b(n,e)}catch(t){typeof console!="undefined"&&console.debug&&console.debug(`[zQuery EXPR_EVAL] Failed to evaluate: "${s}"`,t.message);return}}const ne=new Map,z=new Map,he=new Map;let vt=0;if(typeof document!="undefined"&&!document.querySelector("[data-zq-cloak]")){const s=document.createElement("style");s.textContent="[z-cloak]{display:none!important}*,*::before,*::after{-webkit-tap-highlight-color:transparent}",s.setAttribute("data-zq-cloak",""),document.head.appendChild(s)}const de=new WeakMap,pe=new WeakMap;function se(s){if(he.has(s))return he.get(s);if(typeof window!="undefined"&&window.__zqInline){for(const[n,r]of Object.entries(window.__zqInline))if(s===n||s.endsWith("/"+n)||s.endsWith("\\"+n)){const i=Promise.resolve(r);return he.set(s,i),i}}let e=s;if(typeof s=="string"&&!s.startsWith("/")&&!s.includes(":")&&!s.startsWith("//"))try{const n=document.querySelector("base"),r=n?n.href:window.location.origin+"/";e=new URL(s,r).href}catch{}const t=fetch(e).then(n=>{if(!n.ok)throw new Error(`zQuery: Failed to load resource "${s}" (${n.status})`);return n.text()});return he.set(s,t),t}function J(s,e){if(!e||!s||typeof s!="string"||s.startsWith("/")||s.includes("://")||s.startsWith("//"))return s;try{if(e.includes("://"))return new URL(s,e).href;const t=document.querySelector("base"),n=t?t.href:window.location.origin+"/",r=new URL(e.endsWith("/")?e:e+"/",n).href;return new URL(s,r).href}catch{return s}}let Me;try{typeof document!="undefined"&&document.currentScript&&document.currentScript.src&&(Me=document.currentScript.src.replace(/[?#].*$/,""))}catch{}function Tt(){try{const e=(new Error().stack||"").match(/(?:https?|file):\/\/[^\s\)]+/g)||[];for(const t of e){const n=t.replace(/:\d+:\d+$/,"").replace(/:\d+$/,"");if(!/zquery(\.min)?\.js$/i.test(n)&&!(Me&&n.replace(/[?#].*$/,"")===Me))return n.replace(/\/[^/]*$/,"/")}}catch{}}function _e(s,e){return e.split(".").reduce((t,n)=>t==null?void 0:t[n],s)}function An(s,e,t){const n=e.split("."),r=n.pop(),i=n.reduce((o,a)=>o&&typeof o=="object"?o[a]:void 0,s);i&&typeof i=="object"&&(i[r]=t)}class Ie{constructor(e,t,n={}){this._uid=++vt,this._el=e,this._def=t,this._mounted=!1,this._destroyed=!1,this._updateQueued=!1,this._listeners=[],this._watchCleanups=[],this.refs={},this._slotContent={};const r=[];if([...e.childNodes].forEach(o=>{if(o.nodeType===1&&o.hasAttribute("slot")){const a=o.getAttribute("slot")||"default";this._slotContent[a]||(this._slotContent[a]=""),this._slotContent[a]+=o.outerHTML}else(o.nodeType===1||o.nodeType===3&&o.textContent.trim())&&r.push(o.nodeType===1?o.outerHTML:o.textContent)}),r.length&&(this._slotContent.default=r.join("")),t.props&&typeof t.props=="object"&&!Array.isArray(t.props)?(this.props=this._resolveReactiveProps(t.props,n),this._propObserver=new MutationObserver(o=>{if(this._destroyed)return;let a=!1;for(const c of o)if(c.type==="attributes"){const u=c.attributeName;if(u.startsWith("z-")||u.startsWith("@")||u.startsWith(":")||u.startsWith("data-zq"))continue;(u.startsWith(":")?u.slice(1):u)in t.props&&(a=!0)}a&&(this.props=this._resolveReactiveProps(t.props,{}),this._scheduleUpdate())}),this._propObserver.observe(e,{attributes:!0})):this.props=Object.freeze({...n}),this._storeCleanups=[],this.stores={},t.stores&&typeof t.stores=="object")for(const[o,a]of Object.entries(t.stores)){if(!a||!a._zqConnector)continue;const{store:c,keys:u}=a,l={};for(const h of u)l[h]=c.state[h];this.stores[o]=l;const p=c.subscribe(u,(h,d)=>{this.stores[o][h]=d,this._destroyed||this._scheduleUpdate()});this._storeCleanups.push(p)}const i=typeof t.state=="function"?t.state():{...t.state||{}};if(this.state=Ne(i,(o,a,c)=>{this._destroyed||(this._runWatchers(o,a,c),this._scheduleUpdate())}),this.computed={},t.computed)for(const[o,a]of Object.entries(t.computed))Object.defineProperty(this.computed,o,{get:()=>a.call(this,this.state.__raw||this.state),enumerable:!0});for(const[o,a]of Object.entries(t))typeof a=="function"&&!Rn.has(o)&&(this[o]=a.bind(this));if(t.init)try{t.init.call(this)}catch(o){C(S.COMP_LIFECYCLE,`Component "${t._name}" init() threw`,{component:t._name},o)}if(t.watch){this._prevWatchValues={};for(const o of Object.keys(t.watch))this._prevWatchValues[o]=_e(this.state.__raw||this.state,o)}}_runWatchers(e,t,n){var i;const r=this._def.watch;if(r){for(const[o,a]of Object.entries(r))if(e===o||o.startsWith(e+".")||e.startsWith(o+".")){const c=_e(this.state.__raw||this.state,o),u=(i=this._prevWatchValues)==null?void 0:i[o];if(c!==u){const l=typeof a=="function"?a:a.handler;typeof l=="function"&&l.call(this,c,u),this._prevWatchValues&&(this._prevWatchValues[o]=c)}}}}_scheduleUpdate(){this._updateQueued||(this._updateQueued=!0,queueMicrotask(()=>{try{this._destroyed||this._render()}finally{this._updateQueued=!1}}))}_resolveReactiveProps(e,t){const n={};for(const[r,i]of Object.entries(e)){const o=typeof i=="object"&&i!==null?i:{type:i},a=o.type,c=o.default;if(r in t){n[r]=t[r];continue}let u=this._el.getAttribute(":"+r),l=u!==null;l||(u=this._el.getAttribute(r),l=u!==null),l&&u!==null?n[r]=this._coercePropValue(u,a):c!==void 0?n[r]=typeof c=="function"?c():c:n[r]=void 0}return Object.freeze(n)}_coercePropValue(e,t){if(t===Number)return Number(e);if(t===Boolean)return e!=="false"&&e!=="0"&&e!=="";if(t===Object||t===Array)try{return JSON.parse(e)}catch{return e}return e}async _loadExternals(){const e=this._def,t=e._base;if(e.templateUrl&&!e._templateLoaded){const n=e.templateUrl;if(typeof n=="string")e._externalTemplate=await se(J(n,t));else if(Array.isArray(n)){const r=n.map(o=>J(o,t)),i=await Promise.all(r.map(o=>se(o)));e._externalTemplates={},i.forEach((o,a)=>{e._externalTemplates[a]=o})}else if(typeof n=="object"){const r=Object.entries(n),i=await Promise.all(r.map(([,o])=>se(J(o,t))));e._externalTemplates={},r.forEach(([o],a)=>{e._externalTemplates[o]=i[a]})}e._templateLoaded=!0}if(e.styleUrl&&!e._styleLoaded){const n=e.styleUrl;if(typeof n=="string"){const r=J(n,t);e._externalStyles=await se(r),e._resolvedStyleUrls=[r]}else if(Array.isArray(n)){const r=n.map(o=>J(o,t)),i=await Promise.all(r.map(o=>se(o)));e._externalStyles=i.join(`
|
|
12
|
+
`),e._resolvedStyleUrls=r}e._styleLoaded=!0}}_render(){var o,a;if(this._def.templateUrl&&!this._def._templateLoaded||this._def.styleUrl&&!this._def._styleLoaded){this._loadExternals().then(()=>{this._destroyed||this._render()});return}this._def._externalTemplates&&(this.templates=this._def._externalTemplates);let e;this._def.render?(e=this._def.render.call(this),e=this._expandZFor(e)):this._def._externalTemplate?(e=this._expandZFor(this._def._externalTemplate),e=e.replace(/\{\{(.+?)\}\}/g,(c,u)=>{try{const l=G(u.trim(),[this.state.__raw||this.state,{props:this.props,computed:this.computed,$:typeof window!="undefined"?window.$:void 0}]);return l!=null?ye(String(l)):""}catch{return""}})):e="",e=this._expandContentDirectives(e),e.includes("<slot")&&(e=e.replace(/<slot(?:\s+name="([^"]*)")?\s*(?:\/>|>([\s\S]*?)<\/slot>)/g,(c,u,l)=>{const p=u||"default";return this._slotContent[p]||l||""}));const t=[this._def.styles||"",this._def._externalStyles||""].filter(Boolean).join(`
|
|
13
|
+
`);if(!this._mounted&&t){const c=`z-s${this._uid}`;this._el.setAttribute(c,"");let u=0,l=0;const p=t.replace(/([^{}]+)\{|\}/g,(d,_)=>{if(d==="}")return u>0&&l<=u&&(u=0),l--,d;l++;const w=_.trim();return w.startsWith("@")?(/^@(keyframes|font-face)\b/.test(w)&&(u=l),d):u>0&&l>u?d:_.split(",").map(m=>`[${c}] ${m.trim()}`).join(", ")+" {"}),h=document.createElement("style");h.textContent=p,h.setAttribute("data-zq-component",this._def._name||""),h.setAttribute("data-zq-scope",c),this._def._resolvedStyleUrls&&(h.setAttribute("data-zq-style-urls",this._def._resolvedStyleUrls.join(" ")),this._def.styles&&h.setAttribute("data-zq-inline",this._def.styles)),document.head.appendChild(h),this._styleEl=h}let n=null;const r=document.activeElement;if(r&&this._el.contains(r)){const c=(o=r.getAttribute)==null?void 0:o.call(r,"z-model"),u=(a=r.getAttribute)==null?void 0:a.call(r,"z-ref");let l=null;if(c)l=`[z-model="${c}"]`;else if(u)l=`[z-ref="${u}"]`;else{const p=r.tagName.toLowerCase();if(p==="input"||p==="textarea"||p==="select"){let h=p;r.type&&(h+=`[type="${r.type}"]`),r.name&&(h+=`[name="${r.name}"]`),r.placeholder&&(h+=`[placeholder="${CSS.escape(r.placeholder)}"]`),l=h}}l&&(n={selector:l,start:r.selectionStart,end:r.selectionEnd,dir:r.selectionDirection})}const i=typeof window!="undefined"&&(window.__zqMorphHook||window.__zqRenderHook)?performance.now():0;if(this._mounted?Be(this._el,e):(this._el.innerHTML=e,i&&window.__zqRenderHook&&window.__zqRenderHook(this._el,performance.now()-i,"mount",this._def._name)),this._processDirectives(),this._bindEvents(),this._bindRefs(),this._bindModels(),n){const c=this._el.querySelector(n.selector);if(c){c!==document.activeElement&&c.focus();try{n.start!==null&&n.start!==void 0&&c.setSelectionRange(n.start,n.end,n.dir)}catch{}}}if(At(this._el),this._mounted){if(this._def.updated)try{this._def.updated.call(this)}catch(c){C(S.COMP_LIFECYCLE,`Component "${this._def._name}" updated() threw`,{component:this._def._name},c)}}else if(this._mounted=!0,this._def.mounted)try{this._def.mounted.call(this)}catch(c){C(S.COMP_LIFECYCLE,`Component "${this._def._name}" mounted() threw`,{component:this._def._name},c)}}_bindEvents(){const e=new Map;if(this._el.querySelectorAll("*").forEach(n=>{if(n.closest("[z-pre]"))return;const r=n.attributes;for(let i=0;i<r.length;i++){const o=r[i];let a;if(o.name.charCodeAt(0)===64)a=o.name.slice(1);else if(o.name.startsWith("z-on:"))a=o.name.slice(5);else continue;const c=a.split("."),u=c[0],l=c.slice(1),p=o.value;n.dataset.zqEid||(n.dataset.zqEid=String(++vt));const h=`[data-zq-eid="${n.dataset.zqEid}"]`;e.has(u)||e.set(u,[]),e.get(u).push({selector:h,methodExpr:p,modifiers:l,el:n})}}),this._eventBindings=e,this._delegatedEvents){for(const n of e.keys())this._delegatedEvents.has(n)||this._attachDelegatedEvent(n,e.get(n));for(const n of this._delegatedEvents.keys())if(!e.has(n)){const{handler:r,opts:i}=this._delegatedEvents.get(n);this._el.removeEventListener(n,r,i),this._delegatedEvents.delete(n),this._listeners=this._listeners.filter(o=>o.event!==n)}return}this._delegatedEvents=new Map;for(const[n,r]of e)this._attachDelegatedEvent(n,r);this._outsideListeners=this._outsideListeners||[];for(const[n,r]of e)for(const i of r){if(!i.modifiers.includes("outside"))continue;const o=a=>{if(i.el.contains(a.target))return;const c=i.methodExpr.match(/^(\w+)(?:\(([^)]*)\))?$/);if(!c)return;const u=this[c[1]];typeof u=="function"&&u.call(this,a)};document.addEventListener(n,o,!0),this._outsideListeners.push({event:n,handler:o})}}_attachDelegatedEvent(e,t){const n=t.some(a=>a.modifiers.includes("capture")),r=t.some(a=>a.modifiers.includes("passive")),i=n||r?{capture:n,passive:r}:!1,o=a=>{var p;const c=((p=this._eventBindings)==null?void 0:p.get(e))||[],u=[];for(const h of c){const d=a.target.closest(h.selector);d&&u.push({...h,matched:d})}u.sort((h,d)=>h.matched===d.matched?0:h.matched.contains(d.matched)?1:-1);let l=null;for(const{selector:h,methodExpr:d,modifiers:_,el:w,matched:m}of u){if(l){let k=!1;for(const A of l)if(m.contains(A)&&m!==A){k=!0;break}if(k)continue}if(_.includes("self")&&a.target!==w||_.includes("outside")&&w.contains(a.target))continue;const v={enter:"Enter",escape:"Escape",tab:"Tab",space:" ",delete:"Delete|Backspace",up:"ArrowUp",down:"ArrowDown",left:"ArrowLeft",right:"ArrowRight"},N=new Set(["prevent","stop","self","once","outside","capture","passive","debounce","throttle","ctrl","shift","alt","meta"]);let W=!1;for(let k=0;k<_.length;k++){const A=_[k];if(v[A]){const Fe=v[A].split("|");if(!a.key||!Fe.includes(a.key)){W=!0;break}}else{if(N.has(A))continue;if(/^\d+$/.test(A)&&k>0&&(_[k-1]==="debounce"||_[k-1]==="throttle"))continue;if(!a.key||a.key.toLowerCase()!==A.toLowerCase()){W=!0;break}}}if(W||_.includes("ctrl")&&!a.ctrlKey||_.includes("shift")&&!a.shiftKey||_.includes("alt")&&!a.altKey||_.includes("meta")&&!a.metaKey)continue;_.includes("prevent")&&a.preventDefault(),_.includes("stop")&&(a.stopPropagation(),l||(l=[]),l.push(m));const Q=k=>{const A=d.match(/^(\w+)(?:\(([^)]*)\))?$/);if(!A)return;const Fe=A[1],je=this[Fe];if(typeof je=="function")if(A[2]!==void 0){const Es=A[2].split(",").map(x=>{if(x=x.trim(),x!=="")return x==="$event"?k:x==="true"?!0:x==="false"?!1:x==="null"?null:/^-?\d+(\.\d+)?$/.test(x)?Number(x):x.startsWith("'")&&x.endsWith("'")||x.startsWith('"')&&x.endsWith('"')?x.slice(1,-1):x.startsWith("state.")?_e(this.state,x.slice(6)):x}).filter(x=>x!==void 0);je(...Es)}else je(k)},qe=_.indexOf("debounce");if(qe!==-1){const k=parseInt(_[qe+1],10)||250,A=de.get(w)||{};clearTimeout(A[e]),A[e]=setTimeout(()=>Q(a),k),de.set(w,A);continue}const we=_.indexOf("throttle");if(we!==-1){const k=parseInt(_[we+1],10)||250,A=pe.get(w)||{};if(A[e])continue;Q(a),A[e]=setTimeout(()=>{A[e]=null},k),pe.set(w,A);continue}if(_.includes("once")){if(w.dataset.zqOnce===e)continue;w.dataset.zqOnce=e}Q(a)}};this._el.addEventListener(e,o,i),this._listeners.push({event:e,handler:o}),this._delegatedEvents.set(e,{handler:o,opts:i})}_bindRefs(){this.refs={},this._el.querySelectorAll("[z-ref]").forEach(e=>{this.refs[e.getAttribute("z-ref")]=e})}_bindModels(){this._el.querySelectorAll("[z-model]").forEach(e=>{const t=e.getAttribute("z-model"),n=e.tagName.toLowerCase(),r=(e.type||"").toLowerCase(),i=e.hasAttribute("contenteditable"),o=e.hasAttribute("z-lazy"),a=e.hasAttribute("z-trim"),c=e.hasAttribute("z-number"),u=e.hasAttribute("z-uppercase"),l=e.hasAttribute("z-lowercase"),p=e.hasAttribute("z-debounce"),h=p?parseInt(e.getAttribute("z-debounce"),10)||250:0,d=_e(this.state,t);if(n==="input"&&r==="checkbox")e.checked=!!d;else if(n==="input"&&r==="radio")e.checked=e.value===String(d);else if(n==="select"&&e.multiple){const m=Array.isArray(d)?d.map(String):[];[...e.options].forEach(v=>{v.selected=m.includes(v.value)})}else i?e.textContent!==String(d!=null?d:"")&&(e.textContent=d!=null?d:""):e.value=d!=null?d:"";const _=o||n==="select"||r==="checkbox"||r==="radio"?"change":"input";if(e._zqModelBound)return;e._zqModelBound=!0;const w=()=>{let m;r==="checkbox"?m=e.checked:n==="select"&&e.multiple?m=[...e.selectedOptions].map(v=>v.value):i?m=e.textContent:m=e.value,a&&typeof m=="string"&&(m=m.trim()),u&&typeof m=="string"&&(m=m.toUpperCase()),l&&typeof m=="string"&&(m=m.toLowerCase()),(c||r==="number"||r==="range")&&(m=Number(m)),An(this.state,t,m)};if(p){let m=null;e.addEventListener(_,()=>{clearTimeout(m),m=setTimeout(w,h)})}else e.addEventListener(_,w)})}_evalExpr(e){return G(e,[this.state.__raw||this.state,{props:this.props,refs:this.refs,computed:this.computed,$:typeof window!="undefined"?window.$:void 0}])}_expandZFor(e){if(!e.includes("z-for"))return e;const t=document.createElement("div");t.innerHTML=e;const n=r=>{let i=[...r.querySelectorAll("[z-for]")].filter(o=>!o.querySelector("[z-for]"));if(i.length){for(const o of i){if(!o.parentNode)continue;const c=o.getAttribute("z-for").match(/^\s*(?:\(\s*(\w+)(?:\s*,\s*(\w+))?\s*\)|(\w+))\s+in\s+(.+)\s*$/);if(!c){o.removeAttribute("z-for");continue}const u=c[1]||c[3],l=c[2]||"$index",p=c[4].trim();let h=this._evalExpr(p);if(h==null){o.remove();continue}if(typeof h=="number"&&(h=Array.from({length:h},(N,W)=>W+1)),!Array.isArray(h)&&typeof h=="object"&&typeof h[Symbol.iterator]!="function"&&(h=Object.entries(h).map(([N,W])=>({key:N,value:W}))),!Array.isArray(h)&&typeof h[Symbol.iterator]=="function"&&(h=[...h]),!Array.isArray(h)){o.remove();continue}const d=o.parentNode,_=o.cloneNode(!0);_.removeAttribute("z-for");const w=_.outerHTML,m=document.createDocumentFragment(),v=(N,W,Q)=>N.replace(/\{\{(.+?)\}\}/g,(qe,we)=>{try{const k={};k[u]=W,k[l]=Q;const A=G(we.trim(),[k,this.state.__raw||this.state,{props:this.props,computed:this.computed,$:typeof window!="undefined"?window.$:void 0}]);return A!=null?ye(String(A)):""}catch{return""}});for(let N=0;N<h.length;N++){const W=v(w,h[N],N),Q=document.createElement("div");for(Q.innerHTML=W;Q.firstChild;)m.appendChild(Q.firstChild)}d.replaceChild(m,o)}r.querySelector("[z-for]")&&n(r)}};return n(t),t.innerHTML}_expandContentDirectives(e){if(!e.includes("z-html")&&!e.includes("z-text"))return e;const t=document.createElement("div");return t.innerHTML=e,t.querySelectorAll("[z-html]").forEach(n=>{if(n.closest("[z-pre]"))return;const r=this._evalExpr(n.getAttribute("z-html"));n.innerHTML=r!=null?String(r):"",n.removeAttribute("z-html")}),t.querySelectorAll("[z-text]").forEach(n=>{if(n.closest("[z-pre]"))return;const r=this._evalExpr(n.getAttribute("z-text"));n.textContent=r!=null?String(r):"",n.removeAttribute("z-text")}),t.innerHTML}_processDirectives(){const e=[...this._el.querySelectorAll("[z-if]")];for(const r of e){if(!r.parentNode||r.closest("[z-pre]"))continue;const i=!!this._evalExpr(r.getAttribute("z-if")),o=[{el:r,show:i}];let a=r.nextElementSibling;for(;a;)if(a.hasAttribute("z-else-if"))o.push({el:a,show:!!this._evalExpr(a.getAttribute("z-else-if"))}),a=a.nextElementSibling;else if(a.hasAttribute("z-else")){o.push({el:a,show:!0});break}else break;let c=!1;for(const u of o)if(!c&&u.show){c=!0,u.el.removeAttribute("z-if"),u.el.removeAttribute("z-else-if"),u.el.removeAttribute("z-else");const l=u.el.getAttribute("z-transition");l&&(u.el.removeAttribute("z-transition"),this._transitionEnter(u.el,l))}else{const l=u.el.getAttribute("z-transition");l?this._transitionLeave(u.el,l,()=>u.el.remove()):u.el.remove()}}this._el.querySelectorAll("[z-show]").forEach(r=>{if(r.closest("[z-pre]"))return;const i=!!this._evalExpr(r.getAttribute("z-show")),o=r.getAttribute("z-transition"),a=r.style.display==="none"||r.hasAttribute("data-zq-hidden");o?(r.removeAttribute("z-show"),i&&a?(r.style.display="",r.removeAttribute("data-zq-hidden"),this._transitionEnter(r,o)):!i&&!a?(r.setAttribute("data-zq-hidden",""),this._transitionLeave(r,o,()=>{r.style.display="none"})):(r.style.display=i?"":"none",i?r.removeAttribute("data-zq-hidden"):r.setAttribute("data-zq-hidden",""))):(r.style.display=i?"":"none",r.removeAttribute("z-show"))});const t=document.createTreeWalker(this._el,NodeFilter.SHOW_ELEMENT,{acceptNode(r){return r.hasAttribute("z-pre")?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}});let n;for(;n=t.nextNode();){const r=n.attributes;for(let i=r.length-1;i>=0;i--){const o=r[i];let a;if(o.name.startsWith("z-bind:"))a=o.name.slice(7);else if(o.name.charCodeAt(0)===58&&o.name.charCodeAt(1)!==58)a=o.name.slice(1);else continue;const c=this._evalExpr(o.value);n.removeAttribute(o.name),c===!1||c===null||c===void 0?n.removeAttribute(a):c===!0?n.setAttribute(a,""):n.setAttribute(a,String(c))}}this._el.querySelectorAll("[z-class]").forEach(r=>{if(r.closest("[z-pre]"))return;const i=this._evalExpr(r.getAttribute("z-class"));if(typeof i=="string")i.split(/\s+/).filter(Boolean).forEach(o=>r.classList.add(o));else if(Array.isArray(i))i.filter(Boolean).forEach(o=>r.classList.add(String(o)));else if(i&&typeof i=="object")for(const[o,a]of Object.entries(i))r.classList.toggle(o,!!a);r.removeAttribute("z-class")}),this._el.querySelectorAll("[z-style]").forEach(r=>{if(r.closest("[z-pre]"))return;const i=this._evalExpr(r.getAttribute("z-style"));if(typeof i=="string")r.style.cssText+=";"+i;else if(i&&typeof i=="object")for(const[o,a]of Object.entries(i))r.style[o]=a;r.removeAttribute("z-style")}),this._el.querySelectorAll("[z-stream]").forEach(r=>{if(r.closest("[z-pre]"))return;const i=this._evalExpr(r.getAttribute("z-stream")),o=typeof MediaStream!="undefined";i==null?r.srcObject=null:o&&i instanceof MediaStream||i&&typeof i.getTracks=="function"?r.srcObject=i:r.srcObject=null,r.removeAttribute("z-stream")}),this._el.querySelectorAll("[z-cloak]").forEach(r=>{r.removeAttribute("z-cloak")})}_transitionEnter(e,t){const n=this._def.transition;if(n&&n.enter){e.classList.add(n.enter);const r=n.duration||0,i=()=>e.classList.remove(n.enter);r>0?setTimeout(i,r):(e.addEventListener("transitionend",i,{once:!0}),e.addEventListener("animationend",i,{once:!0}));return}e.classList.add(`${t}-enter-from`,`${t}-enter-active`),e.offsetHeight,requestAnimationFrame(()=>{e.classList.remove(`${t}-enter-from`),e.classList.add(`${t}-enter-to`);const r=()=>{e.classList.remove(`${t}-enter-active`,`${t}-enter-to`)};e.addEventListener("transitionend",r,{once:!0}),e.addEventListener("animationend",r,{once:!0})})}_transitionLeave(e,t,n){const r=this._def.transition;if(r&&r.leave){e.classList.add(r.leave);const i=r.duration||0,o=()=>{e.classList.remove(r.leave),n()};i>0?setTimeout(o,i):(e.addEventListener("transitionend",o,{once:!0}),e.addEventListener("animationend",o,{once:!0}));return}e.classList.add(`${t}-leave-from`,`${t}-leave-active`),e.offsetHeight,requestAnimationFrame(()=>{e.classList.remove(`${t}-leave-from`),e.classList.add(`${t}-leave-to`);const i=()=>{e.classList.remove(`${t}-leave-active`,`${t}-leave-to`),n()};e.addEventListener("transitionend",i,{once:!0}),e.addEventListener("animationend",i,{once:!0})})}setState(e){e&&Object.keys(e).length>0?Object.assign(this.state,e):this._scheduleUpdate()}emit(e,t){this._el.dispatchEvent(new CustomEvent(e,{detail:t,bubbles:!0,cancelable:!0}))}destroy(){if(this._destroyed)return;if(this._destroyed=!0,this._def.destroyed)try{this._def.destroyed.call(this)}catch(t){C(S.COMP_LIFECYCLE,`Component "${this._def._name}" destroyed() threw`,{component:this._def._name},t)}this._propObserver&&(this._propObserver.disconnect(),this._propObserver=null),this._storeCleanups&&(this._storeCleanups.forEach(t=>t()),this._storeCleanups=[]),this._listeners.forEach(({event:t,handler:n})=>this._el.removeEventListener(t,n)),this._listeners=[],this._outsideListeners&&(this._outsideListeners.forEach(({event:t,handler:n})=>document.removeEventListener(t,n,!0)),this._outsideListeners=[]),this._delegatedEvents=null,this._eventBindings=null,this._el.querySelectorAll("*").forEach(t=>{const n=de.get(t);if(n){for(const i in n)clearTimeout(n[i]);de.delete(t)}const r=pe.get(t);if(r){for(const i in r)clearTimeout(r[i]);pe.delete(t)}}),this._styleEl&&this._styleEl.remove(),z.delete(this._el),this._el.innerHTML=""}}const Rn=new Set(["state","render","styles","init","mounted","updated","destroyed","props","templateUrl","styleUrl","templates","base","computed","watch","stores","transition","activated","deactivated"]);function kn(s,e){if(!s||typeof s!="string")throw new I(S.COMP_INVALID_NAME,"Component name must be a non-empty string");if(!s.includes("-"))throw new I(S.COMP_INVALID_NAME,`Component name "${s}" must contain a hyphen (Web Component convention)`);e._name=s,e.base!==void 0?e._base=e.base:e._base=Tt(),ne.set(s,e)}function Ct(s,e,t={}){const n=typeof s=="string"?document.querySelector(s):s;if(!n)throw new I(S.COMP_MOUNT_TARGET,`Mount target "${s}" not found`,{target:s});const r=ne.get(e);if(!r)throw new I(S.COMP_NOT_FOUND,`Component "${e}" not registered`,{component:e});z.has(n)&&z.get(n).destroy();const i=new Ie(n,r,t);return z.set(n,i),i._render(),i}function At(s=document.body){for(const[e,t]of ne)s.querySelectorAll(e).forEach(r=>{if(z.has(r))return;const i={};let o=null,a=r.parentElement;for(;a;){if(z.has(a)){o=z.get(a);break}a=a.parentElement}[...r.attributes].forEach(u=>{if(!(u.name.startsWith("@")||u.name.startsWith("z-"))){if(u.name.startsWith(":")){const l=u.name.slice(1);if(o)i[l]=G(u.value,[o.state.__raw||o.state,{props:o.props,refs:o.refs,computed:o.computed,$:typeof window!="undefined"?window.$:void 0}]);else try{i[l]=JSON.parse(u.value)}catch{i[l]=u.value}return}try{i[u.name]=JSON.parse(u.value)}catch{i[u.name]=u.value}}});const c=new Ie(r,t,i);z.set(r,c),c._render()})}function On(s){const e=typeof s=="string"?document.querySelector(s):s;return z.get(e)||null}function xn(s){const e=typeof s=="string"?document.querySelector(s):s,t=z.get(e);t&&t.destroy()}function Ln(){return Object.fromEntries(ne)}async function Rt(s){const e=ne.get(s);e&&(e.templateUrl&&!e._templateLoaded||e.styleUrl&&!e._styleLoaded)&&await Ie.prototype._loadExternals.call({_def:e})}const re=new Map;function Nn(s,e={}){const t=Tt(),n=Array.isArray(s)?s:[s],r=[],i=[];let o=null;e.critical!==!1&&(o=document.createElement("style"),o.setAttribute("data-zq-critical",""),o.textContent=`html{visibility:hidden!important;background:${e.bg||"#0d1117"}}`,document.head.insertBefore(o,document.head.firstChild));for(let c of n){if(typeof c=="string"&&!c.startsWith("/")&&!c.includes(":")&&!c.startsWith("//")&&(c=J(c,t)),re.has(c)){r.push(re.get(c));continue}const u=document.createElement("link");u.rel="stylesheet",u.href=c,u.setAttribute("data-zq-style","");const l=new Promise(p=>{u.onload=p,u.onerror=p});i.push(l),document.head.appendChild(u),re.set(c,u),r.push(u)}return{ready:Promise.all(i).then(()=>{o&&o.remove()}),remove(){for(const c of r){c.remove();for(const[u,l]of re)if(l===c){re.delete(u);break}}}}}const F="__zq";function kt(s,e){if(s===e)return!0;if(!s||!e)return!1;const t=Object.keys(s),n=Object.keys(e);if(t.length!==n.length)return!1;for(let r=0;r<t.length;r++){const i=t[r];if(s[i]!==e[i])return!1}return!0}class Pn{constructor(e={}){this._el=null;const t=typeof location!="undefined"&&location.protocol==="file:";this._mode=t?"hash":e.mode||"history",this._keepAliveCache=new Map;let n=e.base;if(n==null&&(n=typeof window!="undefined"&&window.__ZQ_BASE||"",!n&&typeof document!="undefined")){const r=document.querySelector("base");if(r){try{n=new URL(r.href).pathname}catch{n=r.getAttribute("href")||""}n==="/"&&(n="")}}if(this._base=String(n).replace(/\/+$/,""),this._base&&!this._base.startsWith("/")&&(this._base="/"+this._base),this._routes=[],this._fallback=e.fallback||null,this._current=null,this._guards={before:[],after:[]},this._listeners=new Set,this._instance=null,this._resolving=!1,this._substateListeners=[],this._inSubstate=!1,e.el)this._el=typeof e.el=="string"?document.querySelector(e.el):e.el;else if(typeof document!="undefined"){const r=document.querySelector("z-outlet");if(r){if(this._el=r,!e.fallback&&r.getAttribute("fallback")&&(this._fallback=r.getAttribute("fallback")),!e.mode&&r.getAttribute("mode")){const i=r.getAttribute("mode");(i==="hash"||i==="history")&&(this._mode=t?"hash":i)}if(e.base==null&&r.getAttribute("base")){let i=r.getAttribute("base");i=String(i).replace(/\/+$/,""),i&&!i.startsWith("/")&&(i="/"+i),this._base=i}}}e.routes&&e.routes.forEach(r=>this.add(r)),this._mode==="hash"?(this._onNavEvent=()=>this._resolve(),window.addEventListener("hashchange",this._onNavEvent),this._onPopState=r=>{const i=r.state;if(i&&i[F]==="substate"){if(this._fireSubstate(i.key,i.data,"pop"))return;this._resolve().then(()=>{this._fireSubstate(i.key,i.data,"pop")});return}else this._inSubstate&&(this._inSubstate=!1,this._fireSubstate(null,null,"reset"))},window.addEventListener("popstate",this._onPopState)):(this._onNavEvent=r=>{const i=r.state;if(i&&i[F]==="substate"){if(this._fireSubstate(i.key,i.data,"pop"))return;this._resolve().then(()=>{this._fireSubstate(i.key,i.data,"pop")});return}else this._inSubstate&&(this._inSubstate=!1,this._fireSubstate(null,null,"reset"));this._resolve()},window.addEventListener("popstate",this._onNavEvent)),this._onLinkClick=r=>{if(r.metaKey||r.ctrlKey||r.shiftKey||r.altKey)return;const i=r.target.closest("[z-link]");if(!i||i.getAttribute("target")==="_blank")return;r.preventDefault();let o=i.getAttribute("z-link");if(o&&/^[a-z][a-z0-9+.-]*:/i.test(o))return;const a=i.getAttribute("z-link-params");if(a)try{const c=JSON.parse(a);o=this._interpolateParams(o,c)}catch(c){C(S.ROUTER_RESOLVE,"Malformed JSON in z-link-params",{href:o,paramsAttr:a},c)}if(this.navigate(o),i.hasAttribute("z-to-top")){const c=i.getAttribute("z-to-top")||"instant";window.scrollTo({top:0,behavior:c})}},document.addEventListener("click",this._onLinkClick),this._el&&queueMicrotask(()=>this._resolve())}add(e){const{regex:t,keys:n}=me(e.path);if(this._routes.push({...e,_regex:t,_keys:n}),e.fallback){const r=me(e.fallback);this._routes.push({...e,path:e.fallback,_regex:r.regex,_keys:r.keys})}return this}remove(e){return this._routes=this._routes.filter(t=>t.path!==e),this}_interpolateParams(e,t){return!t||typeof t!="object"?e:e.replace(/:([\w]+)/g,(n,r)=>{const i=t[r];return i!=null?encodeURIComponent(String(i)):":"+r})}_currentURL(){if(this._mode==="hash")return window.location.hash.slice(1)||"/";const e=window.location.pathname||"/",t=window.location.hash||"";return e+t}navigate(e,t={}){t.params&&(e=this._interpolateParams(e,t.params));const[n,r]=(e||"").split("#");let i=this._normalizePath(n);const o=r?"#"+r:"";if(this._mode==="hash"){r&&(window.__zqScrollTarget=r);const a="#"+i;if(window.location.hash===a&&!t.force)return this;window.location.hash=a}else{const a=this._base+i+o,c=(window.location.pathname||"/")+(window.location.hash||"");if(a===c&&!t.force){if(r){const p=document.getElementById(r);p&&p.scrollIntoView({behavior:"smooth",block:"start"})}return this}const u=this._base+i,l=window.location.pathname||"/";if(u===l&&o&&!t.force){if(window.history.replaceState({...t.state,[F]:"route"},"",a),r){const p=document.getElementById(r);p&&p.scrollIntoView({behavior:"smooth",block:"start"})}return this}window.history.pushState({...t.state,[F]:"route"},"",a),this._resolve()}return this}replace(e,t={}){t.params&&(e=this._interpolateParams(e,t.params));const[n,r]=(e||"").split("#");let i=this._normalizePath(n);const o=r?"#"+r:"";return this._mode==="hash"?(r&&(window.__zqScrollTarget=r),window.location.replace("#"+i)):(window.history.replaceState({...t.state,[F]:"route"},"",this._base+i+o),this._resolve()),this}_normalizePath(e){let t=e&&e.startsWith("/")?e:e?`/${e}`:"/";if(this._base){if(t===this._base)return"/";t.startsWith(this._base+"/")&&(t=t.slice(this._base.length)||"/")}return t}resolve(e){const t=e&&e.startsWith("/")?e:e?`/${e}`:"/";return this._base+t}back(){return window.history.back(),this}forward(){return window.history.forward(),this}go(e){return window.history.go(e),this}beforeEach(e){return this._guards.before.push(e),this}afterEach(e){return this._guards.after.push(e),this}onChange(e){return this._listeners.add(e),()=>this._listeners.delete(e)}pushSubstate(e,t){if(this._inSubstate=!0,this._mode==="hash"){const n=window.location.hash||"#/";window.history.pushState({[F]:"substate",key:e,data:t},"",window.location.href)}else window.history.pushState({[F]:"substate",key:e,data:t},"",window.location.href);return this}onSubstate(e){return this._substateListeners.push(e),()=>{this._substateListeners=this._substateListeners.filter(t=>t!==e)}}_fireSubstate(e,t,n){for(const r of this._substateListeners)try{if(r(e,t,n)===!0)return!0}catch(i){C(S.ROUTER_GUARD,"onSubstate listener threw",{key:e,data:t},i)}return!1}get current(){return this._current}get base(){return this._base}get path(){if(this._mode==="hash"){const t=window.location.hash.slice(1)||"/";if(t&&!t.startsWith("/")){window.__zqScrollTarget=t;const n=this._current&&this._current.path||"/";return window.location.replace("#"+n),n}return t}let e=window.location.pathname||"/";if(e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),this._base){if(e===this._base)return"/";if(e.startsWith(this._base+"/"))return e.slice(this._base.length)||"/"}return e}get query(){const e=this._mode==="hash"?window.location.hash.split("?")[1]||"":window.location.search.slice(1);return Object.fromEntries(new URLSearchParams(e))}async _resolve(){if(!this._resolving){this._resolving=!0,this._redirectCount=0;try{await this.__resolve()}finally{this._resolving=!1}}}async __resolve(){const e=window.history.state;if(e&&e[F]==="substate"&&this._fireSubstate(e.key,e.data,"resolve"))return;const t=this.path,[n,r]=t.split("?"),i=n||"/",o=Object.fromEntries(new URLSearchParams(r||""));let a=null,c={};for(const p of this._routes){const h=i.match(p._regex);if(h){a=p,p._keys.forEach((d,_)=>{c[d]=h[_+1]});break}}if(!a&&this._fallback&&(a={component:this._fallback,path:"*",_keys:[],_regex:/.*/}),!a)return;const u={route:a,params:c,query:o,path:i},l=this._current;if(l&&this._instance&&a.component===l.route.component){const p=kt(c,l.params),h=kt(o,l.query);if(p&&h)return}for(const p of this._guards.before)try{const h=await p(u,l);if(h===!1)return;if(typeof h=="string"){if(++this._redirectCount>10){C(S.ROUTER_GUARD,"Too many guard redirects (possible loop)",{to:u},null);return}const[d,_]=h.split("#"),w=this._normalizePath(d||"/"),m=_?"#"+_:"";return this._mode==="hash"?(_&&(window.__zqScrollTarget=_),window.location.replace("#"+w)):window.history.replaceState({[F]:"route"},"",this._base+w+m),this.__resolve()}}catch(h){C(S.ROUTER_GUARD,"Before-guard threw",{to:u,from:l},h);return}if(a.load)try{await a.load()}catch(p){C(S.ROUTER_LOAD,`Failed to load module for route "${a.path}"`,{path:a.path},p);return}if(this._current=u,this._el&&a.component){typeof a.component=="string"&&await Rt(a.component);const p=!!a.keepAlive,h=typeof a.component=="string"?a.component:null;if(this._instance&&this._currentKeepAlive&&this._currentComponentName){const w=this._keepAliveCache.get(this._currentComponentName);if(w&&(w.container.style.display="none",w.instance._def.deactivated))try{w.instance._def.deactivated.call(w.instance)}catch(m){C(S.COMP_LIFECYCLE,`Component "${this._currentComponentName}" deactivated() threw`,{component:this._currentComponentName},m)}this._instance=null}else this._instance&&(this._instance.destroy(),this._instance=null);const d=typeof window!="undefined"&&window.__zqRenderHook?performance.now():0,_={...c,$route:u,$query:o,$params:c};if(p&&h&&this._keepAliveCache.has(h)){const w=this._keepAliveCache.get(h);if([...this._el.children].forEach(m=>{m.style.display="none"}),w.container.style.display="",this._instance=w.instance,this._currentKeepAlive=!0,this._currentComponentName=h,w.instance._def.activated)try{w.instance._def.activated.call(w.instance)}catch(m){C(S.COMP_LIFECYCLE,`Component "${h}" activated() threw`,{component:h},m)}d&&window.__zqRenderHook(this._el,performance.now()-d,"route",h)}else if(h){[...this._el.children].forEach(m=>{m.dataset.zqKeepAlive&&(m.style.display="none")}),[...this._el.children].forEach(m=>{m.dataset.zqKeepAlive||m.remove()});const w=document.createElement(h);p&&(w.dataset.zqKeepAlive=h),this._el.appendChild(w);try{this._instance=Ct(w,h,_)}catch(m){C(S.COMP_NOT_FOUND,`Failed to mount component for route "${a.path}"`,{component:a.component,path:a.path},m);return}if(p&&(this._keepAliveCache.set(h,{container:w,instance:this._instance}),this._instance._def.activated))try{this._instance._def.activated.call(this._instance)}catch(m){C(S.COMP_LIFECYCLE,`Component "${h}" activated() threw`,{component:h},m)}this._currentKeepAlive=p,this._currentComponentName=h,d&&window.__zqRenderHook(this._el,performance.now()-d,"route",h)}else if(typeof a.component=="function"){[...this._el.children].forEach(m=>{m.dataset.zqKeepAlive?m.style.display="none":m.remove()});const w=document.createElement("div");for(w.innerHTML=a.component(u);w.firstChild;)this._el.appendChild(w.firstChild);this._currentKeepAlive=!1,this._currentComponentName=null,d&&window.__zqRenderHook(this._el,performance.now()-d,"route",u)}}this._updateActiveRoutes(i);for(const p of this._guards.after)await p(u,l);this._listeners.forEach(p=>p(u,l))}_updateActiveRoutes(e){if(typeof document=="undefined")return;const t=document.querySelectorAll("[z-active-route]");for(let n=0;n<t.length;n++){const r=t[n],i=r.getAttribute("z-active-route"),o=r.getAttribute("z-active-class")||"active",c=r.hasAttribute("z-active-exact")?e===i:i==="/"?e==="/":e.startsWith(i);r.classList.toggle(o,c)}}destroy(){this._onNavEvent&&(window.removeEventListener(this._mode==="hash"?"hashchange":"popstate",this._onNavEvent),this._onNavEvent=null),this._onPopState&&(window.removeEventListener("popstate",this._onPopState),this._onPopState=null),this._onLinkClick&&(document.removeEventListener("click",this._onLinkClick),this._onLinkClick=null);for(const[,e]of this._keepAliveCache)e.instance.destroy();this._keepAliveCache.clear(),this._instance&&this._instance.destroy(),this._listeners.clear(),this._substateListeners=[],this._inSubstate=!1,this._routes=[],this._guards={before:[],after:[]}}}function me(s){const e=[],t=s.replace(/:(\w+)/g,(n,r)=>(e.push(r),"([^/]+)")).replace(/\*/g,"(.*)");return{regex:new RegExp(`^${t}$`),keys:e}}function Bn(s,e,t="not-found"){for(const n of s){const{regex:r,keys:i}=me(n.path),o=e.match(r);if(o){const a={};return i.forEach((c,u)=>{a[c]=o[u+1]}),{component:n.component,params:a}}if(n.fallback){const a=me(n.fallback),c=e.match(a.regex);if(c){const u={};return a.keys.forEach((l,p)=>{u[l]=c[p+1]}),{component:n.component,params:u}}}}return{component:t,params:{}}}let De=null;function Un(s){return De=new Pn(s),De}function Mn(){return De}class In{constructor(e={}){this._subscribers=new Map,this._wildcards=new Set,this._actions=e.actions||{},this._getters=e.getters||{},this._middleware=[],this._history=[],this._maxHistory=e.maxHistory||1e3,this._debug=e.debug||!1,this._batching=!1,this._batchQueue=[],this._undoStack=[],this._redoStack=[],this._maxUndo=e.maxUndo||50;const t=typeof e.state=="function"?e.state():{...e.state||{}};this._initialState=JSON.parse(JSON.stringify(t)),this.state=Ne(t,(n,r,i)=>{if(this._batching){this._batchQueue.push({key:n,value:r,old:i});return}this._notifySubscribers(n,r,i)}),this.getters={};for(const[n,r]of Object.entries(this._getters))Object.defineProperty(this.getters,n,{get:()=>r(this.state.__raw||this.state),enumerable:!0})}_notifySubscribers(e,t,n){const r=this._subscribers.get(e);r&&r.forEach(i=>{try{i(e,t,n)}catch(o){C(S.STORE_SUBSCRIBE,`Subscriber for "${e}" threw`,{key:e},o)}}),this._wildcards.forEach(i=>{try{i(e,t,n)}catch(o){C(S.STORE_SUBSCRIBE,"Wildcard subscriber threw",{key:e},o)}})}batch(e){this._batching=!0,this._batchQueue=[];let t;try{t=e(this.state)}finally{this._batching=!1;const n=new Map;for(const r of this._batchQueue)n.set(r.key,r);this._batchQueue=[];for(const{key:r,value:i,old:o}of n.values())this._notifySubscribers(r,i,o)}return t}checkpoint(){const e=JSON.parse(JSON.stringify(this.state.__raw||this.state));this._undoStack.push(e),this._undoStack.length>this._maxUndo&&this._undoStack.splice(0,this._undoStack.length-this._maxUndo),this._redoStack=[]}undo(){if(this._undoStack.length===0)return!1;const e=JSON.parse(JSON.stringify(this.state.__raw||this.state));this._redoStack.push(e);const t=this._undoStack.pop();return this.replaceState(t),!0}redo(){if(this._redoStack.length===0)return!1;const e=JSON.parse(JSON.stringify(this.state.__raw||this.state));this._undoStack.push(e);const t=this._redoStack.pop();return this.replaceState(t),!0}get canUndo(){return this._undoStack.length>0}get canRedo(){return this._redoStack.length>0}dispatch(e,...t){const n=this._actions[e];if(!n){C(S.STORE_ACTION,`Unknown action "${e}"`,{action:e,args:t});return}for(const r of this._middleware)try{if(r(e,t,this.state)===!1)return}catch(i){C(S.STORE_MIDDLEWARE,`Middleware threw during "${e}"`,{action:e},i);return}this._debug&&console.log(`%c[Store] ${e}`,"color: #4CAF50; font-weight: bold;",...t);try{const r=n(this.state,...t);return this._history.push({action:e,args:t,timestamp:Date.now()}),this._history.length>this._maxHistory&&this._history.splice(0,this._history.length-this._maxHistory),r}catch(r){C(S.STORE_ACTION,`Action "${e}" threw`,{action:e,args:t},r)}}subscribe(e,t){if(typeof e=="function")return this._wildcards.add(e),()=>this._wildcards.delete(e);if(Array.isArray(e)){const n=e,r=(i,o,a)=>{n.includes(i)&&t(i,o,a)};return this._wildcards.add(r),()=>this._wildcards.delete(r)}return this._subscribers.has(e)||this._subscribers.set(e,new Set),this._subscribers.get(e).add(t),()=>{var n;return(n=this._subscribers.get(e))==null?void 0:n.delete(t)}}snapshot(){return JSON.parse(JSON.stringify(this.state.__raw||this.state))}replaceState(e){const t=this.state.__raw||this.state;for(const n of Object.keys(t))delete this.state[n];Object.assign(this.state,e)}use(e){return this._middleware.push(e),this}get history(){return[...this._history]}reset(e){this.replaceState(e||JSON.parse(JSON.stringify(this._initialState))),this._history=[],this._undoStack=[],this._redoStack=[]}}let Ot=new Map;function Dn(s,e){typeof s=="object"&&(e=s,s="default");const t=new In(e);return Ot.set(s,t),t}function Wn(s="default"){return Ot.get(s)||null}function zn(s,e){return{_zqConnector:!0,store:s,keys:e}}const j={baseURL:"",headers:{"Content-Type":"application/json"},timeout:3e4},q={request:[],response:[]};async function V(s,e,t,n={}){var h;if(!e||typeof e!="string")throw new Error(`HTTP request requires a URL string, got ${typeof e}`);let r=e.startsWith("http")?e:j.baseURL+e,i={...j.headers,...n.headers},o;const a={method:s.toUpperCase(),headers:i,...n};if(t!==void 0&&s!=="GET"&&s!=="HEAD"&&(t instanceof FormData?(o=t,delete a.headers["Content-Type"]):typeof t=="object"?o=JSON.stringify(t):o=t,a.body=o),t&&(s==="GET"||s==="HEAD")&&typeof t=="object"){const d=new URLSearchParams(t).toString();r+=(r.includes("?")?"&":"?")+d}const c=new AbortController,u=(h=n.timeout)!=null?h:j.timeout;let l;n.signal?typeof AbortSignal.any=="function"?a.signal=AbortSignal.any([n.signal,c.signal]):(a.signal=c.signal,n.signal.aborted?c.abort(n.signal.reason):n.signal.addEventListener("abort",()=>c.abort(n.signal.reason),{once:!0})):a.signal=c.signal;let p=!1;u>0&&(l=setTimeout(()=>{p=!0,c.abort()},u));for(const d of q.request){const _=await d(a,r);if(_===!1)throw new Error("Request blocked by interceptor");_!=null&&_.url&&(r=_.url),_!=null&&_.options&&Object.assign(a,_.options)}try{const d=await fetch(r,a);l&&clearTimeout(l);const _=d.headers.get("Content-Type")||"";let w;try{if(_.includes("application/json"))w=await d.json();else if(_.includes("text/"))w=await d.text();else if(_.includes("application/octet-stream")||_.includes("image/"))w=await d.blob();else{const v=await d.text();try{w=JSON.parse(v)}catch{w=v}}}catch(v){w=null,console.warn(`[zQuery HTTP] Failed to parse response body from ${s} ${r}:`,v.message)}const m={ok:d.ok,status:d.status,statusText:d.statusText,headers:Object.fromEntries(d.headers.entries()),data:w,response:d};for(const v of q.response)await v(m);if(!d.ok){const v=new Error(`HTTP ${d.status}: ${d.statusText}`);throw v.response=m,v}return m}catch(d){throw l&&clearTimeout(l),d.name==="AbortError"?p?new Error(`Request timeout after ${u}ms: ${s} ${r}`):new Error(`Request aborted: ${s} ${r}`):d}}const H={get:(s,e,t)=>V("GET",s,e,t),post:(s,e,t)=>V("POST",s,e,t),put:(s,e,t)=>V("PUT",s,e,t),patch:(s,e,t)=>V("PATCH",s,e,t),delete:(s,e,t)=>V("DELETE",s,e,t),head:(s,e)=>V("HEAD",s,void 0,e),configure(s){s.baseURL!==void 0&&(j.baseURL=s.baseURL),s.headers&&Object.assign(j.headers,s.headers),s.timeout!==void 0&&(j.timeout=s.timeout)},getConfig(){return{baseURL:j.baseURL,headers:{...j.headers},timeout:j.timeout}},onRequest(s){return q.request.push(s),()=>{const e=q.request.indexOf(s);e!==-1&&q.request.splice(e,1)}},onResponse(s){return q.response.push(s),()=>{const e=q.response.indexOf(s);e!==-1&&q.response.splice(e,1)}},clearInterceptors(s){(!s||s==="request")&&(q.request.length=0),(!s||s==="response")&&(q.response.length=0)},all(s){return Promise.all(s)},createAbort(){return new AbortController},raw:(s,e)=>fetch(s,e)};function qn(s,e=250){let t;const n=(...r)=>{clearTimeout(t),t=setTimeout(()=>s(...r),e)};return n.cancel=()=>clearTimeout(t),n}function Fn(s,e=250){let t=0,n;return(...r)=>{const i=Date.now(),o=e-(i-t);clearTimeout(n),o<=0?(t=i,s(...r)):n=setTimeout(()=>{t=Date.now(),s(...r)},o)}}function jn(...s){return e=>s.reduce((t,n)=>n(t),e)}function Qn(s){let e=!1,t;return(...n)=>(e||(e=!0,t=s(...n)),t)}function $n(s){return new Promise(e=>setTimeout(e,s))}function ye(s){const e={"&":"&","<":"<",">":">",'"':""","'":"'"};return String(s).replace(/[&<>"']/g,t=>e[t])}function Zn(s){return String(s).replace(/<[^>]*>/g,"")}function Hn(s,...e){return s.reduce((t,n,r)=>{const i=e[r-1],o=i instanceof We?i.toString():ye(i!=null?i:"");return t+o+n})}class We{constructor(e){this._html=e}toString(){return this._html}}function Kn(s){return new We(s)}function Gn(){return crypto!=null&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,s=>{const e=new Uint8Array(1);crypto.getRandomValues(e);const t=e[0]&15;return(s==="x"?t:t&3|8).toString(16)})}function Jn(s){return s.replace(/-([a-z])/g,(e,t)=>t.toUpperCase())}function Vn(s){return s.replace(/([A-Z]+)([A-Z][a-z])/g,"$1-$2").replace(/([a-z\d])([A-Z])/g,"$1-$2").toLowerCase()}function Yn(s){if(typeof structuredClone=="function")return structuredClone(s);const e=new Map;function t(n){if(n===null||typeof n!="object")return n;if(e.has(n))return e.get(n);if(n instanceof Date)return new Date(n.getTime());if(n instanceof RegExp)return new RegExp(n.source,n.flags);if(n instanceof Map){const i=new Map;return e.set(n,i),n.forEach((o,a)=>i.set(t(a),t(o))),i}if(n instanceof Set){const i=new Set;return e.set(n,i),n.forEach(o=>i.add(t(o))),i}if(ArrayBuffer.isView(n))return new n.constructor(n.buffer.slice(0));if(n instanceof ArrayBuffer)return n.slice(0);if(Array.isArray(n)){const i=[];e.set(n,i);for(let o=0;o<n.length;o++)i[o]=t(n[o]);return i}const r=Object.create(Object.getPrototypeOf(n));e.set(n,r);for(const i of Object.keys(n))r[i]=t(n[i]);return r}return t(s)}const ze=new Set(["__proto__","constructor","prototype"]);function Xn(s,...e){const t=new WeakSet;function n(r,i){if(t.has(i))return r;t.add(i);for(const o of Object.keys(i))ze.has(o)||(i[o]&&typeof i[o]=="object"&&!Array.isArray(i[o])?((!r[o]||typeof r[o]!="object")&&(r[o]={}),n(r[o],i[o])):r[o]=i[o]);return r}for(const r of e)n(s,r);return s}function xt(s,e,t){if(s===e)return!0;if(typeof s!=typeof e||typeof s!="object"||s===null||e===null||Array.isArray(s)!==Array.isArray(e))return!1;if(t||(t=new Set),t.has(s))return!0;t.add(s);const n=Object.keys(s),r=Object.keys(e);return n.length!==r.length?!1:n.every(i=>xt(s[i],e[i],t))}function es(s){return new URLSearchParams(s).toString()}function ts(s){return Object.fromEntries(new URLSearchParams(s))}const ns={get(s,e=null){try{const t=localStorage.getItem(s);return t!==null?JSON.parse(t):e}catch{return e}},set(s,e){localStorage.setItem(s,JSON.stringify(e))},remove(s){localStorage.removeItem(s)},clear(){localStorage.clear()}},ss={get(s,e=null){try{const t=sessionStorage.getItem(s);return t!==null?JSON.parse(t):e}catch{return e}},set(s,e){sessionStorage.setItem(s,JSON.stringify(e))},remove(s){sessionStorage.removeItem(s)},clear(){sessionStorage.clear()}};class Lt{constructor(){this._handlers=new Map}on(e,t){return this._handlers.has(e)||this._handlers.set(e,new Set),this._handlers.get(e).add(t),()=>this.off(e,t)}off(e,t){var n;(n=this._handlers.get(e))==null||n.delete(t)}emit(e,...t){var n;(n=this._handlers.get(e))==null||n.forEach(r=>r(...t))}once(e,t){const n=(...r)=>{t(...r),this.off(e,n)};return this.on(e,n)}clear(){this._handlers.clear()}}const rs=new Lt;function is(s,e,t){let n,r,i;if(e===void 0?(n=0,r=s,i=1):(n=s,r=e,i=t!==void 0?t:1),i===0)return[];const o=[];if(i>0)for(let a=n;a<r;a+=i)o.push(a);else for(let a=n;a>r;a+=i)o.push(a);return o}function os(s,e){if(!e)return[...new Set(s)];const t=new Set;return s.filter(n=>{const r=e(n);return t.has(r)?!1:(t.add(r),!0)})}function as(s,e){const t=[];for(let n=0;n<s.length;n+=e)t.push(s.slice(n,n+e));return t}function cs(s,e){var n;const t={};for(const r of s){const i=e(r);((n=t[i])!=null?n:t[i]=[]).push(r)}return t}function us(s,e){const t={};for(const n of e)n in s&&(t[n]=s[n]);return t}function ls(s,e){const t=new Set(e),n={};for(const r of Object.keys(s))t.has(r)||(n[r]=s[r]);return n}function fs(s,e,t){const n=e.split(".");let r=s;for(const i of n){if(r==null||typeof r!="object")return t;r=r[i]}return r===void 0?t:r}function hs(s,e,t){const n=e.split(".");let r=s;for(let o=0;o<n.length-1;o++){const a=n[o];if(ze.has(a))return s;(r[a]==null||typeof r[a]!="object")&&(r[a]={}),r=r[a]}const i=n[n.length-1];return ze.has(i)||(r[i]=t),s}function ds(s){return s==null?!0:typeof s=="string"||Array.isArray(s)?s.length===0:s instanceof Map||s instanceof Set?s.size===0:typeof s=="object"?Object.keys(s).length===0:!1}function ps(s){return s?s[0].toUpperCase()+s.slice(1).toLowerCase():""}function _s(s,e,t="…"){if(s.length<=e)return s;const n=Math.max(0,e-t.length);return s.slice(0,n)+t}function ms(s,e,t){return s<e?e:s>t?t:s}function ys(s,e){let t,n=0;typeof e=="function"?t=e:e&&typeof e=="object"&&(n=e.maxSize||0);const r=new Map,i=(...o)=>{const a=t?t(...o):o[0];if(r.has(a)){const u=r.get(a);return r.delete(a),r.set(a,u),u}const c=s(...o);return r.set(a,c),n>0&&r.size>n&&r.delete(r.keys().next().value),c};return i.clear=()=>r.clear(),i}function ws(s,e={}){const{attempts:t=3,delay:n=1e3,backoff:r=1}=e;return new Promise((i,o)=>{let a=0,c=n;const u=()=>{a++,s(a).then(i,l=>{if(a>=t)return o(l);const p=c;c*=r,setTimeout(u,p)})};u()})}function gs(s,e,t){let n;return Promise.race([s,new Promise((i,o)=>{n=setTimeout(()=>o(new Error(t||`Timed out after ${e}ms`)),e)})]).finally(()=>clearTimeout(n))}function f(s,e){if(typeof s=="function"){T.ready(s);return}return T(s,e)}f.id=T.id,f.class=T.class,f.classes=T.classes,f.tag=T.tag,Object.defineProperty(f,"name",{value:T.name,writable:!0,configurable:!0}),f.children=T.children,f.qs=T.qs,f.qsa=T.qsa,f.all=function(s,e){return yn(s,e)},f.create=T.create,f.ready=T.ready,f.on=T.on,f.off=T.off,f.fn=T.fn,f.reactive=Ne,f.Signal=R,f.signal=$,f.computed=un,f.effect=yt,f.batch=ln,f.untracked=fn,f.component=kn,f.mount=Ct,f.mountAll=At,f.getInstance=On,f.destroy=xn,f.components=Ln,f.prefetch=Rt,f.style=Nn,f.morph=Be,f.morphElement=gt,f.safeEval=G,f.router=Un,f.getRouter=Mn,f.matchRoute=Bn,f.store=Dn,f.getStore=Wn,f.connectStore=zn,f.http=H,f.get=H.get,f.post=H.post,f.put=H.put,f.patch=H.patch,f.delete=H.delete,f.head=H.head,f.debounce=qn,f.throttle=Fn,f.pipe=jn,f.once=Qn,f.sleep=$n,f.escapeHtml=ye,f.stripHtml=Zn,f.html=Hn,f.trust=Kn,f.TrustedHTML=We,f.uuid=Gn,f.camelCase=Jn,f.kebabCase=Vn,f.deepClone=Yn,f.deepMerge=Xn,f.isEqual=xt,f.param=es,f.parseQuery=ts,f.storage=ns,f.session=ss,f.EventBus=Lt,f.bus=rs,f.range=is,f.unique=os,f.chunk=as,f.groupBy=cs,f.pick=us,f.omit=ls,f.getPath=fs,f.setPath=hs,f.isEmpty=ds,f.capitalize=ps,f.truncate=_s,f.clamp=ms,f.memoize=ys,f.retry=ws,f.timeout=gs,f.onError=Nt,f.ZQueryError=I,f.ErrorCode=S,f.guardCallback=Pt,f.guardAsync=Ut,f.validate=Bt,f.formatError=Qe,f.webrtc=cn,f.SignalingClient=Ae,f.Peer=Re,f.Room=K,f.useRoom=Ye,f.usePeer=Xe,f.useTracks=et,f.useDataChannel=tt,f.useConnectionQuality=nt,f.fetchTurnCredentials=ke,f.mergeIceServers=rt,f.createTurnRefresher=it,f.deriveSFrameKey=ct,f.generateSFrameKey=ut,f.SFrameContext=ee,f.encryptFrame=Oe,f.decryptFrame=xe,f.attachE2ee=lt,f.loadSfuAdapter=mt,f.SfuError=O,f.decodeJoinToken=ht,f.isJoinTokenExpired=dt,f.samplePeerStats=Le,f.createStatsSampler=pt,f.classifyStats=_t,f.parseSdp=ge,f.validateSdp=Ze,f.parseCandidate=be,f.stringifyCandidate=He,f.filterCandidates=Ke,f.isPrivateIp=Se,f.isLoopbackIp=ve,f.isLinkLocalIp=Te,f.isMdnsHostname=Ce,f.WebRtcError=E,f.SignalingError=P,f.IceError=U,f.SdpError=B,f.TurnError=M,f.E2eeError=L,f.version="1.2.0",f.libSize="~129 KB",f.unitTests={"passed":2322,"failed":0,"total":2508,"suites":617,"duration":8697,"ok":true},f.meta={},f.isElectron=typeof navigator!="undefined"&&/Electron/i.test(navigator.userAgent)||typeof process!="undefined"&&process.versions!=null&&!!process.versions.electron,f.platform=f.isElectron?"electron":typeof window!="undefined"?"browser":"node",f.noConflict=()=>(typeof window!="undefined"&&window.$===f&&delete window.$,f),typeof window!="undefined"&&(window.$=f,window.zQuery=f)})(typeof window!="undefined"?window:globalThis);
|