zero-query 1.2.9 → 1.2.10

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.
@@ -124,7 +124,12 @@ $.component('video-room', {
124
124
  const btn = e && e.currentTarget;
125
125
  const name = btn && btn.getAttribute('data-room');
126
126
  if (!name) return;
127
+ if (this.state.joined || this.state.connecting) return;
128
+ // Update the input field for visual feedback, then jump straight into
129
+ // join() so a click on a pill behaves like "join that room now"
130
+ // instead of just selecting the name.
127
131
  this.setState({ roomName: name });
132
+ this.join();
128
133
  },
129
134
 
130
135
  // ---- Join / leave ----------------------------------------------------
Binary file
package/dist/zquery.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * zQuery (zeroQuery) v1.2.9
2
+ * zQuery (zeroQuery) v1.2.10
3
3
  * Lightweight Frontend Library
4
4
  * https://github.com/tonywied17/zero-query
5
5
  * (c) 2026 Anthony Wiedman - MIT License
@@ -1323,7 +1323,7 @@ class SignalingClient {
1323
1323
  * Wire-protocol mapping (mirrors @zero-server/webrtc):
1324
1324
  * - outgoing `offer` -> `{ type: 'offer', target, sdp }` (sdp is the string)
1325
1325
  * - outgoing `answer` -> `{ type: 'answer', target, sdp }`
1326
- * - outgoing `ice` -> `{ type: 'ice', target, candidate }` (raw a=candidate: line or null)
1326
+ * - outgoing `ice` -> `{ type: 'ice', target, candidate }` (RTCIceCandidateInit-shaped dict or null for EOC)
1327
1327
  * - incoming filtered by `msg.from === this.id`.
1328
1328
  *
1329
1329
  * Server-side constraints honored here:
@@ -1563,7 +1563,18 @@ class Peer {
1563
1563
  if (cand.indexOf('.local') !== -1) return;
1564
1564
  if (this._sentCandidates >= this._maxIceCandidates) return;
1565
1565
  this._sentCandidates++;
1566
- this.signaling.send('ice', { target: this.id, candidate: cand });
1566
+ // Browsers REQUIRE sdpMid or sdpMLineIndex when re-applying a candidate
1567
+ // with addIceCandidate(); ship the full init dict so the remote peer
1568
+ // can reconstruct it exactly.
1569
+ const init = (typeof candidate === 'object' && candidate)
1570
+ ? {
1571
+ candidate: cand,
1572
+ sdpMid: candidate.sdpMid != null ? candidate.sdpMid : null,
1573
+ sdpMLineIndex: candidate.sdpMLineIndex != null ? candidate.sdpMLineIndex : null,
1574
+ usernameFragment: candidate.usernameFragment != null ? candidate.usernameFragment : null,
1575
+ }
1576
+ : { candidate: cand, sdpMid: null, sdpMLineIndex: null, usernameFragment: null };
1577
+ this.signaling.send('ice', { target: this.id, candidate: init });
1567
1578
  };
1568
1579
 
1569
1580
  this.pc.ontrack = (event) => {
@@ -1639,7 +1650,8 @@ class Peer {
1639
1650
  }
1640
1651
 
1641
1652
  /**
1642
- * @param {string|null} candidate - raw `a=candidate:` line or `null` for EOC.
1653
+ * @param {string|object|null} candidate - raw `a=candidate:` line, a full
1654
+ * `RTCIceCandidateInit`-shaped dict, or `null` for end-of-candidates.
1643
1655
  * @private
1644
1656
  */
1645
1657
  async _onRemoteCandidate(candidate) {
@@ -1649,7 +1661,19 @@ class Peer {
1649
1661
  await this.pc.addIceCandidate(null);
1650
1662
  return;
1651
1663
  }
1652
- await this.pc.addIceCandidate({ candidate });
1664
+ // Older zero-query clients relayed only the bare `a=candidate:` string,
1665
+ // which browsers reject with "missing values for both sdpMid and
1666
+ // sdpMLineIndex". Newer clients send a full init dict - normalize both.
1667
+ const init = (typeof candidate === 'string')
1668
+ ? { candidate, sdpMid: '', sdpMLineIndex: 0 }
1669
+ : {
1670
+ candidate: candidate.candidate,
1671
+ sdpMid: candidate.sdpMid != null ? candidate.sdpMid : '',
1672
+ sdpMLineIndex: candidate.sdpMLineIndex != null ? candidate.sdpMLineIndex : 0,
1673
+ usernameFragment: candidate.usernameFragment != null ? candidate.usernameFragment : undefined,
1674
+ };
1675
+ if (!init.candidate) return;
1676
+ await this.pc.addIceCandidate(init);
1653
1677
  } catch (err) {
1654
1678
  // The W3C pattern: suppress errors while we're explicitly ignoring an offer.
1655
1679
  if (this.ignoreOffer) return;
@@ -10449,9 +10473,9 @@ $.TurnError = TurnError;
10449
10473
  $.E2eeError = E2eeError;
10450
10474
 
10451
10475
  // --- Meta ------------------------------------------------------------------
10452
- $.version = '1.2.9';
10476
+ $.version = '1.2.10';
10453
10477
  $.libSize = '~130 KB';
10454
- $.unitTests = {"passed":2348,"failed":0,"total":2534,"suites":620,"duration":8190,"ok":true};
10478
+ $.unitTests = {"passed":2348,"failed":0,"total":2534,"suites":620,"duration":8235,"ok":true};
10455
10479
  $.meta = {}; // populated at build time by CLI bundler
10456
10480
 
10457
10481
  // --- Environment detection -------------------------------------------------
@@ -1,13 +1,13 @@
1
1
  /**
2
- * zQuery (zeroQuery) v1.2.9
2
+ * zQuery (zeroQuery) v1.2.10
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(Ss){"use strict";const v=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 ee=[];function Bt(s){return s===null?(ee=[],()=>{}):typeof s!="function"?()=>{}:(ee.push(s),()=>{const e=ee.indexOf(s);e!==-1&&ee.splice(e,1)})}function A(s,e,t={},n){const r=n instanceof I?n:new I(s,e,t,n);for(const i of ee)try{i(r)}catch{}console.error(`[zQuery ${s}] ${e}`,t,n||"")}function Ut(s,e,t={}){return(...n)=>{try{return s(...n)}catch(r){A(e,r.message||"Callback error",t,r)}}}function Mt(s,e,t){if(s==null)throw new I(v.INVALID_ARGUMENT,`"${e}" is required but got ${s}`);if(t&&typeof s!==t)throw new I(v.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 It(s,e,t={}){return async(...n)=>{try{return await s(...n)}catch(r){A(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 N extends E{constructor(e,t={}){super(e,{code:t.code||"ZQ_WEBRTC_E2EE",context:t.context,cause:t.cause}),this.name="E2eeError"}}class k extends E{constructor(e,t={}){super(e,{code:t.code||"ZQ_WEBRTC_SFU",context:t.context,cause:t.cause}),this.name="SfuError"}}const Dt=65536,$e="UDP/TLS/RTP/SAVPF",vs=Object.freeze(["sendrecv","sendonly","recvonly","inactive"]);function Ee(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:Dt;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,`
7
+ (function(Ss){"use strict";const v=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 ee=[];function Bt(s){return s===null?(ee=[],()=>{}):typeof s!="function"?()=>{}:(ee.push(s),()=>{const e=ee.indexOf(s);e!==-1&&ee.splice(e,1)})}function A(s,e,t={},n){const r=n instanceof I?n:new I(s,e,t,n);for(const i of ee)try{i(r)}catch{}console.error(`[zQuery ${s}] ${e}`,t,n||"")}function Mt(s,e,t={}){return(...n)=>{try{return s(...n)}catch(r){A(e,r.message||"Callback error",t,r)}}}function Ut(s,e,t){if(s==null)throw new I(v.INVALID_ARGUMENT,`"${e}" is required but got ${s}`);if(t&&typeof s!==t)throw new I(v.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 It(s,e,t={}){return async(...n)=>{try{return await s(...n)}catch(r){A(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 M 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 U extends E{constructor(e,t={}){super(e,{code:t.code||"ZQ_WEBRTC_TURN",context:t.context,cause:t.cause}),this.name="TurnError"}}class N extends E{constructor(e,t={}){super(e,{code:t.code||"ZQ_WEBRTC_E2EE",context:t.context,cause:t.cause}),this.name="E2eeError"}}class k extends E{constructor(e,t={}){super(e,{code:t.code||"ZQ_WEBRTC_SFU",context:t.context,cause:t.cause}),this.name="SfuError"}}const Dt=65536,$e="UDP/TLS/RTP/SAVPF",vs=Object.freeze(["sendrecv","sendonly","recvonly","inactive"]);function Ee(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:Dt;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
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],l=c.indexOf("=");if(l<1)throw new B(`parseSdp: malformed line ${a+1}`,{code:"ZQ_WEBRTC_SDP_PARSE",context:{line:a+1}});const u=c.slice(0,l),d=c.slice(l+1);if(a===0&&u!=="v")throw new B("parseSdp: SDP must start with v=",{code:"ZQ_WEBRTC_SDP_PARSE",context:{line:1}});switch(u){case"v":r.version=Number(d);break;case"o":r.origin=Wt(d);break;case"s":r.sessionName=d;break;case"m":{o=zt(d),r.media.push(o),i=o;break}case"a":qt(i,d);break;default:break}}return r}function Ze(s){const e=Ee(s);if(e.media.length===0)throw new B("validateSdp: SDP has no m-lines",{code:"ZQ_WEBRTC_SDP_NO_MEDIA"});const t=be(e.attributes,"ice-ufrag"),n=be(e.attributes,"ice-pwd"),r=be(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,l=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(!l)throw new B(`validateSdp: m-line ${i} missing fingerprint`,{code:"ZQ_WEBRTC_SDP_NO_FINGERPRINT",context:{index:i}})}return e}function Wt(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 zt(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 qt(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 be(s,e){for(let t=0;t<s.length;t++)if(s[t].key===e)return s[t].value||!0}const jt=Object.freeze(["host","srflx","prflx","relay"]),Cs=Object.freeze(["active","passive","so"]);function Se(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],l=t[6],u=t[7],d=t.slice(8);if(l!=="typ")throw new U('parseCandidate: expected "typ" keyword',{code:"ZQ_WEBRTC_ICE_PARSE",context:{candidate:s}});if(jt.indexOf(u)===-1)throw new U(`parseCandidate: unknown type "${u}"`,{code:"ZQ_WEBRTC_ICE_PARSE",context:{candidate:s}});const p=Number(r),f=Number(o),_=Number(c);if(!Number.isInteger(p)||p<0)throw new U("parseCandidate: invalid component",{code:"ZQ_WEBRTC_ICE_PARSE",context:{candidate:s}});if(!Number.isFinite(f))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 g={foundation:n,component:p,transport:i.toLowerCase(),priority:f,address:a,port:_,type:u,extensions:{}};for(let m=0;m<d.length-1;m+=2){const S=d[m],L=d[m+1];S==="raddr"?g.relatedAddress=L:S==="rport"?g.relatedPort=Number(L):S==="tcptype"?g.tcpType=L:g.extensions[S]=L}return g}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 ae(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 ce(s){return typeof s!="string"?!1:s.indexOf(":")!==-1&&/^[0-9a-fA-F:]+$/.test(s)}function ve(s){if(ae(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(ce(s)){const e=s.toLowerCase().split(":")[0];return e.length===0?!1:(parseInt(e,16)&65024)===64512}return!1}function Ce(s){return ae(s)?s.indexOf("127.")===0:ce(s)?s==="::1"||/^0*:0*:0*:0*:0*:0*:0*:0*1$/.test(s):!1}function Ae(s){if(ae(s))return s.indexOf("169.254.")===0;if(ce(s)){const e=s.toLowerCase().split(":")[0];return e.length===0?!1:(parseInt(e,16)&65472)===65152}return!1}function Te(s){return typeof s!="string"||ae(s)||ce(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,l=typeof e.predicate=="function"?e.predicate:null,u=[];for(const d of s){if(u.length>=c)break;const p=typeof d=="string";let f;if(p)try{f=Se(d)}catch{continue}else f=d;f&&(a&&a.indexOf(f.type)===-1||o&&f.transport==="tcp"||i&&Te(f.address)||t&&ve(f.address)||n&&Ce(f.address)||r&&Ae(f.address)||l&&!l(f)||u.push(d))}return u}const Ft=250,Qt=8e3,$t=10,Zt=200,Ht=10,Ge=1e3;class Re{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:Ft,capMs:Qt,maxRetries:$t},t.reconnect||{});this.url=e,this.options={reconnect:n,iceFlushMs:t.iceFlushMs||Zt,iceBatch:t.iceBatch||Ht,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 Kt=30;class ke{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||Kt,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",{target: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",{target: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",{target: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",{target: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 G{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 ke(e,this.signaling,Object.assign({polite:n},this.peerOptions)),i={id:e,peer:r,pc:r.pc,stream:Vt(),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 l=this._channels.get(c.label);l&&l._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:l}of this._publishedTracks)try{const u=r.addTrack(c,l);a.set(c,u)}catch(u){this._emit("error",u)}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(l){this._emit("error",l)}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 Gt(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 Gt{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 Ve(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 Re(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=Je(n,"hello",i),a=Je(n,"joined",i);a.catch(()=>{});try{await n.connect();const c=await o,l=c&&c.peerId;if(typeof l!="string"||l.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 u=await a,d=u&&Array.isArray(u.peers)?u.peers:[],p=new G({id:e.room,self:l,signaling:n,peerOptions:r});for(const f of d)p._addPeer(f);if(e.media){const f=e.media===!0?{audio:!0,video:!0}:e.media,_=e.navigator||(typeof navigator!="undefined"?navigator:null),g=_&&_.mediaDevices;if(!g||typeof g.getUserMedia!="function")throw new E("webrtc.join: navigator.mediaDevices.getUserMedia is unavailable",{code:"ZQ_WEBRTC_JOIN_NO_MEDIA_DEVICES"});const m=await g.getUserMedia(f);await p.publish(m)}return p}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 Je(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 Vt(){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 G?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"})):Ve(s,e||{})}function Xe(s,e){if(!(s instanceof G))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 G))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 l={data:a,from:c,at:Date.now()},u=i.peek().slice();u.push(l),u.length>n&&u.splice(0,u.length-n),i.value=u});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(),l=Jt(c);l!==r.peek()&&(r.value=l)}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 Jt(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 xe(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 Yt(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(l=>typeof l!="string"||!l||n.has(l)?!1:(n.add(l),!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,l=!1,u=null;const d={get value(){return u},peek(){return u},async refresh(){if(l)return null;try{const f=t?{...a||{},fetch:t}:a,_=await xe(e,f);return l||(u=_,p(_.ttl),i&&i(_)),_}catch(f){throw!l&&o&&o(f),l||p(60),f}},async start(){return l?null:d.refresh()},stop(){l=!0,c&&(clearTimeout(c),c=null)}};function p(f){c&&(clearTimeout(c),c=null);const _=Math.max(r,f*1e3-n);c=setTimeout(()=>{c=null,d.refresh().catch(()=>{})},_),c&&typeof c.unref=="function"&&c.unref()}return d}function Yt(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,te=1+at,Xt=1e5,en=new TextEncoder().encode("zquery-sframe-v1");function le(){const s=typeof crypto!="undefined"&&crypto.subtle?crypto.subtle:null;if(!s)throw new N("WebCrypto SubtleCrypto is not available in this environment",{code:"ZQ_WEBRTC_E2EE_NO_WEBCRYPTO"});return s}function tn(s){const e=new Uint8Array(s);if(typeof crypto=="undefined"||typeof crypto.getRandomValues!="function")throw new N("crypto.getRandomValues is not available in this environment",{code:"ZQ_WEBRTC_E2EE_NO_RANDOM"});return crypto.getRandomValues(e),e}function ue(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 N("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 N("deriveSFrameKey: passphrase must be a non-empty string",{code:"ZQ_WEBRTC_E2EE_BAD_PASSPHRASE"});if(typeof e!="string"||!e)throw new N("deriveSFrameKey: salt must be a non-empty string",{code:"ZQ_WEBRTC_E2EE_BAD_SALT"});const t=le(),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:Xt},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:en},o,{name:"AES-GCM",length:ot},!1,["encrypt","decrypt"])}async function lt(){return le().generateKey({name:"AES-GCM",length:ot},!0,["encrypt","decrypt"])}class ne{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 N("SFrameContext.setKey: epoch must be an integer in [0, 255]",{code:"ZQ_WEBRTC_E2EE_BAD_EPOCH"});if(!t)throw new N("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 Le(s,e){if(!(s instanceof ne))throw new N("encryptFrame: ctx must be an SFrameContext",{code:"ZQ_WEBRTC_E2EE_BAD_CTX"});const t=s.getKey(s.currentEpoch);if(!t)throw new N(`encryptFrame: no key installed for epoch ${s.currentEpoch}`,{code:"ZQ_WEBRTC_E2EE_NO_KEY",context:{epoch:s.currentEpoch}});const n=ue(e),r=tn(at),i=new Uint8Array(await le().encrypt({name:"AES-GCM",iv:r},t,n)),o=new Uint8Array(te+i.byteLength);return o[0]=s.currentEpoch&255,o.set(r,1),o.set(i,te),o}async function Oe(s,e){if(!(s instanceof ne))throw new N("decryptFrame: ctx must be an SFrameContext",{code:"ZQ_WEBRTC_E2EE_BAD_CTX"});const t=ue(e);if(t.byteLength<=te)throw new N("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 N(`decryptFrame: no key for epoch ${n}`,{code:"ZQ_WEBRTC_E2EE_UNKNOWN_EPOCH",context:{epoch:n}});const i=t.subarray(1,te),o=t.subarray(te);let a;try{a=new Uint8Array(await le().decrypt({name:"AES-GCM",iv:i},r,o))}catch(c){throw new N("decryptFrame: AES-GCM authentication failed",{code:"ZQ_WEBRTC_E2EE_AUTH_FAILED",cause:c instanceof Error?c:void 0,context:{epoch:n}})}return a}function ut(s,e){if(!s||typeof s.getSenders!="function"||typeof s.getReceivers!="function")throw new N("attachE2ee: pc must look like an RTCPeerConnection",{code:"ZQ_WEBRTC_E2EE_BAD_PC"});if(!(e instanceof ne))throw new N("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 l=new TransformStream({async transform(u,d){try{const p=ue(u.data),f=await Le(e,p);u.data=f.buffer,d.enqueue(u)}catch{}}});c.readable.pipeThrough(l).pipeTo(c.writable).catch(()=>{})}function i(a){if(n||t.has(a))return;t.add(a);const c=ft(a);if(!c)return;const l=new TransformStream({async transform(u,d){try{const p=ue(u.data),f=await Oe(e,p);u.data=f.buffer,d.enqueue(u)}catch{}}});c.readable.pipeThrough(l).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=sn(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:nn(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 nn(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 sn(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 Ne(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 rn(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 u=await Ne(s);if(a)return;if(o=u,r)try{r(u)}catch{}}catch(u){if(i)try{i(u)}catch{}}};n&&c();const l=setInterval(c,t);return{stop(){a||(a=!0,clearInterval(l))},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 rn(s){const e=[],t=[];let n=null;const r=p=>{!p||typeof p!="object"||(p.type==="inbound-rtp"&&e.push(p),p.type==="outbound-rtp"&&t.push(p),p.type==="candidate-pair"&&(p.nominated||p.state==="succeeded")&&(n||(n=p)))};if(s&&typeof s.forEach=="function")s.forEach(r);else if(s&&typeof s=="object")for(const p of Object.keys(s))r(s[p]);let i=0,o=0,a=0,c=0;for(const p of t)typeof p.bytesSent=="number"&&(i+=p.bytesSent);for(const p of e)typeof p.bytesReceived=="number"&&(o+=p.bytesReceived),typeof p.packetsLost=="number"&&(a+=p.packetsLost),typeof p.packetsReceived=="number"&&(c+=p.packetsReceived);const l=a+c,u=l>0?a/l*100:0;let d=null;return n&&typeof n.currentRoundTripTime=="number"&&(d=n.currentRoundTripTime*1e3),{report:s,inboundRtp:e,outboundRtp:t,candidatePair:n,summary:{rttMs:d,lossPct:u,bytesSent:i,bytesReceived:o}}}async function on(){try{return await import(["mediasoup","client"].join("-"))}catch(s){throw new k("mediasoup-client peer dependency is not installed; run `npm install mediasoup-client`",{code:"ZQ_WEBRTC_SFU_PEER_MISSING",cause:s})}}async function an(s={}){const e=s.client||await on(),t=e.Device||e.default&&e.default.Device;if(typeof t!="function")throw new k("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 k("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 k("load(routerRtpCapabilities): routerRtpCapabilities required",{code:"ZQ_WEBRTC_SFU_BAD_RTP_CAPS"});if(!n.loaded)try{await n.load({routerRtpCapabilities:r})}catch(i){throw new k("device.load() failed",{code:"ZQ_WEBRTC_SFU_LOAD_FAILED",cause:i})}},canProduce(r){if(!n.loaded)throw new k("canProduce(): device not loaded yet",{code:"ZQ_WEBRTC_SFU_NOT_LOADED"});return!!n.canProduce(r)},createSendTransport(r){if(!n.loaded)throw new k("createSendTransport(): device not loaded yet",{code:"ZQ_WEBRTC_SFU_NOT_LOADED"});return n.createSendTransport(r)},createRecvTransport(r){if(!n.loaded)throw new k("createRecvTransport(): device not loaded yet",{code:"ZQ_WEBRTC_SFU_NOT_LOADED"});return n.createRecvTransport(r)},async join(r){throw new k("mediasoup adapter.join() not implemented; use device + createSendTransport/createRecvTransport with your SFU signaling layer",{code:"ZQ_WEBRTC_SFU_JOIN_UNAVAILABLE"})}}}async function cn(){try{return await import(["livekit","client"].join("-"))}catch(s){throw new k("livekit-client peer dependency is not installed; run `npm install livekit-client`",{code:"ZQ_WEBRTC_SFU_PEER_MISSING",cause:s})}}async function ln(s={}){const e=s.client||await cn(),t=e.Room||e.default&&e.default.Room;if(typeof t!="function")throw new k("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 k("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 k("connect(url, token): url required",{code:"ZQ_WEBRTC_SFU_BAD_URL"});if(typeof o!="string"||!o)throw new k("connect(url, token): token required",{code:"ZQ_WEBRTC_SFU_BAD_TOKEN"});try{await n.connect(i,o,a),r=!0}catch(c){throw new k("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 k("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 an(e);if(s==="livekit")return ln(e);throw new k(`unknown SFU adapter: ${s}`,{code:"ZQ_WEBRTC_SFU_UNKNOWN",context:{name:s}})}const un={SignalingClient:Re,Peer:ke,Room:G,join:Ve,useRoom:Ye,usePeer:Xe,useTracks:et,useDataChannel:tt,useConnectionQuality:nt,fetchTurnCredentials:xe,mergeIceServers:rt,createTurnRefresher:it,deriveSFrameKey:ct,generateSFrameKey:lt,SFrameContext:ne,encryptFrame:Le,decryptFrame:Oe,attachE2ee:ut,loadSfuAdapter:mt,decodeJoinToken:ht,isJoinTokenExpired:dt,samplePeerStats:Ne,createStatsSampler:pt,classifyStats:_t,parseSdp:Ee,validateSdp:Ze,parseCandidate:Se,stringifyCandidate:He,filterCandidates:Ke,isPrivateIp:ve,isLoopbackIp:Ce,isLinkLocalIp:Ae,isMdnsHostname:Te,WebRtcError:E,SignalingError:P,IceError:U,SdpError:B,TurnError:M,E2eeError:N,SfuError:k};function yt(s){if(s===null||typeof s!="object")return!1;if(Array.isArray(s))return!0;const e=Object.getPrototypeOf(s);return e===Object.prototype||e===null}function Pe(s,e,t=""){if(!yt(s))return s;typeof e!="function"&&(A(v.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(yt(a)){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(l){A(v.REACTIVE_CALLBACK,`Reactive onChange threw for key "${String(o)}"`,{key:o,value:a,old:c},l)}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){A(v.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){A(v.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 fn(s){const e=new R(void 0);return gt(()=>{const t=s();t!==e._value&&(e._value=t,e._notify())}),e}function gt(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){A(v.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 hn(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){A(v.SIGNAL_CALLBACK,"Signal subscriber threw",{},r)}}return e}function dn(s){const e=R._activeEffect;R._activeEffect=null;try{return s()}finally{R._activeEffect=e}}let Be=null;function wt(){return Be||(Be=document.createElement("template")),Be}function Ue(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);fe(s,i),t&&window.__zqMorphHook(s,performance.now()-t)}function Et(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 vt(s,r),fe(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 bt=Ue,pn=Et;function fe(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 d=0;d<r;d++)o[d]=t[d];for(let d=0;d<i;d++)a[d]=n[d];let c=!1,l,u;for(let d=0;d<r;d++)if(D(o[d])!=null){c=!0;break}if(!c){for(let d=0;d<i;d++)if(D(a[d])!=null){c=!0;break}}if(c){l=new Map,u=new Map;for(let d=0;d<r;d++){const p=D(o[d]);p!=null&&l.set(p,d)}for(let d=0;d<i;d++){const p=D(a[d]);p!=null&&u.set(p,d)}mn(s,o,a,l,u)}else _n(s,o,a)}function _n(s,e,t){const n=e.length,r=t.length,i=n<r?n:r;for(let o=0;o<i;o++)St(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 mn(s,e,t,n,r){const i=new Set,o=t.length,a=new Array(o);for(let f=0;f<o;f++){const _=D(t[f]);if(_!=null&&n.has(_)){const g=n.get(_);a[f]=e[g],i.add(g)}else a[f]=null}for(let f=e.length-1;f>=0;f--)if(!i.has(f)){const _=D(e[f]);_!=null&&!r.has(_)&&s.removeChild(e[f])}const c=[];for(let f=0;f<o;f++)if(a[f]){const _=D(t[f]);c.push(n.get(_))}else c.push(-1);const l=yn(c);let u=s.firstChild;const d=[];for(let f=0;f<e.length;f++)!i.has(f)&&D(e[f])==null&&d.push(e[f]);let p=0;for(let f=0;f<o;f++){const _=t[f],g=D(_);let m=a[f];if(!m&&g==null&&(m=d[p++]||null),m){l.has(f)||s.insertBefore(m,u);const S=m.nextSibling;St(s,m,_),u=S}else{const S=_.cloneNode(!0);u?s.insertBefore(S,u):s.appendChild(S)}}for(;p<d.length;){const f=d[p++];f.parentNode===s&&s.removeChild(f)}for(let f=0;f<e.length;f++)if(!i.has(f)){const _=e[f];_.parentNode===s&&D(_)!=null&&!r.has(D(_))&&s.removeChild(_)}}function yn(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 l=0,u=n.length;for(;l<u;){const d=l+u>>1;n[d]<c?l=d+1:u=d}n[l]=c,i[l]=a,r[a]=l>0?i[l-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 St(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;vt(e,t);const n=e.nodeName;if(n==="INPUT"){gn(e,t);return}if(n==="TEXTAREA"){e.value!==t.textContent&&(e.value=t.textContent||"");return}if(n==="SELECT"){fe(e,t),e.value!==t.value&&(e.value=t.value);return}fe(e,t)}}function vt(s,e){const t=e.attributes,n=s.attributes,r=t.length,i=n.length;if(r===i){let c=!0;for(let l=0;l<r;l++){const u=t[l];if(s.getAttribute(u.name)!==u.value){c=!1;break}}if(c){for(let l=0;l<i;l++)if(!e.hasAttribute(n[l].name)){c=!1;break}}if(c)return}const o=new Set;for(let c=0;c<r;c++){const l=t[c];o.add(l.name),s.getAttribute(l.name)!==l.value&&s.setAttribute(l.name,l.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 gn(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 w{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 w(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 w(t)}parent(){const e=[...new Set(this.elements.map(t=>t.parentElement).filter(Boolean))];return new w(e)}closest(e){return new w(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 w([...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 w(t)}next(e){const t=this.elements.map(n=>n.nextElementSibling).filter(Boolean);return new w(e?t.filter(n=>n.matches(e)):t)}prev(e){const t=this.elements.map(n=>n.previousElementSibling).filter(Boolean);return new w(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 w(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 w(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 w(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 w(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 w([...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 w([...new Set(n)])}contents(){const e=[];return this.elements.forEach(t=>e.push(...t.childNodes)),new w(e)}filter(e){return typeof e=="function"?new w(this.elements.filter(e)):new w(this.elements.filter(t=>t.matches(e)))}not(e){return typeof e=="function"?new w(this.elements.filter((t,n)=>!e.call(t,n,t))):new w(this.elements.filter(t=>!t.matches(e)))}has(e){return new w(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 w(this.elements.slice(e,t))}add(e,t){const n=e instanceof w?e.elements:e instanceof Node?[e]:Array.from((t||document).querySelectorAll(e));return new w([...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 r;if(typeof e=="object"&&e!==null)return this.each((i,o)=>{for(const[a,c]of Object.entries(e))o.setAttribute(a,c)});if(t===void 0)return(r=this.first())==null?void 0:r.getAttribute(e);const n=this.elements;for(let i=0;i<n.length;i++)n[i].setAttribute(e,t);return this}removeAttr(e){const t=this.elements;for(let n=0;n<t.length;n++)t[n].removeAttribute(e);return this}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?bt(r,e):r.innerHTML=e})}morph(e){return this.each((t,n)=>{bt(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 w?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"?se(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 w(this.elements.map(t=>t.cloneNode(e)))}replaceWith(e){return this.each((t,n)=>{typeof e=="string"?pn(n,e):e instanceof Node&&n.parentNode.replaceChild(e,n)})}appendTo(e){const t=typeof e=="string"?document.querySelector(e):e instanceof w?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 w?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 w?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 w?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 w?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"?se(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"?se(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=l=>{if(!l.target||typeof l.target.closest!="function")return;const u=l.target.closest(t);u&&o.contains(u)&&n.call(u,l)};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,l)=>{l.style.transition=`all ${t}ms ${n}`,requestAnimationFrame(()=>{Object.assign(l.style,e);const u=()=>{l.removeEventListener("transitionend",u),l.style.transition="",!i&&++o.done>=this.length&&(i=!0,r(this))};l.addEventListener("transitionend",u),a.push({el:l,onEnd:u})})}),setTimeout(()=>{if(!i){i=!0;for(const{el:c,onEnd:l}of a)c.removeEventListener("transitionend",l),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 w([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 se(s){const e=document.createElement("template");return e.innerHTML=s.trim(),e.content}function C(s,e){if(!s)return new w([]);if(s instanceof w)return s;if(s instanceof Node||s===window)return new w([s]);if(s instanceof NodeList||s instanceof HTMLCollection||Array.isArray(s))return new w(Array.from(s));if(typeof s=="string"&&s.trim().startsWith("<")){const t=se(s);return new w([...t.childNodes].filter(n=>n.nodeType===1))}if(typeof s=="string"){const t=e?typeof e=="string"?document.querySelector(e):e:document;return new w([...t.querySelectorAll(s)])}return new w([])}function wn(s,e){if(!s)return new w([]);if(s instanceof w)return s;if(s instanceof Node||s===window)return new w([s]);if(s instanceof NodeList||s instanceof HTMLCollection||Array.isArray(s))return new w(Array.from(s));if(typeof s=="string"&&s.trim().startsWith("<")){const t=se(s);return new w([...t.childNodes].filter(n=>n.nodeType===1))}if(typeof s=="string"){const t=e?typeof e=="string"?document.querySelector(e):e:document;return new w([...t.querySelectorAll(s)])}return new w([])}C.id=s=>document.getElementById(s),C.class=s=>document.querySelector(`.${typeof CSS!="undefined"&&CSS.escape?CSS.escape(s):s}`),C.classes=s=>new w(Array.from(document.getElementsByClassName(s))),C.tag=s=>new w(Array.from(document.getElementsByTagName(s))),Object.defineProperty(C,"name",{value:s=>new w(Array.from(document.getElementsByName(s))),writable:!0,configurable:!0}),C.children=s=>{const e=document.getElementById(s);return new w(e?Array.from(e.children):[])},C.qs=(s,e=document)=>e.querySelector(s),C.qsa=(s,e=document)=>Array.from(e.querySelectorAll(s)),C.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 w(n)},C.ready=s=>{document.readyState!=="loading"?s():document.addEventListener("DOMContentLoaded",s)},C.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)})},C.off=(s,e)=>{document.removeEventListener(s,e)},C.fn=w.prototype;const y={NUM:1,STR:2,IDENT:3,OP:4,PUNC:5,TMPL:6,EOF:7},he={"??":2,"||":3,"&&":4,"==":8,"!=":8,"===":8,"!==":8,"<":9,">":9,"<=":9,">=":9,instanceof:9,in:9,"+":11,"-":11,"*":12,"/":12,"%":12},En=new Set(["true","false","null","undefined","typeof","instanceof","in","new","void"]);function bn(s){const e=[];let t=0;const n=s.length;for(;t<n;){const r=s[t];if(r===" "||r===" "||r===`
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],l=c.indexOf("=");if(l<1)throw new B(`parseSdp: malformed line ${a+1}`,{code:"ZQ_WEBRTC_SDP_PARSE",context:{line:a+1}});const u=c.slice(0,l),d=c.slice(l+1);if(a===0&&u!=="v")throw new B("parseSdp: SDP must start with v=",{code:"ZQ_WEBRTC_SDP_PARSE",context:{line:1}});switch(u){case"v":r.version=Number(d);break;case"o":r.origin=Wt(d);break;case"s":r.sessionName=d;break;case"m":{o=zt(d),r.media.push(o),i=o;break}case"a":Ft(i,d);break;default:break}}return r}function Ze(s){const e=Ee(s);if(e.media.length===0)throw new B("validateSdp: SDP has no m-lines",{code:"ZQ_WEBRTC_SDP_NO_MEDIA"});const t=be(e.attributes,"ice-ufrag"),n=be(e.attributes,"ice-pwd"),r=be(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,l=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(!l)throw new B(`validateSdp: m-line ${i} missing fingerprint`,{code:"ZQ_WEBRTC_SDP_NO_FINGERPRINT",context:{index:i}})}return e}function Wt(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 zt(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 Ft(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 be(s,e){for(let t=0;t<s.length;t++)if(s[t].key===e)return s[t].value||!0}const qt=Object.freeze(["host","srflx","prflx","relay"]),Cs=Object.freeze(["active","passive","so"]);function Se(s){if(typeof s!="string")throw new M("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 M('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 M("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],l=t[6],u=t[7],d=t.slice(8);if(l!=="typ")throw new M('parseCandidate: expected "typ" keyword',{code:"ZQ_WEBRTC_ICE_PARSE",context:{candidate:s}});if(qt.indexOf(u)===-1)throw new M(`parseCandidate: unknown type "${u}"`,{code:"ZQ_WEBRTC_ICE_PARSE",context:{candidate:s}});const p=Number(r),f=Number(o),_=Number(c);if(!Number.isInteger(p)||p<0)throw new M("parseCandidate: invalid component",{code:"ZQ_WEBRTC_ICE_PARSE",context:{candidate:s}});if(!Number.isFinite(f))throw new M("parseCandidate: invalid priority",{code:"ZQ_WEBRTC_ICE_PARSE",context:{candidate:s}});if(!Number.isInteger(_)||_<0||_>65535)throw new M("parseCandidate: invalid port",{code:"ZQ_WEBRTC_ICE_PARSE",context:{candidate:s}});const g={foundation:n,component:p,transport:i.toLowerCase(),priority:f,address:a,port:_,type:u,extensions:{}};for(let m=0;m<d.length-1;m+=2){const S=d[m],L=d[m+1];S==="raddr"?g.relatedAddress=L:S==="rport"?g.relatedPort=Number(L):S==="tcptype"?g.tcpType=L:g.extensions[S]=L}return g}function He(s){if(!s||typeof s!="object")throw new M("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 M(`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 ae(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 ce(s){return typeof s!="string"?!1:s.indexOf(":")!==-1&&/^[0-9a-fA-F:]+$/.test(s)}function ve(s){if(ae(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(ce(s)){const e=s.toLowerCase().split(":")[0];return e.length===0?!1:(parseInt(e,16)&65024)===64512}return!1}function Ce(s){return ae(s)?s.indexOf("127.")===0:ce(s)?s==="::1"||/^0*:0*:0*:0*:0*:0*:0*:0*1$/.test(s):!1}function Ae(s){if(ae(s))return s.indexOf("169.254.")===0;if(ce(s)){const e=s.toLowerCase().split(":")[0];return e.length===0?!1:(parseInt(e,16)&65472)===65152}return!1}function Te(s){return typeof s!="string"||ae(s)||ce(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,l=typeof e.predicate=="function"?e.predicate:null,u=[];for(const d of s){if(u.length>=c)break;const p=typeof d=="string";let f;if(p)try{f=Se(d)}catch{continue}else f=d;f&&(a&&a.indexOf(f.type)===-1||o&&f.transport==="tcp"||i&&Te(f.address)||t&&ve(f.address)||n&&Ce(f.address)||r&&Ae(f.address)||l&&!l(f)||u.push(d))}return u}const jt=250,Qt=8e3,$t=10,Zt=200,Ht=10,Ge=1e3;class Re{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:jt,capMs:Qt,maxRetries:$t},t.reconnect||{});this.url=e,this.options={reconnect:n,iceFlushMs:t.iceFlushMs||Zt,iceBatch:t.iceBatch||Ht,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 Kt=30;class ke{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||Kt,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 M(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",{target: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",{target:this.id,candidate:null});return}const n=typeof t=="string"?t:t.candidate;if(!n||n.indexOf(".local")!==-1||this._sentCandidates>=this._maxIceCandidates)return;this._sentCandidates++;const r=typeof t=="object"&&t?{candidate:n,sdpMid:t.sdpMid!=null?t.sdpMid:null,sdpMLineIndex:t.sdpMLineIndex!=null?t.sdpMLineIndex:null,usernameFragment:t.usernameFragment!=null?t.usernameFragment:null}:{candidate:n,sdpMid:null,sdpMLineIndex:null,usernameFragment:null};this.signaling.send("ice",{target:this.id,candidate:r})},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",{target: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}const t=typeof e=="string"?{candidate:e,sdpMid:"",sdpMLineIndex:0}:{candidate:e.candidate,sdpMid:e.sdpMid!=null?e.sdpMid:"",sdpMLineIndex:e.sdpMLineIndex!=null?e.sdpMLineIndex:0,usernameFragment:e.usernameFragment!=null?e.usernameFragment:void 0};if(!t.candidate)return;await this.pc.addIceCandidate(t)}catch(t){if(this.ignoreOffer)return;this._emit("error",new M(t.message||"addIceCandidate failed",{code:"ZQ_WEBRTC_ICE_ADD_FAILED",cause:t}))}}}class G{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 ke(e,this.signaling,Object.assign({polite:n},this.peerOptions)),i={id:e,peer:r,pc:r.pc,stream:Vt(),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 l=this._channels.get(c.label);l&&l._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:l}of this._publishedTracks)try{const u=r.addTrack(c,l);a.set(c,u)}catch(u){this._emit("error",u)}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(l){this._emit("error",l)}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 Gt(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 Gt{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 Ve(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 Re(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=Je(n,"hello",i),a=Je(n,"joined",i);a.catch(()=>{});try{await n.connect();const c=await o,l=c&&c.peerId;if(typeof l!="string"||l.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 u=await a,d=u&&Array.isArray(u.peers)?u.peers:[],p=new G({id:e.room,self:l,signaling:n,peerOptions:r});for(const f of d)p._addPeer(f);if(e.media){const f=e.media===!0?{audio:!0,video:!0}:e.media,_=e.navigator||(typeof navigator!="undefined"?navigator:null),g=_&&_.mediaDevices;if(!g||typeof g.getUserMedia!="function")throw new E("webrtc.join: navigator.mediaDevices.getUserMedia is unavailable",{code:"ZQ_WEBRTC_JOIN_NO_MEDIA_DEVICES"});const m=await g.getUserMedia(f);await p.publish(m)}return p}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 Je(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 Vt(){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 G?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"})):Ve(s,e||{})}function Xe(s,e){if(!(s instanceof G))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 G))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 l={data:a,from:c,at:Date.now()},u=i.peek().slice();u.push(l),u.length>n&&u.splice(0,u.length-n),i.value=u});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(),l=Jt(c);l!==r.peek()&&(r.value=l)}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 Jt(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 xe(s,e){if(typeof s!="string"||!s)throw new U("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 U("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 U(`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 U(`fetchTurnCredentials: HTTP ${o}`,{code:"ZQ_WEBRTC_TURN_HTTP",context:{url:s,status:o}})}let i;try{i=await r.json()}catch(o){throw new U("fetchTurnCredentials: response is not valid JSON",{code:"ZQ_WEBRTC_TURN_BAD_JSON",cause:o instanceof Error?o:void 0,context:{url:s}})}return Yt(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(l=>typeof l!="string"||!l||n.has(l)?!1:(n.add(l),!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 U("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,l=!1,u=null;const d={get value(){return u},peek(){return u},async refresh(){if(l)return null;try{const f=t?{...a||{},fetch:t}:a,_=await xe(e,f);return l||(u=_,p(_.ttl),i&&i(_)),_}catch(f){throw!l&&o&&o(f),l||p(60),f}},async start(){return l?null:d.refresh()},stop(){l=!0,c&&(clearTimeout(c),c=null)}};function p(f){c&&(clearTimeout(c),c=null);const _=Math.max(r,f*1e3-n);c=setTimeout(()=>{c=null,d.refresh().catch(()=>{})},_),c&&typeof c.unref=="function"&&c.unref()}return d}function Yt(s,e){if(!s||typeof s!="object")throw new U("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 U("fetchTurnCredentials: response.username missing",{code:"ZQ_WEBRTC_TURN_BAD_BODY",context:{url:e,field:"username"}});if(typeof n!="string"||!n)throw new U("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 U("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 U("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,te=1+at,Xt=1e5,en=new TextEncoder().encode("zquery-sframe-v1");function le(){const s=typeof crypto!="undefined"&&crypto.subtle?crypto.subtle:null;if(!s)throw new N("WebCrypto SubtleCrypto is not available in this environment",{code:"ZQ_WEBRTC_E2EE_NO_WEBCRYPTO"});return s}function tn(s){const e=new Uint8Array(s);if(typeof crypto=="undefined"||typeof crypto.getRandomValues!="function")throw new N("crypto.getRandomValues is not available in this environment",{code:"ZQ_WEBRTC_E2EE_NO_RANDOM"});return crypto.getRandomValues(e),e}function ue(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 N("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 N("deriveSFrameKey: passphrase must be a non-empty string",{code:"ZQ_WEBRTC_E2EE_BAD_PASSPHRASE"});if(typeof e!="string"||!e)throw new N("deriveSFrameKey: salt must be a non-empty string",{code:"ZQ_WEBRTC_E2EE_BAD_SALT"});const t=le(),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:Xt},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:en},o,{name:"AES-GCM",length:ot},!1,["encrypt","decrypt"])}async function lt(){return le().generateKey({name:"AES-GCM",length:ot},!0,["encrypt","decrypt"])}class ne{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 N("SFrameContext.setKey: epoch must be an integer in [0, 255]",{code:"ZQ_WEBRTC_E2EE_BAD_EPOCH"});if(!t)throw new N("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 Le(s,e){if(!(s instanceof ne))throw new N("encryptFrame: ctx must be an SFrameContext",{code:"ZQ_WEBRTC_E2EE_BAD_CTX"});const t=s.getKey(s.currentEpoch);if(!t)throw new N(`encryptFrame: no key installed for epoch ${s.currentEpoch}`,{code:"ZQ_WEBRTC_E2EE_NO_KEY",context:{epoch:s.currentEpoch}});const n=ue(e),r=tn(at),i=new Uint8Array(await le().encrypt({name:"AES-GCM",iv:r},t,n)),o=new Uint8Array(te+i.byteLength);return o[0]=s.currentEpoch&255,o.set(r,1),o.set(i,te),o}async function Oe(s,e){if(!(s instanceof ne))throw new N("decryptFrame: ctx must be an SFrameContext",{code:"ZQ_WEBRTC_E2EE_BAD_CTX"});const t=ue(e);if(t.byteLength<=te)throw new N("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 N(`decryptFrame: no key for epoch ${n}`,{code:"ZQ_WEBRTC_E2EE_UNKNOWN_EPOCH",context:{epoch:n}});const i=t.subarray(1,te),o=t.subarray(te);let a;try{a=new Uint8Array(await le().decrypt({name:"AES-GCM",iv:i},r,o))}catch(c){throw new N("decryptFrame: AES-GCM authentication failed",{code:"ZQ_WEBRTC_E2EE_AUTH_FAILED",cause:c instanceof Error?c:void 0,context:{epoch:n}})}return a}function ut(s,e){if(!s||typeof s.getSenders!="function"||typeof s.getReceivers!="function")throw new N("attachE2ee: pc must look like an RTCPeerConnection",{code:"ZQ_WEBRTC_E2EE_BAD_PC"});if(!(e instanceof ne))throw new N("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 l=new TransformStream({async transform(u,d){try{const p=ue(u.data),f=await Le(e,p);u.data=f.buffer,d.enqueue(u)}catch{}}});c.readable.pipeThrough(l).pipeTo(c.writable).catch(()=>{})}function i(a){if(n||t.has(a))return;t.add(a);const c=ft(a);if(!c)return;const l=new TransformStream({async transform(u,d){try{const p=ue(u.data),f=await Oe(e,p);u.data=f.buffer,d.enqueue(u)}catch{}}});c.readable.pipeThrough(l).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=sn(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:nn(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 nn(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 sn(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 Ne(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 rn(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 u=await Ne(s);if(a)return;if(o=u,r)try{r(u)}catch{}}catch(u){if(i)try{i(u)}catch{}}};n&&c();const l=setInterval(c,t);return{stop(){a||(a=!0,clearInterval(l))},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 rn(s){const e=[],t=[];let n=null;const r=p=>{!p||typeof p!="object"||(p.type==="inbound-rtp"&&e.push(p),p.type==="outbound-rtp"&&t.push(p),p.type==="candidate-pair"&&(p.nominated||p.state==="succeeded")&&(n||(n=p)))};if(s&&typeof s.forEach=="function")s.forEach(r);else if(s&&typeof s=="object")for(const p of Object.keys(s))r(s[p]);let i=0,o=0,a=0,c=0;for(const p of t)typeof p.bytesSent=="number"&&(i+=p.bytesSent);for(const p of e)typeof p.bytesReceived=="number"&&(o+=p.bytesReceived),typeof p.packetsLost=="number"&&(a+=p.packetsLost),typeof p.packetsReceived=="number"&&(c+=p.packetsReceived);const l=a+c,u=l>0?a/l*100:0;let d=null;return n&&typeof n.currentRoundTripTime=="number"&&(d=n.currentRoundTripTime*1e3),{report:s,inboundRtp:e,outboundRtp:t,candidatePair:n,summary:{rttMs:d,lossPct:u,bytesSent:i,bytesReceived:o}}}async function on(){try{return await import(["mediasoup","client"].join("-"))}catch(s){throw new k("mediasoup-client peer dependency is not installed; run `npm install mediasoup-client`",{code:"ZQ_WEBRTC_SFU_PEER_MISSING",cause:s})}}async function an(s={}){const e=s.client||await on(),t=e.Device||e.default&&e.default.Device;if(typeof t!="function")throw new k("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 k("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 k("load(routerRtpCapabilities): routerRtpCapabilities required",{code:"ZQ_WEBRTC_SFU_BAD_RTP_CAPS"});if(!n.loaded)try{await n.load({routerRtpCapabilities:r})}catch(i){throw new k("device.load() failed",{code:"ZQ_WEBRTC_SFU_LOAD_FAILED",cause:i})}},canProduce(r){if(!n.loaded)throw new k("canProduce(): device not loaded yet",{code:"ZQ_WEBRTC_SFU_NOT_LOADED"});return!!n.canProduce(r)},createSendTransport(r){if(!n.loaded)throw new k("createSendTransport(): device not loaded yet",{code:"ZQ_WEBRTC_SFU_NOT_LOADED"});return n.createSendTransport(r)},createRecvTransport(r){if(!n.loaded)throw new k("createRecvTransport(): device not loaded yet",{code:"ZQ_WEBRTC_SFU_NOT_LOADED"});return n.createRecvTransport(r)},async join(r){throw new k("mediasoup adapter.join() not implemented; use device + createSendTransport/createRecvTransport with your SFU signaling layer",{code:"ZQ_WEBRTC_SFU_JOIN_UNAVAILABLE"})}}}async function cn(){try{return await import(["livekit","client"].join("-"))}catch(s){throw new k("livekit-client peer dependency is not installed; run `npm install livekit-client`",{code:"ZQ_WEBRTC_SFU_PEER_MISSING",cause:s})}}async function ln(s={}){const e=s.client||await cn(),t=e.Room||e.default&&e.default.Room;if(typeof t!="function")throw new k("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 k("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 k("connect(url, token): url required",{code:"ZQ_WEBRTC_SFU_BAD_URL"});if(typeof o!="string"||!o)throw new k("connect(url, token): token required",{code:"ZQ_WEBRTC_SFU_BAD_TOKEN"});try{await n.connect(i,o,a),r=!0}catch(c){throw new k("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 k("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 an(e);if(s==="livekit")return ln(e);throw new k(`unknown SFU adapter: ${s}`,{code:"ZQ_WEBRTC_SFU_UNKNOWN",context:{name:s}})}const un={SignalingClient:Re,Peer:ke,Room:G,join:Ve,useRoom:Ye,usePeer:Xe,useTracks:et,useDataChannel:tt,useConnectionQuality:nt,fetchTurnCredentials:xe,mergeIceServers:rt,createTurnRefresher:it,deriveSFrameKey:ct,generateSFrameKey:lt,SFrameContext:ne,encryptFrame:Le,decryptFrame:Oe,attachE2ee:ut,loadSfuAdapter:mt,decodeJoinToken:ht,isJoinTokenExpired:dt,samplePeerStats:Ne,createStatsSampler:pt,classifyStats:_t,parseSdp:Ee,validateSdp:Ze,parseCandidate:Se,stringifyCandidate:He,filterCandidates:Ke,isPrivateIp:ve,isLoopbackIp:Ce,isLinkLocalIp:Ae,isMdnsHostname:Te,WebRtcError:E,SignalingError:P,IceError:M,SdpError:B,TurnError:U,E2eeError:N,SfuError:k};function yt(s){if(s===null||typeof s!="object")return!1;if(Array.isArray(s))return!0;const e=Object.getPrototypeOf(s);return e===Object.prototype||e===null}function Pe(s,e,t=""){if(!yt(s))return s;typeof e!="function"&&(A(v.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(yt(a)){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(l){A(v.REACTIVE_CALLBACK,`Reactive onChange threw for key "${String(o)}"`,{key:o,value:a,old:c},l)}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){A(v.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){A(v.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 fn(s){const e=new R(void 0);return gt(()=>{const t=s();t!==e._value&&(e._value=t,e._notify())}),e}function gt(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){A(v.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 hn(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){A(v.SIGNAL_CALLBACK,"Signal subscriber threw",{},r)}}return e}function dn(s){const e=R._activeEffect;R._activeEffect=null;try{return s()}finally{R._activeEffect=e}}let Be=null;function wt(){return Be||(Be=document.createElement("template")),Be}function Me(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);fe(s,i),t&&window.__zqMorphHook(s,performance.now()-t)}function Et(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 vt(s,r),fe(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 bt=Me,pn=Et;function fe(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 d=0;d<r;d++)o[d]=t[d];for(let d=0;d<i;d++)a[d]=n[d];let c=!1,l,u;for(let d=0;d<r;d++)if(D(o[d])!=null){c=!0;break}if(!c){for(let d=0;d<i;d++)if(D(a[d])!=null){c=!0;break}}if(c){l=new Map,u=new Map;for(let d=0;d<r;d++){const p=D(o[d]);p!=null&&l.set(p,d)}for(let d=0;d<i;d++){const p=D(a[d]);p!=null&&u.set(p,d)}mn(s,o,a,l,u)}else _n(s,o,a)}function _n(s,e,t){const n=e.length,r=t.length,i=n<r?n:r;for(let o=0;o<i;o++)St(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 mn(s,e,t,n,r){const i=new Set,o=t.length,a=new Array(o);for(let f=0;f<o;f++){const _=D(t[f]);if(_!=null&&n.has(_)){const g=n.get(_);a[f]=e[g],i.add(g)}else a[f]=null}for(let f=e.length-1;f>=0;f--)if(!i.has(f)){const _=D(e[f]);_!=null&&!r.has(_)&&s.removeChild(e[f])}const c=[];for(let f=0;f<o;f++)if(a[f]){const _=D(t[f]);c.push(n.get(_))}else c.push(-1);const l=yn(c);let u=s.firstChild;const d=[];for(let f=0;f<e.length;f++)!i.has(f)&&D(e[f])==null&&d.push(e[f]);let p=0;for(let f=0;f<o;f++){const _=t[f],g=D(_);let m=a[f];if(!m&&g==null&&(m=d[p++]||null),m){l.has(f)||s.insertBefore(m,u);const S=m.nextSibling;St(s,m,_),u=S}else{const S=_.cloneNode(!0);u?s.insertBefore(S,u):s.appendChild(S)}}for(;p<d.length;){const f=d[p++];f.parentNode===s&&s.removeChild(f)}for(let f=0;f<e.length;f++)if(!i.has(f)){const _=e[f];_.parentNode===s&&D(_)!=null&&!r.has(D(_))&&s.removeChild(_)}}function yn(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 l=0,u=n.length;for(;l<u;){const d=l+u>>1;n[d]<c?l=d+1:u=d}n[l]=c,i[l]=a,r[a]=l>0?i[l-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 St(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;vt(e,t);const n=e.nodeName;if(n==="INPUT"){gn(e,t);return}if(n==="TEXTAREA"){e.value!==t.textContent&&(e.value=t.textContent||"");return}if(n==="SELECT"){fe(e,t),e.value!==t.value&&(e.value=t.value);return}fe(e,t)}}function vt(s,e){const t=e.attributes,n=s.attributes,r=t.length,i=n.length;if(r===i){let c=!0;for(let l=0;l<r;l++){const u=t[l];if(s.getAttribute(u.name)!==u.value){c=!1;break}}if(c){for(let l=0;l<i;l++)if(!e.hasAttribute(n[l].name)){c=!1;break}}if(c)return}const o=new Set;for(let c=0;c<r;c++){const l=t[c];o.add(l.name),s.getAttribute(l.name)!==l.value&&s.setAttribute(l.name,l.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 gn(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 w{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 w(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 w(t)}parent(){const e=[...new Set(this.elements.map(t=>t.parentElement).filter(Boolean))];return new w(e)}closest(e){return new w(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 w([...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 w(t)}next(e){const t=this.elements.map(n=>n.nextElementSibling).filter(Boolean);return new w(e?t.filter(n=>n.matches(e)):t)}prev(e){const t=this.elements.map(n=>n.previousElementSibling).filter(Boolean);return new w(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 w(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 w(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 w(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 w(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 w([...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 w([...new Set(n)])}contents(){const e=[];return this.elements.forEach(t=>e.push(...t.childNodes)),new w(e)}filter(e){return typeof e=="function"?new w(this.elements.filter(e)):new w(this.elements.filter(t=>t.matches(e)))}not(e){return typeof e=="function"?new w(this.elements.filter((t,n)=>!e.call(t,n,t))):new w(this.elements.filter(t=>!t.matches(e)))}has(e){return new w(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 w(this.elements.slice(e,t))}add(e,t){const n=e instanceof w?e.elements:e instanceof Node?[e]:Array.from((t||document).querySelectorAll(e));return new w([...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 r;if(typeof e=="object"&&e!==null)return this.each((i,o)=>{for(const[a,c]of Object.entries(e))o.setAttribute(a,c)});if(t===void 0)return(r=this.first())==null?void 0:r.getAttribute(e);const n=this.elements;for(let i=0;i<n.length;i++)n[i].setAttribute(e,t);return this}removeAttr(e){const t=this.elements;for(let n=0;n<t.length;n++)t[n].removeAttribute(e);return this}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?bt(r,e):r.innerHTML=e})}morph(e){return this.each((t,n)=>{bt(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 w?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"?se(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 w(this.elements.map(t=>t.cloneNode(e)))}replaceWith(e){return this.each((t,n)=>{typeof e=="string"?pn(n,e):e instanceof Node&&n.parentNode.replaceChild(e,n)})}appendTo(e){const t=typeof e=="string"?document.querySelector(e):e instanceof w?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 w?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 w?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 w?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 w?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"?se(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"?se(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=l=>{if(!l.target||typeof l.target.closest!="function")return;const u=l.target.closest(t);u&&o.contains(u)&&n.call(u,l)};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,l)=>{l.style.transition=`all ${t}ms ${n}`,requestAnimationFrame(()=>{Object.assign(l.style,e);const u=()=>{l.removeEventListener("transitionend",u),l.style.transition="",!i&&++o.done>=this.length&&(i=!0,r(this))};l.addEventListener("transitionend",u),a.push({el:l,onEnd:u})})}),setTimeout(()=>{if(!i){i=!0;for(const{el:c,onEnd:l}of a)c.removeEventListener("transitionend",l),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 w([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 se(s){const e=document.createElement("template");return e.innerHTML=s.trim(),e.content}function C(s,e){if(!s)return new w([]);if(s instanceof w)return s;if(s instanceof Node||s===window)return new w([s]);if(s instanceof NodeList||s instanceof HTMLCollection||Array.isArray(s))return new w(Array.from(s));if(typeof s=="string"&&s.trim().startsWith("<")){const t=se(s);return new w([...t.childNodes].filter(n=>n.nodeType===1))}if(typeof s=="string"){const t=e?typeof e=="string"?document.querySelector(e):e:document;return new w([...t.querySelectorAll(s)])}return new w([])}function wn(s,e){if(!s)return new w([]);if(s instanceof w)return s;if(s instanceof Node||s===window)return new w([s]);if(s instanceof NodeList||s instanceof HTMLCollection||Array.isArray(s))return new w(Array.from(s));if(typeof s=="string"&&s.trim().startsWith("<")){const t=se(s);return new w([...t.childNodes].filter(n=>n.nodeType===1))}if(typeof s=="string"){const t=e?typeof e=="string"?document.querySelector(e):e:document;return new w([...t.querySelectorAll(s)])}return new w([])}C.id=s=>document.getElementById(s),C.class=s=>document.querySelector(`.${typeof CSS!="undefined"&&CSS.escape?CSS.escape(s):s}`),C.classes=s=>new w(Array.from(document.getElementsByClassName(s))),C.tag=s=>new w(Array.from(document.getElementsByTagName(s))),Object.defineProperty(C,"name",{value:s=>new w(Array.from(document.getElementsByName(s))),writable:!0,configurable:!0}),C.children=s=>{const e=document.getElementById(s);return new w(e?Array.from(e.children):[])},C.qs=(s,e=document)=>e.querySelector(s),C.qsa=(s,e=document)=>Array.from(e.querySelectorAll(s)),C.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 w(n)},C.ready=s=>{document.readyState!=="loading"?s():document.addEventListener("DOMContentLoaded",s)},C.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)})},C.off=(s,e)=>{document.removeEventListener(s,e)},C.fn=w.prototype;const y={NUM:1,STR:2,IDENT:3,OP:4,PUNC:5,TMPL:6,EOF:7},he={"??":2,"||":3,"&&":4,"==":8,"!=":8,"===":8,"!==":8,"<":9,">":9,"<=":9,">=":9,instanceof:9,in:9,"+":11,"-":11,"*":12,"/":12,"%":12},En=new Set(["true","false","null","undefined","typeof","instanceof","in","new","void"]);function bn(s){const e=[];let t=0;const n=s.length;for(;t<n;){const r=s[t];if(r===" "||r===" "||r===`
10
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 l=s[++t];l==="n"?c+=`
11
- `:l==="t"?c+=" ":l==="r"?c+="\r":l==="\\"?c+="\\":l===a?c+=a:c+=l}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 l=1,u="";for(;t<n&&l>0;){if(s[t]==="{")l++;else if(s[t]==="}"&&(l--,l===0))break;u+=s[t++]}t++,a.push({expr:u})}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 Sn{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.depth=0,this.parseExpression(0)}parseExpression(e){if(++this.depth>96)throw this.depth--,new Error("Expression nesting depth exceeded (max 96)");try{return this._parseExpressionImpl(e)}finally{this.depth--}}_parseExpressionImpl(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 he){const i=he[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")&&he[r.v]>e){const i=he[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&&!En.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 vn=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"]),Cn=new Set(["toFixed","toPrecision","toString","valueOf"]);function de(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"?vn.has(e):typeof s=="number"?Cn.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=V(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 de(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 de(n,r)?n[r]:void 0}case"call":return An(s,e,!1);case"optional_call":{const n=s.callee,r=Me(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(!de(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=Me(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,l)=>{a[c]=o[l]}),b(r,[a,...i])}}default:return}}function Me(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 An(s,e){const t=s.callee,n=Me(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(!de(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,Rn=512,Ct=8192;function V(s,e){try{if(typeof s!="string")return;if(s.length>Ct)throw new Error(`Expression exceeds max length (${Ct} bytes)`);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=bn(t);if(n=new Sn(r,e).parse(),Z.size>=Rn){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 re=new Map,z=new Map,pe=new Map;let At=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 _e=new WeakMap,me=new WeakMap;function ie(s){if(pe.has(s))return pe.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 pe.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 pe.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 Ie;try{typeof document!="undefined"&&document.currentScript&&document.currentScript.src&&(Ie=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)&&!(Ie&&n.replace(/[?#].*$/,"")===Ie))return n.replace(/\/[^/]*$/,"/")}}catch{}}function ye(s,e){return e.split(".").reduce((t,n)=>t==null?void 0:t[n],s)}function kn(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 De{constructor(e,t,n={}){this._uid=++At,this._el=e,this._def=t,this._mounted=!1,this._destroyed=!1,this._updateQueued=!1,this._listeners=[],this._watchCleanups=[],this._timerEls=new Set,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);const o=Object.keys(t.props),a=[];for(const c of o)a.push(c.toLowerCase()),a.push(":"+c.toLowerCase());this._propObserver=new MutationObserver(c=>{if(this._destroyed)return;let l=!1;for(const u of c)if(u.type==="attributes"){const d=u.attributeName;(d.startsWith(":")?d.slice(1):d)in t.props&&(l=!0)}l&&(this.props=this._resolveReactiveProps(t.props,{}),this._scheduleUpdate())}),this._propObserver.observe(e,{attributes:!0,attributeFilter:a})}else this.props=Object.freeze({...n});if(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:l}=a,u={};for(const p of l)u[p]=c.state[p];this.stores[o]=u;const d=c.subscribe(l,(p,f)=>{this.stores[o][p]=f,this._destroyed||this._scheduleUpdate()});this._storeCleanups.push(d)}const i=typeof t.state=="function"?t.state():{...t.state||{}};if(this.state=Pe(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"&&!xn.has(o)&&(this[o]=a.bind(this));if(t.init)try{t.init.call(this)}catch(o){A(v.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]=ye(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=ye(this.state.__raw||this.state,o),l=(i=this._prevWatchValues)==null?void 0:i[o];if(c!==l){const u=typeof a=="function"?a:a.handler;typeof u=="function"&&u.call(this,c,l),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 l=this._el.getAttribute(":"+r),u=l!==null;u||(l=this._el.getAttribute(r),u=l!==null),u&&l!==null?n[r]=this._coercePropValue(l,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 ie(J(n,t));else if(Array.isArray(n)){const r=n.map(o=>J(o,t)),i=await Promise.all(r.map(o=>ie(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])=>ie(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 ie(r),e._resolvedStyleUrls=[r]}else if(Array.isArray(n)){const r=n.map(o=>J(o,t)),i=await Promise.all(r.map(o=>ie(o)));e._externalStyles=i.join(`
11
+ `:l==="t"?c+=" ":l==="r"?c+="\r":l==="\\"?c+="\\":l===a?c+=a:c+=l}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 l=1,u="";for(;t<n&&l>0;){if(s[t]==="{")l++;else if(s[t]==="}"&&(l--,l===0))break;u+=s[t++]}t++,a.push({expr:u})}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 Sn{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.depth=0,this.parseExpression(0)}parseExpression(e){if(++this.depth>96)throw this.depth--,new Error("Expression nesting depth exceeded (max 96)");try{return this._parseExpressionImpl(e)}finally{this.depth--}}_parseExpressionImpl(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 he){const i=he[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")&&he[r.v]>e){const i=he[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&&!En.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 vn=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"]),Cn=new Set(["toFixed","toPrecision","toString","valueOf"]);function de(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"?vn.has(e):typeof s=="number"?Cn.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=V(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 de(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 de(n,r)?n[r]:void 0}case"call":return An(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(!de(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,l)=>{a[c]=o[l]}),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 An(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(!de(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,Rn=512,Ct=8192;function V(s,e){try{if(typeof s!="string")return;if(s.length>Ct)throw new Error(`Expression exceeds max length (${Ct} bytes)`);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=bn(t);if(n=new Sn(r,e).parse(),Z.size>=Rn){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 re=new Map,z=new Map,pe=new Map;let At=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 _e=new WeakMap,me=new WeakMap;function ie(s){if(pe.has(s))return pe.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 pe.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 pe.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 Ie;try{typeof document!="undefined"&&document.currentScript&&document.currentScript.src&&(Ie=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)&&!(Ie&&n.replace(/[?#].*$/,"")===Ie))return n.replace(/\/[^/]*$/,"/")}}catch{}}function ye(s,e){return e.split(".").reduce((t,n)=>t==null?void 0:t[n],s)}function kn(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 De{constructor(e,t,n={}){this._uid=++At,this._el=e,this._def=t,this._mounted=!1,this._destroyed=!1,this._updateQueued=!1,this._listeners=[],this._watchCleanups=[],this._timerEls=new Set,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);const o=Object.keys(t.props),a=[];for(const c of o)a.push(c.toLowerCase()),a.push(":"+c.toLowerCase());this._propObserver=new MutationObserver(c=>{if(this._destroyed)return;let l=!1;for(const u of c)if(u.type==="attributes"){const d=u.attributeName;(d.startsWith(":")?d.slice(1):d)in t.props&&(l=!0)}l&&(this.props=this._resolveReactiveProps(t.props,{}),this._scheduleUpdate())}),this._propObserver.observe(e,{attributes:!0,attributeFilter:a})}else this.props=Object.freeze({...n});if(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:l}=a,u={};for(const p of l)u[p]=c.state[p];this.stores[o]=u;const d=c.subscribe(l,(p,f)=>{this.stores[o][p]=f,this._destroyed||this._scheduleUpdate()});this._storeCleanups.push(d)}const i=typeof t.state=="function"?t.state():{...t.state||{}};if(this.state=Pe(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"&&!xn.has(o)&&(this[o]=a.bind(this));if(t.init)try{t.init.call(this)}catch(o){A(v.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]=ye(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=ye(this.state.__raw||this.state,o),l=(i=this._prevWatchValues)==null?void 0:i[o];if(c!==l){const u=typeof a=="function"?a:a.handler;typeof u=="function"&&u.call(this,c,l),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 l=this._el.getAttribute(":"+r),u=l!==null;u||(l=this._el.getAttribute(r),u=l!==null),u&&l!==null?n[r]=this._coercePropValue(l,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 ie(J(n,t));else if(Array.isArray(n)){const r=n.map(o=>J(o,t)),i=await Promise.all(r.map(o=>ie(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])=>ie(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 ie(r),e._resolvedStyleUrls=[r]}else if(Array.isArray(n)){const r=n.map(o=>J(o,t)),i=await Promise.all(r.map(o=>ie(o)));e._externalStyles=i.join(`
12
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,l)=>{try{const u=V(l.trim(),[this.state.__raw||this.state,{props:this.props,computed:this.computed,$:typeof window!="undefined"?window.$:void 0}]);return u!=null?we(String(u)):""}catch{return""}})):e="",e=this._expandContentDirectives(e),e.includes("<slot")&&(e=e.replace(/<slot(?:\s+name="([^"]*)")?\s*(?:\/>|>([\s\S]*?)<\/slot>)/g,(c,l,u)=>{const d=l||"default";return this._slotContent[d]||u||""}));const t=[this._def.styles||"",this._def._externalStyles||""].filter(Boolean).join(`
13
- `);if(!this._mounted&&t){const c=this._def;let l=c._scopeAttr;if(l||(l=c._name?`z-s-${c._name}`:`z-s${this._uid}`,c._scopeAttr=l),this._el.setAttribute(l,""),this._scopeAttr=l,c._styleEl&&c._styleEl.isConnected)c._styleRefCount=(c._styleRefCount||0)+1;else{let u=0,d=0;const p=t.replace(/([^{}]+)\{|\}/g,(_,g)=>{if(_==="}")return u>0&&d<=u&&(u=0),d--,_;d++;const m=g.trim();return m.startsWith("@")?(/^@(keyframes|font-face)\b/.test(m)&&(u=d),_):u>0&&d>u?_:g.split(",").map(S=>`[${l}] ${S.trim()}`).join(", ")+" {"}),f=document.createElement("style");f.textContent=p,f.setAttribute("data-zq-component",c._name||""),f.setAttribute("data-zq-scope",l),c._resolvedStyleUrls&&(f.setAttribute("data-zq-style-urls",c._resolvedStyleUrls.join(" ")),c.styles&&f.setAttribute("data-zq-inline",c.styles)),document.head.appendChild(f),c._styleEl=f,c._styleRefCount=1}}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"),l=(a=r.getAttribute)==null?void 0:a.call(r,"z-ref");let u=null;if(c)u=`[z-model="${c}"]`;else if(l)u=`[z-ref="${l}"]`;else{const d=r.tagName.toLowerCase();if(d==="input"||d==="textarea"||d==="select"){let p=d;r.type&&(p+=`[type="${r.type}"]`),r.name&&(p+=`[name="${r.name}"]`),r.placeholder&&(p+=`[placeholder="${CSS.escape(r.placeholder)}"]`),u=p}}u&&(n={selector:u,start:r.selectionStart,end:r.selectionEnd,dir:r.selectionDirection})}const i=typeof window!="undefined"&&(window.__zqMorphHook||window.__zqRenderHook)?performance.now():0;if(this._mounted?Ue(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(kt(this._el),this._mounted){if(this._def.updated)try{this._def.updated.call(this)}catch(c){A(v.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){A(v.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("."),l=c[0],u=c.slice(1),d=o.value;n.dataset.zqEid||(n.dataset.zqEid=String(++At));const p=`[data-zq-eid="${n.dataset.zqEid}"]`;e.has(l)||e.set(l,[]),e.get(l).push({selector:p,methodExpr:d,modifiers:u,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 l=this[c[1]];typeof l=="function"&&l.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 d;const c=((d=this._eventBindings)==null?void 0:d.get(e))||[],l=[];for(const p of c){const f=a.target.closest(p.selector);f&&l.push({...p,matched:f})}l.sort((p,f)=>p.matched===f.matched?0:p.matched.contains(f.matched)?1:-1);let u=null;for(const{methodExpr:p,modifiers:f,el:_,matched:g}of l){if(u){let O=!1;for(const T of u)if(g.contains(T)&&g!==T){O=!0;break}if(O)continue}if(f.includes("self")&&a.target!==_||f.includes("outside")&&_.contains(a.target))continue;const m={enter:"Enter",escape:"Escape",tab:"Tab",space:" ",delete:"Delete|Backspace",up:"ArrowUp",down:"ArrowDown",left:"ArrowLeft",right:"ArrowRight"},S=new Set(["prevent","stop","self","once","outside","capture","passive","debounce","throttle","ctrl","shift","alt","meta"]);let L=!1;for(let O=0;O<f.length;O++){const T=f[O];if(m[T]){const X=m[T].split("|");if(!a.key||!X.includes(a.key)){L=!0;break}}else{if(S.has(T))continue;if(/^\d+$/.test(T)&&O>0&&(f[O-1]==="debounce"||f[O-1]==="throttle"))continue;if(!a.key||a.key.toLowerCase()!==T.toLowerCase()){L=!0;break}}}if(L||f.includes("ctrl")&&!a.ctrlKey||f.includes("shift")&&!a.shiftKey||f.includes("alt")&&!a.altKey||f.includes("meta")&&!a.metaKey)continue;f.includes("prevent")&&a.preventDefault(),f.includes("stop")&&(a.stopPropagation(),u||(u=[]),u.push(g));const W=O=>{const T=p.match(/^(\w+)(?:\(([^)]*)\))?$/);if(!T)return;const X=T[1],Fe=this[X];if(typeof Fe=="function")if(T[2]!==void 0){const bs=T[2].split(",").map(x=>{if(x=x.trim(),x!=="")return x==="$event"?O: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.")?ye(this.state,x.slice(6)):x}).filter(x=>x!==void 0);Fe(...bs)}else Fe(O)},Q=f.indexOf("debounce");if(Q!==-1){const O=parseInt(f[Q+1],10)||250,T=_e.get(_)||{};clearTimeout(T[e]),T[e]=setTimeout(()=>W(a),O),_e.set(_,T),this._timerEls.add(_);continue}const je=f.indexOf("throttle");if(je!==-1){const O=parseInt(f[je+1],10)||250,T=me.get(_)||{};if(T[e])continue;W(a),T[e]=setTimeout(()=>{T[e]=null},O),me.set(_,T),this._timerEls.add(_);continue}if(f.includes("once")){if(_.dataset.zqOnce===e)continue;_.dataset.zqOnce=e}W(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"),l=e.hasAttribute("z-uppercase"),u=e.hasAttribute("z-lowercase"),d=e.hasAttribute("z-debounce"),p=d?parseInt(e.getAttribute("z-debounce"),10)||250:0,f=ye(this.state,t);if(n==="input"&&r==="checkbox")e.checked=!!f;else if(n==="input"&&r==="radio")e.checked=e.value===String(f);else if(n==="select"&&e.multiple){const m=Array.isArray(f)?f.map(String):[];[...e.options].forEach(S=>{S.selected=m.includes(S.value)})}else i?e.textContent!==String(f!=null?f:"")&&(e.textContent=f!=null?f:""):e.value=f!=null?f:"";const _=o||n==="select"||r==="checkbox"||r==="radio"?"change":"input";if(e._zqModelUnbind){try{e._zqModelUnbind()}catch{}e._zqModelUnbind=null}const g=()=>{let m;r==="checkbox"?m=e.checked:n==="select"&&e.multiple?m=[...e.selectedOptions].map(S=>S.value):i?m=e.textContent:m=e.value,a&&typeof m=="string"&&(m=m.trim()),l&&typeof m=="string"&&(m=m.toUpperCase()),u&&typeof m=="string"&&(m=m.toLowerCase()),(c||r==="number"||r==="range")&&(m=Number(m)),kn(this.state,t,m)};if(d){let m=null;const S=()=>{clearTimeout(m),m=setTimeout(g,p)};e.addEventListener(_,S),e._zqModelUnbind=()=>{e.removeEventListener(_,S),clearTimeout(m)}}else e.addEventListener(_,g),e._zqModelUnbind=()=>e.removeEventListener(_,g)})}_evalExpr(e){return V(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 l=c[1]||c[3],u=c[2]||"$index",d=c[4].trim();let p=this._evalExpr(d);if(p==null){o.remove();continue}if(typeof p=="number"&&(p=Array.from({length:p},(L,W)=>W+1)),!Array.isArray(p)&&typeof p=="object"&&typeof p[Symbol.iterator]!="function"&&(p=Object.entries(p).map(([L,W])=>({key:L,value:W}))),!Array.isArray(p)&&typeof p[Symbol.iterator]=="function"&&(p=[...p]),!Array.isArray(p)){o.remove();continue}const f=o.parentNode,_=o.cloneNode(!0);_.removeAttribute("z-for");const g=_.outerHTML,m=document.createDocumentFragment(),S=(L,W,Q)=>L.replace(/\{\{(.+?)\}\}/g,(je,O)=>{try{const T={};T[l]=W,T[u]=Q;const X=V(O.trim(),[T,this.state.__raw||this.state,{props:this.props,computed:this.computed,$:typeof window!="undefined"?window.$:void 0}]);return X!=null?we(String(X)):""}catch{return""}});for(let L=0;L<p.length;L++){const W=S(g,p[L],L),Q=document.createElement("div");for(Q.innerHTML=W;Q.firstChild;)m.appendChild(Q.firstChild)}f.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 i of e){if(!i.parentNode||i.closest("[z-pre]"))continue;const o=!!this._evalExpr(i.getAttribute("z-if")),a=[{el:i,show:o}];let c=i.nextElementSibling;for(;c;)if(c.hasAttribute("z-else-if"))a.push({el:c,show:!!this._evalExpr(c.getAttribute("z-else-if"))}),c=c.nextElementSibling;else if(c.hasAttribute("z-else")){a.push({el:c,show:!0});break}else break;let l=!1;for(const u of a)if(!l&&u.show){l=!0,u.el.removeAttribute("z-if"),u.el.removeAttribute("z-else-if"),u.el.removeAttribute("z-else");const d=u.el.getAttribute("z-transition");d&&(u.el.removeAttribute("z-transition"),this._transitionEnter(u.el,d))}else{const d=u.el.getAttribute("z-transition");d?this._transitionLeave(u.el,d,()=>u.el.remove()):u.el.remove()}}this._el.querySelectorAll("[z-show]").forEach(i=>{if(i.closest("[z-pre]"))return;const o=!!this._evalExpr(i.getAttribute("z-show")),a=i.getAttribute("z-transition"),c=i.style.display==="none"||i.hasAttribute("data-zq-hidden");a?(i.removeAttribute("z-show"),o&&c?(i.style.display="",i.removeAttribute("data-zq-hidden"),this._transitionEnter(i,a)):!o&&!c?(i.setAttribute("data-zq-hidden",""),this._transitionLeave(i,a,()=>{i.style.display="none"})):(i.style.display=o?"":"none",o?i.removeAttribute("data-zq-hidden"):i.setAttribute("data-zq-hidden",""))):(i.style.display=o?"":"none",i.removeAttribute("z-show"))});const t=document.createTreeWalker(this._el,NodeFilter.SHOW_ELEMENT,{acceptNode(i){return i.hasAttribute("z-pre")?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}}),n=typeof MediaStream!="undefined";let r;for(;r=t.nextNode();){const i=r.attributes;for(let o=i.length-1;o>=0;o--){const a=i[o];let c;if(a.name.startsWith("z-bind:"))c=a.name.slice(7);else if(a.name.charCodeAt(0)===58&&a.name.charCodeAt(1)!==58)c=a.name.slice(1);else continue;const l=this._evalExpr(a.value);r.removeAttribute(a.name),l===!1||l===null||l===void 0?r.toggleAttribute(c,!1):l===!0?r.toggleAttribute(c,!0):r.setAttribute(c,String(l))}if(r.hasAttribute("z-class")){const o=this._evalExpr(r.getAttribute("z-class"));if(typeof o=="string")o.split(/\s+/).filter(Boolean).forEach(a=>r.classList.add(a));else if(Array.isArray(o))o.filter(Boolean).forEach(a=>r.classList.add(String(a)));else if(o&&typeof o=="object")for(const[a,c]of Object.entries(o))r.classList.toggle(a,!!c);r.removeAttribute("z-class")}if(r.hasAttribute("z-style")){const o=this._evalExpr(r.getAttribute("z-style"));if(typeof o=="string")r.style.cssText+=";"+o;else if(o&&typeof o=="object")for(const[a,c]of Object.entries(o))r.style[a]=c;r.removeAttribute("z-style")}if(r.hasAttribute("z-stream")){const o=this._evalExpr(r.getAttribute("z-stream"));o==null?r.srcObject=null:n&&o instanceof MediaStream||o&&typeof o.getTracks=="function"?r.srcObject=o:r.srcObject=null,r.removeAttribute("z-stream")}r.hasAttribute("z-cloak")&&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){if(this._destroyed=!0,this._def.destroyed)try{this._def.destroyed.call(this)}catch(e){A(v.COMP_LIFECYCLE,`Component "${this._def._name}" destroyed() threw`,{component:this._def._name},e)}if(this._propObserver&&(this._propObserver.disconnect(),this._propObserver=null),this._storeCleanups&&(this._storeCleanups.forEach(e=>e()),this._storeCleanups=[]),this._listeners.forEach(({event:e,handler:t})=>this._el.removeEventListener(e,t)),this._listeners=[],this._outsideListeners&&(this._outsideListeners.forEach(({event:e,handler:t})=>document.removeEventListener(e,t,!0)),this._outsideListeners=[]),this._delegatedEvents=null,this._eventBindings=null,this._timerEls&&(this._timerEls.forEach(e=>{const t=_e.get(e);if(t){for(const r in t)clearTimeout(t[r]);_e.delete(e)}const n=me.get(e);if(n){for(const r in n)clearTimeout(n[r]);me.delete(e)}}),this._timerEls.clear()),this._scopeAttr){const e=this._def;e&&e._styleEl&&e._scopeAttr===this._scopeAttr&&(e._styleRefCount=(e._styleRefCount||1)-1,e._styleRefCount<=0&&(e._styleEl.remove(),e._styleEl=null,e._styleRefCount=0))}z.delete(this._el),this._el.innerHTML=""}}}const xn=new Set(["state","render","styles","init","mounted","updated","destroyed","props","templateUrl","styleUrl","templates","base","computed","watch","stores","transition","activated","deactivated"]);function Ln(s,e){if(!s||typeof s!="string")throw new I(v.COMP_INVALID_NAME,"Component name must be a non-empty string");if(!s.includes("-"))throw new I(v.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(),re.set(s,e)}function Rt(s,e,t={}){const n=typeof s=="string"?document.querySelector(s):s;if(!n)throw new I(v.COMP_MOUNT_TARGET,`Mount target "${s}" not found`,{target:s});const r=re.get(e);if(!r)throw new I(v.COMP_NOT_FOUND,`Component "${e}" not registered`,{component:e});z.has(n)&&z.get(n).destroy();const i=new De(n,r,t);return z.set(n,i),i._render(),i}function kt(s=document.body){for(const[e,t]of re)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(l=>{if(!(l.name.startsWith("@")||l.name.startsWith("z-"))){if(l.name.startsWith(":")){const u=l.name.slice(1);if(o)i[u]=V(l.value,[o.state.__raw||o.state,{props:o.props,refs:o.refs,computed:o.computed,$:typeof window!="undefined"?window.$:void 0}]);else try{i[u]=JSON.parse(l.value)}catch{i[u]=l.value}return}try{i[l.name]=JSON.parse(l.value)}catch{i[l.name]=l.value}}});const c=new De(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 Nn(s){const e=typeof s=="string"?document.querySelector(s):s,t=z.get(e);t&&t.destroy()}function Pn(){return Object.fromEntries(re)}async function xt(s){const e=re.get(s);e&&(e.templateUrl&&!e._templateLoaded||e.styleUrl&&!e._styleLoaded)&&await De.prototype._loadExternals.call({_def:e})}const oe=new Map;function Bn(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)),oe.has(c)){r.push(oe.get(c));continue}const l=document.createElement("link");l.rel="stylesheet",l.href=c,l.setAttribute("data-zq-style","");const u=new Promise(d=>{l.onload=d,l.onerror=d});i.push(u),document.head.appendChild(l),oe.set(c,l),r.push(l)}return{ready:Promise.all(i).then(()=>{o&&o.remove()}),remove(){for(const c of r){c.remove();for(const[l,u]of oe)if(u===c){oe.delete(l);break}}}}}const j="__zq";function Lt(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 Un{constructor(e={}){this._el=null;const t=typeof location!="undefined"&&location.protocol==="file:";this._mode=t?"hash":e.mode||"history",this._keepAliveCache=new Map,this._keepAliveMax=typeof e.keepAliveMax=="number"&&e.keepAliveMax>0?e.keepAliveMax:null;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[j]==="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[j]==="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);typeof c!="object"||c===null||Array.isArray(c)?A(v.ROUTER_RESOLVE,"z-link-params must be a JSON object",{href:o,paramsAttr:a}):o=this._interpolateParams(o,c)}catch(c){A(v.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}=ge(e.path);if(this._routes.push({...e,_regex:t,_keys:n}),e.fallback){const r=ge(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 d=document.getElementById(r);d&&d.scrollIntoView({behavior:"smooth",block:"start"})}return this}const l=this._base+i,u=window.location.pathname||"/";if(l===u&&o&&!t.force){if(window.history.replaceState({...t.state,[j]:"route"},"",a),r){const d=document.getElementById(r);d&&d.scrollIntoView({behavior:"smooth",block:"start"})}return this}window.history.pushState({...t.state,[j]:"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,[j]:"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){return this._inSubstate=!0,this._mode==="hash"?window.history.pushState({[j]:"substate",key:e,data:t},"",window.location.href):window.history.pushState({[j]:"substate",key:e,data:t},"",window.location.href),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){A(v.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[j]==="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 d of this._routes){const p=i.match(d._regex);if(p){a=d,d._keys.forEach((f,_)=>{c[f]=p[_+1]});break}}if(!a&&this._fallback&&(a={component:this._fallback,path:"*",_keys:[],_regex:/.*/}),!a)return;const l={route:a,params:c,query:o,path:i},u=this._current;if(u&&this._instance&&a.component===u.route.component){const d=Lt(c,u.params),p=Lt(o,u.query);if(d&&p)return}for(const d of this._guards.before)try{const p=await d(l,u);if(p===!1)return;if(typeof p=="string"){if(++this._redirectCount>10){A(v.ROUTER_GUARD,"Too many guard redirects (possible loop)",{to:l},null);return}const[f,_]=p.split("#"),g=this._normalizePath(f||"/"),m=_?"#"+_:"";return this._mode==="hash"?(_&&(window.__zqScrollTarget=_),window.location.replace("#"+g)):window.history.replaceState({[j]:"route"},"",this._base+g+m),this.__resolve()}}catch(p){A(v.ROUTER_GUARD,"Before-guard threw",{to:l,from:u},p);return}if(a.load)try{await a.load()}catch(d){A(v.ROUTER_LOAD,`Failed to load module for route "${a.path}"`,{path:a.path},d);return}if(this._current=l,this._el&&a.component){typeof a.component=="string"&&await xt(a.component);const d=!!a.keepAlive,p=typeof a.component=="string"?a.component:null;if(this._instance&&this._currentKeepAlive&&this._currentComponentName){const g=this._keepAliveCache.get(this._currentComponentName);if(g&&(g.container.style.display="none",g.instance._def.deactivated))try{g.instance._def.deactivated.call(g.instance)}catch(m){A(v.COMP_LIFECYCLE,`Component "${this._currentComponentName}" deactivated() threw`,{component:this._currentComponentName},m)}this._instance=null}else this._instance&&(this._instance.destroy(),this._instance=null);const f=typeof window!="undefined"&&window.__zqRenderHook?performance.now():0,_={...c,$route:l,$query:o,$params:c};if(d&&p&&this._keepAliveCache.has(p)){const g=this._keepAliveCache.get(p);if(this._keepAliveCache.delete(p),this._keepAliveCache.set(p,g),[...this._el.children].forEach(m=>{m.style.display="none"}),g.container.style.display="",this._instance=g.instance,this._currentKeepAlive=!0,this._currentComponentName=p,g.instance._def.activated)try{g.instance._def.activated.call(g.instance)}catch(m){A(v.COMP_LIFECYCLE,`Component "${p}" activated() threw`,{component:p},m)}f&&window.__zqRenderHook(this._el,performance.now()-f,"route",p)}else if(p){[...this._el.children].forEach(m=>{m.dataset.zqKeepAlive&&(m.style.display="none")}),[...this._el.children].forEach(m=>{m.dataset.zqKeepAlive||m.remove()});const g=document.createElement(p);d&&(g.dataset.zqKeepAlive=p),this._el.appendChild(g);try{this._instance=Rt(g,p,_)}catch(m){A(v.COMP_NOT_FOUND,`Failed to mount component for route "${a.path}"`,{component:a.component,path:a.path},m);return}if(d&&(this._keepAliveCache.set(p,{container:g,instance:this._instance}),this._evictKeepAliveLRU(),this._instance._def.activated))try{this._instance._def.activated.call(this._instance)}catch(m){A(v.COMP_LIFECYCLE,`Component "${p}" activated() threw`,{component:p},m)}this._currentKeepAlive=d,this._currentComponentName=p,f&&window.__zqRenderHook(this._el,performance.now()-f,"route",p)}else if(typeof a.component=="function"){[...this._el.children].forEach(m=>{m.dataset.zqKeepAlive?m.style.display="none":m.remove()});const g=document.createElement("div");for(g.innerHTML=a.component(l);g.firstChild;)this._el.appendChild(g.firstChild);this._currentKeepAlive=!1,this._currentComponentName=null,f&&window.__zqRenderHook(this._el,performance.now()-f,"route",l)}}this._updateActiveRoutes(i);for(const d of this._guards.after)await d(l,u);this._listeners.forEach(d=>d(l,u))}_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)}}_evictKeepAliveLRU(){if(this._keepAliveMax!=null)for(;this._keepAliveCache.size>this._keepAliveMax;){let e=null;for(const n of this._keepAliveCache.keys())if(n!==this._currentComponentName){e=n;break}if(e==null)break;const t=this._keepAliveCache.get(e);this._keepAliveCache.delete(e);try{t.instance.destroy()}catch{}t.container&&t.container.parentNode&&t.container.remove()}}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 ge(s){const e=[],t=s.replace(/:(\w+)/g,(n,r)=>(e.push(r),"([^/]+)")).replace(/\*/g,"(.*)");return{regex:new RegExp(`^${t}$`),keys:e}}function Mn(s,e,t="not-found"){for(const n of s){const{regex:r,keys:i}=ge(n.path),o=e.match(r);if(o){const a={};return i.forEach((c,l)=>{a[c]=o[l+1]}),{component:n.component,params:a}}if(n.fallback){const a=ge(n.fallback),c=e.match(a.regex);if(c){const l={};return a.keys.forEach((u,d)=>{l[u]=c[d+1]}),{component:n.component,params:l}}}}return{component:t,params:{}}}let We=null;function In(s){return We=new Un(s),We}function Dn(){return We}class Wn{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=K(t),this.state=Pe(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){A(v.STORE_SUBSCRIBE,`Subscriber for "${e}" threw`,{key:e},o)}}),this._wildcards.forEach(i=>{try{i(e,t,n)}catch(o){A(v.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=K(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=K(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=K(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){A(v.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){A(v.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){A(v.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(e){const t=this.state.__raw||this.state;return e&&e.clone===!1?t:K(t)}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||K(this._initialState)),this._history=[],this._undoStack=[],this._redoStack=[]}}let Ot=new Map;function zn(s,e){typeof s=="object"&&(e=s,s="default");const t=new Wn(e);return Ot.set(s,t),t}function qn(s="default"){return Ot.get(s)||null}function jn(s,e){return{_zqConnector:!0,store:s,keys:e}}const F={baseURL:"",headers:{"Content-Type":"application/json"},timeout:3e4},q={request:[],response:[]};async function Y(s,e,t,n={}){var p;if(!e||typeof e!="string")throw new Error(`HTTP request requires a URL string, got ${typeof e}`);let r=e.startsWith("http")?e:F.baseURL+e,i={...F.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 f=new URLSearchParams(t).toString();r+=(r.includes("?")?"&":"?")+f}const c=new AbortController,l=(p=n.timeout)!=null?p:F.timeout;let u;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 d=!1;l>0&&(u=setTimeout(()=>{d=!0,c.abort()},l));for(const f of q.request){const _=await f(a,r);if(_===!1)throw new Error("Request blocked by interceptor");_!=null&&_.url&&(r=_.url),_!=null&&_.options&&Object.assign(a,_.options)}try{const f=await fetch(r,a);u&&clearTimeout(u);const _=f.headers.get("Content-Type")||"";let g;try{if(_.includes("application/json"))g=await f.json();else if(_.includes("text/"))g=await f.text();else if(_.includes("application/octet-stream")||_.includes("image/"))g=await f.blob();else{const S=await f.text();try{g=JSON.parse(S)}catch{g=S}}}catch(S){g=null,console.warn(`[zQuery HTTP] Failed to parse response body from ${s} ${r}:`,S.message)}const m={ok:f.ok,status:f.status,statusText:f.statusText,headers:Object.fromEntries(f.headers.entries()),data:g,response:f};for(const S of q.response)await S(m);if(!f.ok){const S=new Error(`HTTP ${f.status}: ${f.statusText}`);throw S.response=m,S}return m}catch(f){throw u&&clearTimeout(u),f.name==="AbortError"?d?new Error(`Request timeout after ${l}ms: ${s} ${r}`):new Error(`Request aborted: ${s} ${r}`):f}}const H={get:(s,e,t)=>Y("GET",s,e,t),post:(s,e,t)=>Y("POST",s,e,t),put:(s,e,t)=>Y("PUT",s,e,t),patch:(s,e,t)=>Y("PATCH",s,e,t),delete:(s,e,t)=>Y("DELETE",s,e,t),head:(s,e)=>Y("HEAD",s,void 0,e),configure(s){s.baseURL!==void 0&&(F.baseURL=s.baseURL),s.headers&&Object.assign(F.headers,s.headers),s.timeout!==void 0&&(F.timeout=s.timeout)},getConfig(){return{baseURL:F.baseURL,headers:{...F.headers},timeout:F.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 Fn(s,e=250,t={}){let n;const r=t.signal,i=(...o)=>{r&&r.aborted||(clearTimeout(n),n=setTimeout(()=>s(...o),e))};return i.cancel=()=>clearTimeout(n),r&&(r.aborted?i.cancel():r.addEventListener("abort",i.cancel,{once:!0})),i}function Qn(s,e=250,t={}){let n=0,r;const i=t.signal,o=(...a)=>{if(i&&i.aborted)return;const c=Date.now(),l=e-(c-n);clearTimeout(r),l<=0?(n=c,s(...a)):r=setTimeout(()=>{n=Date.now(),s(...a)},l)};return o.cancel=()=>clearTimeout(r),i&&(i.aborted?o.cancel():i.addEventListener("abort",o.cancel,{once:!0})),o}function $n(...s){return e=>s.reduce((t,n)=>n(t),e)}function Zn(s){let e=!1,t;return(...n)=>(e||(e=!0,t=s(...n)),t)}function Hn(s){return new Promise(e=>setTimeout(e,s))}function we(s){const e={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"};return String(s).replace(/[&<>"']/g,t=>e[t])}function Kn(s){return String(s).replace(/<[^>]*>/g,"")}function Gn(s,...e){return s.reduce((t,n,r)=>{const i=e[r-1],o=i instanceof ze?i.toString():we(i!=null?i:"");return t+o+n})}class ze{constructor(e){this._html=e}toString(){return this._html}}function Vn(s){return new ze(s)}function Jn(){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 Yn(s){return s.replace(/-([a-z])/g,(e,t)=>t.toUpperCase())}function Xn(s){return s.replace(/([A-Z]+)([A-Z][a-z])/g,"$1-$2").replace(/([a-z\d])([A-Z])/g,"$1-$2").toLowerCase()}function K(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 qe=new Set(["__proto__","constructor","prototype"]);function es(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))qe.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 Nt(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=>Nt(s[i],e[i],t))}function ts(s){return new URLSearchParams(s).toString()}function ns(s){return Object.fromEntries(new URLSearchParams(s))}const ss={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()}},rs={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 Pt{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 is=new Pt;function os(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 as(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 cs(s,e){const t=[];for(let n=0;n<s.length;n+=e)t.push(s.slice(n,n+e));return t}function ls(s,e){var n;if(typeof Object.groupBy=="function")return Object.groupBy(s,e);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 fs(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 hs(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 ds(s,e,t){const n=e.split(".");let r=s;for(let o=0;o<n.length-1;o++){const a=n[o];if(qe.has(a))return s;(r[a]==null||typeof r[a]!="object")&&(r[a]={}),r=r[a]}const i=n[n.length-1];return qe.has(i)||(r[i]=t),s}function ps(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 _s(s){return s?s[0].toUpperCase()+s.slice(1).toLowerCase():""}function ms(s,e,t="…"){if(s.length<=e)return s;const n=Math.max(0,e-t.length);return s.slice(0,n)+t}function ys(s,e,t){return s<e?e:s>t?t:s}function gs(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 l=r.get(a);return r.delete(a),r.set(a,l),l}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 l=()=>{a++,s(a).then(i,u=>{if(a>=t)return o(u);const d=c;c*=r,setTimeout(l,d)})};l()})}function Es(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 h(s,e){if(typeof s=="function"){C.ready(s);return}return C(s,e)}h.id=C.id,h.class=C.class,h.classes=C.classes,h.tag=C.tag,Object.defineProperty(h,"name",{value:C.name,writable:!0,configurable:!0}),h.children=C.children,h.qs=C.qs,h.qsa=C.qsa,h.all=function(s,e){return wn(s,e)},h.create=C.create,h.ready=C.ready,h.on=C.on,h.off=C.off,h.fn=C.fn,h.reactive=Pe,h.Signal=R,h.signal=$,h.computed=fn,h.effect=gt,h.batch=hn,h.untracked=dn,h.component=Ln,h.mount=Rt,h.mountAll=kt,h.getInstance=On,h.destroy=Nn,h.components=Pn,h.prefetch=xt,h.style=Bn,h.morph=Ue,h.morphElement=Et,h.safeEval=V,h.router=In,h.getRouter=Dn,h.matchRoute=Mn,h.store=zn,h.getStore=qn,h.connectStore=jn,h.http=H,h.get=H.get,h.post=H.post,h.put=H.put,h.patch=H.patch,h.delete=H.delete,h.head=H.head,h.debounce=Fn,h.throttle=Qn,h.pipe=$n,h.once=Zn,h.sleep=Hn,h.escapeHtml=we,h.stripHtml=Kn,h.html=Gn,h.trust=Vn,h.TrustedHTML=ze,h.uuid=Jn,h.camelCase=Yn,h.kebabCase=Xn,h.deepClone=K,h.deepMerge=es,h.isEqual=Nt,h.param=ts,h.parseQuery=ns,h.storage=ss,h.session=rs,h.EventBus=Pt,h.bus=is,h.range=os,h.unique=as,h.chunk=cs,h.groupBy=ls,h.pick=us,h.omit=fs,h.getPath=hs,h.setPath=ds,h.isEmpty=ps,h.capitalize=_s,h.truncate=ms,h.clamp=ys,h.memoize=gs,h.retry=ws,h.timeout=Es,h.onError=Bt,h.ZQueryError=I,h.ErrorCode=v,h.guardCallback=Ut,h.guardAsync=It,h.validate=Mt,h.formatError=Qe,h.webrtc=un,h.SignalingClient=Re,h.Peer=ke,h.Room=G,h.useRoom=Ye,h.usePeer=Xe,h.useTracks=et,h.useDataChannel=tt,h.useConnectionQuality=nt,h.fetchTurnCredentials=xe,h.mergeIceServers=rt,h.createTurnRefresher=it,h.deriveSFrameKey=ct,h.generateSFrameKey=lt,h.SFrameContext=ne,h.encryptFrame=Le,h.decryptFrame=Oe,h.attachE2ee=ut,h.loadSfuAdapter=mt,h.SfuError=k,h.decodeJoinToken=ht,h.isJoinTokenExpired=dt,h.samplePeerStats=Ne,h.createStatsSampler=pt,h.classifyStats=_t,h.parseSdp=Ee,h.validateSdp=Ze,h.parseCandidate=Se,h.stringifyCandidate=He,h.filterCandidates=Ke,h.isPrivateIp=ve,h.isLoopbackIp=Ce,h.isLinkLocalIp=Ae,h.isMdnsHostname=Te,h.WebRtcError=E,h.SignalingError=P,h.IceError=U,h.SdpError=B,h.TurnError=M,h.E2eeError=N,h.version="1.2.9",h.libSize="~130 KB",h.unitTests={"passed":2348,"failed":0,"total":2534,"suites":620,"duration":8190,"ok":true},h.meta={},h.isElectron=typeof navigator!="undefined"&&/Electron/i.test(navigator.userAgent)||typeof process!="undefined"&&process.versions!=null&&!!process.versions.electron,h.platform=h.isElectron?"electron":typeof window!="undefined"?"browser":"node",h.noConflict=()=>(typeof window!="undefined"&&window.$===h&&delete window.$,h),typeof window!="undefined"&&(window.$=h,window.zQuery=h)})(typeof window!="undefined"?window:globalThis);
13
+ `);if(!this._mounted&&t){const c=this._def;let l=c._scopeAttr;if(l||(l=c._name?`z-s-${c._name}`:`z-s${this._uid}`,c._scopeAttr=l),this._el.setAttribute(l,""),this._scopeAttr=l,c._styleEl&&c._styleEl.isConnected)c._styleRefCount=(c._styleRefCount||0)+1;else{let u=0,d=0;const p=t.replace(/([^{}]+)\{|\}/g,(_,g)=>{if(_==="}")return u>0&&d<=u&&(u=0),d--,_;d++;const m=g.trim();return m.startsWith("@")?(/^@(keyframes|font-face)\b/.test(m)&&(u=d),_):u>0&&d>u?_:g.split(",").map(S=>`[${l}] ${S.trim()}`).join(", ")+" {"}),f=document.createElement("style");f.textContent=p,f.setAttribute("data-zq-component",c._name||""),f.setAttribute("data-zq-scope",l),c._resolvedStyleUrls&&(f.setAttribute("data-zq-style-urls",c._resolvedStyleUrls.join(" ")),c.styles&&f.setAttribute("data-zq-inline",c.styles)),document.head.appendChild(f),c._styleEl=f,c._styleRefCount=1}}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"),l=(a=r.getAttribute)==null?void 0:a.call(r,"z-ref");let u=null;if(c)u=`[z-model="${c}"]`;else if(l)u=`[z-ref="${l}"]`;else{const d=r.tagName.toLowerCase();if(d==="input"||d==="textarea"||d==="select"){let p=d;r.type&&(p+=`[type="${r.type}"]`),r.name&&(p+=`[name="${r.name}"]`),r.placeholder&&(p+=`[placeholder="${CSS.escape(r.placeholder)}"]`),u=p}}u&&(n={selector:u,start:r.selectionStart,end:r.selectionEnd,dir:r.selectionDirection})}const i=typeof window!="undefined"&&(window.__zqMorphHook||window.__zqRenderHook)?performance.now():0;if(this._mounted?Me(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(kt(this._el),this._mounted){if(this._def.updated)try{this._def.updated.call(this)}catch(c){A(v.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){A(v.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("."),l=c[0],u=c.slice(1),d=o.value;n.dataset.zqEid||(n.dataset.zqEid=String(++At));const p=`[data-zq-eid="${n.dataset.zqEid}"]`;e.has(l)||e.set(l,[]),e.get(l).push({selector:p,methodExpr:d,modifiers:u,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 l=this[c[1]];typeof l=="function"&&l.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 d;const c=((d=this._eventBindings)==null?void 0:d.get(e))||[],l=[];for(const p of c){const f=a.target.closest(p.selector);f&&l.push({...p,matched:f})}l.sort((p,f)=>p.matched===f.matched?0:p.matched.contains(f.matched)?1:-1);let u=null;for(const{methodExpr:p,modifiers:f,el:_,matched:g}of l){if(u){let O=!1;for(const T of u)if(g.contains(T)&&g!==T){O=!0;break}if(O)continue}if(f.includes("self")&&a.target!==_||f.includes("outside")&&_.contains(a.target))continue;const m={enter:"Enter",escape:"Escape",tab:"Tab",space:" ",delete:"Delete|Backspace",up:"ArrowUp",down:"ArrowDown",left:"ArrowLeft",right:"ArrowRight"},S=new Set(["prevent","stop","self","once","outside","capture","passive","debounce","throttle","ctrl","shift","alt","meta"]);let L=!1;for(let O=0;O<f.length;O++){const T=f[O];if(m[T]){const X=m[T].split("|");if(!a.key||!X.includes(a.key)){L=!0;break}}else{if(S.has(T))continue;if(/^\d+$/.test(T)&&O>0&&(f[O-1]==="debounce"||f[O-1]==="throttle"))continue;if(!a.key||a.key.toLowerCase()!==T.toLowerCase()){L=!0;break}}}if(L||f.includes("ctrl")&&!a.ctrlKey||f.includes("shift")&&!a.shiftKey||f.includes("alt")&&!a.altKey||f.includes("meta")&&!a.metaKey)continue;f.includes("prevent")&&a.preventDefault(),f.includes("stop")&&(a.stopPropagation(),u||(u=[]),u.push(g));const W=O=>{const T=p.match(/^(\w+)(?:\(([^)]*)\))?$/);if(!T)return;const X=T[1],je=this[X];if(typeof je=="function")if(T[2]!==void 0){const bs=T[2].split(",").map(x=>{if(x=x.trim(),x!=="")return x==="$event"?O: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.")?ye(this.state,x.slice(6)):x}).filter(x=>x!==void 0);je(...bs)}else je(O)},Q=f.indexOf("debounce");if(Q!==-1){const O=parseInt(f[Q+1],10)||250,T=_e.get(_)||{};clearTimeout(T[e]),T[e]=setTimeout(()=>W(a),O),_e.set(_,T),this._timerEls.add(_);continue}const qe=f.indexOf("throttle");if(qe!==-1){const O=parseInt(f[qe+1],10)||250,T=me.get(_)||{};if(T[e])continue;W(a),T[e]=setTimeout(()=>{T[e]=null},O),me.set(_,T),this._timerEls.add(_);continue}if(f.includes("once")){if(_.dataset.zqOnce===e)continue;_.dataset.zqOnce=e}W(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"),l=e.hasAttribute("z-uppercase"),u=e.hasAttribute("z-lowercase"),d=e.hasAttribute("z-debounce"),p=d?parseInt(e.getAttribute("z-debounce"),10)||250:0,f=ye(this.state,t);if(n==="input"&&r==="checkbox")e.checked=!!f;else if(n==="input"&&r==="radio")e.checked=e.value===String(f);else if(n==="select"&&e.multiple){const m=Array.isArray(f)?f.map(String):[];[...e.options].forEach(S=>{S.selected=m.includes(S.value)})}else i?e.textContent!==String(f!=null?f:"")&&(e.textContent=f!=null?f:""):e.value=f!=null?f:"";const _=o||n==="select"||r==="checkbox"||r==="radio"?"change":"input";if(e._zqModelUnbind){try{e._zqModelUnbind()}catch{}e._zqModelUnbind=null}const g=()=>{let m;r==="checkbox"?m=e.checked:n==="select"&&e.multiple?m=[...e.selectedOptions].map(S=>S.value):i?m=e.textContent:m=e.value,a&&typeof m=="string"&&(m=m.trim()),l&&typeof m=="string"&&(m=m.toUpperCase()),u&&typeof m=="string"&&(m=m.toLowerCase()),(c||r==="number"||r==="range")&&(m=Number(m)),kn(this.state,t,m)};if(d){let m=null;const S=()=>{clearTimeout(m),m=setTimeout(g,p)};e.addEventListener(_,S),e._zqModelUnbind=()=>{e.removeEventListener(_,S),clearTimeout(m)}}else e.addEventListener(_,g),e._zqModelUnbind=()=>e.removeEventListener(_,g)})}_evalExpr(e){return V(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 l=c[1]||c[3],u=c[2]||"$index",d=c[4].trim();let p=this._evalExpr(d);if(p==null){o.remove();continue}if(typeof p=="number"&&(p=Array.from({length:p},(L,W)=>W+1)),!Array.isArray(p)&&typeof p=="object"&&typeof p[Symbol.iterator]!="function"&&(p=Object.entries(p).map(([L,W])=>({key:L,value:W}))),!Array.isArray(p)&&typeof p[Symbol.iterator]=="function"&&(p=[...p]),!Array.isArray(p)){o.remove();continue}const f=o.parentNode,_=o.cloneNode(!0);_.removeAttribute("z-for");const g=_.outerHTML,m=document.createDocumentFragment(),S=(L,W,Q)=>L.replace(/\{\{(.+?)\}\}/g,(qe,O)=>{try{const T={};T[l]=W,T[u]=Q;const X=V(O.trim(),[T,this.state.__raw||this.state,{props:this.props,computed:this.computed,$:typeof window!="undefined"?window.$:void 0}]);return X!=null?we(String(X)):""}catch{return""}});for(let L=0;L<p.length;L++){const W=S(g,p[L],L),Q=document.createElement("div");for(Q.innerHTML=W;Q.firstChild;)m.appendChild(Q.firstChild)}f.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 i of e){if(!i.parentNode||i.closest("[z-pre]"))continue;const o=!!this._evalExpr(i.getAttribute("z-if")),a=[{el:i,show:o}];let c=i.nextElementSibling;for(;c;)if(c.hasAttribute("z-else-if"))a.push({el:c,show:!!this._evalExpr(c.getAttribute("z-else-if"))}),c=c.nextElementSibling;else if(c.hasAttribute("z-else")){a.push({el:c,show:!0});break}else break;let l=!1;for(const u of a)if(!l&&u.show){l=!0,u.el.removeAttribute("z-if"),u.el.removeAttribute("z-else-if"),u.el.removeAttribute("z-else");const d=u.el.getAttribute("z-transition");d&&(u.el.removeAttribute("z-transition"),this._transitionEnter(u.el,d))}else{const d=u.el.getAttribute("z-transition");d?this._transitionLeave(u.el,d,()=>u.el.remove()):u.el.remove()}}this._el.querySelectorAll("[z-show]").forEach(i=>{if(i.closest("[z-pre]"))return;const o=!!this._evalExpr(i.getAttribute("z-show")),a=i.getAttribute("z-transition"),c=i.style.display==="none"||i.hasAttribute("data-zq-hidden");a?(i.removeAttribute("z-show"),o&&c?(i.style.display="",i.removeAttribute("data-zq-hidden"),this._transitionEnter(i,a)):!o&&!c?(i.setAttribute("data-zq-hidden",""),this._transitionLeave(i,a,()=>{i.style.display="none"})):(i.style.display=o?"":"none",o?i.removeAttribute("data-zq-hidden"):i.setAttribute("data-zq-hidden",""))):(i.style.display=o?"":"none",i.removeAttribute("z-show"))});const t=document.createTreeWalker(this._el,NodeFilter.SHOW_ELEMENT,{acceptNode(i){return i.hasAttribute("z-pre")?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}}),n=typeof MediaStream!="undefined";let r;for(;r=t.nextNode();){const i=r.attributes;for(let o=i.length-1;o>=0;o--){const a=i[o];let c;if(a.name.startsWith("z-bind:"))c=a.name.slice(7);else if(a.name.charCodeAt(0)===58&&a.name.charCodeAt(1)!==58)c=a.name.slice(1);else continue;const l=this._evalExpr(a.value);r.removeAttribute(a.name),l===!1||l===null||l===void 0?r.toggleAttribute(c,!1):l===!0?r.toggleAttribute(c,!0):r.setAttribute(c,String(l))}if(r.hasAttribute("z-class")){const o=this._evalExpr(r.getAttribute("z-class"));if(typeof o=="string")o.split(/\s+/).filter(Boolean).forEach(a=>r.classList.add(a));else if(Array.isArray(o))o.filter(Boolean).forEach(a=>r.classList.add(String(a)));else if(o&&typeof o=="object")for(const[a,c]of Object.entries(o))r.classList.toggle(a,!!c);r.removeAttribute("z-class")}if(r.hasAttribute("z-style")){const o=this._evalExpr(r.getAttribute("z-style"));if(typeof o=="string")r.style.cssText+=";"+o;else if(o&&typeof o=="object")for(const[a,c]of Object.entries(o))r.style[a]=c;r.removeAttribute("z-style")}if(r.hasAttribute("z-stream")){const o=this._evalExpr(r.getAttribute("z-stream"));o==null?r.srcObject=null:n&&o instanceof MediaStream||o&&typeof o.getTracks=="function"?r.srcObject=o:r.srcObject=null,r.removeAttribute("z-stream")}r.hasAttribute("z-cloak")&&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){if(this._destroyed=!0,this._def.destroyed)try{this._def.destroyed.call(this)}catch(e){A(v.COMP_LIFECYCLE,`Component "${this._def._name}" destroyed() threw`,{component:this._def._name},e)}if(this._propObserver&&(this._propObserver.disconnect(),this._propObserver=null),this._storeCleanups&&(this._storeCleanups.forEach(e=>e()),this._storeCleanups=[]),this._listeners.forEach(({event:e,handler:t})=>this._el.removeEventListener(e,t)),this._listeners=[],this._outsideListeners&&(this._outsideListeners.forEach(({event:e,handler:t})=>document.removeEventListener(e,t,!0)),this._outsideListeners=[]),this._delegatedEvents=null,this._eventBindings=null,this._timerEls&&(this._timerEls.forEach(e=>{const t=_e.get(e);if(t){for(const r in t)clearTimeout(t[r]);_e.delete(e)}const n=me.get(e);if(n){for(const r in n)clearTimeout(n[r]);me.delete(e)}}),this._timerEls.clear()),this._scopeAttr){const e=this._def;e&&e._styleEl&&e._scopeAttr===this._scopeAttr&&(e._styleRefCount=(e._styleRefCount||1)-1,e._styleRefCount<=0&&(e._styleEl.remove(),e._styleEl=null,e._styleRefCount=0))}z.delete(this._el),this._el.innerHTML=""}}}const xn=new Set(["state","render","styles","init","mounted","updated","destroyed","props","templateUrl","styleUrl","templates","base","computed","watch","stores","transition","activated","deactivated"]);function Ln(s,e){if(!s||typeof s!="string")throw new I(v.COMP_INVALID_NAME,"Component name must be a non-empty string");if(!s.includes("-"))throw new I(v.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(),re.set(s,e)}function Rt(s,e,t={}){const n=typeof s=="string"?document.querySelector(s):s;if(!n)throw new I(v.COMP_MOUNT_TARGET,`Mount target "${s}" not found`,{target:s});const r=re.get(e);if(!r)throw new I(v.COMP_NOT_FOUND,`Component "${e}" not registered`,{component:e});z.has(n)&&z.get(n).destroy();const i=new De(n,r,t);return z.set(n,i),i._render(),i}function kt(s=document.body){for(const[e,t]of re)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(l=>{if(!(l.name.startsWith("@")||l.name.startsWith("z-"))){if(l.name.startsWith(":")){const u=l.name.slice(1);if(o)i[u]=V(l.value,[o.state.__raw||o.state,{props:o.props,refs:o.refs,computed:o.computed,$:typeof window!="undefined"?window.$:void 0}]);else try{i[u]=JSON.parse(l.value)}catch{i[u]=l.value}return}try{i[l.name]=JSON.parse(l.value)}catch{i[l.name]=l.value}}});const c=new De(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 Nn(s){const e=typeof s=="string"?document.querySelector(s):s,t=z.get(e);t&&t.destroy()}function Pn(){return Object.fromEntries(re)}async function xt(s){const e=re.get(s);e&&(e.templateUrl&&!e._templateLoaded||e.styleUrl&&!e._styleLoaded)&&await De.prototype._loadExternals.call({_def:e})}const oe=new Map;function Bn(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)),oe.has(c)){r.push(oe.get(c));continue}const l=document.createElement("link");l.rel="stylesheet",l.href=c,l.setAttribute("data-zq-style","");const u=new Promise(d=>{l.onload=d,l.onerror=d});i.push(u),document.head.appendChild(l),oe.set(c,l),r.push(l)}return{ready:Promise.all(i).then(()=>{o&&o.remove()}),remove(){for(const c of r){c.remove();for(const[l,u]of oe)if(u===c){oe.delete(l);break}}}}}const q="__zq";function Lt(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 Mn{constructor(e={}){this._el=null;const t=typeof location!="undefined"&&location.protocol==="file:";this._mode=t?"hash":e.mode||"history",this._keepAliveCache=new Map,this._keepAliveMax=typeof e.keepAliveMax=="number"&&e.keepAliveMax>0?e.keepAliveMax:null;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[q]==="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[q]==="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);typeof c!="object"||c===null||Array.isArray(c)?A(v.ROUTER_RESOLVE,"z-link-params must be a JSON object",{href:o,paramsAttr:a}):o=this._interpolateParams(o,c)}catch(c){A(v.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}=ge(e.path);if(this._routes.push({...e,_regex:t,_keys:n}),e.fallback){const r=ge(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 d=document.getElementById(r);d&&d.scrollIntoView({behavior:"smooth",block:"start"})}return this}const l=this._base+i,u=window.location.pathname||"/";if(l===u&&o&&!t.force){if(window.history.replaceState({...t.state,[q]:"route"},"",a),r){const d=document.getElementById(r);d&&d.scrollIntoView({behavior:"smooth",block:"start"})}return this}window.history.pushState({...t.state,[q]:"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,[q]:"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){return this._inSubstate=!0,this._mode==="hash"?window.history.pushState({[q]:"substate",key:e,data:t},"",window.location.href):window.history.pushState({[q]:"substate",key:e,data:t},"",window.location.href),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){A(v.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[q]==="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 d of this._routes){const p=i.match(d._regex);if(p){a=d,d._keys.forEach((f,_)=>{c[f]=p[_+1]});break}}if(!a&&this._fallback&&(a={component:this._fallback,path:"*",_keys:[],_regex:/.*/}),!a)return;const l={route:a,params:c,query:o,path:i},u=this._current;if(u&&this._instance&&a.component===u.route.component){const d=Lt(c,u.params),p=Lt(o,u.query);if(d&&p)return}for(const d of this._guards.before)try{const p=await d(l,u);if(p===!1)return;if(typeof p=="string"){if(++this._redirectCount>10){A(v.ROUTER_GUARD,"Too many guard redirects (possible loop)",{to:l},null);return}const[f,_]=p.split("#"),g=this._normalizePath(f||"/"),m=_?"#"+_:"";return this._mode==="hash"?(_&&(window.__zqScrollTarget=_),window.location.replace("#"+g)):window.history.replaceState({[q]:"route"},"",this._base+g+m),this.__resolve()}}catch(p){A(v.ROUTER_GUARD,"Before-guard threw",{to:l,from:u},p);return}if(a.load)try{await a.load()}catch(d){A(v.ROUTER_LOAD,`Failed to load module for route "${a.path}"`,{path:a.path},d);return}if(this._current=l,this._el&&a.component){typeof a.component=="string"&&await xt(a.component);const d=!!a.keepAlive,p=typeof a.component=="string"?a.component:null;if(this._instance&&this._currentKeepAlive&&this._currentComponentName){const g=this._keepAliveCache.get(this._currentComponentName);if(g&&(g.container.style.display="none",g.instance._def.deactivated))try{g.instance._def.deactivated.call(g.instance)}catch(m){A(v.COMP_LIFECYCLE,`Component "${this._currentComponentName}" deactivated() threw`,{component:this._currentComponentName},m)}this._instance=null}else this._instance&&(this._instance.destroy(),this._instance=null);const f=typeof window!="undefined"&&window.__zqRenderHook?performance.now():0,_={...c,$route:l,$query:o,$params:c};if(d&&p&&this._keepAliveCache.has(p)){const g=this._keepAliveCache.get(p);if(this._keepAliveCache.delete(p),this._keepAliveCache.set(p,g),[...this._el.children].forEach(m=>{m.style.display="none"}),g.container.style.display="",this._instance=g.instance,this._currentKeepAlive=!0,this._currentComponentName=p,g.instance._def.activated)try{g.instance._def.activated.call(g.instance)}catch(m){A(v.COMP_LIFECYCLE,`Component "${p}" activated() threw`,{component:p},m)}f&&window.__zqRenderHook(this._el,performance.now()-f,"route",p)}else if(p){[...this._el.children].forEach(m=>{m.dataset.zqKeepAlive&&(m.style.display="none")}),[...this._el.children].forEach(m=>{m.dataset.zqKeepAlive||m.remove()});const g=document.createElement(p);d&&(g.dataset.zqKeepAlive=p),this._el.appendChild(g);try{this._instance=Rt(g,p,_)}catch(m){A(v.COMP_NOT_FOUND,`Failed to mount component for route "${a.path}"`,{component:a.component,path:a.path},m);return}if(d&&(this._keepAliveCache.set(p,{container:g,instance:this._instance}),this._evictKeepAliveLRU(),this._instance._def.activated))try{this._instance._def.activated.call(this._instance)}catch(m){A(v.COMP_LIFECYCLE,`Component "${p}" activated() threw`,{component:p},m)}this._currentKeepAlive=d,this._currentComponentName=p,f&&window.__zqRenderHook(this._el,performance.now()-f,"route",p)}else if(typeof a.component=="function"){[...this._el.children].forEach(m=>{m.dataset.zqKeepAlive?m.style.display="none":m.remove()});const g=document.createElement("div");for(g.innerHTML=a.component(l);g.firstChild;)this._el.appendChild(g.firstChild);this._currentKeepAlive=!1,this._currentComponentName=null,f&&window.__zqRenderHook(this._el,performance.now()-f,"route",l)}}this._updateActiveRoutes(i);for(const d of this._guards.after)await d(l,u);this._listeners.forEach(d=>d(l,u))}_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)}}_evictKeepAliveLRU(){if(this._keepAliveMax!=null)for(;this._keepAliveCache.size>this._keepAliveMax;){let e=null;for(const n of this._keepAliveCache.keys())if(n!==this._currentComponentName){e=n;break}if(e==null)break;const t=this._keepAliveCache.get(e);this._keepAliveCache.delete(e);try{t.instance.destroy()}catch{}t.container&&t.container.parentNode&&t.container.remove()}}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 ge(s){const e=[],t=s.replace(/:(\w+)/g,(n,r)=>(e.push(r),"([^/]+)")).replace(/\*/g,"(.*)");return{regex:new RegExp(`^${t}$`),keys:e}}function Un(s,e,t="not-found"){for(const n of s){const{regex:r,keys:i}=ge(n.path),o=e.match(r);if(o){const a={};return i.forEach((c,l)=>{a[c]=o[l+1]}),{component:n.component,params:a}}if(n.fallback){const a=ge(n.fallback),c=e.match(a.regex);if(c){const l={};return a.keys.forEach((u,d)=>{l[u]=c[d+1]}),{component:n.component,params:l}}}}return{component:t,params:{}}}let We=null;function In(s){return We=new Mn(s),We}function Dn(){return We}class Wn{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=K(t),this.state=Pe(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){A(v.STORE_SUBSCRIBE,`Subscriber for "${e}" threw`,{key:e},o)}}),this._wildcards.forEach(i=>{try{i(e,t,n)}catch(o){A(v.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=K(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=K(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=K(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){A(v.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){A(v.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){A(v.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(e){const t=this.state.__raw||this.state;return e&&e.clone===!1?t:K(t)}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||K(this._initialState)),this._history=[],this._undoStack=[],this._redoStack=[]}}let Ot=new Map;function zn(s,e){typeof s=="object"&&(e=s,s="default");const t=new Wn(e);return Ot.set(s,t),t}function Fn(s="default"){return Ot.get(s)||null}function qn(s,e){return{_zqConnector:!0,store:s,keys:e}}const j={baseURL:"",headers:{"Content-Type":"application/json"},timeout:3e4},F={request:[],response:[]};async function Y(s,e,t,n={}){var p;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 f=new URLSearchParams(t).toString();r+=(r.includes("?")?"&":"?")+f}const c=new AbortController,l=(p=n.timeout)!=null?p:j.timeout;let u;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 d=!1;l>0&&(u=setTimeout(()=>{d=!0,c.abort()},l));for(const f of F.request){const _=await f(a,r);if(_===!1)throw new Error("Request blocked by interceptor");_!=null&&_.url&&(r=_.url),_!=null&&_.options&&Object.assign(a,_.options)}try{const f=await fetch(r,a);u&&clearTimeout(u);const _=f.headers.get("Content-Type")||"";let g;try{if(_.includes("application/json"))g=await f.json();else if(_.includes("text/"))g=await f.text();else if(_.includes("application/octet-stream")||_.includes("image/"))g=await f.blob();else{const S=await f.text();try{g=JSON.parse(S)}catch{g=S}}}catch(S){g=null,console.warn(`[zQuery HTTP] Failed to parse response body from ${s} ${r}:`,S.message)}const m={ok:f.ok,status:f.status,statusText:f.statusText,headers:Object.fromEntries(f.headers.entries()),data:g,response:f};for(const S of F.response)await S(m);if(!f.ok){const S=new Error(`HTTP ${f.status}: ${f.statusText}`);throw S.response=m,S}return m}catch(f){throw u&&clearTimeout(u),f.name==="AbortError"?d?new Error(`Request timeout after ${l}ms: ${s} ${r}`):new Error(`Request aborted: ${s} ${r}`):f}}const H={get:(s,e,t)=>Y("GET",s,e,t),post:(s,e,t)=>Y("POST",s,e,t),put:(s,e,t)=>Y("PUT",s,e,t),patch:(s,e,t)=>Y("PATCH",s,e,t),delete:(s,e,t)=>Y("DELETE",s,e,t),head:(s,e)=>Y("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 F.request.push(s),()=>{const e=F.request.indexOf(s);e!==-1&&F.request.splice(e,1)}},onResponse(s){return F.response.push(s),()=>{const e=F.response.indexOf(s);e!==-1&&F.response.splice(e,1)}},clearInterceptors(s){(!s||s==="request")&&(F.request.length=0),(!s||s==="response")&&(F.response.length=0)},all(s){return Promise.all(s)},createAbort(){return new AbortController},raw:(s,e)=>fetch(s,e)};function jn(s,e=250,t={}){let n;const r=t.signal,i=(...o)=>{r&&r.aborted||(clearTimeout(n),n=setTimeout(()=>s(...o),e))};return i.cancel=()=>clearTimeout(n),r&&(r.aborted?i.cancel():r.addEventListener("abort",i.cancel,{once:!0})),i}function Qn(s,e=250,t={}){let n=0,r;const i=t.signal,o=(...a)=>{if(i&&i.aborted)return;const c=Date.now(),l=e-(c-n);clearTimeout(r),l<=0?(n=c,s(...a)):r=setTimeout(()=>{n=Date.now(),s(...a)},l)};return o.cancel=()=>clearTimeout(r),i&&(i.aborted?o.cancel():i.addEventListener("abort",o.cancel,{once:!0})),o}function $n(...s){return e=>s.reduce((t,n)=>n(t),e)}function Zn(s){let e=!1,t;return(...n)=>(e||(e=!0,t=s(...n)),t)}function Hn(s){return new Promise(e=>setTimeout(e,s))}function we(s){const e={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"};return String(s).replace(/[&<>"']/g,t=>e[t])}function Kn(s){return String(s).replace(/<[^>]*>/g,"")}function Gn(s,...e){return s.reduce((t,n,r)=>{const i=e[r-1],o=i instanceof ze?i.toString():we(i!=null?i:"");return t+o+n})}class ze{constructor(e){this._html=e}toString(){return this._html}}function Vn(s){return new ze(s)}function Jn(){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 Yn(s){return s.replace(/-([a-z])/g,(e,t)=>t.toUpperCase())}function Xn(s){return s.replace(/([A-Z]+)([A-Z][a-z])/g,"$1-$2").replace(/([a-z\d])([A-Z])/g,"$1-$2").toLowerCase()}function K(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 Fe=new Set(["__proto__","constructor","prototype"]);function es(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))Fe.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 Nt(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=>Nt(s[i],e[i],t))}function ts(s){return new URLSearchParams(s).toString()}function ns(s){return Object.fromEntries(new URLSearchParams(s))}const ss={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()}},rs={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 Pt{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 is=new Pt;function os(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 as(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 cs(s,e){const t=[];for(let n=0;n<s.length;n+=e)t.push(s.slice(n,n+e));return t}function ls(s,e){var n;if(typeof Object.groupBy=="function")return Object.groupBy(s,e);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 fs(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 hs(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 ds(s,e,t){const n=e.split(".");let r=s;for(let o=0;o<n.length-1;o++){const a=n[o];if(Fe.has(a))return s;(r[a]==null||typeof r[a]!="object")&&(r[a]={}),r=r[a]}const i=n[n.length-1];return Fe.has(i)||(r[i]=t),s}function ps(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 _s(s){return s?s[0].toUpperCase()+s.slice(1).toLowerCase():""}function ms(s,e,t="…"){if(s.length<=e)return s;const n=Math.max(0,e-t.length);return s.slice(0,n)+t}function ys(s,e,t){return s<e?e:s>t?t:s}function gs(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 l=r.get(a);return r.delete(a),r.set(a,l),l}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 l=()=>{a++,s(a).then(i,u=>{if(a>=t)return o(u);const d=c;c*=r,setTimeout(l,d)})};l()})}function Es(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 h(s,e){if(typeof s=="function"){C.ready(s);return}return C(s,e)}h.id=C.id,h.class=C.class,h.classes=C.classes,h.tag=C.tag,Object.defineProperty(h,"name",{value:C.name,writable:!0,configurable:!0}),h.children=C.children,h.qs=C.qs,h.qsa=C.qsa,h.all=function(s,e){return wn(s,e)},h.create=C.create,h.ready=C.ready,h.on=C.on,h.off=C.off,h.fn=C.fn,h.reactive=Pe,h.Signal=R,h.signal=$,h.computed=fn,h.effect=gt,h.batch=hn,h.untracked=dn,h.component=Ln,h.mount=Rt,h.mountAll=kt,h.getInstance=On,h.destroy=Nn,h.components=Pn,h.prefetch=xt,h.style=Bn,h.morph=Me,h.morphElement=Et,h.safeEval=V,h.router=In,h.getRouter=Dn,h.matchRoute=Un,h.store=zn,h.getStore=Fn,h.connectStore=qn,h.http=H,h.get=H.get,h.post=H.post,h.put=H.put,h.patch=H.patch,h.delete=H.delete,h.head=H.head,h.debounce=jn,h.throttle=Qn,h.pipe=$n,h.once=Zn,h.sleep=Hn,h.escapeHtml=we,h.stripHtml=Kn,h.html=Gn,h.trust=Vn,h.TrustedHTML=ze,h.uuid=Jn,h.camelCase=Yn,h.kebabCase=Xn,h.deepClone=K,h.deepMerge=es,h.isEqual=Nt,h.param=ts,h.parseQuery=ns,h.storage=ss,h.session=rs,h.EventBus=Pt,h.bus=is,h.range=os,h.unique=as,h.chunk=cs,h.groupBy=ls,h.pick=us,h.omit=fs,h.getPath=hs,h.setPath=ds,h.isEmpty=ps,h.capitalize=_s,h.truncate=ms,h.clamp=ys,h.memoize=gs,h.retry=ws,h.timeout=Es,h.onError=Bt,h.ZQueryError=I,h.ErrorCode=v,h.guardCallback=Mt,h.guardAsync=It,h.validate=Ut,h.formatError=Qe,h.webrtc=un,h.SignalingClient=Re,h.Peer=ke,h.Room=G,h.useRoom=Ye,h.usePeer=Xe,h.useTracks=et,h.useDataChannel=tt,h.useConnectionQuality=nt,h.fetchTurnCredentials=xe,h.mergeIceServers=rt,h.createTurnRefresher=it,h.deriveSFrameKey=ct,h.generateSFrameKey=lt,h.SFrameContext=ne,h.encryptFrame=Le,h.decryptFrame=Oe,h.attachE2ee=ut,h.loadSfuAdapter=mt,h.SfuError=k,h.decodeJoinToken=ht,h.isJoinTokenExpired=dt,h.samplePeerStats=Ne,h.createStatsSampler=pt,h.classifyStats=_t,h.parseSdp=Ee,h.validateSdp=Ze,h.parseCandidate=Se,h.stringifyCandidate=He,h.filterCandidates=Ke,h.isPrivateIp=ve,h.isLoopbackIp=Ce,h.isLinkLocalIp=Ae,h.isMdnsHostname=Te,h.WebRtcError=E,h.SignalingError=P,h.IceError=M,h.SdpError=B,h.TurnError=U,h.E2eeError=N,h.version="1.2.10",h.libSize="~130 KB",h.unitTests={"passed":2348,"failed":0,"total":2534,"suites":620,"duration":8235,"ok":true},h.meta={},h.isElectron=typeof navigator!="undefined"&&/Electron/i.test(navigator.userAgent)||typeof process!="undefined"&&process.versions!=null&&!!process.versions.electron,h.platform=h.isElectron?"electron":typeof window!="undefined"?"browser":"node",h.noConflict=()=>(typeof window!="undefined"&&window.$===h&&delete window.$,h),typeof window!="undefined"&&(window.$=h,window.zQuery=h)})(typeof window!="undefined"?window:globalThis);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "zero-query",
3
- "version": "1.2.9",
3
+ "version": "1.2.10",
4
4
  "description": "Lightweight modern frontend library - jQuery-like selectors, reactive components, SPA router, and state management with zero dependencies.",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",
@@ -10,7 +10,7 @@
10
10
  * Wire-protocol mapping (mirrors @zero-server/webrtc):
11
11
  * - outgoing `offer` -> `{ type: 'offer', target, sdp }` (sdp is the string)
12
12
  * - outgoing `answer` -> `{ type: 'answer', target, sdp }`
13
- * - outgoing `ice` -> `{ type: 'ice', target, candidate }` (raw a=candidate: line or null)
13
+ * - outgoing `ice` -> `{ type: 'ice', target, candidate }` (RTCIceCandidateInit-shaped dict or null for EOC)
14
14
  * - incoming filtered by `msg.from === this.id`.
15
15
  *
16
16
  * Server-side constraints honored here:
@@ -252,7 +252,18 @@ export class Peer {
252
252
  if (cand.indexOf('.local') !== -1) return;
253
253
  if (this._sentCandidates >= this._maxIceCandidates) return;
254
254
  this._sentCandidates++;
255
- this.signaling.send('ice', { target: this.id, candidate: cand });
255
+ // Browsers REQUIRE sdpMid or sdpMLineIndex when re-applying a candidate
256
+ // with addIceCandidate(); ship the full init dict so the remote peer
257
+ // can reconstruct it exactly.
258
+ const init = (typeof candidate === 'object' && candidate)
259
+ ? {
260
+ candidate: cand,
261
+ sdpMid: candidate.sdpMid != null ? candidate.sdpMid : null,
262
+ sdpMLineIndex: candidate.sdpMLineIndex != null ? candidate.sdpMLineIndex : null,
263
+ usernameFragment: candidate.usernameFragment != null ? candidate.usernameFragment : null,
264
+ }
265
+ : { candidate: cand, sdpMid: null, sdpMLineIndex: null, usernameFragment: null };
266
+ this.signaling.send('ice', { target: this.id, candidate: init });
256
267
  };
257
268
 
258
269
  this.pc.ontrack = (event) => {
@@ -328,7 +339,8 @@ export class Peer {
328
339
  }
329
340
 
330
341
  /**
331
- * @param {string|null} candidate - raw `a=candidate:` line or `null` for EOC.
342
+ * @param {string|object|null} candidate - raw `a=candidate:` line, a full
343
+ * `RTCIceCandidateInit`-shaped dict, or `null` for end-of-candidates.
332
344
  * @private
333
345
  */
334
346
  async _onRemoteCandidate(candidate) {
@@ -338,7 +350,19 @@ export class Peer {
338
350
  await this.pc.addIceCandidate(null);
339
351
  return;
340
352
  }
341
- await this.pc.addIceCandidate({ candidate });
353
+ // Older zero-query clients relayed only the bare `a=candidate:` string,
354
+ // which browsers reject with "missing values for both sdpMid and
355
+ // sdpMLineIndex". Newer clients send a full init dict - normalize both.
356
+ const init = (typeof candidate === 'string')
357
+ ? { candidate, sdpMid: '', sdpMLineIndex: 0 }
358
+ : {
359
+ candidate: candidate.candidate,
360
+ sdpMid: candidate.sdpMid != null ? candidate.sdpMid : '',
361
+ sdpMLineIndex: candidate.sdpMLineIndex != null ? candidate.sdpMLineIndex : 0,
362
+ usernameFragment: candidate.usernameFragment != null ? candidate.usernameFragment : undefined,
363
+ };
364
+ if (!init.candidate) return;
365
+ await this.pc.addIceCandidate(init);
342
366
  } catch (err) {
343
367
  // The W3C pattern: suppress errors while we're explicitly ignoring an offer.
344
368
  if (this.ignoreOffer) return;
@@ -247,7 +247,11 @@ export class FakeRTCPeerConnection {
247
247
  */
248
248
  fakeIceCandidate(candidate) {
249
249
  if (typeof this.onicecandidate === 'function') {
250
- this.onicecandidate({ candidate: candidate ? { candidate } : null });
250
+ this.onicecandidate({
251
+ candidate: candidate
252
+ ? { candidate, sdpMid: '0', sdpMLineIndex: 0, usernameFragment: 'ufrag' }
253
+ : null,
254
+ });
251
255
  }
252
256
  }
253
257
 
@@ -147,7 +147,9 @@ describe('Peer (perfect negotiation)', () => {
147
147
  // queue depth matches the candidate count we trickled.
148
148
  expect(sig._iceQueue.length).toBe(3);
149
149
  expect(sig._iceQueue[0].target).toBe('peer_a');
150
- expect(sig._iceQueue[0].candidate).toContain('typ host');
150
+ expect(sig._iceQueue[0].candidate.candidate).toContain('typ host');
151
+ expect(sig._iceQueue[0].candidate.sdpMid).toBe('0');
152
+ expect(sig._iceQueue[0].candidate.sdpMLineIndex).toBe(0);
151
153
  expect(sig._iceQueue[2].candidate).toBeNull();
152
154
  peer.close();
153
155
  });
@@ -160,7 +162,7 @@ describe('Peer (perfect negotiation)', () => {
160
162
  lastPc().fakeIceCandidate('candidate:2 1 udp 1686052607 198.51.100.1 5001 typ srflx');
161
163
 
162
164
  expect(sig._iceQueue.length).toBe(1);
163
- expect(sig._iceQueue[0].candidate).not.toContain('.local');
165
+ expect(sig._iceQueue[0].candidate.candidate).not.toContain('.local');
164
166
  peer.close();
165
167
  });
166
168
 
@@ -231,7 +233,11 @@ describe('Peer (perfect negotiation)', () => {
231
233
  await Promise.resolve(); await Promise.resolve();
232
234
 
233
235
  expect(lastPc().addIceCandidateCalls).toHaveLength(2);
234
- expect(lastPc().addIceCandidateCalls[0]).toEqual({ candidate: 'candidate:7 1 udp 1 192.0.2.7 5000 typ host' });
236
+ expect(lastPc().addIceCandidateCalls[0]).toEqual({
237
+ candidate: 'candidate:7 1 udp 1 192.0.2.7 5000 typ host',
238
+ sdpMid: '',
239
+ sdpMLineIndex: 0,
240
+ });
235
241
  expect(lastPc().addIceCandidateCalls[1]).toBeNull();
236
242
  peer.close();
237
243
  });