@urun-sh/openai 0.6.23 → 0.6.25
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-JOOR4RUT.js → chunk-PPPJ42Z7.js} +1 -1
- package/dist/{chunk-ERRG6R4T.js → chunk-SOAZAPCO.js} +1 -1
- package/dist/{chunk-FHGSREBO.js → chunk-VY333OKA.js} +4 -4
- package/dist/hosted/bin.cjs +10 -10
- package/dist/hosted/bin.js +1 -1
- package/dist/hosted/index.cjs +10 -10
- package/dist/hosted/index.js +1 -1
- package/dist/pi-extension/standalone.cjs +14 -14
- package/dist/proxy/cli.cjs +1 -1
- package/dist/proxy/cli.js +1 -1
- package/dist/proxy/index.js +1 -1
- package/package.json +2 -2
|
@@ -28,16 +28,16 @@ ${e.join(`
|
|
|
28
28
|
`:`
|
|
29
29
|
`}function M5(t){return t.replace(/[^0-9a-f]/gi,"")}function jX(t){let e=t.match(/[0-9A-Fa-f]+|[^0-9A-Fa-f]+/g)??[];if(e.length<3)return;let r=e.filter((o,a)=>a%2===0),s=e.filter((o,a)=>a%2===1),n=s[0];if(!n||s.some(o=>o!==n)||r.some(o=>o.length===0||o.length%2!==0))return;let i=r[0]?.length??0;if(i&&!r.slice(0,-1).some(o=>o.length!==i)&&!((r[r.length-1]?.length??0)>i))return{size:i/2,separator:n}}function $X(t){let e=t.trim(),r=/^0x/i.test(e)?"0x":"",s=r?e.slice(2):e,n=MX(s),i=s.split(/\r\n|\n/).filter(d=>d.length>0),o=i[0]?.trim()??"",a=jX(o),c={case:UX(e),prefix:r};if(a&&(c.group=a),n&&i.length>1){let d=M5(i[0]??"").length/2;d>0&&i.slice(0,-1).every(u=>M5(u).length/2===d)&&(c.line={bytesPerLine:d,separator:n})}return c}function FX(t,e){let r=e.allowPrefix??!0,s=[...LX(e)].sort((a,c)=>c.length-a.length);for(let a of s)OX(a);let n=t.trim();if(/^0x/i.test(n)){if(!r)throw new TypeError("Hexadecimal text must not include a 0x prefix");n=n.slice(2)}let i="",o=!1;for(let a=0;a<n.length;){let c=n[a]??"";if(DX.test(c)){i+=c,o=!1,a+=1;continue}let d=NX(n,a,s);if(!d)throw new TypeError("Input is not valid hexadecimal text");if(e.strict&&(o||i.length===0))throw new TypeError("Hexadecimal text contains misplaced separators");o=!0,a+=d.length}if(e.strict&&o&&i.length>0)throw new TypeError("Hexadecimal text must not end with a separator");if(i.length%2!==0){if(!e.allowOddLength)throw new TypeError("Hexadecimal text must contain an even number of characters");i=`0${i}`}return i.toLowerCase()}function j5(t,e){if(!e)return t.join("");if(!Number.isInteger(e.size)||e.size<1)throw new RangeError("Hex group size must be a positive integer");let r=[];for(let s=0;s<t.length;s+=e.size)r.push(t.slice(s,s+e.size).join(""));return r.join(e.separator)}function xp(t,e={}){return FX(t,e)}function $5(t,e={}){if(typeof t!="string")return!1;try{return xp(t,e),!0}catch{return!1}}function GS(t,e={}){let r=ln(t),s=e.case??"lower",n=Array.from(r,o=>{let a=o.toString(16).padStart(2,"0");return s==="upper"?a.toUpperCase():a}),i="";if(e.line){let o=e.line.bytesPerLine;if(!Number.isInteger(o)||o<1)throw new RangeError("Hex bytesPerLine must be a positive integer");let a=e.line.separator??`
|
|
30
30
|
`,c=[];for(let d=0;d<n.length;d+=o)c.push(j5(n.slice(d,d+o),e.group));i=c.join(a)}else i=j5(n,e.group);return`${e.prefix??""}${i}`}function XS(t,e={}){let r=xp(t,e),s=new Uint8Array(r.length/2);for(let n=0;n<r.length;n+=2)s[n/2]=Number.parseInt(r.slice(n,n+2),16);return s}function F5(t,e={}){let r=xp(t,e);return{bytes:XS(r),format:$X(t),normalized:r}}function H5(t,e){return GS(t,e)}var DX,BX,q5,HX,V5=V(()=>{"use strict";g();y();Hs();DX=/^[0-9a-f]$/i,BX=[" "," ",`
|
|
31
|
-
`,"\r",":","-","."];q5={compact:Object.freeze({}),upper:Object.freeze({case:"upper"}),colon:Object.freeze({group:{size:1,separator:":"}}),colonUpper:Object.freeze({case:"upper",group:{size:1,separator:":"}}),groupsOf4:Object.freeze({group:{size:4,separator:" "}}),prefixed:Object.freeze({prefix:"0x"})},HX={encode:GS,decode:XS,format:H5,formats:q5,is:$5,normalize:xp,parse:F5}});var z5=V(()=>{"use strict";g();y();Hs()});var W5=V(()=>{"use strict";g();y();Hs()});var YS=V(()=>{"use strict";g();y();Hs();KS()});var K5=V(()=>{"use strict";g();y();YS()});var JS=V(()=>{"use strict";g();y();KS();V5();z5();W5();YS();K5()});var wp,G5=V(()=>{"use strict";g();y();JS();wp=class{static isIPv4(e){return/^(\d{1,3}\.){3}\d{1,3}$/.test(e)}static parseIPv4(e){let r=e.split(".");if(r.length!==4)throw new Error("Invalid IPv4 address");return r.map(s=>{let n=parseInt(s,10);if(isNaN(n)||n<0||n>255)throw new Error("Invalid IPv4 address part");return n})}static parseIPv6(e){let s=this.expandIPv6(e).split(":");if(s.length!==8)throw new Error("Invalid IPv6 address");return s.reduce((n,i)=>{let o=parseInt(i,16);if(isNaN(o)||o<0||o>65535)throw new Error("Invalid IPv6 address part");return n.push(o>>8&255),n.push(o&255),n},[])}static expandIPv6(e){if(!e.includes("::"))return e;let r=e.split("::");if(r.length>2)throw new Error("Invalid IPv6 address");let s=r[0]?r[0].split(":"):[],n=r[1]?r[1].split(":"):[],i=8-(s.length+n.length);if(i<0)throw new Error("Invalid IPv6 address");return[...s,...Array(i).fill("0"),...n].join(":")}static formatIPv6(e){let r=[];for(let s=0;s<16;s+=2)r.push((e[s]<<8|e[s+1]).toString(16));return this.compressIPv6(r.join(":"))}static compressIPv6(e){let r=e.split(":"),s=-1,n=0,i=-1,o=0;for(let a=0;a<r.length;a++)r[a]==="0"?(i===-1&&(i=a),o++):(o>n&&(s=i,n=o),i=-1,o=0);if(o>n&&(s=i,n=o),n>1){let a=r.slice(0,s).join(":"),c=r.slice(s+n).join(":");return`${a}::${c}`}return e}static parseCIDR(e){let[r,s]=e.split("/"),n=parseInt(s,10);if(this.isIPv4(r)){if(n<0||n>32)throw new Error("Invalid IPv4 prefix length");return[this.parseIPv4(r),n]}else{if(n<0||n>128)throw new Error("Invalid IPv6 prefix length");return[this.parseIPv6(r),n]}}static decodeIP(e){if(e.length===64&&parseInt(e,16)===0)return"::/0";if(e.length!==16)return e;let r=parseInt(e.slice(8),16).toString(2).split("").reduce((n,i)=>n+ +i,0),s=e.slice(0,8).replace(/(.{2})/g,n=>`${parseInt(n,16)}.`);return s=s.slice(0,-1),`${s}/${r}`}static toString(e){let r=new Uint8Array(e);if(r.length===4)return Array.from(r).join(".");if(r.length===16)return this.formatIPv6(r);if(r.length===8||r.length===32){let s=r.length/2,n=r.slice(0,s),i=r.slice(s);if(r.every(c=>c===0))return r.length===8?"0.0.0.0/0":"::/0";let a=i.reduce((c,d)=>c+(d.toString(2).match(/1/g)||[]).length,0);return r.length===8?`${Array.from(n).join(".")}/${a}`:`${this.formatIPv6(n)}/${a}`}return this.decodeIP(Eu.encode(e))}static fromString(e){if(e.includes("/")){let[s,n]=this.parseCIDR(e),i=new Uint8Array(s.length),o=n;for(let c=0;c<i.length;c++)o>=8?(i[c]=255,o-=8):o>0&&(i[c]=255<<8-o,o=0);let a=new Uint8Array(s.length*2);return a.set(s,0),a.set(i,s.length),a.buffer}let r=this.isIPv4(e)?this.parseIPv4(e):this.parseIPv6(e);return new Uint8Array(r).buffer}}});var QS,ZS,e2,_r,Cu,md,ka,t2,Vt,Tu=V(()=>{"use strict";g();y();ge();pe();JS();_r=class{teletexString;printableString;universalString;utf8String;bmpString;constructor(e={}){Object.assign(this,e)}toString(){return this.bmpString||this.printableString||this.teletexString||this.universalString||this.utf8String||""}};v([A({type:$.TeletexString})],_r.prototype,"teletexString",void 0);v([A({type:$.PrintableString})],_r.prototype,"printableString",void 0);v([A({type:$.UniversalString})],_r.prototype,"universalString",void 0);v([A({type:$.Utf8String})],_r.prototype,"utf8String",void 0);v([A({type:$.BmpString})],_r.prototype,"bmpString",void 0);_r=v([ie({type:re.Choice})],_r);Cu=class extends _r{ia5String;anyValue;constructor(e={}){super(e),Object.assign(this,e)}toString(){return this.ia5String||(this.anyValue?Eu.encode(this.anyValue):super.toString())}};v([A({type:$.IA5String})],Cu.prototype,"ia5String",void 0);v([A({type:$.Any})],Cu.prototype,"anyValue",void 0);Cu=v([ie({type:re.Choice})],Cu);md=class{type="";value=new Cu;constructor(e={}){Object.assign(this,e)}};v([A({type:$.ObjectIdentifier})],md.prototype,"type",void 0);v([A({type:Cu})],md.prototype,"value",void 0);ka=QS=class extends Ke{constructor(e){super(e),Object.setPrototypeOf(this,QS.prototype)}};ka=QS=v([ie({type:re.Set,itemType:md})],ka);t2=ZS=class extends Ke{constructor(e){super(e),Object.setPrototypeOf(this,ZS.prototype)}};t2=ZS=v([ie({type:re.Sequence,itemType:ka})],t2);Vt=e2=class extends t2{constructor(e){super(e),Object.setPrototypeOf(this,e2.prototype)}};Vt=e2=v([ie({type:re.Sequence})],Vt)});var KX,Aa,vp,et,gd=V(()=>{"use strict";g();y();ge();pe();G5();Tu();KX={fromASN:t=>wp.toString(Su.fromASN(t)),toASN:t=>Su.toASN(wp.fromString(t))},Aa=class{typeId="";value=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};v([A({type:$.ObjectIdentifier})],Aa.prototype,"typeId",void 0);v([A({type:$.Any,context:0})],Aa.prototype,"value",void 0);vp=class{nameAssigner;partyName=new _r;constructor(e={}){Object.assign(this,e)}};v([A({type:_r,optional:!0,context:0,implicit:!0})],vp.prototype,"nameAssigner",void 0);v([A({type:_r,context:1,implicit:!0})],vp.prototype,"partyName",void 0);et=class{otherName;rfc822Name;dNSName;x400Address;directoryName;ediPartyName;uniformResourceIdentifier;iPAddress;registeredID;constructor(e={}){Object.assign(this,e)}};v([A({type:Aa,context:0,implicit:!0})],et.prototype,"otherName",void 0);v([A({type:$.IA5String,context:1,implicit:!0})],et.prototype,"rfc822Name",void 0);v([A({type:$.IA5String,context:2,implicit:!0})],et.prototype,"dNSName",void 0);v([A({type:$.Any,context:3,implicit:!0})],et.prototype,"x400Address",void 0);v([A({type:Vt,context:4,implicit:!1})],et.prototype,"directoryName",void 0);v([A({type:vp,context:5})],et.prototype,"ediPartyName",void 0);v([A({type:$.IA5String,context:6,implicit:!0})],et.prototype,"uniformResourceIdentifier",void 0);v([A({type:$.OctetString,context:7,implicit:!0,converter:KX})],et.prototype,"iPAddress",void 0);v([A({type:$.ObjectIdentifier,context:8,implicit:!0})],et.prototype,"registeredID",void 0);et=v([ie({type:re.Choice})],et)});var Ia,Ra,X5,yd,Rb,bpe,xpe,r2,s2,n2,i2,lt,Kt=V(()=>{"use strict";g();y();Ia="1.3.6.1.5.5.7",Ra=`${Ia}.1`,X5=`${Ia}.2`,yd=`${Ia}.3`,Rb=`${Ia}.48`,bpe=`${X5}.1`,xpe=`${X5}.2`,r2=`${Rb}.1`,s2=`${Rb}.2`,n2=`${Rb}.3`,i2=`${Rb}.5`,lt="2.5.29"});var o2,Pb,po,bd,a2=V(()=>{"use strict";g();y();ge();pe();gd();Kt();Pb=`${Ra}.1`,po=class{accessMethod="";accessLocation=new et;constructor(e={}){Object.assign(this,e)}};v([A({type:$.ObjectIdentifier})],po.prototype,"accessMethod",void 0);v([A({type:et})],po.prototype,"accessLocation",void 0);bd=o2=class extends Ke{constructor(e){super(e),Object.setPrototypeOf(this,o2.prototype)}};bd=o2=v([ie({type:re.Sequence,itemType:po})],bd)});var Db,xd,bi,c2=V(()=>{"use strict";g();y();ge();pe();gd();Kt();Db=`${lt}.35`,xd=class extends Xe{},bi=class{keyIdentifier;authorityCertIssuer;authorityCertSerialNumber;constructor(e={}){e&&Object.assign(this,e)}};v([A({type:xd,context:0,optional:!0,implicit:!0})],bi.prototype,"keyIdentifier",void 0);v([A({type:et,context:1,optional:!0,implicit:!0,repeated:"sequence"})],bi.prototype,"authorityCertIssuer",void 0);v([A({type:$.Integer,context:2,optional:!0,implicit:!0,converter:Tt})],bi.prototype,"authorityCertSerialNumber",void 0)});var Bb,wd,Y5=V(()=>{"use strict";g();y();ge();pe();Kt();Bb=`${lt}.19`,wd=class{cA=!1;pathLenConstraint;constructor(e={}){Object.assign(this,e)}};v([A({type:$.Boolean,defaultValue:!1})],wd.prototype,"cA",void 0);v([A({type:$.Integer,optional:!0})],wd.prototype,"pathLenConstraint",void 0)});var d2,Jt,_p=V(()=>{"use strict";g();y();ge();pe();gd();Jt=d2=class extends Ke{constructor(e){super(e),Object.setPrototypeOf(this,d2.prototype)}};Jt=d2=v([ie({type:re.Sequence,itemType:et})],Jt)});var l2,GX,J5,Q5=V(()=>{"use strict";g();y();ge();pe();_p();Kt();GX=`${lt}.29`,J5=l2=class extends Jt{constructor(e){super(e),Object.setPrototypeOf(this,l2.prototype)}};J5=l2=v([ie({type:re.Sequence})],J5)});var u2,Ob,c0e,mo,Sp,Ep,Lb,Cp,vd,Tp,Z5=V(()=>{"use strict";g();y();ge();pe();Kt();Ob=`${lt}.32`,c0e=`${Ob}.0`,mo=class{ia5String;visibleString;bmpString;utf8String;constructor(e={}){Object.assign(this,e)}toString(){return this.ia5String||this.visibleString||this.bmpString||this.utf8String||""}};v([A({type:$.IA5String})],mo.prototype,"ia5String",void 0);v([A({type:$.VisibleString})],mo.prototype,"visibleString",void 0);v([A({type:$.BmpString})],mo.prototype,"bmpString",void 0);v([A({type:$.Utf8String})],mo.prototype,"utf8String",void 0);mo=v([ie({type:re.Choice})],mo);Sp=class{organization=new mo;noticeNumbers=[];constructor(e={}){Object.assign(this,e)}};v([A({type:mo})],Sp.prototype,"organization",void 0);v([A({type:$.Integer,repeated:"sequence"})],Sp.prototype,"noticeNumbers",void 0);Ep=class{noticeRef;explicitText;constructor(e={}){Object.assign(this,e)}};v([A({type:Sp,optional:!0})],Ep.prototype,"noticeRef",void 0);v([A({type:mo,optional:!0})],Ep.prototype,"explicitText",void 0);Lb=class{cPSuri;userNotice;constructor(e={}){Object.assign(this,e)}};v([A({type:$.IA5String})],Lb.prototype,"cPSuri",void 0);v([A({type:Ep})],Lb.prototype,"userNotice",void 0);Lb=v([ie({type:re.Choice})],Lb);Cp=class{policyQualifierId="";qualifier=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};v([A({type:$.ObjectIdentifier})],Cp.prototype,"policyQualifierId",void 0);v([A({type:$.Any})],Cp.prototype,"qualifier",void 0);vd=class{policyIdentifier="";policyQualifiers;constructor(e={}){Object.assign(this,e)}};v([A({type:$.ObjectIdentifier})],vd.prototype,"policyIdentifier",void 0);v([A({type:Cp,repeated:"sequence",optional:!0})],vd.prototype,"policyQualifiers",void 0);Tp=u2=class extends Ke{constructor(e){super(e),Object.setPrototypeOf(this,u2.prototype)}};Tp=u2=v([ie({type:re.Sequence,itemType:vd})],Tp)});var b0e,kp,h2=V(()=>{"use strict";g();y();ge();pe();Kt();b0e=`${lt}.20`,kp=class{value;constructor(e=0){this.value=e}};v([A({type:$.Integer})],kp.prototype,"value",void 0);kp=v([ie({type:re.Choice})],kp)});var k0e,eP,tP=V(()=>{"use strict";g();y();ge();pe();Kt();h2();k0e=`${lt}.27`,eP=class extends kp{};eP=v([ie({type:re.Choice})],eP)});var f2,Nb,Pn,Ap,go,xi,Pa,Ub=V(()=>{"use strict";g();y();ge();pe();Tu();gd();Kt();Nb=`${lt}.31`;(function(t){t[t.unused=1]="unused",t[t.keyCompromise=2]="keyCompromise",t[t.cACompromise=4]="cACompromise",t[t.affiliationChanged=8]="affiliationChanged",t[t.superseded=16]="superseded",t[t.cessationOfOperation=32]="cessationOfOperation",t[t.certificateHold=64]="certificateHold",t[t.privilegeWithdrawn=128]="privilegeWithdrawn",t[t.aACompromise=256]="aACompromise"})(Pn||(Pn={}));Ap=class extends yi{toJSON(){let e=[],r=this.toNumber();return r&Pn.aACompromise&&e.push("aACompromise"),r&Pn.affiliationChanged&&e.push("affiliationChanged"),r&Pn.cACompromise&&e.push("cACompromise"),r&Pn.certificateHold&&e.push("certificateHold"),r&Pn.cessationOfOperation&&e.push("cessationOfOperation"),r&Pn.keyCompromise&&e.push("keyCompromise"),r&Pn.privilegeWithdrawn&&e.push("privilegeWithdrawn"),r&Pn.superseded&&e.push("superseded"),r&Pn.unused&&e.push("unused"),e}toString(){return`[${this.toJSON().join(", ")}]`}},go=class{fullName;nameRelativeToCRLIssuer;constructor(e={}){Object.assign(this,e)}};v([A({type:et,context:0,repeated:"sequence",implicit:!0})],go.prototype,"fullName",void 0);v([A({type:ka,context:1,implicit:!0})],go.prototype,"nameRelativeToCRLIssuer",void 0);go=v([ie({type:re.Choice})],go);xi=class{distributionPoint;reasons;cRLIssuer;constructor(e={}){Object.assign(this,e)}};v([A({type:go,context:0,optional:!0})],xi.prototype,"distributionPoint",void 0);v([A({type:Ap,context:1,optional:!0,implicit:!0})],xi.prototype,"reasons",void 0);v([A({type:et,context:2,optional:!0,repeated:"sequence",implicit:!0})],xi.prototype,"cRLIssuer",void 0);Pa=f2=class extends Ke{constructor(e){super(e),Object.setPrototypeOf(this,f2.prototype)}};Pa=f2=v([ie({type:re.Sequence,itemType:xi})],Pa)});var p2,W0e,rP,sP=V(()=>{"use strict";g();y();ge();pe();Kt();Ub();W0e=`${lt}.46`,rP=p2=class extends Pa{constructor(e){super(e),Object.setPrototypeOf(this,p2.prototype)}};rP=p2=v([ie({type:re.Sequence,itemType:xi})],rP)});var tme,fn,nP=V(()=>{"use strict";g();y();ge();pe();Kt();Ub();tme=`${lt}.28`,fn=class t{static ONLY=!1;distributionPoint;onlyContainsUserCerts=t.ONLY;onlyContainsCACerts=t.ONLY;onlySomeReasons;indirectCRL=t.ONLY;onlyContainsAttributeCerts=t.ONLY;constructor(e={}){Object.assign(this,e)}};v([A({type:go,context:0,optional:!0})],fn.prototype,"distributionPoint",void 0);v([A({type:$.Boolean,context:1,defaultValue:fn.ONLY,implicit:!0})],fn.prototype,"onlyContainsUserCerts",void 0);v([A({type:$.Boolean,context:2,defaultValue:fn.ONLY,implicit:!0})],fn.prototype,"onlyContainsCACerts",void 0);v([A({type:Ap,context:3,optional:!0,implicit:!0})],fn.prototype,"onlySomeReasons",void 0);v([A({type:$.Boolean,context:4,defaultValue:fn.ONLY,implicit:!0})],fn.prototype,"indirectCRL",void 0);v([A({type:$.Boolean,context:5,defaultValue:fn.ONLY,implicit:!0})],fn.prototype,"onlyContainsAttributeCerts",void 0)});var iP,Ip,Rp,oP=V(()=>{"use strict";g();y();ge();pe();Kt();iP=`${lt}.21`;(function(t){t[t.unspecified=0]="unspecified",t[t.keyCompromise=1]="keyCompromise",t[t.cACompromise=2]="cACompromise",t[t.affiliationChanged=3]="affiliationChanged",t[t.superseded=4]="superseded",t[t.cessationOfOperation=5]="cessationOfOperation",t[t.certificateHold=6]="certificateHold",t[t.removeFromCRL=8]="removeFromCRL",t[t.privilegeWithdrawn=9]="privilegeWithdrawn",t[t.aACompromise=10]="aACompromise"})(Ip||(Ip={}));Rp=class{reason=Ip.unspecified;constructor(e=Ip.unspecified){this.reason=e}toJSON(){return Ip[this.reason]}toString(){return this.toJSON()}};v([A({type:$.Enumerated})],Rp.prototype,"reason",void 0);Rp=v([ie({type:re.Choice})],Rp)});var m2,Mb,Pp,gme,aP,cP,dP,lP,uP,hP,fP=V(()=>{"use strict";g();y();ge();pe();Kt();Mb=`${lt}.37`,Pp=m2=class extends Ke{constructor(e){super(e),Object.setPrototypeOf(this,m2.prototype)}};Pp=m2=v([ie({type:re.Sequence,itemType:$.ObjectIdentifier})],Pp);gme=`${Mb}.0`,aP=`${yd}.1`,cP=`${yd}.2`,dP=`${yd}.3`,lP=`${yd}.4`,uP=`${yd}.8`,hP=`${yd}.9`});var Sme,g2,pP=V(()=>{"use strict";g();y();ge();pe();Kt();Sme=`${lt}.54`,g2=class{value;constructor(e=new ArrayBuffer(0)){this.value=e}};v([A({type:$.Integer,converter:Tt})],g2.prototype,"value",void 0);g2=v([ie({type:re.Choice})],g2)});var mP,Dp,gP=V(()=>{"use strict";g();y();ge();pe();Kt();mP=`${lt}.24`,Dp=class{value=new Date;constructor(e){e&&(this.value=e)}};v([A({type:$.GeneralizedTime})],Dp.prototype,"value",void 0);Dp=v([ie({type:re.Choice})],Dp)});var y2,b2,yP,bP=V(()=>{"use strict";g();y();ge();pe();_p();Kt();b2=`${lt}.18`,yP=y2=class extends Jt{constructor(e){super(e),Object.setPrototypeOf(this,y2.prototype)}};yP=y2=v([ie({type:re.Sequence})],yP)});var jb,Dn,ku,xP=V(()=>{"use strict";g();y();pe();Kt();jb=`${lt}.15`;(function(t){t[t.digitalSignature=1]="digitalSignature",t[t.nonRepudiation=2]="nonRepudiation",t[t.keyEncipherment=4]="keyEncipherment",t[t.dataEncipherment=8]="dataEncipherment",t[t.keyAgreement=16]="keyAgreement",t[t.keyCertSign=32]="keyCertSign",t[t.cRLSign=64]="cRLSign",t[t.encipherOnly=128]="encipherOnly",t[t.decipherOnly=256]="decipherOnly"})(Dn||(Dn={}));ku=class extends yi{toJSON(){let e=this.toNumber(),r=[];return e&Dn.cRLSign&&r.push("crlSign"),e&Dn.dataEncipherment&&r.push("dataEncipherment"),e&Dn.decipherOnly&&r.push("decipherOnly"),e&Dn.digitalSignature&&r.push("digitalSignature"),e&Dn.encipherOnly&&r.push("encipherOnly"),e&Dn.keyAgreement&&r.push("keyAgreement"),e&Dn.keyCertSign&&r.push("keyCertSign"),e&Dn.keyEncipherment&&r.push("keyEncipherment"),e&Dn.nonRepudiation&&r.push("nonRepudiation"),r}toString(){return`[${this.toJSON().join(", ")}]`}}});var x2,Qme,Au,$b,Fb,wP=V(()=>{"use strict";g();y();ge();pe();gd();Kt();Qme=`${lt}.30`,Au=class{base=new et;minimum=0;maximum;constructor(e={}){Object.assign(this,e)}};v([A({type:et})],Au.prototype,"base",void 0);v([A({type:$.Integer,context:0,defaultValue:0,implicit:!0})],Au.prototype,"minimum",void 0);v([A({type:$.Integer,context:1,optional:!0,implicit:!0})],Au.prototype,"maximum",void 0);$b=x2=class extends Ke{constructor(e){super(e),Object.setPrototypeOf(this,x2.prototype)}};$b=x2=v([ie({type:re.Sequence,itemType:Au})],$b);Fb=class{permittedSubtrees;excludedSubtrees;constructor(e={}){Object.assign(this,e)}};v([A({type:$b,context:0,optional:!0,implicit:!0})],Fb.prototype,"permittedSubtrees",void 0);v([A({type:$b,context:1,optional:!0,implicit:!0})],Fb.prototype,"excludedSubtrees",void 0)});var oge,Hb,vP=V(()=>{"use strict";g();y();ge();pe();Kt();oge=`${lt}.36`,Hb=class{requireExplicitPolicy;inhibitPolicyMapping;constructor(e={}){Object.assign(this,e)}};v([A({type:$.Integer,context:0,implicit:!0,optional:!0,converter:Tt})],Hb.prototype,"requireExplicitPolicy",void 0);v([A({type:$.Integer,context:1,implicit:!0,optional:!0,converter:Tt})],Hb.prototype,"inhibitPolicyMapping",void 0)});var w2,fge,Bp,_P,SP=V(()=>{"use strict";g();y();ge();pe();Kt();fge=`${lt}.33`,Bp=class{issuerDomainPolicy="";subjectDomainPolicy="";constructor(e={}){Object.assign(this,e)}};v([A({type:$.ObjectIdentifier})],Bp.prototype,"issuerDomainPolicy",void 0);v([A({type:$.ObjectIdentifier})],Bp.prototype,"subjectDomainPolicy",void 0);_P=w2=class extends Ke{constructor(e){super(e),Object.setPrototypeOf(this,w2.prototype)}};_P=w2=v([ie({type:re.Sequence,itemType:Bp})],_P)});var v2,_2,qb,EP=V(()=>{"use strict";g();y();ge();pe();_p();Kt();_2=`${lt}.17`,qb=v2=class extends Jt{constructor(e){super(e),Object.setPrototypeOf(this,v2.prototype)}};qb=v2=v([ie({type:re.Sequence})],qb)});var Fr,S2=V(()=>{"use strict";g();y();ge();pe();Fr=class{type="";values=[];constructor(e={}){Object.assign(this,e)}};v([A({type:$.ObjectIdentifier})],Fr.prototype,"type",void 0);v([A({type:$.Any,repeated:"set"})],Fr.prototype,"values",void 0)});var E2,Oge,CP,TP=V(()=>{"use strict";g();y();ge();pe();S2();Kt();Oge=`${lt}.9`,CP=E2=class extends Ke{constructor(e){super(e),Object.setPrototypeOf(this,E2.prototype)}};CP=E2=v([ie({type:re.Sequence,itemType:Fr})],CP)});var C2,Es,kP=V(()=>{"use strict";g();y();Kt();c2();C2=`${lt}.14`,Es=class extends xd{}});var Gge,Vb,AP=V(()=>{"use strict";g();y();ge();pe();Kt();Gge=`${lt}.16`,Vb=class{notBefore;notAfter;constructor(e={}){Object.assign(this,e)}};v([A({type:$.GeneralizedTime,context:0,implicit:!0,optional:!0})],Vb.prototype,"notBefore",void 0);v([A({type:$.GeneralizedTime,context:1,implicit:!0,optional:!0})],Vb.prototype,"notAfter",void 0)});var Lp,zb,Wb,IP=V(()=>{"use strict";g();y();ge();pe();(function(t){t[t.keyUpdateAllowed=1]="keyUpdateAllowed",t[t.newExtensions=2]="newExtensions",t[t.pKIXCertificate=4]="pKIXCertificate"})(Lp||(Lp={}));zb=class extends yi{toJSON(){let e=[],r=this.toNumber();return r&Lp.pKIXCertificate&&e.push("pKIXCertificate"),r&Lp.newExtensions&&e.push("newExtensions"),r&Lp.keyUpdateAllowed&&e.push("keyUpdateAllowed"),e}toString(){return`[${this.toJSON().join(", ")}]`}},Wb=class{entrustVers="";entrustInfoFlags=new zb;constructor(e={}){Object.assign(this,e)}};v([A({type:$.GeneralString})],Wb.prototype,"entrustVers",void 0);v([A({type:zb})],Wb.prototype,"entrustInfoFlags",void 0)});var T2,aye,RP,PP=V(()=>{"use strict";g();y();ge();pe();Kt();a2();aye=`${Ra}.11`,RP=T2=class extends Ke{constructor(e){super(e),Object.setPrototypeOf(this,T2.prototype)}};RP=T2=v([ie({type:re.Sequence,itemType:po})],RP)});var DP=V(()=>{"use strict";g();y();a2();c2();Y5();Q5();Z5();tP();Ub();sP();nP();h2();oP();fP();pP();gP();bP();xP();wP();vP();SP();EP();TP();kP();AP();IP();PP()});var _e,_d=V(()=>{"use strict";g();y();ge();pe();Hs();_e=class t{algorithm="";parameters;constructor(e={}){Object.assign(this,e)}isEqual(e){return e instanceof t&&e.algorithm==this.algorithm&&(e.parameters&&this.parameters&&jS(e.parameters,this.parameters)||e.parameters===this.parameters)}};v([A({type:$.ObjectIdentifier})],_e.prototype,"algorithm",void 0);v([A({type:$.Any,optional:!0})],_e.prototype,"parameters",void 0)});var Hr,k2=V(()=>{"use strict";g();y();ge();pe();_d();Hr=class{algorithm=new _e;subjectPublicKey=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};v([A({type:_e})],Hr.prototype,"algorithm",void 0);v([A({type:$.BitString})],Hr.prototype,"subjectPublicKey",void 0)});var ur,Kb=V(()=>{"use strict";g();y();ge();pe();ur=class{utcTime;generalTime;constructor(e){if(e)if(typeof e=="string"||typeof e=="number"||e instanceof Date){let r=new Date(e);r.setMilliseconds(0),r.getUTCFullYear()>2049?this.generalTime=r:this.utcTime=r}else Object.assign(this,e)}getTime(){let e=this.utcTime||this.generalTime;if(!e)throw new Error("Cannot get time from CHOICE object");return e}};v([A({type:$.UTCTime})],ur.prototype,"utcTime",void 0);v([A({type:$.GeneralizedTime})],ur.prototype,"generalTime",void 0);ur=v([ie({type:re.Choice})],ur)});var yo,A2=V(()=>{"use strict";g();y();ge();pe();Kb();yo=class{notBefore=new ur(new Date);notAfter=new ur(new Date);constructor(e){e&&(this.notBefore=new ur(e.notBefore),this.notAfter=new ur(e.notAfter))}};v([A({type:ur})],yo.prototype,"notBefore",void 0);v([A({type:ur})],yo.prototype,"notAfter",void 0)});var I2,as,qs,Gb=V(()=>{"use strict";g();y();ge();pe();as=class t{static CRITICAL=!1;extnID="";critical=t.CRITICAL;extnValue=new Xe;constructor(e={}){Object.assign(this,e)}};v([A({type:$.ObjectIdentifier})],as.prototype,"extnID",void 0);v([A({type:$.Boolean,defaultValue:as.CRITICAL})],as.prototype,"critical",void 0);v([A({type:Xe})],as.prototype,"extnValue",void 0);qs=I2=class extends Ke{constructor(e){super(e),Object.setPrototypeOf(this,I2.prototype)}};qs=I2=v([ie({type:re.Sequence,itemType:as})],qs)});var wi,R2=V(()=>{"use strict";g();y();(function(t){t[t.v1=0]="v1",t[t.v2=1]="v2",t[t.v3=2]="v3"})(wi||(wi={}))});var qr,P2=V(()=>{"use strict";g();y();ge();pe();_d();Tu();k2();A2();Gb();R2();qr=class{version=wi.v1;serialNumber=new ArrayBuffer(0);signature=new _e;issuer=new Vt;validity=new yo;subject=new Vt;subjectPublicKeyInfo=new Hr;issuerUniqueID;subjectUniqueID;extensions;constructor(e={}){Object.assign(this,e)}};v([A({type:$.Integer,context:0,defaultValue:wi.v1})],qr.prototype,"version",void 0);v([A({type:$.Integer,converter:Tt})],qr.prototype,"serialNumber",void 0);v([A({type:_e})],qr.prototype,"signature",void 0);v([A({type:Vt})],qr.prototype,"issuer",void 0);v([A({type:yo})],qr.prototype,"validity",void 0);v([A({type:Vt})],qr.prototype,"subject",void 0);v([A({type:Hr})],qr.prototype,"subjectPublicKeyInfo",void 0);v([A({type:$.BitString,context:1,implicit:!0,optional:!0})],qr.prototype,"issuerUniqueID",void 0);v([A({type:$.BitString,context:2,implicit:!0,optional:!0})],qr.prototype,"subjectUniqueID",void 0);v([A({type:qs,context:3,optional:!0})],qr.prototype,"extensions",void 0)});var pn,BP=V(()=>{"use strict";g();y();ge();pe();_d();P2();pn=class{tbsCertificate=new qr;tbsCertificateRaw;signatureAlgorithm=new _e;signatureValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};v([A({type:qr,raw:!0})],pn.prototype,"tbsCertificate",void 0);v([A({type:_e})],pn.prototype,"signatureAlgorithm",void 0);v([A({type:$.BitString})],pn.prototype,"signatureValue",void 0)});var Sd,Vs,D2=V(()=>{"use strict";g();y();ge();pe();_d();Tu();Kb();Gb();Sd=class{userCertificate=new ArrayBuffer(0);revocationDate=new ur;crlEntryExtensions;constructor(e={}){Object.assign(this,e)}};v([A({type:$.Integer,converter:Tt})],Sd.prototype,"userCertificate",void 0);v([A({type:ur})],Sd.prototype,"revocationDate",void 0);v([A({type:as,optional:!0,repeated:"sequence"})],Sd.prototype,"crlEntryExtensions",void 0);Vs=class{version;signature=new _e;issuer=new Vt;thisUpdate=new ur;nextUpdate;revokedCertificates;crlExtensions;constructor(e={}){Object.assign(this,e)}};v([A({type:$.Integer,optional:!0})],Vs.prototype,"version",void 0);v([A({type:_e})],Vs.prototype,"signature",void 0);v([A({type:Vt})],Vs.prototype,"issuer",void 0);v([A({type:ur})],Vs.prototype,"thisUpdate",void 0);v([A({type:ur,optional:!0})],Vs.prototype,"nextUpdate",void 0);v([A({type:Sd,repeated:"sequence",optional:!0})],Vs.prototype,"revokedCertificates",void 0);v([A({type:as,optional:!0,context:0,repeated:"sequence"})],Vs.prototype,"crlExtensions",void 0)});var Ed,LP=V(()=>{"use strict";g();y();ge();pe();_d();D2();Ed=class{tbsCertList=new Vs;tbsCertListRaw;signatureAlgorithm=new _e;signature=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};v([A({type:Vs,raw:!0})],Ed.prototype,"tbsCertList",void 0);v([A({type:_e})],Ed.prototype,"signatureAlgorithm",void 0);v([A({type:$.BitString})],Ed.prototype,"signature",void 0)});var kt=V(()=>{"use strict";g();y();DP();_d();S2();BP();LP();Gb();gd();_p();Tu();Kt();k2();D2();P2();Kb();R2();A2()});var Bn,Op=V(()=>{"use strict";g();y();ge();pe();kt();Bn=class{issuer=new Vt;serialNumber=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};v([A({type:Vt})],Bn.prototype,"issuer",void 0);v([A({type:$.Integer,converter:Tt})],Bn.prototype,"serialNumber",void 0)});var Cd,B2=V(()=>{"use strict";g();y();ge();pe();kt();Op();Cd=class{subjectKeyIdentifier;issuerAndSerialNumber;constructor(e={}){Object.assign(this,e)}};v([A({type:Es,context:0,implicit:!0})],Cd.prototype,"subjectKeyIdentifier",void 0);v([A({type:Bn})],Cd.prototype,"issuerAndSerialNumber",void 0);Cd=v([ie({type:re.Choice})],Cd)});var Vr,Td,Np,Cs,Up,NP,Xb,vi=V(()=>{"use strict";g();y();ge();kt();pe();(function(t){t[t.v0=0]="v0",t[t.v1=1]="v1",t[t.v2=2]="v2",t[t.v3=3]="v3",t[t.v4=4]="v4",t[t.v5=5]="v5"})(Vr||(Vr={}));Td=class extends _e{};Td=v([ie({type:re.Sequence})],Td);Np=class extends _e{};Np=v([ie({type:re.Sequence})],Np);Cs=class extends _e{};Cs=v([ie({type:re.Sequence})],Cs);Up=class extends _e{};Up=v([ie({type:re.Sequence})],Up);NP=class extends _e{};NP=v([ie({type:re.Sequence})],NP);Xb=class extends _e{};Xb=v([ie({type:re.Sequence})],Xb)});var Ln,Yb=V(()=>{"use strict";g();y();ge();pe();Ln=class{attrType="";attrValues=[];constructor(e={}){Object.assign(this,e)}};v([A({type:$.ObjectIdentifier})],Ln.prototype,"attrType",void 0);v([A({type:$.Any,repeated:"set"})],Ln.prototype,"attrValues",void 0)});var L2,Ts,Mp,Jb=V(()=>{"use strict";g();y();ge();pe();B2();vi();Yb();Ts=class{version=Vr.v0;sid=new Cd;digestAlgorithm=new Td;signedAttrs;signedAttrsRaw;signatureAlgorithm=new Np;signature=new Xe;unsignedAttrs;constructor(e={}){Object.assign(this,e)}};v([A({type:$.Integer})],Ts.prototype,"version",void 0);v([A({type:Cd})],Ts.prototype,"sid",void 0);v([A({type:Td})],Ts.prototype,"digestAlgorithm",void 0);v([A({type:Ln,repeated:"set",context:0,implicit:!0,optional:!0,raw:!0})],Ts.prototype,"signedAttrs",void 0);v([A({type:Np})],Ts.prototype,"signatureAlgorithm",void 0);v([A({type:Xe})],Ts.prototype,"signature",void 0);v([A({type:Ln,repeated:"set",context:1,implicit:!0,optional:!0})],Ts.prototype,"unsignedAttrs",void 0);Mp=L2=class extends Ke{constructor(e){super(e),Object.setPrototypeOf(this,L2.prototype)}};Mp=L2=v([ie({type:re.Set,itemType:Ts})],Mp)});var UP,MP=V(()=>{"use strict";g();y();ge();pe();Jb();UP=class extends Ts{};UP=v([ie({type:re.Sequence})],UP)});var jP=V(()=>{"use strict";g();y();pe()});var $P,FP=V(()=>{"use strict";g();y();ge();kt();pe();$P=class extends ur{};$P=v([ie({type:re.Choice})],$P)});var HP=V(()=>{"use strict";g();y();MP();jP();FP()});var jp,qP=V(()=>{"use strict";g();y();ge();pe();kt();jp=class{acIssuer=new et;acSerial=0;attrs=[];constructor(e={}){Object.assign(this,e)}};v([A({type:et})],jp.prototype,"acIssuer",void 0);v([A({type:$.Integer})],jp.prototype,"acSerial",void 0);v([A({type:Fr,repeated:"sequence"})],jp.prototype,"attrs",void 0)});var O2,$p,N2=V(()=>{"use strict";g();y();ge();pe();$p=O2=class extends Ke{constructor(e){super(e),Object.setPrototypeOf(this,O2.prototype)}};$p=O2=v([ie({type:re.Sequence,itemType:$.ObjectIdentifier})],$p)});var Iu,VP=V(()=>{"use strict";g();y();ge();pe();N2();Iu=class{pathLenConstraint;permittedAttrs;excludedAttrs;permitUnSpecified=!0;constructor(e={}){Object.assign(this,e)}};v([A({type:$.Integer,optional:!0})],Iu.prototype,"pathLenConstraint",void 0);v([A({type:$p,implicit:!0,context:0,optional:!0})],Iu.prototype,"permittedAttrs",void 0);v([A({type:$p,implicit:!0,context:1,optional:!0})],Iu.prototype,"excludedAttrs",void 0);v([A({type:$.Boolean,defaultValue:!0})],Iu.prototype,"permitUnSpecified",void 0)});var mn,Fp=V(()=>{"use strict";g();y();ge();pe();kt();mn=class{issuer=new Jt;serial=new ArrayBuffer(0);issuerUID=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};v([A({type:Jt})],mn.prototype,"issuer",void 0);v([A({type:$.Integer,converter:Tt})],mn.prototype,"serial",void 0);v([A({type:$.BitString,optional:!0})],mn.prototype,"issuerUID",void 0)});var U2,gn,Hp=V(()=>{"use strict";g();y();ge();pe();kt();(function(t){t[t.publicKey=0]="publicKey",t[t.publicKeyCert=1]="publicKeyCert",t[t.otherObjectTypes=2]="otherObjectTypes"})(U2||(U2={}));gn=class{digestedObjectType=U2.publicKey;otherObjectTypeID;digestAlgorithm=new _e;objectDigest=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};v([A({type:$.Enumerated})],gn.prototype,"digestedObjectType",void 0);v([A({type:$.ObjectIdentifier,optional:!0})],gn.prototype,"otherObjectTypeID",void 0);v([A({type:_e})],gn.prototype,"digestAlgorithm",void 0);v([A({type:$.BitString})],gn.prototype,"objectDigest",void 0)});var kd,M2=V(()=>{"use strict";g();y();ge();pe();kt();Fp();Hp();kd=class{issuerName;baseCertificateID;objectDigestInfo;constructor(e={}){Object.assign(this,e)}};v([A({type:Jt,optional:!0})],kd.prototype,"issuerName",void 0);v([A({type:mn,context:0,implicit:!0,optional:!0})],kd.prototype,"baseCertificateID",void 0);v([A({type:gn,context:1,implicit:!0,optional:!0})],kd.prototype,"objectDigestInfo",void 0)});var Ad,j2=V(()=>{"use strict";g();y();ge();pe();kt();M2();Ad=class{v1Form;v2Form;constructor(e={}){Object.assign(this,e)}};v([A({type:et,repeated:"sequence"})],Ad.prototype,"v1Form",void 0);v([A({type:kd,context:0,implicit:!0})],Ad.prototype,"v2Form",void 0);Ad=v([ie({type:re.Choice})],Ad)});var Id,$2=V(()=>{"use strict";g();y();ge();pe();Id=class{notBeforeTime=new Date;notAfterTime=new Date;constructor(e={}){Object.assign(this,e)}};v([A({type:$.GeneralizedTime})],Id.prototype,"notBeforeTime",void 0);v([A({type:$.GeneralizedTime})],Id.prototype,"notAfterTime",void 0)});var Da,F2=V(()=>{"use strict";g();y();ge();pe();kt();Fp();Hp();Da=class{baseCertificateID;entityName;objectDigestInfo;constructor(e={}){Object.assign(this,e)}};v([A({type:mn,implicit:!0,context:0,optional:!0})],Da.prototype,"baseCertificateID",void 0);v([A({type:Jt,implicit:!0,context:1,optional:!0})],Da.prototype,"entityName",void 0);v([A({type:gn,implicit:!0,context:2,optional:!0})],Da.prototype,"objectDigestInfo",void 0)});var H2,ks,q2=V(()=>{"use strict";g();y();ge();pe();kt();F2();j2();$2();(function(t){t[t.v2=1]="v2"})(H2||(H2={}));ks=class{version=H2.v2;holder=new Da;issuer=new Ad;signature=new _e;serialNumber=new ArrayBuffer(0);attrCertValidityPeriod=new Id;attributes=[];issuerUniqueID;extensions;constructor(e={}){Object.assign(this,e)}};v([A({type:$.Integer})],ks.prototype,"version",void 0);v([A({type:Da})],ks.prototype,"holder",void 0);v([A({type:Ad})],ks.prototype,"issuer",void 0);v([A({type:_e})],ks.prototype,"signature",void 0);v([A({type:$.Integer,converter:Tt})],ks.prototype,"serialNumber",void 0);v([A({type:Id})],ks.prototype,"attrCertValidityPeriod",void 0);v([A({type:Fr,repeated:"sequence"})],ks.prototype,"attributes",void 0);v([A({type:$.BitString,optional:!0})],ks.prototype,"issuerUniqueID",void 0);v([A({type:qs,optional:!0})],ks.prototype,"extensions",void 0)});var Rd,zP=V(()=>{"use strict";g();y();ge();pe();kt();q2();Rd=class{acinfo=new ks;signatureAlgorithm=new _e;signatureValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};v([A({type:ks})],Rd.prototype,"acinfo",void 0);v([A({type:_e})],Rd.prototype,"signatureAlgorithm",void 0);v([A({type:$.BitString})],Rd.prototype,"signatureValue",void 0)});var qp,Ru,V2=V(()=>{"use strict";g();y();pe();(function(t){t[t.unmarked=1]="unmarked",t[t.unclassified=2]="unclassified",t[t.restricted=4]="restricted",t[t.confidential=8]="confidential",t[t.secret=16]="secret",t[t.topSecret=32]="topSecret"})(qp||(qp={}));Ru=class extends yi{}});var Pu,z2=V(()=>{"use strict";g();y();ge();pe();Pu=class{type="";value=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};v([A({type:$.ObjectIdentifier,implicit:!0,context:0})],Pu.prototype,"type",void 0);v([A({type:$.Any,implicit:!0,context:1})],Pu.prototype,"value",void 0)});var Vp,WP=V(()=>{"use strict";g();y();ge();pe();V2();z2();Vp=class{policyId="";classList=new Ru(qp.unclassified);securityCategories;constructor(e={}){Object.assign(this,e)}};v([A({type:$.ObjectIdentifier})],Vp.prototype,"policyId",void 0);v([A({type:Ru,defaultValue:new Ru(qp.unclassified)})],Vp.prototype,"classList",void 0);v([A({type:Pu,repeated:"set"})],Vp.prototype,"securityCategories",void 0)});var Du,Qb,KP=V(()=>{"use strict";g();y();ge();pe();kt();Du=class{cotets;oid;string;constructor(e={}){Object.assign(this,e)}};v([A({type:Xe})],Du.prototype,"cotets",void 0);v([A({type:$.ObjectIdentifier})],Du.prototype,"oid",void 0);v([A({type:$.Utf8String})],Du.prototype,"string",void 0);Qb=class{policyAuthority;values=[];constructor(e={}){Object.assign(this,e)}};v([A({type:Jt,implicit:!0,context:0,optional:!0})],Qb.prototype,"policyAuthority",void 0);v([A({type:Du,repeated:"sequence"})],Qb.prototype,"values",void 0)});var yve,bve,xve,wve,zp,vve,_ve,Sve,Eve,Cve,W2,Tve,GP=V(()=>{"use strict";g();y();kt();yve=`${Ra}.4`,bve=`${Ra}.6`,xve=`${Ra}.10`,wve=`${lt}.55`,zp=`${Ia}.10`,vve=`${zp}.1`,_ve=`${zp}.2`,Sve=`${zp}.3`,Eve=`${zp}.4`,Cve=`${zp}.6`,W2="2.5.4",Tve=`${W2}.72`});var K2,Bu,Lu,Zb,G2=V(()=>{"use strict";g();y();ge();pe();kt();Fp();Hp();Bu=class{targetCertificate=new mn;targetName;certDigestInfo;constructor(e={}){Object.assign(this,e)}};v([A({type:mn})],Bu.prototype,"targetCertificate",void 0);v([A({type:et,optional:!0})],Bu.prototype,"targetName",void 0);v([A({type:gn,optional:!0})],Bu.prototype,"certDigestInfo",void 0);Lu=class{targetName;targetGroup;targetCert;constructor(e={}){Object.assign(this,e)}};v([A({type:et,context:0,implicit:!0})],Lu.prototype,"targetName",void 0);v([A({type:et,context:1,implicit:!0})],Lu.prototype,"targetGroup",void 0);v([A({type:Bu,context:2,implicit:!0})],Lu.prototype,"targetCert",void 0);Lu=v([ie({type:re.Choice})],Lu);Zb=K2=class extends Ke{constructor(e){super(e),Object.setPrototypeOf(this,K2.prototype)}};Zb=K2=v([ie({type:re.Sequence,itemType:Lu})],Zb)});var X2,XP,YP=V(()=>{"use strict";g();y();ge();pe();G2();XP=X2=class extends Ke{constructor(e){super(e),Object.setPrototypeOf(this,X2.prototype)}};XP=X2=v([ie({type:re.Sequence,itemType:Zb})],XP)});var ex,JP=V(()=>{"use strict";g();y();ge();pe();kt();ex=class{roleAuthority;roleName;constructor(e={}){Object.assign(this,e)}};v([A({type:Jt,implicit:!0,context:0,optional:!0})],ex.prototype,"roleAuthority",void 0);v([A({type:et,implicit:!0,context:1})],ex.prototype,"roleName",void 0)});var Wp,QP=V(()=>{"use strict";g();y();ge();pe();kt();Wp=class{service=new et;ident=new et;authInfo;constructor(e={}){Object.assign(this,e)}};v([A({type:et})],Wp.prototype,"service",void 0);v([A({type:et})],Wp.prototype,"ident",void 0);v([A({type:Xe,optional:!0})],Wp.prototype,"authInfo",void 0)});var Y2=V(()=>{"use strict";g();y();qP();VP();j2();$2();N2();zP();q2();V2();WP();F2();KP();Fp();Hp();GP();YP();JP();z2();QP();G2();M2()});var J2,Kp,Pd,Dd,tx=V(()=>{"use strict";g();y();ge();pe();kt();Y2();Kp=class{otherCertFormat="";otherCert=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};v([A({type:$.ObjectIdentifier})],Kp.prototype,"otherCertFormat",void 0);v([A({type:$.Any})],Kp.prototype,"otherCert",void 0);Pd=class{certificate;v2AttrCert;other;constructor(e={}){Object.assign(this,e)}};v([A({type:pn})],Pd.prototype,"certificate",void 0);v([A({type:Rd,context:2,implicit:!0})],Pd.prototype,"v2AttrCert",void 0);v([A({type:Kp,context:3,implicit:!0})],Pd.prototype,"other",void 0);Pd=v([ie({type:re.Choice})],Pd);Dd=J2=class extends Ke{constructor(e){super(e),Object.setPrototypeOf(this,J2.prototype)}};Dd=J2=v([ie({type:re.Set,itemType:Pd})],Dd)});var yn,ZP=V(()=>{"use strict";g();y();ge();pe();yn=class{contentType="";content=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};v([A({type:$.ObjectIdentifier})],yn.prototype,"contentType",void 0);v([A({type:$.Any,context:0})],yn.prototype,"content",void 0)});var Ou,Bd,Q2=V(()=>{"use strict";g();y();ge();pe();Ou=class{single;any;constructor(e={}){Object.assign(this,e)}};v([A({type:Xe})],Ou.prototype,"single",void 0);v([A({type:$.Any})],Ou.prototype,"any",void 0);Ou=v([ie({type:re.Choice})],Ou);Bd=class{eContentType="";eContent;constructor(e={}){Object.assign(this,e)}};v([A({type:$.ObjectIdentifier})],Bd.prototype,"eContentType",void 0);v([A({type:Ou,context:0,optional:!0})],Bd.prototype,"eContent",void 0)});var Gp,Ba,Z2=V(()=>{"use strict";g();y();ge();pe();vi();Gp=class{value;constructedValue;constructor(e={}){Object.assign(this,e)}};v([A({type:Xe,context:0,implicit:!0,optional:!0})],Gp.prototype,"value",void 0);v([A({type:Xe,converter:P5,context:0,implicit:!0,optional:!0,repeated:"sequence"})],Gp.prototype,"constructedValue",void 0);Gp=v([ie({type:re.Choice})],Gp);Ba=class{contentType="";contentEncryptionAlgorithm=new Up;encryptedContent;constructor(e={}){Object.assign(this,e)}};v([A({type:$.ObjectIdentifier})],Ba.prototype,"contentType",void 0);v([A({type:Up})],Ba.prototype,"contentEncryptionAlgorithm",void 0);v([A({type:Gp,optional:!0})],Ba.prototype,"encryptedContent",void 0)});var La,eE=V(()=>{"use strict";g();y();ge();pe();La=class{keyAttrId="";keyAttr;constructor(e={}){Object.assign(this,e)}};v([A({type:$.ObjectIdentifier})],La.prototype,"keyAttrId",void 0);v([A({type:$.Any,optional:!0})],La.prototype,"keyAttr",void 0)});var tE,Nu,Uu,Xp,rx,Yp,Ld,bo,rE=V(()=>{"use strict";g();y();ge();pe();kt();vi();Op();eE();Nu=class{subjectKeyIdentifier=new Es;date;other;constructor(e={}){Object.assign(this,e)}};v([A({type:Es})],Nu.prototype,"subjectKeyIdentifier",void 0);v([A({type:$.GeneralizedTime,optional:!0})],Nu.prototype,"date",void 0);v([A({type:La,optional:!0})],Nu.prototype,"other",void 0);Uu=class{rKeyId;issuerAndSerialNumber;constructor(e={}){Object.assign(this,e)}};v([A({type:Nu,context:0,implicit:!0,optional:!0})],Uu.prototype,"rKeyId",void 0);v([A({type:Bn,optional:!0})],Uu.prototype,"issuerAndSerialNumber",void 0);Uu=v([ie({type:re.Choice})],Uu);Xp=class{rid=new Uu;encryptedKey=new Xe;constructor(e={}){Object.assign(this,e)}};v([A({type:Uu})],Xp.prototype,"rid",void 0);v([A({type:Xe})],Xp.prototype,"encryptedKey",void 0);rx=tE=class extends Ke{constructor(e){super(e),Object.setPrototypeOf(this,tE.prototype)}};rx=tE=v([ie({type:re.Sequence,itemType:Xp})],rx);Yp=class{algorithm=new _e;publicKey=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};v([A({type:_e})],Yp.prototype,"algorithm",void 0);v([A({type:$.BitString})],Yp.prototype,"publicKey",void 0);Ld=class{subjectKeyIdentifier;originatorKey;issuerAndSerialNumber;constructor(e={}){Object.assign(this,e)}};v([A({type:Es,context:0,implicit:!0,optional:!0})],Ld.prototype,"subjectKeyIdentifier",void 0);v([A({type:Yp,context:1,implicit:!0,optional:!0})],Ld.prototype,"originatorKey",void 0);v([A({type:Bn,optional:!0})],Ld.prototype,"issuerAndSerialNumber",void 0);Ld=v([ie({type:re.Choice})],Ld);bo=class{version=Vr.v3;originator=new Ld;ukm;keyEncryptionAlgorithm=new Cs;recipientEncryptedKeys=new rx;constructor(e={}){Object.assign(this,e)}};v([A({type:$.Integer})],bo.prototype,"version",void 0);v([A({type:Ld,context:0})],bo.prototype,"originator",void 0);v([A({type:Xe,context:1,optional:!0})],bo.prototype,"ukm",void 0);v([A({type:Cs})],bo.prototype,"keyEncryptionAlgorithm",void 0);v([A({type:rx})],bo.prototype,"recipientEncryptedKeys",void 0)});var Mu,Oa,sE=V(()=>{"use strict";g();y();ge();pe();kt();vi();Op();Mu=class{subjectKeyIdentifier;issuerAndSerialNumber;constructor(e={}){Object.assign(this,e)}};v([A({type:Es,context:0,implicit:!0})],Mu.prototype,"subjectKeyIdentifier",void 0);v([A({type:Bn})],Mu.prototype,"issuerAndSerialNumber",void 0);Mu=v([ie({type:re.Choice})],Mu);Oa=class{version=Vr.v0;rid=new Mu;keyEncryptionAlgorithm=new Cs;encryptedKey=new Xe;constructor(e={}){Object.assign(this,e)}};v([A({type:$.Integer})],Oa.prototype,"version",void 0);v([A({type:Mu})],Oa.prototype,"rid",void 0);v([A({type:Cs})],Oa.prototype,"keyEncryptionAlgorithm",void 0);v([A({type:Xe})],Oa.prototype,"encryptedKey",void 0)});var Od,Na,nE=V(()=>{"use strict";g();y();ge();pe();eE();vi();Od=class{keyIdentifier=new Xe;date;other;constructor(e={}){Object.assign(this,e)}};v([A({type:Xe})],Od.prototype,"keyIdentifier",void 0);v([A({type:$.GeneralizedTime,optional:!0})],Od.prototype,"date",void 0);v([A({type:La,optional:!0})],Od.prototype,"other",void 0);Na=class{version=Vr.v4;kekid=new Od;keyEncryptionAlgorithm=new Cs;encryptedKey=new Xe;constructor(e={}){Object.assign(this,e)}};v([A({type:$.Integer})],Na.prototype,"version",void 0);v([A({type:Od})],Na.prototype,"kekid",void 0);v([A({type:Cs})],Na.prototype,"keyEncryptionAlgorithm",void 0);v([A({type:Xe})],Na.prototype,"encryptedKey",void 0)});var Ua,iE=V(()=>{"use strict";g();y();ge();pe();vi();Ua=class{version=Vr.v0;keyDerivationAlgorithm;keyEncryptionAlgorithm=new Cs;encryptedKey=new Xe;constructor(e={}){Object.assign(this,e)}};v([A({type:$.Integer})],Ua.prototype,"version",void 0);v([A({type:Xb,context:0,optional:!0})],Ua.prototype,"keyDerivationAlgorithm",void 0);v([A({type:Cs})],Ua.prototype,"keyEncryptionAlgorithm",void 0);v([A({type:Xe})],Ua.prototype,"encryptedKey",void 0)});var Jp,xo,oE=V(()=>{"use strict";g();y();ge();pe();rE();sE();nE();iE();Jp=class{oriType="";oriValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};v([A({type:$.ObjectIdentifier})],Jp.prototype,"oriType",void 0);v([A({type:$.Any})],Jp.prototype,"oriValue",void 0);xo=class{ktri;kari;kekri;pwri;ori;constructor(e={}){Object.assign(this,e)}};v([A({type:Oa,optional:!0})],xo.prototype,"ktri",void 0);v([A({type:bo,context:1,implicit:!0,optional:!0})],xo.prototype,"kari",void 0);v([A({type:Na,context:2,implicit:!0,optional:!0})],xo.prototype,"kekri",void 0);v([A({type:Ua,context:3,implicit:!0,optional:!0})],xo.prototype,"pwri",void 0);v([A({type:Jp,context:4,implicit:!0,optional:!0})],xo.prototype,"ori",void 0);xo=v([ie({type:re.Choice})],xo)});var aE,Qp,cE=V(()=>{"use strict";g();y();ge();pe();oE();Qp=aE=class extends Ke{constructor(e){super(e),Object.setPrototypeOf(this,aE.prototype)}};Qp=aE=v([ie({type:re.Set,itemType:xo})],Qp)});var dE,eD,i2e,o2e,ju,sx,$u,nx=V(()=>{"use strict";g();y();ge();pe();kt();eD=`${Ia}.16`,i2e=`${eD}.2`,o2e=`${eD}.4`,ju=class{otherRevInfoFormat="";otherRevInfo=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};v([A({type:$.ObjectIdentifier})],ju.prototype,"otherRevInfoFormat",void 0);v([A({type:$.Any})],ju.prototype,"otherRevInfo",void 0);sx=class{other=new ju;constructor(e={}){Object.assign(this,e)}};v([A({type:ju,context:1,implicit:!0})],sx.prototype,"other",void 0);sx=v([ie({type:re.Choice})],sx);$u=dE=class extends Ke{constructor(e){super(e),Object.setPrototypeOf(this,dE.prototype)}};$u=dE=v([ie({type:re.Set,itemType:sx})],$u)});var Fu,lE=V(()=>{"use strict";g();y();ge();pe();tx();nx();Fu=class{certs;crls;constructor(e={}){Object.assign(this,e)}};v([A({type:Dd,context:0,implicit:!0,optional:!0})],Fu.prototype,"certs",void 0);v([A({type:$u,context:1,implicit:!0,optional:!0})],Fu.prototype,"crls",void 0)});var uE,hE,Nd,tD=V(()=>{"use strict";g();y();ge();pe();vi();Yb();cE();lE();Z2();hE=uE=class extends Ke{constructor(e){super(e),Object.setPrototypeOf(this,uE.prototype)}};hE=uE=v([ie({type:re.Set,itemType:Ln})],hE);Nd=class{version=Vr.v0;originatorInfo;recipientInfos=new Qp;encryptedContentInfo=new Ba;unprotectedAttrs;constructor(e={}){Object.assign(this,e)}};v([A({type:$.Integer})],Nd.prototype,"version",void 0);v([A({type:Fu,context:0,implicit:!0,optional:!0})],Nd.prototype,"originatorInfo",void 0);v([A({type:Qp})],Nd.prototype,"recipientInfos",void 0);v([A({type:Ba})],Nd.prototype,"encryptedContentInfo",void 0);v([A({type:hE,context:1,implicit:!0,optional:!0})],Nd.prototype,"unprotectedAttrs",void 0)});var rD,sD=V(()=>{"use strict";g();y();rD="1.2.840.113549.1.7.2"});var fE,ix,wo,nD=V(()=>{"use strict";g();y();ge();pe();tx();vi();Q2();nx();Jb();ix=fE=class extends Ke{constructor(e){super(e),Object.setPrototypeOf(this,fE.prototype)}};ix=fE=v([ie({type:re.Set,itemType:Td})],ix);wo=class{version=Vr.v0;digestAlgorithms=new ix;encapContentInfo=new Bd;certificates;crls;signerInfos=new Mp;constructor(e={}){Object.assign(this,e)}};v([A({type:$.Integer})],wo.prototype,"version",void 0);v([A({type:ix})],wo.prototype,"digestAlgorithms",void 0);v([A({type:Bd})],wo.prototype,"encapContentInfo",void 0);v([A({type:Dd,context:0,implicit:!0,optional:!0})],wo.prototype,"certificates",void 0);v([A({type:$u,context:1,implicit:!0,optional:!0})],wo.prototype,"crls",void 0);v([A({type:Mp})],wo.prototype,"signerInfos",void 0)});var Zp=V(()=>{"use strict";g();y();HP();Yb();tx();ZP();Q2();Z2();tD();Op();nE();rE();sE();sD();lE();iE();oE();cE();nx();nD();B2();Jb();vi()});var Ud,e0,ox,t0,r0,s0,pE,mE,gE,yE=V(()=>{"use strict";g();y();Ud="1.2.840.10045.2.1",e0="1.2.840.10045.4.1",ox="1.2.840.10045.4.3.1",t0="1.2.840.10045.4.3.2",r0="1.2.840.10045.4.3.3",s0="1.2.840.10045.4.3.4",pE="1.2.840.10045.3.1.7",mE="1.3.132.0.34",gE="1.3.132.0.35"});function n0(t){return new _e({algorithm:t})}var oD,gEe,aD,cD,dD,lD=V(()=>{"use strict";g();y();kt();yE();oD=n0(e0),gEe=n0(ox),aD=n0(t0),cD=n0(r0),dD=n0(s0)});var i0,bE,Hu,xE,_i,wE=V(()=>{"use strict";g();y();ge();pe();i0=class{fieldType;parameters;constructor(e={}){Object.assign(this,e)}};v([A({type:$.ObjectIdentifier})],i0.prototype,"fieldType",void 0);v([A({type:$.Any})],i0.prototype,"parameters",void 0);i0=v([ie({type:re.Sequence})],i0);bE=class extends Xe{},Hu=class{a;b;seed;constructor(e={}){Object.assign(this,e)}};v([A({type:$.OctetString})],Hu.prototype,"a",void 0);v([A({type:$.OctetString})],Hu.prototype,"b",void 0);v([A({type:$.BitString,optional:!0})],Hu.prototype,"seed",void 0);Hu=v([ie({type:re.Sequence})],Hu);(function(t){t[t.ecpVer1=1]="ecpVer1"})(xE||(xE={}));_i=class{version=xE.ecpVer1;fieldID;curve;base;order;cofactor;constructor(e={}){Object.assign(this,e)}};v([A({type:$.Integer})],_i.prototype,"version",void 0);v([A({type:i0})],_i.prototype,"fieldID",void 0);v([A({type:Hu})],_i.prototype,"curve",void 0);v([A({type:bE})],_i.prototype,"base",void 0);v([A({type:$.Integer,converter:Tt})],_i.prototype,"order",void 0);v([A({type:$.Integer,optional:!0})],_i.prototype,"cofactor",void 0);_i=v([ie({type:re.Sequence})],_i)});var Si,vE=V(()=>{"use strict";g();y();ge();pe();wE();Si=class{namedCurve;implicitCurve;specifiedCurve;constructor(e={}){Object.assign(this,e)}};v([A({type:$.ObjectIdentifier})],Si.prototype,"namedCurve",void 0);v([A({type:$.Null})],Si.prototype,"implicitCurve",void 0);v([A({type:_i})],Si.prototype,"specifiedCurve",void 0);Si=v([ie({type:re.Choice})],Si)});var qu,uD=V(()=>{"use strict";g();y();ge();pe();vE();qu=class{version=1;privateKey=new Xe;parameters;publicKey;constructor(e={}){Object.assign(this,e)}};v([A({type:$.Integer})],qu.prototype,"version",void 0);v([A({type:Xe})],qu.prototype,"privateKey",void 0);v([A({type:Si,context:0,optional:!0})],qu.prototype,"parameters",void 0);v([A({type:$.BitString,context:1,optional:!0})],qu.prototype,"publicKey",void 0)});var Md,hD=V(()=>{"use strict";g();y();ge();pe();Md=class{r=new ArrayBuffer(0);s=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};v([A({type:$.Integer,converter:Tt})],Md.prototype,"r",void 0);v([A({type:$.Integer,converter:Tt})],Md.prototype,"s",void 0)});var _E=V(()=>{"use strict";g();y();lD();vE();uD();hD();yE();wE()});var As,Ei,fD,pD,Ma,mD,gD,Vu,yD,ax,zu,Wu,SE,EE,jd,cx,$d,Fd,Hd,bD,xD,wD,vD,ja,o0=V(()=>{"use strict";g();y();As="1.2.840.113549.1.1",Ei=`${As}.1`,fD=`${As}.7`,pD=`${As}.9`,Ma=`${As}.10`,mD=`${As}.2`,gD=`${As}.4`,Vu=`${As}.5`,yD=`${As}.14`,ax=`${As}.11`,zu=`${As}.12`,Wu=`${As}.13`,SE=`${As}.15`,EE=`${As}.16`,jd="1.3.14.3.2.26",cx="2.16.840.1.101.3.4.2.4",$d="2.16.840.1.101.3.4.2.1",Fd="2.16.840.1.101.3.4.2.2",Hd="2.16.840.1.101.3.4.2.3",bD="2.16.840.1.101.3.4.2.5",xD="2.16.840.1.101.3.4.2.6",wD="1.2.840.113549.2.2",vD="1.2.840.113549.2.5",ja=`${As}.8`});function Dr(t){return new _e({algorithm:t,parameters:null})}var nCe,iCe,vo,oCe,aCe,cCe,dCe,lCe,uCe,dx,CE,hCe,fCe,pCe,mCe,gCe,yCe,bCe,xCe,wCe,vCe,lx=V(()=>{"use strict";g();y();pe();kt();o0();nCe=Dr(wD),iCe=Dr(vD),vo=Dr(jd),oCe=Dr(cx),aCe=Dr($d),cCe=Dr(Fd),dCe=Dr(Hd),lCe=Dr(bD),uCe=Dr(xD),dx=new _e({algorithm:ja,parameters:Ee.serialize(vo)}),CE=new _e({algorithm:pD,parameters:Ee.serialize(Su.toASN(new Uint8Array([218,57,163,238,94,107,75,13,50,85,191,239,149,96,24,144,175,216,7,9]).buffer))}),hCe=Dr(Ei),fCe=Dr(mD),pCe=Dr(gD),mCe=Dr(Vu),gCe=Dr(SE),yCe=Dr(EE),bCe=Dr(zu),xCe=Dr(Wu),wCe=Dr(SE),vCe=Dr(EE)});var Ku,RCe,_D=V(()=>{"use strict";g();y();ge();pe();kt();o0();lx();Ku=class{hashAlgorithm=new _e(vo);maskGenAlgorithm=new _e({algorithm:ja,parameters:Ee.serialize(vo)});pSourceAlgorithm=new _e(CE);constructor(e={}){Object.assign(this,e)}};v([A({type:_e,context:0,defaultValue:vo})],Ku.prototype,"hashAlgorithm",void 0);v([A({type:_e,context:1,defaultValue:dx})],Ku.prototype,"maskGenAlgorithm",void 0);v([A({type:_e,context:2,defaultValue:CE})],Ku.prototype,"pSourceAlgorithm",void 0);RCe=new _e({algorithm:fD,parameters:Ee.serialize(new Ku)})});var Ci,jCe,SD=V(()=>{"use strict";g();y();ge();pe();kt();o0();lx();Ci=class{hashAlgorithm=new _e(vo);maskGenAlgorithm=new _e({algorithm:ja,parameters:Ee.serialize(vo)});saltLength=20;trailerField=1;constructor(e={}){Object.assign(this,e)}};v([A({type:_e,context:0,defaultValue:vo})],Ci.prototype,"hashAlgorithm",void 0);v([A({type:_e,context:1,defaultValue:dx})],Ci.prototype,"maskGenAlgorithm",void 0);v([A({type:$.Integer,context:2,defaultValue:20})],Ci.prototype,"saltLength",void 0);v([A({type:$.Integer,context:3,defaultValue:1})],Ci.prototype,"trailerField",void 0);jCe=new _e({algorithm:Ma,parameters:Ee.serialize(new Ci)})});var qd,ED=V(()=>{"use strict";g();y();ge();kt();pe();qd=class{digestAlgorithm=new _e;digest=new Xe;constructor(e={}){Object.assign(this,e)}};v([A({type:_e})],qd.prototype,"digestAlgorithm",void 0);v([A({type:Xe})],qd.prototype,"digest",void 0)});var CD=V(()=>{"use strict";g();y();_D();SD();ED()});var TE,Gu,ux,kE=V(()=>{"use strict";g();y();ge();pe();Gu=class{prime=new ArrayBuffer(0);exponent=new ArrayBuffer(0);coefficient=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};v([A({type:$.Integer,converter:Tt})],Gu.prototype,"prime",void 0);v([A({type:$.Integer,converter:Tt})],Gu.prototype,"exponent",void 0);v([A({type:$.Integer,converter:Tt})],Gu.prototype,"coefficient",void 0);ux=TE=class extends Ke{constructor(e){super(e),Object.setPrototypeOf(this,TE.prototype)}};ux=TE=v([ie({type:re.Sequence,itemType:Gu})],ux)});var bn,TD=V(()=>{"use strict";g();y();ge();pe();kE();bn=class{version=0;modulus=new ArrayBuffer(0);publicExponent=new ArrayBuffer(0);privateExponent=new ArrayBuffer(0);prime1=new ArrayBuffer(0);prime2=new ArrayBuffer(0);exponent1=new ArrayBuffer(0);exponent2=new ArrayBuffer(0);coefficient=new ArrayBuffer(0);otherPrimeInfos;constructor(e={}){Object.assign(this,e)}};v([A({type:$.Integer})],bn.prototype,"version",void 0);v([A({type:$.Integer,converter:Tt})],bn.prototype,"modulus",void 0);v([A({type:$.Integer,converter:Tt})],bn.prototype,"publicExponent",void 0);v([A({type:$.Integer,converter:Tt})],bn.prototype,"privateExponent",void 0);v([A({type:$.Integer,converter:Tt})],bn.prototype,"prime1",void 0);v([A({type:$.Integer,converter:Tt})],bn.prototype,"prime2",void 0);v([A({type:$.Integer,converter:Tt})],bn.prototype,"exponent1",void 0);v([A({type:$.Integer,converter:Tt})],bn.prototype,"exponent2",void 0);v([A({type:$.Integer,converter:Tt})],bn.prototype,"coefficient",void 0);v([A({type:ux,optional:!0})],bn.prototype,"otherPrimeInfos",void 0)});var Xu,kD=V(()=>{"use strict";g();y();ge();pe();Xu=class{modulus=new ArrayBuffer(0);publicExponent=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};v([A({type:$.Integer,converter:Tt})],Xu.prototype,"modulus",void 0);v([A({type:$.Integer,converter:Tt})],Xu.prototype,"publicExponent",void 0)});var hx=V(()=>{"use strict";g();y();CD();lx();o0();kE();TD();kD()});var AE,zr,IE=V(()=>{"use strict";g();y();(function(t){t[t.Transient=0]="Transient",t[t.Singleton=1]="Singleton",t[t.ResolutionScoped=2]="ResolutionScoped",t[t.ContainerScoped=3]="ContainerScoped"})(AE||(AE={}));zr=AE});var AD=V(()=>{"use strict";g();y();IE()});function a0(t,e){RE(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}function ID(t,e,r,s){function n(i){return i instanceof r?i:new r(function(o){o(i)})}return new(r||(r=Promise))(function(i,o){function a(u){try{d(s.next(u))}catch(l){o(l)}}function c(u){try{d(s.throw(u))}catch(l){o(l)}}function d(u){u.done?i(u.value):n(u.value).then(a,c)}d((s=s.apply(t,e||[])).next())})}function RD(t,e){var r={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},s,n,i,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(d){return function(u){return c([d,u])}}function c(d){if(s)throw new TypeError("Generator is already executing.");for(;r;)try{if(s=1,n&&(i=d[0]&2?n.return:d[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,d[1])).done)return i;switch(n=0,i&&(d=[d[0]&2,i.value]),d[0]){case 0:case 1:i=d;break;case 4:return r.label++,{value:d[1],done:!1};case 5:r.label++,n=d[1],d=[0];continue;case 7:d=r.ops.pop(),r.trys.pop();continue;default:if(i=r.trys,!(i=i.length>0&&i[i.length-1])&&(d[0]===6||d[0]===2)){r=0;continue}if(d[0]===3&&(!i||d[1]>i[0]&&d[1]<i[3])){r.label=d[1];break}if(d[0]===6&&r.label<i[1]){r.label=i[1],i=d;break}if(i&&r.label<i[2]){r.label=i[2],r.ops.push(d);break}i[2]&&r.ops.pop(),r.trys.pop();continue}d=e.call(t,r)}catch(u){d=[6,u],n=0}finally{s=i=0}if(d[0]&5)throw d[1];return{value:d[0]?d[1]:void 0,done:!0}}}function c0(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],s=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&s>=t.length&&(t=void 0),{value:t&&t[s++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Yu(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var s=r.call(t),n,i=[],o;try{for(;(e===void 0||e-- >0)&&!(n=s.next()).done;)i.push(n.value)}catch(a){o={error:a}}finally{try{n&&!n.done&&(r=s.return)&&r.call(s)}finally{if(o)throw o.error}}return i}function Ti(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(Yu(arguments[e]));return t}var RE,Ju=V(()=>{"use strict";g();y();RE=function(t,e){return RE=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,s){r.__proto__=s}||function(r,s){for(var n in s)s.hasOwnProperty(n)&&(r[n]=s[n])},RE(t,e)}});function PE(t){var e=Reflect.getMetadata("design:paramtypes",t)||[],r=Reflect.getOwnMetadata(eY,t)||{};return Object.keys(r).forEach(function(s){e[+s]=r[s]}),e}var eY,Vd=V(()=>{"use strict";g();y();eY="injectionTokens"});function d0(t){return!!t.useClass}var DE=V(()=>{"use strict";g();y()});function Qu(t){return!!t.useFactory}var BE=V(()=>{"use strict";g();y()});var fx,px=V(()=>{"use strict";g();y();Ju();fx=(function(){function t(e){this.wrap=e,this.reflectMethods=["get","getPrototypeOf","setPrototypeOf","getOwnPropertyDescriptor","defineProperty","has","set","deleteProperty","apply","construct","ownKeys"]}return t.prototype.createProxy=function(e){var r=this,s={},n=!1,i,o=function(){return n||(i=e(r.wrap()),n=!0),i};return new Proxy(s,this.createHandler(o))},t.prototype.createHandler=function(e){var r={},s=function(n){r[n]=function(){for(var i=[],o=0;o<arguments.length;o++)i[o]=arguments[o];i[0]=e();var a=Reflect[n];return a.apply(void 0,Ti(i))}};return this.reflectMethods.forEach(s),r},t})()});function $a(t){return typeof t=="string"||typeof t=="symbol"}function LE(t){return typeof t=="object"&&"token"in t&&"multiple"in t}function mx(t){return typeof t=="object"&&"token"in t&&"transform"in t}function PD(t){return typeof t=="function"||t instanceof fx}var gx=V(()=>{"use strict";g();y();px()});function zd(t){return!!t.useToken}var OE=V(()=>{"use strict";g();y()});function Wd(t){return t.useValue!=null}var NE=V(()=>{"use strict";g();y()});var UE=V(()=>{"use strict";g();y();DE();BE();gx();OE();NE()});function DD(t){return d0(t)||Wd(t)||zd(t)||Qu(t)}var BD=V(()=>{"use strict";g();y();DE();NE();OE();BE()});var tY,l0,ME=V(()=>{"use strict";g();y();tY=(function(){function t(){this._registryMap=new Map}return t.prototype.entries=function(){return this._registryMap.entries()},t.prototype.getAll=function(e){return this.ensure(e),this._registryMap.get(e)},t.prototype.get=function(e){this.ensure(e);var r=this._registryMap.get(e);return r[r.length-1]||null},t.prototype.set=function(e,r){this.ensure(e),this._registryMap.get(e).push(r)},t.prototype.setAll=function(e,r){this._registryMap.set(e,r)},t.prototype.has=function(e){return this.ensure(e),this._registryMap.get(e).length>0},t.prototype.clear=function(){this._registryMap.clear()},t.prototype.ensure=function(e){this._registryMap.has(e)||this._registryMap.set(e,[])},t})(),l0=tY});var rY,LD,OD=V(()=>{"use strict";g();y();Ju();ME();rY=(function(t){a0(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e})(l0),LD=rY});var sY,u0,ND=V(()=>{"use strict";g();y();sY=(function(){function t(){this.scopedResolutions=new Map}return t})(),u0=sY});function nY(t,e){if(t===null)return"at position #"+e;var r=t.split(",")[e].trim();return'"'+r+'" at position #'+e}function iY(t,e,r){return r===void 0&&(r=" "),Ti([t],e.message.split(`
|
|
31
|
+
`,"\r",":","-","."];q5={compact:Object.freeze({}),upper:Object.freeze({case:"upper"}),colon:Object.freeze({group:{size:1,separator:":"}}),colonUpper:Object.freeze({case:"upper",group:{size:1,separator:":"}}),groupsOf4:Object.freeze({group:{size:4,separator:" "}}),prefixed:Object.freeze({prefix:"0x"})},HX={encode:GS,decode:XS,format:H5,formats:q5,is:$5,normalize:xp,parse:F5}});var z5=V(()=>{"use strict";g();y();Hs()});var W5=V(()=>{"use strict";g();y();Hs()});var YS=V(()=>{"use strict";g();y();Hs();KS()});var K5=V(()=>{"use strict";g();y();YS()});var JS=V(()=>{"use strict";g();y();KS();V5();z5();W5();YS();K5()});var wp,G5=V(()=>{"use strict";g();y();JS();wp=class{static isIPv4(e){return/^(\d{1,3}\.){3}\d{1,3}$/.test(e)}static parseIPv4(e){let r=e.split(".");if(r.length!==4)throw new Error("Invalid IPv4 address");return r.map(s=>{let n=parseInt(s,10);if(isNaN(n)||n<0||n>255)throw new Error("Invalid IPv4 address part");return n})}static parseIPv6(e){let s=this.expandIPv6(e).split(":");if(s.length!==8)throw new Error("Invalid IPv6 address");return s.reduce((n,i)=>{let o=parseInt(i,16);if(isNaN(o)||o<0||o>65535)throw new Error("Invalid IPv6 address part");return n.push(o>>8&255),n.push(o&255),n},[])}static expandIPv6(e){if(!e.includes("::"))return e;let r=e.split("::");if(r.length>2)throw new Error("Invalid IPv6 address");let s=r[0]?r[0].split(":"):[],n=r[1]?r[1].split(":"):[],i=8-(s.length+n.length);if(i<0)throw new Error("Invalid IPv6 address");return[...s,...Array(i).fill("0"),...n].join(":")}static formatIPv6(e){let r=[];for(let s=0;s<16;s+=2)r.push((e[s]<<8|e[s+1]).toString(16));return this.compressIPv6(r.join(":"))}static compressIPv6(e){let r=e.split(":"),s=-1,n=0,i=-1,o=0;for(let a=0;a<r.length;a++)r[a]==="0"?(i===-1&&(i=a),o++):(o>n&&(s=i,n=o),i=-1,o=0);if(o>n&&(s=i,n=o),n>1){let a=r.slice(0,s).join(":"),c=r.slice(s+n).join(":");return`${a}::${c}`}return e}static parseCIDR(e){let[r,s]=e.split("/"),n=parseInt(s,10);if(this.isIPv4(r)){if(n<0||n>32)throw new Error("Invalid IPv4 prefix length");return[this.parseIPv4(r),n]}else{if(n<0||n>128)throw new Error("Invalid IPv6 prefix length");return[this.parseIPv6(r),n]}}static decodeIP(e){if(e.length===64&&parseInt(e,16)===0)return"::/0";if(e.length!==16)return e;let r=parseInt(e.slice(8),16).toString(2).split("").reduce((n,i)=>n+ +i,0),s=e.slice(0,8).replace(/(.{2})/g,n=>`${parseInt(n,16)}.`);return s=s.slice(0,-1),`${s}/${r}`}static toString(e){let r=new Uint8Array(e);if(r.length===4)return Array.from(r).join(".");if(r.length===16)return this.formatIPv6(r);if(r.length===8||r.length===32){let s=r.length/2,n=r.slice(0,s),i=r.slice(s);if(r.every(c=>c===0))return r.length===8?"0.0.0.0/0":"::/0";let a=i.reduce((c,d)=>c+(d.toString(2).match(/1/g)||[]).length,0);return r.length===8?`${Array.from(n).join(".")}/${a}`:`${this.formatIPv6(n)}/${a}`}return this.decodeIP(Eu.encode(e))}static fromString(e){if(e.includes("/")){let[s,n]=this.parseCIDR(e),i=new Uint8Array(s.length),o=n;for(let c=0;c<i.length;c++)o>=8?(i[c]=255,o-=8):o>0&&(i[c]=255<<8-o,o=0);let a=new Uint8Array(s.length*2);return a.set(s,0),a.set(i,s.length),a.buffer}let r=this.isIPv4(e)?this.parseIPv4(e):this.parseIPv6(e);return new Uint8Array(r).buffer}}});var QS,ZS,e2,_r,Cu,md,ka,t2,Vt,Tu=V(()=>{"use strict";g();y();ge();pe();JS();_r=class{teletexString;printableString;universalString;utf8String;bmpString;constructor(e={}){Object.assign(this,e)}toString(){return this.bmpString||this.printableString||this.teletexString||this.universalString||this.utf8String||""}};v([A({type:$.TeletexString})],_r.prototype,"teletexString",void 0);v([A({type:$.PrintableString})],_r.prototype,"printableString",void 0);v([A({type:$.UniversalString})],_r.prototype,"universalString",void 0);v([A({type:$.Utf8String})],_r.prototype,"utf8String",void 0);v([A({type:$.BmpString})],_r.prototype,"bmpString",void 0);_r=v([ie({type:re.Choice})],_r);Cu=class extends _r{ia5String;anyValue;constructor(e={}){super(e),Object.assign(this,e)}toString(){return this.ia5String||(this.anyValue?Eu.encode(this.anyValue):super.toString())}};v([A({type:$.IA5String})],Cu.prototype,"ia5String",void 0);v([A({type:$.Any})],Cu.prototype,"anyValue",void 0);Cu=v([ie({type:re.Choice})],Cu);md=class{type="";value=new Cu;constructor(e={}){Object.assign(this,e)}};v([A({type:$.ObjectIdentifier})],md.prototype,"type",void 0);v([A({type:Cu})],md.prototype,"value",void 0);ka=QS=class extends Ke{constructor(e){super(e),Object.setPrototypeOf(this,QS.prototype)}};ka=QS=v([ie({type:re.Set,itemType:md})],ka);t2=ZS=class extends Ke{constructor(e){super(e),Object.setPrototypeOf(this,ZS.prototype)}};t2=ZS=v([ie({type:re.Sequence,itemType:ka})],t2);Vt=e2=class extends t2{constructor(e){super(e),Object.setPrototypeOf(this,e2.prototype)}};Vt=e2=v([ie({type:re.Sequence})],Vt)});var KX,Aa,vp,et,gd=V(()=>{"use strict";g();y();ge();pe();G5();Tu();KX={fromASN:t=>wp.toString(Su.fromASN(t)),toASN:t=>Su.toASN(wp.fromString(t))},Aa=class{typeId="";value=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};v([A({type:$.ObjectIdentifier})],Aa.prototype,"typeId",void 0);v([A({type:$.Any,context:0})],Aa.prototype,"value",void 0);vp=class{nameAssigner;partyName=new _r;constructor(e={}){Object.assign(this,e)}};v([A({type:_r,optional:!0,context:0,implicit:!0})],vp.prototype,"nameAssigner",void 0);v([A({type:_r,context:1,implicit:!0})],vp.prototype,"partyName",void 0);et=class{otherName;rfc822Name;dNSName;x400Address;directoryName;ediPartyName;uniformResourceIdentifier;iPAddress;registeredID;constructor(e={}){Object.assign(this,e)}};v([A({type:Aa,context:0,implicit:!0})],et.prototype,"otherName",void 0);v([A({type:$.IA5String,context:1,implicit:!0})],et.prototype,"rfc822Name",void 0);v([A({type:$.IA5String,context:2,implicit:!0})],et.prototype,"dNSName",void 0);v([A({type:$.Any,context:3,implicit:!0})],et.prototype,"x400Address",void 0);v([A({type:Vt,context:4,implicit:!1})],et.prototype,"directoryName",void 0);v([A({type:vp,context:5})],et.prototype,"ediPartyName",void 0);v([A({type:$.IA5String,context:6,implicit:!0})],et.prototype,"uniformResourceIdentifier",void 0);v([A({type:$.OctetString,context:7,implicit:!0,converter:KX})],et.prototype,"iPAddress",void 0);v([A({type:$.ObjectIdentifier,context:8,implicit:!0})],et.prototype,"registeredID",void 0);et=v([ie({type:re.Choice})],et)});var Ia,Ra,X5,yd,Rb,bpe,xpe,r2,s2,n2,i2,lt,Kt=V(()=>{"use strict";g();y();Ia="1.3.6.1.5.5.7",Ra=`${Ia}.1`,X5=`${Ia}.2`,yd=`${Ia}.3`,Rb=`${Ia}.48`,bpe=`${X5}.1`,xpe=`${X5}.2`,r2=`${Rb}.1`,s2=`${Rb}.2`,n2=`${Rb}.3`,i2=`${Rb}.5`,lt="2.5.29"});var o2,Pb,po,bd,a2=V(()=>{"use strict";g();y();ge();pe();gd();Kt();Pb=`${Ra}.1`,po=class{accessMethod="";accessLocation=new et;constructor(e={}){Object.assign(this,e)}};v([A({type:$.ObjectIdentifier})],po.prototype,"accessMethod",void 0);v([A({type:et})],po.prototype,"accessLocation",void 0);bd=o2=class extends Ke{constructor(e){super(e),Object.setPrototypeOf(this,o2.prototype)}};bd=o2=v([ie({type:re.Sequence,itemType:po})],bd)});var Db,xd,bi,c2=V(()=>{"use strict";g();y();ge();pe();gd();Kt();Db=`${lt}.35`,xd=class extends Xe{},bi=class{keyIdentifier;authorityCertIssuer;authorityCertSerialNumber;constructor(e={}){e&&Object.assign(this,e)}};v([A({type:xd,context:0,optional:!0,implicit:!0})],bi.prototype,"keyIdentifier",void 0);v([A({type:et,context:1,optional:!0,implicit:!0,repeated:"sequence"})],bi.prototype,"authorityCertIssuer",void 0);v([A({type:$.Integer,context:2,optional:!0,implicit:!0,converter:Tt})],bi.prototype,"authorityCertSerialNumber",void 0)});var Bb,wd,Y5=V(()=>{"use strict";g();y();ge();pe();Kt();Bb=`${lt}.19`,wd=class{cA=!1;pathLenConstraint;constructor(e={}){Object.assign(this,e)}};v([A({type:$.Boolean,defaultValue:!1})],wd.prototype,"cA",void 0);v([A({type:$.Integer,optional:!0})],wd.prototype,"pathLenConstraint",void 0)});var d2,Jt,_p=V(()=>{"use strict";g();y();ge();pe();gd();Jt=d2=class extends Ke{constructor(e){super(e),Object.setPrototypeOf(this,d2.prototype)}};Jt=d2=v([ie({type:re.Sequence,itemType:et})],Jt)});var l2,GX,J5,Q5=V(()=>{"use strict";g();y();ge();pe();_p();Kt();GX=`${lt}.29`,J5=l2=class extends Jt{constructor(e){super(e),Object.setPrototypeOf(this,l2.prototype)}};J5=l2=v([ie({type:re.Sequence})],J5)});var u2,Ob,cme,mo,Sp,Ep,Lb,Cp,vd,Tp,Z5=V(()=>{"use strict";g();y();ge();pe();Kt();Ob=`${lt}.32`,cme=`${Ob}.0`,mo=class{ia5String;visibleString;bmpString;utf8String;constructor(e={}){Object.assign(this,e)}toString(){return this.ia5String||this.visibleString||this.bmpString||this.utf8String||""}};v([A({type:$.IA5String})],mo.prototype,"ia5String",void 0);v([A({type:$.VisibleString})],mo.prototype,"visibleString",void 0);v([A({type:$.BmpString})],mo.prototype,"bmpString",void 0);v([A({type:$.Utf8String})],mo.prototype,"utf8String",void 0);mo=v([ie({type:re.Choice})],mo);Sp=class{organization=new mo;noticeNumbers=[];constructor(e={}){Object.assign(this,e)}};v([A({type:mo})],Sp.prototype,"organization",void 0);v([A({type:$.Integer,repeated:"sequence"})],Sp.prototype,"noticeNumbers",void 0);Ep=class{noticeRef;explicitText;constructor(e={}){Object.assign(this,e)}};v([A({type:Sp,optional:!0})],Ep.prototype,"noticeRef",void 0);v([A({type:mo,optional:!0})],Ep.prototype,"explicitText",void 0);Lb=class{cPSuri;userNotice;constructor(e={}){Object.assign(this,e)}};v([A({type:$.IA5String})],Lb.prototype,"cPSuri",void 0);v([A({type:Ep})],Lb.prototype,"userNotice",void 0);Lb=v([ie({type:re.Choice})],Lb);Cp=class{policyQualifierId="";qualifier=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};v([A({type:$.ObjectIdentifier})],Cp.prototype,"policyQualifierId",void 0);v([A({type:$.Any})],Cp.prototype,"qualifier",void 0);vd=class{policyIdentifier="";policyQualifiers;constructor(e={}){Object.assign(this,e)}};v([A({type:$.ObjectIdentifier})],vd.prototype,"policyIdentifier",void 0);v([A({type:Cp,repeated:"sequence",optional:!0})],vd.prototype,"policyQualifiers",void 0);Tp=u2=class extends Ke{constructor(e){super(e),Object.setPrototypeOf(this,u2.prototype)}};Tp=u2=v([ie({type:re.Sequence,itemType:vd})],Tp)});var bme,kp,h2=V(()=>{"use strict";g();y();ge();pe();Kt();bme=`${lt}.20`,kp=class{value;constructor(e=0){this.value=e}};v([A({type:$.Integer})],kp.prototype,"value",void 0);kp=v([ie({type:re.Choice})],kp)});var kme,eP,tP=V(()=>{"use strict";g();y();ge();pe();Kt();h2();kme=`${lt}.27`,eP=class extends kp{};eP=v([ie({type:re.Choice})],eP)});var f2,Nb,Pn,Ap,go,xi,Pa,Ub=V(()=>{"use strict";g();y();ge();pe();Tu();gd();Kt();Nb=`${lt}.31`;(function(t){t[t.unused=1]="unused",t[t.keyCompromise=2]="keyCompromise",t[t.cACompromise=4]="cACompromise",t[t.affiliationChanged=8]="affiliationChanged",t[t.superseded=16]="superseded",t[t.cessationOfOperation=32]="cessationOfOperation",t[t.certificateHold=64]="certificateHold",t[t.privilegeWithdrawn=128]="privilegeWithdrawn",t[t.aACompromise=256]="aACompromise"})(Pn||(Pn={}));Ap=class extends yi{toJSON(){let e=[],r=this.toNumber();return r&Pn.aACompromise&&e.push("aACompromise"),r&Pn.affiliationChanged&&e.push("affiliationChanged"),r&Pn.cACompromise&&e.push("cACompromise"),r&Pn.certificateHold&&e.push("certificateHold"),r&Pn.cessationOfOperation&&e.push("cessationOfOperation"),r&Pn.keyCompromise&&e.push("keyCompromise"),r&Pn.privilegeWithdrawn&&e.push("privilegeWithdrawn"),r&Pn.superseded&&e.push("superseded"),r&Pn.unused&&e.push("unused"),e}toString(){return`[${this.toJSON().join(", ")}]`}},go=class{fullName;nameRelativeToCRLIssuer;constructor(e={}){Object.assign(this,e)}};v([A({type:et,context:0,repeated:"sequence",implicit:!0})],go.prototype,"fullName",void 0);v([A({type:ka,context:1,implicit:!0})],go.prototype,"nameRelativeToCRLIssuer",void 0);go=v([ie({type:re.Choice})],go);xi=class{distributionPoint;reasons;cRLIssuer;constructor(e={}){Object.assign(this,e)}};v([A({type:go,context:0,optional:!0})],xi.prototype,"distributionPoint",void 0);v([A({type:Ap,context:1,optional:!0,implicit:!0})],xi.prototype,"reasons",void 0);v([A({type:et,context:2,optional:!0,repeated:"sequence",implicit:!0})],xi.prototype,"cRLIssuer",void 0);Pa=f2=class extends Ke{constructor(e){super(e),Object.setPrototypeOf(this,f2.prototype)}};Pa=f2=v([ie({type:re.Sequence,itemType:xi})],Pa)});var p2,Wme,rP,sP=V(()=>{"use strict";g();y();ge();pe();Kt();Ub();Wme=`${lt}.46`,rP=p2=class extends Pa{constructor(e){super(e),Object.setPrototypeOf(this,p2.prototype)}};rP=p2=v([ie({type:re.Sequence,itemType:xi})],rP)});var t0e,fn,nP=V(()=>{"use strict";g();y();ge();pe();Kt();Ub();t0e=`${lt}.28`,fn=class t{static ONLY=!1;distributionPoint;onlyContainsUserCerts=t.ONLY;onlyContainsCACerts=t.ONLY;onlySomeReasons;indirectCRL=t.ONLY;onlyContainsAttributeCerts=t.ONLY;constructor(e={}){Object.assign(this,e)}};v([A({type:go,context:0,optional:!0})],fn.prototype,"distributionPoint",void 0);v([A({type:$.Boolean,context:1,defaultValue:fn.ONLY,implicit:!0})],fn.prototype,"onlyContainsUserCerts",void 0);v([A({type:$.Boolean,context:2,defaultValue:fn.ONLY,implicit:!0})],fn.prototype,"onlyContainsCACerts",void 0);v([A({type:Ap,context:3,optional:!0,implicit:!0})],fn.prototype,"onlySomeReasons",void 0);v([A({type:$.Boolean,context:4,defaultValue:fn.ONLY,implicit:!0})],fn.prototype,"indirectCRL",void 0);v([A({type:$.Boolean,context:5,defaultValue:fn.ONLY,implicit:!0})],fn.prototype,"onlyContainsAttributeCerts",void 0)});var iP,Ip,Rp,oP=V(()=>{"use strict";g();y();ge();pe();Kt();iP=`${lt}.21`;(function(t){t[t.unspecified=0]="unspecified",t[t.keyCompromise=1]="keyCompromise",t[t.cACompromise=2]="cACompromise",t[t.affiliationChanged=3]="affiliationChanged",t[t.superseded=4]="superseded",t[t.cessationOfOperation=5]="cessationOfOperation",t[t.certificateHold=6]="certificateHold",t[t.removeFromCRL=8]="removeFromCRL",t[t.privilegeWithdrawn=9]="privilegeWithdrawn",t[t.aACompromise=10]="aACompromise"})(Ip||(Ip={}));Rp=class{reason=Ip.unspecified;constructor(e=Ip.unspecified){this.reason=e}toJSON(){return Ip[this.reason]}toString(){return this.toJSON()}};v([A({type:$.Enumerated})],Rp.prototype,"reason",void 0);Rp=v([ie({type:re.Choice})],Rp)});var m2,Mb,Pp,g0e,aP,cP,dP,lP,uP,hP,fP=V(()=>{"use strict";g();y();ge();pe();Kt();Mb=`${lt}.37`,Pp=m2=class extends Ke{constructor(e){super(e),Object.setPrototypeOf(this,m2.prototype)}};Pp=m2=v([ie({type:re.Sequence,itemType:$.ObjectIdentifier})],Pp);g0e=`${Mb}.0`,aP=`${yd}.1`,cP=`${yd}.2`,dP=`${yd}.3`,lP=`${yd}.4`,uP=`${yd}.8`,hP=`${yd}.9`});var S0e,g2,pP=V(()=>{"use strict";g();y();ge();pe();Kt();S0e=`${lt}.54`,g2=class{value;constructor(e=new ArrayBuffer(0)){this.value=e}};v([A({type:$.Integer,converter:Tt})],g2.prototype,"value",void 0);g2=v([ie({type:re.Choice})],g2)});var mP,Dp,gP=V(()=>{"use strict";g();y();ge();pe();Kt();mP=`${lt}.24`,Dp=class{value=new Date;constructor(e){e&&(this.value=e)}};v([A({type:$.GeneralizedTime})],Dp.prototype,"value",void 0);Dp=v([ie({type:re.Choice})],Dp)});var y2,b2,yP,bP=V(()=>{"use strict";g();y();ge();pe();_p();Kt();b2=`${lt}.18`,yP=y2=class extends Jt{constructor(e){super(e),Object.setPrototypeOf(this,y2.prototype)}};yP=y2=v([ie({type:re.Sequence})],yP)});var jb,Dn,ku,xP=V(()=>{"use strict";g();y();pe();Kt();jb=`${lt}.15`;(function(t){t[t.digitalSignature=1]="digitalSignature",t[t.nonRepudiation=2]="nonRepudiation",t[t.keyEncipherment=4]="keyEncipherment",t[t.dataEncipherment=8]="dataEncipherment",t[t.keyAgreement=16]="keyAgreement",t[t.keyCertSign=32]="keyCertSign",t[t.cRLSign=64]="cRLSign",t[t.encipherOnly=128]="encipherOnly",t[t.decipherOnly=256]="decipherOnly"})(Dn||(Dn={}));ku=class extends yi{toJSON(){let e=this.toNumber(),r=[];return e&Dn.cRLSign&&r.push("crlSign"),e&Dn.dataEncipherment&&r.push("dataEncipherment"),e&Dn.decipherOnly&&r.push("decipherOnly"),e&Dn.digitalSignature&&r.push("digitalSignature"),e&Dn.encipherOnly&&r.push("encipherOnly"),e&Dn.keyAgreement&&r.push("keyAgreement"),e&Dn.keyCertSign&&r.push("keyCertSign"),e&Dn.keyEncipherment&&r.push("keyEncipherment"),e&Dn.nonRepudiation&&r.push("nonRepudiation"),r}toString(){return`[${this.toJSON().join(", ")}]`}}});var x2,Q0e,Au,$b,Fb,wP=V(()=>{"use strict";g();y();ge();pe();gd();Kt();Q0e=`${lt}.30`,Au=class{base=new et;minimum=0;maximum;constructor(e={}){Object.assign(this,e)}};v([A({type:et})],Au.prototype,"base",void 0);v([A({type:$.Integer,context:0,defaultValue:0,implicit:!0})],Au.prototype,"minimum",void 0);v([A({type:$.Integer,context:1,optional:!0,implicit:!0})],Au.prototype,"maximum",void 0);$b=x2=class extends Ke{constructor(e){super(e),Object.setPrototypeOf(this,x2.prototype)}};$b=x2=v([ie({type:re.Sequence,itemType:Au})],$b);Fb=class{permittedSubtrees;excludedSubtrees;constructor(e={}){Object.assign(this,e)}};v([A({type:$b,context:0,optional:!0,implicit:!0})],Fb.prototype,"permittedSubtrees",void 0);v([A({type:$b,context:1,optional:!0,implicit:!0})],Fb.prototype,"excludedSubtrees",void 0)});var oge,Hb,vP=V(()=>{"use strict";g();y();ge();pe();Kt();oge=`${lt}.36`,Hb=class{requireExplicitPolicy;inhibitPolicyMapping;constructor(e={}){Object.assign(this,e)}};v([A({type:$.Integer,context:0,implicit:!0,optional:!0,converter:Tt})],Hb.prototype,"requireExplicitPolicy",void 0);v([A({type:$.Integer,context:1,implicit:!0,optional:!0,converter:Tt})],Hb.prototype,"inhibitPolicyMapping",void 0)});var w2,fge,Bp,_P,SP=V(()=>{"use strict";g();y();ge();pe();Kt();fge=`${lt}.33`,Bp=class{issuerDomainPolicy="";subjectDomainPolicy="";constructor(e={}){Object.assign(this,e)}};v([A({type:$.ObjectIdentifier})],Bp.prototype,"issuerDomainPolicy",void 0);v([A({type:$.ObjectIdentifier})],Bp.prototype,"subjectDomainPolicy",void 0);_P=w2=class extends Ke{constructor(e){super(e),Object.setPrototypeOf(this,w2.prototype)}};_P=w2=v([ie({type:re.Sequence,itemType:Bp})],_P)});var v2,_2,qb,EP=V(()=>{"use strict";g();y();ge();pe();_p();Kt();_2=`${lt}.17`,qb=v2=class extends Jt{constructor(e){super(e),Object.setPrototypeOf(this,v2.prototype)}};qb=v2=v([ie({type:re.Sequence})],qb)});var Fr,S2=V(()=>{"use strict";g();y();ge();pe();Fr=class{type="";values=[];constructor(e={}){Object.assign(this,e)}};v([A({type:$.ObjectIdentifier})],Fr.prototype,"type",void 0);v([A({type:$.Any,repeated:"set"})],Fr.prototype,"values",void 0)});var E2,Oge,CP,TP=V(()=>{"use strict";g();y();ge();pe();S2();Kt();Oge=`${lt}.9`,CP=E2=class extends Ke{constructor(e){super(e),Object.setPrototypeOf(this,E2.prototype)}};CP=E2=v([ie({type:re.Sequence,itemType:Fr})],CP)});var C2,Es,kP=V(()=>{"use strict";g();y();Kt();c2();C2=`${lt}.14`,Es=class extends xd{}});var Gge,Vb,AP=V(()=>{"use strict";g();y();ge();pe();Kt();Gge=`${lt}.16`,Vb=class{notBefore;notAfter;constructor(e={}){Object.assign(this,e)}};v([A({type:$.GeneralizedTime,context:0,implicit:!0,optional:!0})],Vb.prototype,"notBefore",void 0);v([A({type:$.GeneralizedTime,context:1,implicit:!0,optional:!0})],Vb.prototype,"notAfter",void 0)});var Lp,zb,Wb,IP=V(()=>{"use strict";g();y();ge();pe();(function(t){t[t.keyUpdateAllowed=1]="keyUpdateAllowed",t[t.newExtensions=2]="newExtensions",t[t.pKIXCertificate=4]="pKIXCertificate"})(Lp||(Lp={}));zb=class extends yi{toJSON(){let e=[],r=this.toNumber();return r&Lp.pKIXCertificate&&e.push("pKIXCertificate"),r&Lp.newExtensions&&e.push("newExtensions"),r&Lp.keyUpdateAllowed&&e.push("keyUpdateAllowed"),e}toString(){return`[${this.toJSON().join(", ")}]`}},Wb=class{entrustVers="";entrustInfoFlags=new zb;constructor(e={}){Object.assign(this,e)}};v([A({type:$.GeneralString})],Wb.prototype,"entrustVers",void 0);v([A({type:zb})],Wb.prototype,"entrustInfoFlags",void 0)});var T2,aye,RP,PP=V(()=>{"use strict";g();y();ge();pe();Kt();a2();aye=`${Ra}.11`,RP=T2=class extends Ke{constructor(e){super(e),Object.setPrototypeOf(this,T2.prototype)}};RP=T2=v([ie({type:re.Sequence,itemType:po})],RP)});var DP=V(()=>{"use strict";g();y();a2();c2();Y5();Q5();Z5();tP();Ub();sP();nP();h2();oP();fP();pP();gP();bP();xP();wP();vP();SP();EP();TP();kP();AP();IP();PP()});var _e,_d=V(()=>{"use strict";g();y();ge();pe();Hs();_e=class t{algorithm="";parameters;constructor(e={}){Object.assign(this,e)}isEqual(e){return e instanceof t&&e.algorithm==this.algorithm&&(e.parameters&&this.parameters&&jS(e.parameters,this.parameters)||e.parameters===this.parameters)}};v([A({type:$.ObjectIdentifier})],_e.prototype,"algorithm",void 0);v([A({type:$.Any,optional:!0})],_e.prototype,"parameters",void 0)});var Hr,k2=V(()=>{"use strict";g();y();ge();pe();_d();Hr=class{algorithm=new _e;subjectPublicKey=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};v([A({type:_e})],Hr.prototype,"algorithm",void 0);v([A({type:$.BitString})],Hr.prototype,"subjectPublicKey",void 0)});var ur,Kb=V(()=>{"use strict";g();y();ge();pe();ur=class{utcTime;generalTime;constructor(e){if(e)if(typeof e=="string"||typeof e=="number"||e instanceof Date){let r=new Date(e);r.setMilliseconds(0),r.getUTCFullYear()>2049?this.generalTime=r:this.utcTime=r}else Object.assign(this,e)}getTime(){let e=this.utcTime||this.generalTime;if(!e)throw new Error("Cannot get time from CHOICE object");return e}};v([A({type:$.UTCTime})],ur.prototype,"utcTime",void 0);v([A({type:$.GeneralizedTime})],ur.prototype,"generalTime",void 0);ur=v([ie({type:re.Choice})],ur)});var yo,A2=V(()=>{"use strict";g();y();ge();pe();Kb();yo=class{notBefore=new ur(new Date);notAfter=new ur(new Date);constructor(e){e&&(this.notBefore=new ur(e.notBefore),this.notAfter=new ur(e.notAfter))}};v([A({type:ur})],yo.prototype,"notBefore",void 0);v([A({type:ur})],yo.prototype,"notAfter",void 0)});var I2,as,qs,Gb=V(()=>{"use strict";g();y();ge();pe();as=class t{static CRITICAL=!1;extnID="";critical=t.CRITICAL;extnValue=new Xe;constructor(e={}){Object.assign(this,e)}};v([A({type:$.ObjectIdentifier})],as.prototype,"extnID",void 0);v([A({type:$.Boolean,defaultValue:as.CRITICAL})],as.prototype,"critical",void 0);v([A({type:Xe})],as.prototype,"extnValue",void 0);qs=I2=class extends Ke{constructor(e){super(e),Object.setPrototypeOf(this,I2.prototype)}};qs=I2=v([ie({type:re.Sequence,itemType:as})],qs)});var wi,R2=V(()=>{"use strict";g();y();(function(t){t[t.v1=0]="v1",t[t.v2=1]="v2",t[t.v3=2]="v3"})(wi||(wi={}))});var qr,P2=V(()=>{"use strict";g();y();ge();pe();_d();Tu();k2();A2();Gb();R2();qr=class{version=wi.v1;serialNumber=new ArrayBuffer(0);signature=new _e;issuer=new Vt;validity=new yo;subject=new Vt;subjectPublicKeyInfo=new Hr;issuerUniqueID;subjectUniqueID;extensions;constructor(e={}){Object.assign(this,e)}};v([A({type:$.Integer,context:0,defaultValue:wi.v1})],qr.prototype,"version",void 0);v([A({type:$.Integer,converter:Tt})],qr.prototype,"serialNumber",void 0);v([A({type:_e})],qr.prototype,"signature",void 0);v([A({type:Vt})],qr.prototype,"issuer",void 0);v([A({type:yo})],qr.prototype,"validity",void 0);v([A({type:Vt})],qr.prototype,"subject",void 0);v([A({type:Hr})],qr.prototype,"subjectPublicKeyInfo",void 0);v([A({type:$.BitString,context:1,implicit:!0,optional:!0})],qr.prototype,"issuerUniqueID",void 0);v([A({type:$.BitString,context:2,implicit:!0,optional:!0})],qr.prototype,"subjectUniqueID",void 0);v([A({type:qs,context:3,optional:!0})],qr.prototype,"extensions",void 0)});var pn,BP=V(()=>{"use strict";g();y();ge();pe();_d();P2();pn=class{tbsCertificate=new qr;tbsCertificateRaw;signatureAlgorithm=new _e;signatureValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};v([A({type:qr,raw:!0})],pn.prototype,"tbsCertificate",void 0);v([A({type:_e})],pn.prototype,"signatureAlgorithm",void 0);v([A({type:$.BitString})],pn.prototype,"signatureValue",void 0)});var Sd,Vs,D2=V(()=>{"use strict";g();y();ge();pe();_d();Tu();Kb();Gb();Sd=class{userCertificate=new ArrayBuffer(0);revocationDate=new ur;crlEntryExtensions;constructor(e={}){Object.assign(this,e)}};v([A({type:$.Integer,converter:Tt})],Sd.prototype,"userCertificate",void 0);v([A({type:ur})],Sd.prototype,"revocationDate",void 0);v([A({type:as,optional:!0,repeated:"sequence"})],Sd.prototype,"crlEntryExtensions",void 0);Vs=class{version;signature=new _e;issuer=new Vt;thisUpdate=new ur;nextUpdate;revokedCertificates;crlExtensions;constructor(e={}){Object.assign(this,e)}};v([A({type:$.Integer,optional:!0})],Vs.prototype,"version",void 0);v([A({type:_e})],Vs.prototype,"signature",void 0);v([A({type:Vt})],Vs.prototype,"issuer",void 0);v([A({type:ur})],Vs.prototype,"thisUpdate",void 0);v([A({type:ur,optional:!0})],Vs.prototype,"nextUpdate",void 0);v([A({type:Sd,repeated:"sequence",optional:!0})],Vs.prototype,"revokedCertificates",void 0);v([A({type:as,optional:!0,context:0,repeated:"sequence"})],Vs.prototype,"crlExtensions",void 0)});var Ed,LP=V(()=>{"use strict";g();y();ge();pe();_d();D2();Ed=class{tbsCertList=new Vs;tbsCertListRaw;signatureAlgorithm=new _e;signature=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};v([A({type:Vs,raw:!0})],Ed.prototype,"tbsCertList",void 0);v([A({type:_e})],Ed.prototype,"signatureAlgorithm",void 0);v([A({type:$.BitString})],Ed.prototype,"signature",void 0)});var kt=V(()=>{"use strict";g();y();DP();_d();S2();BP();LP();Gb();gd();_p();Tu();Kt();k2();D2();P2();Kb();R2();A2()});var Bn,Op=V(()=>{"use strict";g();y();ge();pe();kt();Bn=class{issuer=new Vt;serialNumber=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};v([A({type:Vt})],Bn.prototype,"issuer",void 0);v([A({type:$.Integer,converter:Tt})],Bn.prototype,"serialNumber",void 0)});var Cd,B2=V(()=>{"use strict";g();y();ge();pe();kt();Op();Cd=class{subjectKeyIdentifier;issuerAndSerialNumber;constructor(e={}){Object.assign(this,e)}};v([A({type:Es,context:0,implicit:!0})],Cd.prototype,"subjectKeyIdentifier",void 0);v([A({type:Bn})],Cd.prototype,"issuerAndSerialNumber",void 0);Cd=v([ie({type:re.Choice})],Cd)});var Vr,Td,Np,Cs,Up,NP,Xb,vi=V(()=>{"use strict";g();y();ge();kt();pe();(function(t){t[t.v0=0]="v0",t[t.v1=1]="v1",t[t.v2=2]="v2",t[t.v3=3]="v3",t[t.v4=4]="v4",t[t.v5=5]="v5"})(Vr||(Vr={}));Td=class extends _e{};Td=v([ie({type:re.Sequence})],Td);Np=class extends _e{};Np=v([ie({type:re.Sequence})],Np);Cs=class extends _e{};Cs=v([ie({type:re.Sequence})],Cs);Up=class extends _e{};Up=v([ie({type:re.Sequence})],Up);NP=class extends _e{};NP=v([ie({type:re.Sequence})],NP);Xb=class extends _e{};Xb=v([ie({type:re.Sequence})],Xb)});var Ln,Yb=V(()=>{"use strict";g();y();ge();pe();Ln=class{attrType="";attrValues=[];constructor(e={}){Object.assign(this,e)}};v([A({type:$.ObjectIdentifier})],Ln.prototype,"attrType",void 0);v([A({type:$.Any,repeated:"set"})],Ln.prototype,"attrValues",void 0)});var L2,Ts,Mp,Jb=V(()=>{"use strict";g();y();ge();pe();B2();vi();Yb();Ts=class{version=Vr.v0;sid=new Cd;digestAlgorithm=new Td;signedAttrs;signedAttrsRaw;signatureAlgorithm=new Np;signature=new Xe;unsignedAttrs;constructor(e={}){Object.assign(this,e)}};v([A({type:$.Integer})],Ts.prototype,"version",void 0);v([A({type:Cd})],Ts.prototype,"sid",void 0);v([A({type:Td})],Ts.prototype,"digestAlgorithm",void 0);v([A({type:Ln,repeated:"set",context:0,implicit:!0,optional:!0,raw:!0})],Ts.prototype,"signedAttrs",void 0);v([A({type:Np})],Ts.prototype,"signatureAlgorithm",void 0);v([A({type:Xe})],Ts.prototype,"signature",void 0);v([A({type:Ln,repeated:"set",context:1,implicit:!0,optional:!0})],Ts.prototype,"unsignedAttrs",void 0);Mp=L2=class extends Ke{constructor(e){super(e),Object.setPrototypeOf(this,L2.prototype)}};Mp=L2=v([ie({type:re.Set,itemType:Ts})],Mp)});var UP,MP=V(()=>{"use strict";g();y();ge();pe();Jb();UP=class extends Ts{};UP=v([ie({type:re.Sequence})],UP)});var jP=V(()=>{"use strict";g();y();pe()});var $P,FP=V(()=>{"use strict";g();y();ge();kt();pe();$P=class extends ur{};$P=v([ie({type:re.Choice})],$P)});var HP=V(()=>{"use strict";g();y();MP();jP();FP()});var jp,qP=V(()=>{"use strict";g();y();ge();pe();kt();jp=class{acIssuer=new et;acSerial=0;attrs=[];constructor(e={}){Object.assign(this,e)}};v([A({type:et})],jp.prototype,"acIssuer",void 0);v([A({type:$.Integer})],jp.prototype,"acSerial",void 0);v([A({type:Fr,repeated:"sequence"})],jp.prototype,"attrs",void 0)});var O2,$p,N2=V(()=>{"use strict";g();y();ge();pe();$p=O2=class extends Ke{constructor(e){super(e),Object.setPrototypeOf(this,O2.prototype)}};$p=O2=v([ie({type:re.Sequence,itemType:$.ObjectIdentifier})],$p)});var Iu,VP=V(()=>{"use strict";g();y();ge();pe();N2();Iu=class{pathLenConstraint;permittedAttrs;excludedAttrs;permitUnSpecified=!0;constructor(e={}){Object.assign(this,e)}};v([A({type:$.Integer,optional:!0})],Iu.prototype,"pathLenConstraint",void 0);v([A({type:$p,implicit:!0,context:0,optional:!0})],Iu.prototype,"permittedAttrs",void 0);v([A({type:$p,implicit:!0,context:1,optional:!0})],Iu.prototype,"excludedAttrs",void 0);v([A({type:$.Boolean,defaultValue:!0})],Iu.prototype,"permitUnSpecified",void 0)});var mn,Fp=V(()=>{"use strict";g();y();ge();pe();kt();mn=class{issuer=new Jt;serial=new ArrayBuffer(0);issuerUID=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};v([A({type:Jt})],mn.prototype,"issuer",void 0);v([A({type:$.Integer,converter:Tt})],mn.prototype,"serial",void 0);v([A({type:$.BitString,optional:!0})],mn.prototype,"issuerUID",void 0)});var U2,gn,Hp=V(()=>{"use strict";g();y();ge();pe();kt();(function(t){t[t.publicKey=0]="publicKey",t[t.publicKeyCert=1]="publicKeyCert",t[t.otherObjectTypes=2]="otherObjectTypes"})(U2||(U2={}));gn=class{digestedObjectType=U2.publicKey;otherObjectTypeID;digestAlgorithm=new _e;objectDigest=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};v([A({type:$.Enumerated})],gn.prototype,"digestedObjectType",void 0);v([A({type:$.ObjectIdentifier,optional:!0})],gn.prototype,"otherObjectTypeID",void 0);v([A({type:_e})],gn.prototype,"digestAlgorithm",void 0);v([A({type:$.BitString})],gn.prototype,"objectDigest",void 0)});var kd,M2=V(()=>{"use strict";g();y();ge();pe();kt();Fp();Hp();kd=class{issuerName;baseCertificateID;objectDigestInfo;constructor(e={}){Object.assign(this,e)}};v([A({type:Jt,optional:!0})],kd.prototype,"issuerName",void 0);v([A({type:mn,context:0,implicit:!0,optional:!0})],kd.prototype,"baseCertificateID",void 0);v([A({type:gn,context:1,implicit:!0,optional:!0})],kd.prototype,"objectDigestInfo",void 0)});var Ad,j2=V(()=>{"use strict";g();y();ge();pe();kt();M2();Ad=class{v1Form;v2Form;constructor(e={}){Object.assign(this,e)}};v([A({type:et,repeated:"sequence"})],Ad.prototype,"v1Form",void 0);v([A({type:kd,context:0,implicit:!0})],Ad.prototype,"v2Form",void 0);Ad=v([ie({type:re.Choice})],Ad)});var Id,$2=V(()=>{"use strict";g();y();ge();pe();Id=class{notBeforeTime=new Date;notAfterTime=new Date;constructor(e={}){Object.assign(this,e)}};v([A({type:$.GeneralizedTime})],Id.prototype,"notBeforeTime",void 0);v([A({type:$.GeneralizedTime})],Id.prototype,"notAfterTime",void 0)});var Da,F2=V(()=>{"use strict";g();y();ge();pe();kt();Fp();Hp();Da=class{baseCertificateID;entityName;objectDigestInfo;constructor(e={}){Object.assign(this,e)}};v([A({type:mn,implicit:!0,context:0,optional:!0})],Da.prototype,"baseCertificateID",void 0);v([A({type:Jt,implicit:!0,context:1,optional:!0})],Da.prototype,"entityName",void 0);v([A({type:gn,implicit:!0,context:2,optional:!0})],Da.prototype,"objectDigestInfo",void 0)});var H2,ks,q2=V(()=>{"use strict";g();y();ge();pe();kt();F2();j2();$2();(function(t){t[t.v2=1]="v2"})(H2||(H2={}));ks=class{version=H2.v2;holder=new Da;issuer=new Ad;signature=new _e;serialNumber=new ArrayBuffer(0);attrCertValidityPeriod=new Id;attributes=[];issuerUniqueID;extensions;constructor(e={}){Object.assign(this,e)}};v([A({type:$.Integer})],ks.prototype,"version",void 0);v([A({type:Da})],ks.prototype,"holder",void 0);v([A({type:Ad})],ks.prototype,"issuer",void 0);v([A({type:_e})],ks.prototype,"signature",void 0);v([A({type:$.Integer,converter:Tt})],ks.prototype,"serialNumber",void 0);v([A({type:Id})],ks.prototype,"attrCertValidityPeriod",void 0);v([A({type:Fr,repeated:"sequence"})],ks.prototype,"attributes",void 0);v([A({type:$.BitString,optional:!0})],ks.prototype,"issuerUniqueID",void 0);v([A({type:qs,optional:!0})],ks.prototype,"extensions",void 0)});var Rd,zP=V(()=>{"use strict";g();y();ge();pe();kt();q2();Rd=class{acinfo=new ks;signatureAlgorithm=new _e;signatureValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};v([A({type:ks})],Rd.prototype,"acinfo",void 0);v([A({type:_e})],Rd.prototype,"signatureAlgorithm",void 0);v([A({type:$.BitString})],Rd.prototype,"signatureValue",void 0)});var qp,Ru,V2=V(()=>{"use strict";g();y();pe();(function(t){t[t.unmarked=1]="unmarked",t[t.unclassified=2]="unclassified",t[t.restricted=4]="restricted",t[t.confidential=8]="confidential",t[t.secret=16]="secret",t[t.topSecret=32]="topSecret"})(qp||(qp={}));Ru=class extends yi{}});var Pu,z2=V(()=>{"use strict";g();y();ge();pe();Pu=class{type="";value=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};v([A({type:$.ObjectIdentifier,implicit:!0,context:0})],Pu.prototype,"type",void 0);v([A({type:$.Any,implicit:!0,context:1})],Pu.prototype,"value",void 0)});var Vp,WP=V(()=>{"use strict";g();y();ge();pe();V2();z2();Vp=class{policyId="";classList=new Ru(qp.unclassified);securityCategories;constructor(e={}){Object.assign(this,e)}};v([A({type:$.ObjectIdentifier})],Vp.prototype,"policyId",void 0);v([A({type:Ru,defaultValue:new Ru(qp.unclassified)})],Vp.prototype,"classList",void 0);v([A({type:Pu,repeated:"set"})],Vp.prototype,"securityCategories",void 0)});var Du,Qb,KP=V(()=>{"use strict";g();y();ge();pe();kt();Du=class{cotets;oid;string;constructor(e={}){Object.assign(this,e)}};v([A({type:Xe})],Du.prototype,"cotets",void 0);v([A({type:$.ObjectIdentifier})],Du.prototype,"oid",void 0);v([A({type:$.Utf8String})],Du.prototype,"string",void 0);Qb=class{policyAuthority;values=[];constructor(e={}){Object.assign(this,e)}};v([A({type:Jt,implicit:!0,context:0,optional:!0})],Qb.prototype,"policyAuthority",void 0);v([A({type:Du,repeated:"sequence"})],Qb.prototype,"values",void 0)});var yve,bve,xve,wve,zp,vve,_ve,Sve,Eve,Cve,W2,Tve,GP=V(()=>{"use strict";g();y();kt();yve=`${Ra}.4`,bve=`${Ra}.6`,xve=`${Ra}.10`,wve=`${lt}.55`,zp=`${Ia}.10`,vve=`${zp}.1`,_ve=`${zp}.2`,Sve=`${zp}.3`,Eve=`${zp}.4`,Cve=`${zp}.6`,W2="2.5.4",Tve=`${W2}.72`});var K2,Bu,Lu,Zb,G2=V(()=>{"use strict";g();y();ge();pe();kt();Fp();Hp();Bu=class{targetCertificate=new mn;targetName;certDigestInfo;constructor(e={}){Object.assign(this,e)}};v([A({type:mn})],Bu.prototype,"targetCertificate",void 0);v([A({type:et,optional:!0})],Bu.prototype,"targetName",void 0);v([A({type:gn,optional:!0})],Bu.prototype,"certDigestInfo",void 0);Lu=class{targetName;targetGroup;targetCert;constructor(e={}){Object.assign(this,e)}};v([A({type:et,context:0,implicit:!0})],Lu.prototype,"targetName",void 0);v([A({type:et,context:1,implicit:!0})],Lu.prototype,"targetGroup",void 0);v([A({type:Bu,context:2,implicit:!0})],Lu.prototype,"targetCert",void 0);Lu=v([ie({type:re.Choice})],Lu);Zb=K2=class extends Ke{constructor(e){super(e),Object.setPrototypeOf(this,K2.prototype)}};Zb=K2=v([ie({type:re.Sequence,itemType:Lu})],Zb)});var X2,XP,YP=V(()=>{"use strict";g();y();ge();pe();G2();XP=X2=class extends Ke{constructor(e){super(e),Object.setPrototypeOf(this,X2.prototype)}};XP=X2=v([ie({type:re.Sequence,itemType:Zb})],XP)});var ex,JP=V(()=>{"use strict";g();y();ge();pe();kt();ex=class{roleAuthority;roleName;constructor(e={}){Object.assign(this,e)}};v([A({type:Jt,implicit:!0,context:0,optional:!0})],ex.prototype,"roleAuthority",void 0);v([A({type:et,implicit:!0,context:1})],ex.prototype,"roleName",void 0)});var Wp,QP=V(()=>{"use strict";g();y();ge();pe();kt();Wp=class{service=new et;ident=new et;authInfo;constructor(e={}){Object.assign(this,e)}};v([A({type:et})],Wp.prototype,"service",void 0);v([A({type:et})],Wp.prototype,"ident",void 0);v([A({type:Xe,optional:!0})],Wp.prototype,"authInfo",void 0)});var Y2=V(()=>{"use strict";g();y();qP();VP();j2();$2();N2();zP();q2();V2();WP();F2();KP();Fp();Hp();GP();YP();JP();z2();QP();G2();M2()});var J2,Kp,Pd,Dd,tx=V(()=>{"use strict";g();y();ge();pe();kt();Y2();Kp=class{otherCertFormat="";otherCert=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};v([A({type:$.ObjectIdentifier})],Kp.prototype,"otherCertFormat",void 0);v([A({type:$.Any})],Kp.prototype,"otherCert",void 0);Pd=class{certificate;v2AttrCert;other;constructor(e={}){Object.assign(this,e)}};v([A({type:pn})],Pd.prototype,"certificate",void 0);v([A({type:Rd,context:2,implicit:!0})],Pd.prototype,"v2AttrCert",void 0);v([A({type:Kp,context:3,implicit:!0})],Pd.prototype,"other",void 0);Pd=v([ie({type:re.Choice})],Pd);Dd=J2=class extends Ke{constructor(e){super(e),Object.setPrototypeOf(this,J2.prototype)}};Dd=J2=v([ie({type:re.Set,itemType:Pd})],Dd)});var yn,ZP=V(()=>{"use strict";g();y();ge();pe();yn=class{contentType="";content=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};v([A({type:$.ObjectIdentifier})],yn.prototype,"contentType",void 0);v([A({type:$.Any,context:0})],yn.prototype,"content",void 0)});var Ou,Bd,Q2=V(()=>{"use strict";g();y();ge();pe();Ou=class{single;any;constructor(e={}){Object.assign(this,e)}};v([A({type:Xe})],Ou.prototype,"single",void 0);v([A({type:$.Any})],Ou.prototype,"any",void 0);Ou=v([ie({type:re.Choice})],Ou);Bd=class{eContentType="";eContent;constructor(e={}){Object.assign(this,e)}};v([A({type:$.ObjectIdentifier})],Bd.prototype,"eContentType",void 0);v([A({type:Ou,context:0,optional:!0})],Bd.prototype,"eContent",void 0)});var Gp,Ba,Z2=V(()=>{"use strict";g();y();ge();pe();vi();Gp=class{value;constructedValue;constructor(e={}){Object.assign(this,e)}};v([A({type:Xe,context:0,implicit:!0,optional:!0})],Gp.prototype,"value",void 0);v([A({type:Xe,converter:P5,context:0,implicit:!0,optional:!0,repeated:"sequence"})],Gp.prototype,"constructedValue",void 0);Gp=v([ie({type:re.Choice})],Gp);Ba=class{contentType="";contentEncryptionAlgorithm=new Up;encryptedContent;constructor(e={}){Object.assign(this,e)}};v([A({type:$.ObjectIdentifier})],Ba.prototype,"contentType",void 0);v([A({type:Up})],Ba.prototype,"contentEncryptionAlgorithm",void 0);v([A({type:Gp,optional:!0})],Ba.prototype,"encryptedContent",void 0)});var La,eE=V(()=>{"use strict";g();y();ge();pe();La=class{keyAttrId="";keyAttr;constructor(e={}){Object.assign(this,e)}};v([A({type:$.ObjectIdentifier})],La.prototype,"keyAttrId",void 0);v([A({type:$.Any,optional:!0})],La.prototype,"keyAttr",void 0)});var tE,Nu,Uu,Xp,rx,Yp,Ld,bo,rE=V(()=>{"use strict";g();y();ge();pe();kt();vi();Op();eE();Nu=class{subjectKeyIdentifier=new Es;date;other;constructor(e={}){Object.assign(this,e)}};v([A({type:Es})],Nu.prototype,"subjectKeyIdentifier",void 0);v([A({type:$.GeneralizedTime,optional:!0})],Nu.prototype,"date",void 0);v([A({type:La,optional:!0})],Nu.prototype,"other",void 0);Uu=class{rKeyId;issuerAndSerialNumber;constructor(e={}){Object.assign(this,e)}};v([A({type:Nu,context:0,implicit:!0,optional:!0})],Uu.prototype,"rKeyId",void 0);v([A({type:Bn,optional:!0})],Uu.prototype,"issuerAndSerialNumber",void 0);Uu=v([ie({type:re.Choice})],Uu);Xp=class{rid=new Uu;encryptedKey=new Xe;constructor(e={}){Object.assign(this,e)}};v([A({type:Uu})],Xp.prototype,"rid",void 0);v([A({type:Xe})],Xp.prototype,"encryptedKey",void 0);rx=tE=class extends Ke{constructor(e){super(e),Object.setPrototypeOf(this,tE.prototype)}};rx=tE=v([ie({type:re.Sequence,itemType:Xp})],rx);Yp=class{algorithm=new _e;publicKey=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};v([A({type:_e})],Yp.prototype,"algorithm",void 0);v([A({type:$.BitString})],Yp.prototype,"publicKey",void 0);Ld=class{subjectKeyIdentifier;originatorKey;issuerAndSerialNumber;constructor(e={}){Object.assign(this,e)}};v([A({type:Es,context:0,implicit:!0,optional:!0})],Ld.prototype,"subjectKeyIdentifier",void 0);v([A({type:Yp,context:1,implicit:!0,optional:!0})],Ld.prototype,"originatorKey",void 0);v([A({type:Bn,optional:!0})],Ld.prototype,"issuerAndSerialNumber",void 0);Ld=v([ie({type:re.Choice})],Ld);bo=class{version=Vr.v3;originator=new Ld;ukm;keyEncryptionAlgorithm=new Cs;recipientEncryptedKeys=new rx;constructor(e={}){Object.assign(this,e)}};v([A({type:$.Integer})],bo.prototype,"version",void 0);v([A({type:Ld,context:0})],bo.prototype,"originator",void 0);v([A({type:Xe,context:1,optional:!0})],bo.prototype,"ukm",void 0);v([A({type:Cs})],bo.prototype,"keyEncryptionAlgorithm",void 0);v([A({type:rx})],bo.prototype,"recipientEncryptedKeys",void 0)});var Mu,Oa,sE=V(()=>{"use strict";g();y();ge();pe();kt();vi();Op();Mu=class{subjectKeyIdentifier;issuerAndSerialNumber;constructor(e={}){Object.assign(this,e)}};v([A({type:Es,context:0,implicit:!0})],Mu.prototype,"subjectKeyIdentifier",void 0);v([A({type:Bn})],Mu.prototype,"issuerAndSerialNumber",void 0);Mu=v([ie({type:re.Choice})],Mu);Oa=class{version=Vr.v0;rid=new Mu;keyEncryptionAlgorithm=new Cs;encryptedKey=new Xe;constructor(e={}){Object.assign(this,e)}};v([A({type:$.Integer})],Oa.prototype,"version",void 0);v([A({type:Mu})],Oa.prototype,"rid",void 0);v([A({type:Cs})],Oa.prototype,"keyEncryptionAlgorithm",void 0);v([A({type:Xe})],Oa.prototype,"encryptedKey",void 0)});var Od,Na,nE=V(()=>{"use strict";g();y();ge();pe();eE();vi();Od=class{keyIdentifier=new Xe;date;other;constructor(e={}){Object.assign(this,e)}};v([A({type:Xe})],Od.prototype,"keyIdentifier",void 0);v([A({type:$.GeneralizedTime,optional:!0})],Od.prototype,"date",void 0);v([A({type:La,optional:!0})],Od.prototype,"other",void 0);Na=class{version=Vr.v4;kekid=new Od;keyEncryptionAlgorithm=new Cs;encryptedKey=new Xe;constructor(e={}){Object.assign(this,e)}};v([A({type:$.Integer})],Na.prototype,"version",void 0);v([A({type:Od})],Na.prototype,"kekid",void 0);v([A({type:Cs})],Na.prototype,"keyEncryptionAlgorithm",void 0);v([A({type:Xe})],Na.prototype,"encryptedKey",void 0)});var Ua,iE=V(()=>{"use strict";g();y();ge();pe();vi();Ua=class{version=Vr.v0;keyDerivationAlgorithm;keyEncryptionAlgorithm=new Cs;encryptedKey=new Xe;constructor(e={}){Object.assign(this,e)}};v([A({type:$.Integer})],Ua.prototype,"version",void 0);v([A({type:Xb,context:0,optional:!0})],Ua.prototype,"keyDerivationAlgorithm",void 0);v([A({type:Cs})],Ua.prototype,"keyEncryptionAlgorithm",void 0);v([A({type:Xe})],Ua.prototype,"encryptedKey",void 0)});var Jp,xo,oE=V(()=>{"use strict";g();y();ge();pe();rE();sE();nE();iE();Jp=class{oriType="";oriValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};v([A({type:$.ObjectIdentifier})],Jp.prototype,"oriType",void 0);v([A({type:$.Any})],Jp.prototype,"oriValue",void 0);xo=class{ktri;kari;kekri;pwri;ori;constructor(e={}){Object.assign(this,e)}};v([A({type:Oa,optional:!0})],xo.prototype,"ktri",void 0);v([A({type:bo,context:1,implicit:!0,optional:!0})],xo.prototype,"kari",void 0);v([A({type:Na,context:2,implicit:!0,optional:!0})],xo.prototype,"kekri",void 0);v([A({type:Ua,context:3,implicit:!0,optional:!0})],xo.prototype,"pwri",void 0);v([A({type:Jp,context:4,implicit:!0,optional:!0})],xo.prototype,"ori",void 0);xo=v([ie({type:re.Choice})],xo)});var aE,Qp,cE=V(()=>{"use strict";g();y();ge();pe();oE();Qp=aE=class extends Ke{constructor(e){super(e),Object.setPrototypeOf(this,aE.prototype)}};Qp=aE=v([ie({type:re.Set,itemType:xo})],Qp)});var dE,eD,i2e,o2e,ju,sx,$u,nx=V(()=>{"use strict";g();y();ge();pe();kt();eD=`${Ia}.16`,i2e=`${eD}.2`,o2e=`${eD}.4`,ju=class{otherRevInfoFormat="";otherRevInfo=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};v([A({type:$.ObjectIdentifier})],ju.prototype,"otherRevInfoFormat",void 0);v([A({type:$.Any})],ju.prototype,"otherRevInfo",void 0);sx=class{other=new ju;constructor(e={}){Object.assign(this,e)}};v([A({type:ju,context:1,implicit:!0})],sx.prototype,"other",void 0);sx=v([ie({type:re.Choice})],sx);$u=dE=class extends Ke{constructor(e){super(e),Object.setPrototypeOf(this,dE.prototype)}};$u=dE=v([ie({type:re.Set,itemType:sx})],$u)});var Fu,lE=V(()=>{"use strict";g();y();ge();pe();tx();nx();Fu=class{certs;crls;constructor(e={}){Object.assign(this,e)}};v([A({type:Dd,context:0,implicit:!0,optional:!0})],Fu.prototype,"certs",void 0);v([A({type:$u,context:1,implicit:!0,optional:!0})],Fu.prototype,"crls",void 0)});var uE,hE,Nd,tD=V(()=>{"use strict";g();y();ge();pe();vi();Yb();cE();lE();Z2();hE=uE=class extends Ke{constructor(e){super(e),Object.setPrototypeOf(this,uE.prototype)}};hE=uE=v([ie({type:re.Set,itemType:Ln})],hE);Nd=class{version=Vr.v0;originatorInfo;recipientInfos=new Qp;encryptedContentInfo=new Ba;unprotectedAttrs;constructor(e={}){Object.assign(this,e)}};v([A({type:$.Integer})],Nd.prototype,"version",void 0);v([A({type:Fu,context:0,implicit:!0,optional:!0})],Nd.prototype,"originatorInfo",void 0);v([A({type:Qp})],Nd.prototype,"recipientInfos",void 0);v([A({type:Ba})],Nd.prototype,"encryptedContentInfo",void 0);v([A({type:hE,context:1,implicit:!0,optional:!0})],Nd.prototype,"unprotectedAttrs",void 0)});var rD,sD=V(()=>{"use strict";g();y();rD="1.2.840.113549.1.7.2"});var fE,ix,wo,nD=V(()=>{"use strict";g();y();ge();pe();tx();vi();Q2();nx();Jb();ix=fE=class extends Ke{constructor(e){super(e),Object.setPrototypeOf(this,fE.prototype)}};ix=fE=v([ie({type:re.Set,itemType:Td})],ix);wo=class{version=Vr.v0;digestAlgorithms=new ix;encapContentInfo=new Bd;certificates;crls;signerInfos=new Mp;constructor(e={}){Object.assign(this,e)}};v([A({type:$.Integer})],wo.prototype,"version",void 0);v([A({type:ix})],wo.prototype,"digestAlgorithms",void 0);v([A({type:Bd})],wo.prototype,"encapContentInfo",void 0);v([A({type:Dd,context:0,implicit:!0,optional:!0})],wo.prototype,"certificates",void 0);v([A({type:$u,context:1,implicit:!0,optional:!0})],wo.prototype,"crls",void 0);v([A({type:Mp})],wo.prototype,"signerInfos",void 0)});var Zp=V(()=>{"use strict";g();y();HP();Yb();tx();ZP();Q2();Z2();tD();Op();nE();rE();sE();sD();lE();iE();oE();cE();nx();nD();B2();Jb();vi()});var Ud,em,ox,tm,rm,sm,pE,mE,gE,yE=V(()=>{"use strict";g();y();Ud="1.2.840.10045.2.1",em="1.2.840.10045.4.1",ox="1.2.840.10045.4.3.1",tm="1.2.840.10045.4.3.2",rm="1.2.840.10045.4.3.3",sm="1.2.840.10045.4.3.4",pE="1.2.840.10045.3.1.7",mE="1.3.132.0.34",gE="1.3.132.0.35"});function nm(t){return new _e({algorithm:t})}var oD,gEe,aD,cD,dD,lD=V(()=>{"use strict";g();y();kt();yE();oD=nm(em),gEe=nm(ox),aD=nm(tm),cD=nm(rm),dD=nm(sm)});var im,bE,Hu,xE,_i,wE=V(()=>{"use strict";g();y();ge();pe();im=class{fieldType;parameters;constructor(e={}){Object.assign(this,e)}};v([A({type:$.ObjectIdentifier})],im.prototype,"fieldType",void 0);v([A({type:$.Any})],im.prototype,"parameters",void 0);im=v([ie({type:re.Sequence})],im);bE=class extends Xe{},Hu=class{a;b;seed;constructor(e={}){Object.assign(this,e)}};v([A({type:$.OctetString})],Hu.prototype,"a",void 0);v([A({type:$.OctetString})],Hu.prototype,"b",void 0);v([A({type:$.BitString,optional:!0})],Hu.prototype,"seed",void 0);Hu=v([ie({type:re.Sequence})],Hu);(function(t){t[t.ecpVer1=1]="ecpVer1"})(xE||(xE={}));_i=class{version=xE.ecpVer1;fieldID;curve;base;order;cofactor;constructor(e={}){Object.assign(this,e)}};v([A({type:$.Integer})],_i.prototype,"version",void 0);v([A({type:im})],_i.prototype,"fieldID",void 0);v([A({type:Hu})],_i.prototype,"curve",void 0);v([A({type:bE})],_i.prototype,"base",void 0);v([A({type:$.Integer,converter:Tt})],_i.prototype,"order",void 0);v([A({type:$.Integer,optional:!0})],_i.prototype,"cofactor",void 0);_i=v([ie({type:re.Sequence})],_i)});var Si,vE=V(()=>{"use strict";g();y();ge();pe();wE();Si=class{namedCurve;implicitCurve;specifiedCurve;constructor(e={}){Object.assign(this,e)}};v([A({type:$.ObjectIdentifier})],Si.prototype,"namedCurve",void 0);v([A({type:$.Null})],Si.prototype,"implicitCurve",void 0);v([A({type:_i})],Si.prototype,"specifiedCurve",void 0);Si=v([ie({type:re.Choice})],Si)});var qu,uD=V(()=>{"use strict";g();y();ge();pe();vE();qu=class{version=1;privateKey=new Xe;parameters;publicKey;constructor(e={}){Object.assign(this,e)}};v([A({type:$.Integer})],qu.prototype,"version",void 0);v([A({type:Xe})],qu.prototype,"privateKey",void 0);v([A({type:Si,context:0,optional:!0})],qu.prototype,"parameters",void 0);v([A({type:$.BitString,context:1,optional:!0})],qu.prototype,"publicKey",void 0)});var Md,hD=V(()=>{"use strict";g();y();ge();pe();Md=class{r=new ArrayBuffer(0);s=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};v([A({type:$.Integer,converter:Tt})],Md.prototype,"r",void 0);v([A({type:$.Integer,converter:Tt})],Md.prototype,"s",void 0)});var _E=V(()=>{"use strict";g();y();lD();vE();uD();hD();yE();wE()});var As,Ei,fD,pD,Ma,mD,gD,Vu,yD,ax,zu,Wu,SE,EE,jd,cx,$d,Fd,Hd,bD,xD,wD,vD,ja,om=V(()=>{"use strict";g();y();As="1.2.840.113549.1.1",Ei=`${As}.1`,fD=`${As}.7`,pD=`${As}.9`,Ma=`${As}.10`,mD=`${As}.2`,gD=`${As}.4`,Vu=`${As}.5`,yD=`${As}.14`,ax=`${As}.11`,zu=`${As}.12`,Wu=`${As}.13`,SE=`${As}.15`,EE=`${As}.16`,jd="1.3.14.3.2.26",cx="2.16.840.1.101.3.4.2.4",$d="2.16.840.1.101.3.4.2.1",Fd="2.16.840.1.101.3.4.2.2",Hd="2.16.840.1.101.3.4.2.3",bD="2.16.840.1.101.3.4.2.5",xD="2.16.840.1.101.3.4.2.6",wD="1.2.840.113549.2.2",vD="1.2.840.113549.2.5",ja=`${As}.8`});function Dr(t){return new _e({algorithm:t,parameters:null})}var nCe,iCe,vo,oCe,aCe,cCe,dCe,lCe,uCe,dx,CE,hCe,fCe,pCe,mCe,gCe,yCe,bCe,xCe,wCe,vCe,lx=V(()=>{"use strict";g();y();pe();kt();om();nCe=Dr(wD),iCe=Dr(vD),vo=Dr(jd),oCe=Dr(cx),aCe=Dr($d),cCe=Dr(Fd),dCe=Dr(Hd),lCe=Dr(bD),uCe=Dr(xD),dx=new _e({algorithm:ja,parameters:Ee.serialize(vo)}),CE=new _e({algorithm:pD,parameters:Ee.serialize(Su.toASN(new Uint8Array([218,57,163,238,94,107,75,13,50,85,191,239,149,96,24,144,175,216,7,9]).buffer))}),hCe=Dr(Ei),fCe=Dr(mD),pCe=Dr(gD),mCe=Dr(Vu),gCe=Dr(SE),yCe=Dr(EE),bCe=Dr(zu),xCe=Dr(Wu),wCe=Dr(SE),vCe=Dr(EE)});var Ku,RCe,_D=V(()=>{"use strict";g();y();ge();pe();kt();om();lx();Ku=class{hashAlgorithm=new _e(vo);maskGenAlgorithm=new _e({algorithm:ja,parameters:Ee.serialize(vo)});pSourceAlgorithm=new _e(CE);constructor(e={}){Object.assign(this,e)}};v([A({type:_e,context:0,defaultValue:vo})],Ku.prototype,"hashAlgorithm",void 0);v([A({type:_e,context:1,defaultValue:dx})],Ku.prototype,"maskGenAlgorithm",void 0);v([A({type:_e,context:2,defaultValue:CE})],Ku.prototype,"pSourceAlgorithm",void 0);RCe=new _e({algorithm:fD,parameters:Ee.serialize(new Ku)})});var Ci,jCe,SD=V(()=>{"use strict";g();y();ge();pe();kt();om();lx();Ci=class{hashAlgorithm=new _e(vo);maskGenAlgorithm=new _e({algorithm:ja,parameters:Ee.serialize(vo)});saltLength=20;trailerField=1;constructor(e={}){Object.assign(this,e)}};v([A({type:_e,context:0,defaultValue:vo})],Ci.prototype,"hashAlgorithm",void 0);v([A({type:_e,context:1,defaultValue:dx})],Ci.prototype,"maskGenAlgorithm",void 0);v([A({type:$.Integer,context:2,defaultValue:20})],Ci.prototype,"saltLength",void 0);v([A({type:$.Integer,context:3,defaultValue:1})],Ci.prototype,"trailerField",void 0);jCe=new _e({algorithm:Ma,parameters:Ee.serialize(new Ci)})});var qd,ED=V(()=>{"use strict";g();y();ge();kt();pe();qd=class{digestAlgorithm=new _e;digest=new Xe;constructor(e={}){Object.assign(this,e)}};v([A({type:_e})],qd.prototype,"digestAlgorithm",void 0);v([A({type:Xe})],qd.prototype,"digest",void 0)});var CD=V(()=>{"use strict";g();y();_D();SD();ED()});var TE,Gu,ux,kE=V(()=>{"use strict";g();y();ge();pe();Gu=class{prime=new ArrayBuffer(0);exponent=new ArrayBuffer(0);coefficient=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};v([A({type:$.Integer,converter:Tt})],Gu.prototype,"prime",void 0);v([A({type:$.Integer,converter:Tt})],Gu.prototype,"exponent",void 0);v([A({type:$.Integer,converter:Tt})],Gu.prototype,"coefficient",void 0);ux=TE=class extends Ke{constructor(e){super(e),Object.setPrototypeOf(this,TE.prototype)}};ux=TE=v([ie({type:re.Sequence,itemType:Gu})],ux)});var bn,TD=V(()=>{"use strict";g();y();ge();pe();kE();bn=class{version=0;modulus=new ArrayBuffer(0);publicExponent=new ArrayBuffer(0);privateExponent=new ArrayBuffer(0);prime1=new ArrayBuffer(0);prime2=new ArrayBuffer(0);exponent1=new ArrayBuffer(0);exponent2=new ArrayBuffer(0);coefficient=new ArrayBuffer(0);otherPrimeInfos;constructor(e={}){Object.assign(this,e)}};v([A({type:$.Integer})],bn.prototype,"version",void 0);v([A({type:$.Integer,converter:Tt})],bn.prototype,"modulus",void 0);v([A({type:$.Integer,converter:Tt})],bn.prototype,"publicExponent",void 0);v([A({type:$.Integer,converter:Tt})],bn.prototype,"privateExponent",void 0);v([A({type:$.Integer,converter:Tt})],bn.prototype,"prime1",void 0);v([A({type:$.Integer,converter:Tt})],bn.prototype,"prime2",void 0);v([A({type:$.Integer,converter:Tt})],bn.prototype,"exponent1",void 0);v([A({type:$.Integer,converter:Tt})],bn.prototype,"exponent2",void 0);v([A({type:$.Integer,converter:Tt})],bn.prototype,"coefficient",void 0);v([A({type:ux,optional:!0})],bn.prototype,"otherPrimeInfos",void 0)});var Xu,kD=V(()=>{"use strict";g();y();ge();pe();Xu=class{modulus=new ArrayBuffer(0);publicExponent=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};v([A({type:$.Integer,converter:Tt})],Xu.prototype,"modulus",void 0);v([A({type:$.Integer,converter:Tt})],Xu.prototype,"publicExponent",void 0)});var hx=V(()=>{"use strict";g();y();CD();lx();om();kE();TD();kD()});var AE,zr,IE=V(()=>{"use strict";g();y();(function(t){t[t.Transient=0]="Transient",t[t.Singleton=1]="Singleton",t[t.ResolutionScoped=2]="ResolutionScoped",t[t.ContainerScoped=3]="ContainerScoped"})(AE||(AE={}));zr=AE});var AD=V(()=>{"use strict";g();y();IE()});function am(t,e){RE(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}function ID(t,e,r,s){function n(i){return i instanceof r?i:new r(function(o){o(i)})}return new(r||(r=Promise))(function(i,o){function a(u){try{d(s.next(u))}catch(l){o(l)}}function c(u){try{d(s.throw(u))}catch(l){o(l)}}function d(u){u.done?i(u.value):n(u.value).then(a,c)}d((s=s.apply(t,e||[])).next())})}function RD(t,e){var r={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},s,n,i,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(d){return function(u){return c([d,u])}}function c(d){if(s)throw new TypeError("Generator is already executing.");for(;r;)try{if(s=1,n&&(i=d[0]&2?n.return:d[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,d[1])).done)return i;switch(n=0,i&&(d=[d[0]&2,i.value]),d[0]){case 0:case 1:i=d;break;case 4:return r.label++,{value:d[1],done:!1};case 5:r.label++,n=d[1],d=[0];continue;case 7:d=r.ops.pop(),r.trys.pop();continue;default:if(i=r.trys,!(i=i.length>0&&i[i.length-1])&&(d[0]===6||d[0]===2)){r=0;continue}if(d[0]===3&&(!i||d[1]>i[0]&&d[1]<i[3])){r.label=d[1];break}if(d[0]===6&&r.label<i[1]){r.label=i[1],i=d;break}if(i&&r.label<i[2]){r.label=i[2],r.ops.push(d);break}i[2]&&r.ops.pop(),r.trys.pop();continue}d=e.call(t,r)}catch(u){d=[6,u],n=0}finally{s=i=0}if(d[0]&5)throw d[1];return{value:d[0]?d[1]:void 0,done:!0}}}function cm(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],s=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&s>=t.length&&(t=void 0),{value:t&&t[s++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Yu(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var s=r.call(t),n,i=[],o;try{for(;(e===void 0||e-- >0)&&!(n=s.next()).done;)i.push(n.value)}catch(a){o={error:a}}finally{try{n&&!n.done&&(r=s.return)&&r.call(s)}finally{if(o)throw o.error}}return i}function Ti(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(Yu(arguments[e]));return t}var RE,Ju=V(()=>{"use strict";g();y();RE=function(t,e){return RE=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,s){r.__proto__=s}||function(r,s){for(var n in s)s.hasOwnProperty(n)&&(r[n]=s[n])},RE(t,e)}});function PE(t){var e=Reflect.getMetadata("design:paramtypes",t)||[],r=Reflect.getOwnMetadata(eY,t)||{};return Object.keys(r).forEach(function(s){e[+s]=r[s]}),e}var eY,Vd=V(()=>{"use strict";g();y();eY="injectionTokens"});function dm(t){return!!t.useClass}var DE=V(()=>{"use strict";g();y()});function Qu(t){return!!t.useFactory}var BE=V(()=>{"use strict";g();y()});var fx,px=V(()=>{"use strict";g();y();Ju();fx=(function(){function t(e){this.wrap=e,this.reflectMethods=["get","getPrototypeOf","setPrototypeOf","getOwnPropertyDescriptor","defineProperty","has","set","deleteProperty","apply","construct","ownKeys"]}return t.prototype.createProxy=function(e){var r=this,s={},n=!1,i,o=function(){return n||(i=e(r.wrap()),n=!0),i};return new Proxy(s,this.createHandler(o))},t.prototype.createHandler=function(e){var r={},s=function(n){r[n]=function(){for(var i=[],o=0;o<arguments.length;o++)i[o]=arguments[o];i[0]=e();var a=Reflect[n];return a.apply(void 0,Ti(i))}};return this.reflectMethods.forEach(s),r},t})()});function $a(t){return typeof t=="string"||typeof t=="symbol"}function LE(t){return typeof t=="object"&&"token"in t&&"multiple"in t}function mx(t){return typeof t=="object"&&"token"in t&&"transform"in t}function PD(t){return typeof t=="function"||t instanceof fx}var gx=V(()=>{"use strict";g();y();px()});function zd(t){return!!t.useToken}var OE=V(()=>{"use strict";g();y()});function Wd(t){return t.useValue!=null}var NE=V(()=>{"use strict";g();y()});var UE=V(()=>{"use strict";g();y();DE();BE();gx();OE();NE()});function DD(t){return dm(t)||Wd(t)||zd(t)||Qu(t)}var BD=V(()=>{"use strict";g();y();DE();NE();OE();BE()});var tY,lm,ME=V(()=>{"use strict";g();y();tY=(function(){function t(){this._registryMap=new Map}return t.prototype.entries=function(){return this._registryMap.entries()},t.prototype.getAll=function(e){return this.ensure(e),this._registryMap.get(e)},t.prototype.get=function(e){this.ensure(e);var r=this._registryMap.get(e);return r[r.length-1]||null},t.prototype.set=function(e,r){this.ensure(e),this._registryMap.get(e).push(r)},t.prototype.setAll=function(e,r){this._registryMap.set(e,r)},t.prototype.has=function(e){return this.ensure(e),this._registryMap.get(e).length>0},t.prototype.clear=function(){this._registryMap.clear()},t.prototype.ensure=function(e){this._registryMap.has(e)||this._registryMap.set(e,[])},t})(),lm=tY});var rY,LD,OD=V(()=>{"use strict";g();y();Ju();ME();rY=(function(t){am(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e})(lm),LD=rY});var sY,um,ND=V(()=>{"use strict";g();y();sY=(function(){function t(){this.scopedResolutions=new Map}return t})(),um=sY});function nY(t,e){if(t===null)return"at position #"+e;var r=t.split(",")[e].trim();return'"'+r+'" at position #'+e}function iY(t,e,r){return r===void 0&&(r=" "),Ti([t],e.message.split(`
|
|
32
32
|
`).map(function(s){return r+s})).join(`
|
|
33
|
-
`)}function jE(t,e,r){var s=Yu(t.toString().match(/constructor\(([\w, ]+)\)/)||[],2),n=s[1],i=n===void 0?null:n,o=nY(i,e);return iY("Cannot inject the dependency "+o+' of "'+t.name+'" constructor. Reason:',r)}var $E=V(()=>{"use strict";g();y();Ju()});function UD(t){if(typeof t.dispose!="function")return!1;var e=t.dispose;return!(e.length>0)}var MD=V(()=>{"use strict";g();y()});var oY,aY,cY,jD,$D=V(()=>{"use strict";g();y();Ju();ME();oY=(function(t){a0(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e})(l0),aY=(function(t){a0(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e})(l0),cY=(function(){function t(){this.preResolution=new oY,this.postResolution=new aY}return t})(),jD=cY});var FE,dY,Gt,Fa=V(()=>{"use strict";g();y();Ju();UE();BD();gx();OD();IE();ND();$E();px();MD();$D();FE=new Map,dY=(function(){function t(e){this.parent=e,this._registry=new LD,this.interceptors=new jD,this.disposed=!1,this.disposables=new Set}return t.prototype.register=function(e,r,s){s===void 0&&(s={lifecycle:zr.Transient}),this.ensureNotDisposed();var n;if(DD(r)?n=r:n={useClass:r},zd(n))for(var i=[e],o=n;o!=null;){var a=o.useToken;if(i.includes(a))throw new Error("Token registration cycle detected! "+Ti(i,[a]).join(" -> "));i.push(a);var c=this._registry.get(a);c&&zd(c.provider)?o=c.provider:o=null}if((s.lifecycle===zr.Singleton||s.lifecycle==zr.ContainerScoped||s.lifecycle==zr.ResolutionScoped)&&(Wd(n)||Qu(n)))throw new Error('Cannot use lifecycle "'+zr[s.lifecycle]+'" with ValueProviders or FactoryProviders');return this._registry.set(e,{provider:n,options:s}),this},t.prototype.registerType=function(e,r){return this.ensureNotDisposed(),$a(r)?this.register(e,{useToken:r}):this.register(e,{useClass:r})},t.prototype.registerInstance=function(e,r){return this.ensureNotDisposed(),this.register(e,{useValue:r})},t.prototype.registerSingleton=function(e,r){if(this.ensureNotDisposed(),$a(e)){if($a(r))return this.register(e,{useToken:r},{lifecycle:zr.Singleton});if(r)return this.register(e,{useClass:r},{lifecycle:zr.Singleton});throw new Error('Cannot register a type name as a singleton without a "to" token')}var s=e;return r&&!$a(r)&&(s=r),this.register(e,{useClass:s},{lifecycle:zr.Singleton})},t.prototype.resolve=function(e,r,s){r===void 0&&(r=new u0),s===void 0&&(s=!1),this.ensureNotDisposed();var n=this.getRegistration(e);if(!n&&$a(e)){if(s)return;throw new Error('Attempted to resolve unregistered dependency token: "'+e.toString()+'"')}if(this.executePreResolutionInterceptor(e,"Single"),n){var i=this.resolveRegistration(n,r);return this.executePostResolutionInterceptor(e,i,"Single"),i}if(PD(e)){var i=this.construct(e,r);return this.executePostResolutionInterceptor(e,i,"Single"),i}throw new Error("Attempted to construct an undefined constructor. Could mean a circular dependency problem. Try using `delay` function.")},t.prototype.executePreResolutionInterceptor=function(e,r){var s,n;if(this.interceptors.preResolution.has(e)){var i=[];try{for(var o=c0(this.interceptors.preResolution.getAll(e)),a=o.next();!a.done;a=o.next()){var c=a.value;c.options.frequency!="Once"&&i.push(c),c.callback(e,r)}}catch(d){s={error:d}}finally{try{a&&!a.done&&(n=o.return)&&n.call(o)}finally{if(s)throw s.error}}this.interceptors.preResolution.setAll(e,i)}},t.prototype.executePostResolutionInterceptor=function(e,r,s){var n,i;if(this.interceptors.postResolution.has(e)){var o=[];try{for(var a=c0(this.interceptors.postResolution.getAll(e)),c=a.next();!c.done;c=a.next()){var d=c.value;d.options.frequency!="Once"&&o.push(d),d.callback(e,r,s)}}catch(u){n={error:u}}finally{try{c&&!c.done&&(i=a.return)&&i.call(a)}finally{if(n)throw n.error}}this.interceptors.postResolution.setAll(e,o)}},t.prototype.resolveRegistration=function(e,r){if(this.ensureNotDisposed(),e.options.lifecycle===zr.ResolutionScoped&&r.scopedResolutions.has(e))return r.scopedResolutions.get(e);var s=e.options.lifecycle===zr.Singleton,n=e.options.lifecycle===zr.ContainerScoped,i=s||n,o;return Wd(e.provider)?o=e.provider.useValue:zd(e.provider)?o=i?e.instance||(e.instance=this.resolve(e.provider.useToken,r)):this.resolve(e.provider.useToken,r):d0(e.provider)?o=i?e.instance||(e.instance=this.construct(e.provider.useClass,r)):this.construct(e.provider.useClass,r):Qu(e.provider)?o=e.provider.useFactory(this):o=this.construct(e.provider,r),e.options.lifecycle===zr.ResolutionScoped&&r.scopedResolutions.set(e,o),o},t.prototype.resolveAll=function(e,r,s){var n=this;r===void 0&&(r=new u0),s===void 0&&(s=!1),this.ensureNotDisposed();var i=this.getAllRegistrations(e);if(!i&&$a(e)){if(s)return[];throw new Error('Attempted to resolve unregistered dependency token: "'+e.toString()+'"')}if(this.executePreResolutionInterceptor(e,"All"),i){var o=i.map(function(c){return n.resolveRegistration(c,r)});return this.executePostResolutionInterceptor(e,o,"All"),o}var a=[this.construct(e,r)];return this.executePostResolutionInterceptor(e,a,"All"),a},t.prototype.isRegistered=function(e,r){return r===void 0&&(r=!1),this.ensureNotDisposed(),this._registry.has(e)||r&&(this.parent||!1)&&this.parent.isRegistered(e,!0)},t.prototype.reset=function(){this.ensureNotDisposed(),this._registry.clear(),this.interceptors.preResolution.clear(),this.interceptors.postResolution.clear()},t.prototype.clearInstances=function(){var e,r;this.ensureNotDisposed();try{for(var s=c0(this._registry.entries()),n=s.next();!n.done;n=s.next()){var i=Yu(n.value,2),o=i[0],a=i[1];this._registry.setAll(o,a.filter(function(c){return!Wd(c.provider)}).map(function(c){return c.instance=void 0,c}))}}catch(c){e={error:c}}finally{try{n&&!n.done&&(r=s.return)&&r.call(s)}finally{if(e)throw e.error}}},t.prototype.createChildContainer=function(){var e,r;this.ensureNotDisposed();var s=new t(this);try{for(var n=c0(this._registry.entries()),i=n.next();!i.done;i=n.next()){var o=Yu(i.value,2),a=o[0],c=o[1];c.some(function(d){var u=d.options;return u.lifecycle===zr.ContainerScoped})&&s._registry.setAll(a,c.map(function(d){return d.options.lifecycle===zr.ContainerScoped?{provider:d.provider,options:d.options}:d}))}}catch(d){e={error:d}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(e)throw e.error}}return s},t.prototype.beforeResolution=function(e,r,s){s===void 0&&(s={frequency:"Always"}),this.interceptors.preResolution.set(e,{callback:r,options:s})},t.prototype.afterResolution=function(e,r,s){s===void 0&&(s={frequency:"Always"}),this.interceptors.postResolution.set(e,{callback:r,options:s})},t.prototype.dispose=function(){return ID(this,void 0,void 0,function(){var e;return RD(this,function(r){switch(r.label){case 0:return this.disposed=!0,e=[],this.disposables.forEach(function(s){var n=s.dispose();n&&e.push(n)}),[4,Promise.all(e)];case 1:return r.sent(),[2]}})})},t.prototype.getRegistration=function(e){return this.isRegistered(e)?this._registry.get(e):this.parent?this.parent.getRegistration(e):null},t.prototype.getAllRegistrations=function(e){return this.isRegistered(e)?this._registry.getAll(e):this.parent?this.parent.getAllRegistrations(e):null},t.prototype.construct=function(e,r){var s=this;if(e instanceof fx)return e.createProxy(function(i){return s.resolve(i,r)});var n=(function(){var i=FE.get(e);if(!i||i.length===0){if(e.length===0)return new e;throw new Error('TypeInfo not known for "'+e.name+'"')}var o=i.map(s.resolveParams(r,e));return new(e.bind.apply(e,Ti([void 0],o)))})();return UD(n)&&this.disposables.add(n),n},t.prototype.resolveParams=function(e,r){var s=this;return function(n,i){var o,a,c;try{return LE(n)?mx(n)?n.multiple?(o=s.resolve(n.transform)).transform.apply(o,Ti([s.resolveAll(n.token,new u0,n.isOptional)],n.transformArgs)):(a=s.resolve(n.transform)).transform.apply(a,Ti([s.resolve(n.token,e,n.isOptional)],n.transformArgs)):n.multiple?s.resolveAll(n.token,new u0,n.isOptional):s.resolve(n.token,e,n.isOptional):mx(n)?(c=s.resolve(n.transform,e)).transform.apply(c,Ti([s.resolve(n.token,e)],n.transformArgs)):s.resolve(n,e)}catch(d){throw new Error(jE(r,i,d))}}},t.prototype.ensureNotDisposed=function(){if(this.disposed)throw new Error("This container has been disposed, you cannot interact with a disposed container")},t})(),Gt=new dY});var FD=V(()=>{"use strict";g();y();Vd();Fa();gx();$E()});var HD=V(()=>{"use strict";g();y();Vd()});function lY(t){return function(e){FE.set(e,PE(e)),t&&t.token&&(Array.isArray(t.token)?t.token.forEach(function(r){Gt.register(r,e)}):Gt.register(t.token,e))}}var Ha,yx=V(()=>{"use strict";g();y();Vd();Fa();Fa();Ha=lY});var qD=V(()=>{"use strict";g();y();Fa()});var VD=V(()=>{"use strict";g();y();yx();Fa()});var zD=V(()=>{"use strict";g();y();Vd()});var WD=V(()=>{"use strict";g();y();Vd()});var KD=V(()=>{"use strict";g();y();Vd()});var GD=V(()=>{"use strict";g();y();yx();Fa()});var XD=V(()=>{"use strict";g();y();FD();HD();yx();qD();VD();zD();WD();KD();GD()});var YD=V(()=>{"use strict";g();y()});var JD=V(()=>{"use strict";g();y()});var QD=V(()=>{"use strict";g();y()});var ZD=V(()=>{"use strict";g();y();YD();JD();QD()});var eB=V(()=>{"use strict";g();y();AD();XD();ZD();UE();px();Fa();if(typeof Reflect>"u"||!Reflect.getMetadata)throw new Error(`tsyringe requires a reflect polyfill. Please add 'import "reflect-metadata"' to the top of your entry point.`)});var qE,Kd,tB,VE=V(()=>{"use strict";g();y();ge();pe();Kd=class{attrId="";attrValues=[];constructor(e={}){Object.assign(e)}};v([A({type:$.ObjectIdentifier})],Kd.prototype,"attrId",void 0);v([A({type:$.Any,repeated:"set"})],Kd.prototype,"attrValues",void 0);tB=qE=class extends Ke{constructor(e){super(e),Object.setPrototypeOf(this,qE.prototype)}};tB=qE=v([ie({type:re.Sequence,itemType:Kd})],tB)});var zE,rB,sB=V(()=>{"use strict";g();y();ge();pe();Zp();rB=zE=class extends Ke{constructor(e){super(e),Object.setPrototypeOf(this,zE.prototype)}};rB=zE=v([ie({type:re.Sequence,itemType:yn})],rB)});var uY,hY,nB,Zu,eRe,tRe,rRe,sRe,nRe,iRe,Gd,WE=V(()=>{"use strict";g();y();uY="1.2.840.113549",hY=`${uY}.1`,nB=`${hY}.12`,Zu=`${nB}.1`,eRe=`${Zu}.1`,tRe=`${Zu}.2`,rRe=`${Zu}.3`,sRe=`${Zu}.4`,nRe=`${Zu}.5`,iRe=`${Zu}.6`,Gd=`${nB}.10.1`});var lRe,uRe,hRe,fRe,pRe,mRe,bx,xx=V(()=>{"use strict";g();y();WE();lRe=`${Gd}.1`,uRe=`${Gd}.2`,hRe=`${Gd}.3`,fRe=`${Gd}.4`,pRe=`${Gd}.5`,mRe=`${Gd}.6`,bx="1.2.840.113549.1.9"});var wx,iB,_Re,SRe,oB=V(()=>{"use strict";g();y();ge();pe();xx();wx=class{certId="";certValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};v([A({type:$.ObjectIdentifier})],wx.prototype,"certId",void 0);v([A({type:$.Any,context:0})],wx.prototype,"certValue",void 0);iB=`${bx}.22`,_Re=`${iB}.1`,SRe=`${iB}.2`});var vx,fY,RRe,aB=V(()=>{"use strict";g();y();ge();pe();xx();vx=class{crlId="";crltValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};v([A({type:$.ObjectIdentifier})],vx.prototype,"crlId",void 0);v([A({type:$.Any,context:0})],vx.prototype,"crltValue",void 0);fY=`${bx}.23`,RRe=`${fY}.1`});var _x,qa,cB=V(()=>{"use strict";g();y();ge();pe();kt();_x=class extends Xe{},qa=class{encryptionAlgorithm=new _e;encryptedData=new _x;constructor(e={}){Object.assign(this,e)}};v([A({type:_e})],qa.prototype,"encryptionAlgorithm",void 0);v([A({type:_x})],qa.prototype,"encryptedData",void 0)});var KE,GE,Sx,XE,Va,dB=V(()=>{"use strict";g();y();ge();pe();kt();(function(t){t[t.v1=0]="v1"})(GE||(GE={}));Sx=class extends Xe{},XE=KE=class extends Ke{constructor(e){super(e),Object.setPrototypeOf(this,KE.prototype)}};XE=KE=v([ie({type:re.Sequence,itemType:Fr})],XE);Va=class{version=GE.v1;privateKeyAlgorithm=new _e;privateKey=new Sx;attributes;constructor(e={}){Object.assign(this,e)}};v([A({type:$.Integer})],Va.prototype,"version",void 0);v([A({type:_e})],Va.prototype,"privateKeyAlgorithm",void 0);v([A({type:Sx})],Va.prototype,"privateKey",void 0);v([A({type:XE,implicit:!0,context:0,optional:!0})],Va.prototype,"attributes",void 0)});var Ex=V(()=>{"use strict";g();y();cB();dB()});var lB,uB=V(()=>{"use strict";g();y();ge();Ex();pe();lB=class extends Va{};lB=v([ie({type:re.Sequence})],lB)});var hB,fB=V(()=>{"use strict";g();y();ge();Ex();pe();hB=class extends qa{};hB=v([ie({type:re.Sequence})],hB)});var Cx,pB=V(()=>{"use strict";g();y();ge();pe();Cx=class{secretTypeId="";secretValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};v([A({type:$.ObjectIdentifier})],Cx.prototype,"secretTypeId",void 0);v([A({type:$.Any,context:0})],Cx.prototype,"secretValue",void 0)});var mB=V(()=>{"use strict";g();y();oB();aB();uB();fB();pB();xx()});var za,YE=V(()=>{"use strict";g();y();ge();hx();pe();za=class{mac=new qd;macSalt=new Xe;iterations=1;constructor(e={}){Object.assign(this,e)}};v([A({type:qd})],za.prototype,"mac",void 0);v([A({type:Xe})],za.prototype,"macSalt",void 0);v([A({type:$.Integer,defaultValue:1})],za.prototype,"iterations",void 0)});var Xd,gB=V(()=>{"use strict";g();y();ge();pe();Zp();YE();Xd=class{version=3;authSafe=new yn;macData=new za;constructor(e={}){Object.assign(this,e)}};v([A({type:$.Integer})],Xd.prototype,"version",void 0);v([A({type:yn})],Xd.prototype,"authSafe",void 0);v([A({type:za,optional:!0})],Xd.prototype,"macData",void 0)});var JE,eh,yB,bB=V(()=>{"use strict";g();y();ge();pe();VE();eh=class{bagId="";bagValue=new ArrayBuffer(0);bagAttributes;constructor(e={}){Object.assign(this,e)}};v([A({type:$.ObjectIdentifier})],eh.prototype,"bagId",void 0);v([A({type:$.Any,context:0})],eh.prototype,"bagValue",void 0);v([A({type:Kd,repeated:"set",optional:!0})],eh.prototype,"bagAttributes",void 0);yB=JE=class extends Ke{constructor(e){super(e),Object.setPrototypeOf(this,JE.prototype)}};yB=JE=v([ie({type:re.Sequence,itemType:eh})],yB)});var xB=V(()=>{"use strict";g();y();VE();sB();mB();YE();WE();gB();bB()});var QE,ZE,eC,hr,r6e,BB,f0,LB,OB,s6e,n6e,i6e,o6e,a6e,c6e,d6e,l6e,cC,u6e,h6e,f6e,p0,p6e,m6e,g6e,y6e,b6e,x6e,w6e,v6e,m0,_6e,S6e,E6e,C6e,T6e,k6e,A6e,I6e,R6e,P6e,D6e,B6e,L6e,Tx,wB,vB,_B,tC,SB,EB,rC,CB,sC,kx,TB,kB,nC,AB,iC,IB,h0,RB,PB,oC,aC,DB,dC=V(()=>{"use strict";g();y();ge();pe();Zp();xB();Ex();kt();Y2();hr="1.2.840.113549.1.9",r6e=`${hr}.0`,BB=`${hr}.24`,f0=`${hr}.25`,LB=`${hr}.26`,OB=`${hr}.27`,s6e=`${BB}.1`,n6e=`${BB}.2`,i6e=`${hr}.1`,o6e=`${hr}.2`,a6e=`${hr}.3`,c6e=`${hr}.4`,d6e=`${hr}.5`,l6e=`${hr}.6`,cC=`${hr}.7`,u6e=`${hr}.8`,h6e=`${hr}.9`,f6e=`${hr}.13`,p0=`${hr}.14`,p6e=`${hr}.15`,m6e=`${hr}.20`,g6e=`${hr}.21`,y6e=`${f0}.1`,b6e=`${f0}.2`,x6e=`${f0}.3`,w6e=`${f0}.4`,v6e=`${f0}.5`,m0="1.3.6.1.5.5.7.9",_6e=`${m0}.1`,S6e=`${m0}.2`,E6e=`${m0}.3`,C6e=`${m0}.4`,T6e=`${m0}.5`,k6e=`${LB}.1`,A6e=`${LB}.2`,I6e=`${OB}.1`,R6e=`${OB}.2`,P6e=`${hr}.16`,D6e=`${hr}.22`,B6e=`${hr}.23`,L6e=`${W2}.65`,Tx=class extends _r{ia5String;constructor(e={}){super(e)}toString(){return{}.toString(),this.ia5String||super.toString()}};v([A({type:$.IA5String})],Tx.prototype,"ia5String",void 0);Tx=v([ie({type:re.Choice})],Tx);wB=class extends yn{};wB=v([ie({type:re.Sequence})],wB);vB=class extends Xd{};vB=v([ie({type:re.Sequence})],vB);_B=class extends qa{};_B=v([ie({type:re.Sequence})],_B);tC=class{value;constructor(e=""){this.value=e}toString(){return this.value}};v([A({type:$.IA5String})],tC.prototype,"value",void 0);tC=v([ie({type:re.Choice})],tC);SB=class extends Tx{};SB=v([ie({type:re.Choice})],SB);EB=class extends _r{};EB=v([ie({type:re.Choice})],EB);rC=class{value;constructor(e=new Date){this.value=e}};v([A({type:$.GeneralizedTime})],rC.prototype,"value",void 0);rC=v([ie({type:re.Choice})],rC);CB=class extends _r{};CB=v([ie({type:re.Choice})],CB);sC=class{value;constructor(e="M"){this.value=e}toString(){return this.value}};v([A({type:$.PrintableString})],sC.prototype,"value",void 0);sC=v([ie({type:re.Choice})],sC);kx=class{value;constructor(e=""){this.value=e}toString(){return this.value}};v([A({type:$.PrintableString})],kx.prototype,"value",void 0);kx=v([ie({type:re.Choice})],kx);TB=class extends kx{};TB=v([ie({type:re.Choice})],TB);kB=class extends _r{};kB=v([ie({type:re.Choice})],kB);nC=class{value;constructor(e=""){this.value=e}toString(){return this.value}};v([A({type:$.ObjectIdentifier})],nC.prototype,"value",void 0);nC=v([ie({type:re.Choice})],nC);AB=class extends ur{};AB=v([ie({type:re.Choice})],AB);iC=class{value;constructor(e=0){this.value=e}toString(){return this.value.toString()}};v([A({type:$.Integer})],iC.prototype,"value",void 0);iC=v([ie({type:re.Choice})],iC);IB=class extends Ts{};IB=v([ie({type:re.Sequence})],IB);h0=class extends _r{};h0=v([ie({type:re.Choice})],h0);RB=QE=class extends qs{constructor(e){super(e),Object.setPrototypeOf(this,QE.prototype)}};RB=QE=v([ie({type:re.Sequence})],RB);PB=ZE=class extends Ke{constructor(e){super(e),Object.setPrototypeOf(this,ZE.prototype)}};PB=ZE=v([ie({type:re.Set,itemType:Ln})],PB);oC=class{value;constructor(e=""){this.value=e}toString(){return this.value}};v([A({type:$.BmpString})],oC.prototype,"value",void 0);oC=v([ie({type:re.Choice})],oC);aC=class extends _e{};aC=v([ie({type:re.Sequence})],aC);DB=eC=class extends Ke{constructor(e){super(e),Object.setPrototypeOf(this,eC.prototype)}};DB=eC=v([ie({type:re.Sequence,itemType:aC})],DB)});var lC,g0,uC=V(()=>{"use strict";g();y();ge();pe();kt();g0=lC=class extends Ke{constructor(e){super(e),Object.setPrototypeOf(this,lC.prototype)}};g0=lC=v([ie({type:re.Sequence,itemType:Fr})],g0)});var ki,hC=V(()=>{"use strict";g();y();ge();pe();kt();uC();ki=class{version=0;subject=new Vt;subjectPKInfo=new Hr;attributes=new g0;constructor(e={}){Object.assign(this,e)}};v([A({type:$.Integer})],ki.prototype,"version",void 0);v([A({type:Vt})],ki.prototype,"subject",void 0);v([A({type:Hr})],ki.prototype,"subjectPKInfo",void 0);v([A({type:g0,implicit:!0,context:0,optional:!0})],ki.prototype,"attributes",void 0)});var Wa,NB=V(()=>{"use strict";g();y();ge();pe();kt();hC();Wa=class{certificationRequestInfo=new ki;certificationRequestInfoRaw;signatureAlgorithm=new _e;signature=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};v([A({type:ki,raw:!0})],Wa.prototype,"certificationRequestInfo",void 0);v([A({type:_e})],Wa.prototype,"signatureAlgorithm",void 0);v([A({type:$.BitString})],Wa.prototype,"signature",void 0)});var UB=V(()=>{"use strict";g();y();uC();NB();hC()});function bY(t){return new RegExp(yY).test(t)}function xY(t,e){return`\\${We.ToHex(We.FromUtf8String(e)).toUpperCase()}`}function wY(t){return t.replace(/([,+"\\<>;])/g,"\\$1").replace(/^([ #])/,"\\$1").replace(/([ ]$)/,"\\$1").replace(/([\r\n\t])/,xY)}function IY(t,e){return t.algorithm=new _e({algorithm:Ei,parameters:null}),e=Ee.serialize(t),e}function Ix(t,e,r){if(r.length===1)t[e]=r[0].toTextObject();else{let s=new Rt("");r.forEach((n,i)=>{let o=n.toTextObject(),a=`${o[Rt.NAME]} ${i+1}`,c=s[a];Array.isArray(c)||(c=[],s[a]=c),c.push(o)}),t[e]=s}}function Rx(t,e,r,s){let n=e[s];n&&(Array.isArray(n)?n:[n]).forEach(o=>{typeof o=="string"&&(o=new Ai("url",o)),t.push(new po({accessMethod:r,accessLocation:Ee.parse(o.rawData,et)}))})}function RY(t,e=Sr.get()){let r=ke.toUint8Array(We.FromHex(t||"")),s=r&&r.length&&r.some(i=>i>0)?new Uint8Array(r):void 0;s||(s=e.getRandomValues(new Uint8Array(16)));let n=0;for(;n<s.length-1&&s[n]===0;)n++;if(s=s.slice(n),s[0]>127){let i=new Uint8Array(s.length+1);i[0]=0,i.set(s,1),s=i}return s.buffer}var L4e,$0,_C,Yd,Px,Rs,MB,jB,$B,FB,HB,qB,VB,zB,WB,KB,GB,XB,YB,JB,QB,ZB,e9,t9,r9,s9,n9,i9,o9,a9,c9,d9,l9,u9,or,N0,_9,S9,Rt,SC,Ii,So,th,Ka,zs,E9,U0,Sr,yY,Bx,Is,On,C9,h9,vY,f9,p9,m9,fC,pC,mC,gC,yC,bC,xC,Ax,Ai,Eo,O0,M0,_Y,SY,EY,nh,CY,TY,kY,AY,g9,Wr,Ga,_o,Lx,Ox,y9,Nx,b9,Ux,Mx,jx,ms,$x,Fx,Hx,qx,ih,Vx,j0,oh,F0,EC,Dx,CC,TC,Co,wC,x9,vC,w9,kC,y0,b0,x0,w0,v0,_0,S0,rh,AC,E0,C0,T0,k0,A0,I0,R0,P0,D0,B0,sh,L0,zx,Wx,PY,DY,BY,LY,OY,v9,NY,UY,MY,jY,$Y,FY,HY,T9=V(()=>{"use strict";g();y();L4e=Le(Tv());pe();kt();kt();RS();ge();Zp();_E();_E();hx();hx();eB();dC();dC();UB();$0="crypto.algorithm",_C=class{getAlgorithms(){return Gt.resolveAll($0)}toAsnAlgorithm(e){({...e});for(let r of this.getAlgorithms()){let s=r.toAsnAlgorithm(e);if(s)return s}if(/^[0-9.]+$/.test(e.name)){let r=new _e({algorithm:e.name});if("parameters"in e){let s=e;r.parameters=s.parameters}return r}throw new Error("Cannot convert WebCrypto algorithm to ASN.1 algorithm")}toWebAlgorithm(e){for(let s of this.getAlgorithms()){let n=s.toWebAlgorithm(e);if(n)return n}return{name:e.algorithm,parameters:e.parameters}}},Yd="crypto.algorithmProvider";Gt.registerSingleton(Yd,_C);Rs="1.3.36.3.3.2.8.1.1",MB=`${Rs}.1`,jB=`${Rs}.2`,$B=`${Rs}.3`,FB=`${Rs}.4`,HB=`${Rs}.5`,qB=`${Rs}.6`,VB=`${Rs}.7`,zB=`${Rs}.8`,WB=`${Rs}.9`,KB=`${Rs}.10`,GB=`${Rs}.11`,XB=`${Rs}.12`,YB=`${Rs}.13`,JB=`${Rs}.14`,QB="brainpoolP160r1",ZB="brainpoolP160t1",e9="brainpoolP192r1",t9="brainpoolP192t1",r9="brainpoolP224r1",s9="brainpoolP224t1",n9="brainpoolP256r1",i9="brainpoolP256t1",o9="brainpoolP320r1",a9="brainpoolP320t1",c9="brainpoolP384r1",d9="brainpoolP384t1",l9="brainpoolP512r1",u9="brainpoolP512t1",or="ECDSA",N0=Px=class{toAsnAlgorithm(e){switch(e.name.toLowerCase()){case or.toLowerCase():if("hash"in e)switch((typeof e.hash=="string"?e.hash:e.hash.name).toLowerCase()){case"sha-1":return oD;case"sha-256":return aD;case"sha-384":return cD;case"sha-512":return dD}else if("namedCurve"in e){let r="";switch(e.namedCurve){case"P-256":r=pE;break;case"K-256":r=Px.SECP256K1;break;case"P-384":r=mE;break;case"P-521":r=gE;break;case QB:r=MB;break;case ZB:r=jB;break;case e9:r=$B;break;case t9:r=FB;break;case r9:r=HB;break;case s9:r=qB;break;case n9:r=VB;break;case i9:r=zB;break;case o9:r=WB;break;case a9:r=KB;break;case c9:r=GB;break;case d9:r=XB;break;case l9:r=YB;break;case u9:r=JB;break}if(r)return new _e({algorithm:Ud,parameters:Ee.serialize(new Si({namedCurve:r}))})}}return null}toWebAlgorithm(e){switch(e.algorithm){case e0:return{name:or,hash:{name:"SHA-1"}};case t0:return{name:or,hash:{name:"SHA-256"}};case r0:return{name:or,hash:{name:"SHA-384"}};case s0:return{name:or,hash:{name:"SHA-512"}};case Ud:{if(!e.parameters)throw new TypeError("Cannot get required parameters from EC algorithm");switch(Ee.parse(e.parameters,Si).namedCurve){case pE:return{name:or,namedCurve:"P-256"};case Px.SECP256K1:return{name:or,namedCurve:"K-256"};case mE:return{name:or,namedCurve:"P-384"};case gE:return{name:or,namedCurve:"P-521"};case MB:return{name:or,namedCurve:QB};case jB:return{name:or,namedCurve:ZB};case $B:return{name:or,namedCurve:e9};case FB:return{name:or,namedCurve:t9};case HB:return{name:or,namedCurve:r9};case qB:return{name:or,namedCurve:s9};case VB:return{name:or,namedCurve:n9};case zB:return{name:or,namedCurve:i9};case WB:return{name:or,namedCurve:o9};case KB:return{name:or,namedCurve:a9};case GB:return{name:or,namedCurve:c9};case XB:return{name:or,namedCurve:d9};case YB:return{name:or,namedCurve:l9};case JB:return{name:or,namedCurve:u9}}}}return null}};N0.SECP256K1="1.3.132.0.10";N0=Px=v([Ha()],N0);Gt.registerSingleton($0,N0);_9=Symbol("name"),S9=Symbol("value"),Rt=class{constructor(e,r={},s=""){this[_9]=e,this[S9]=s;for(let n in r)this[n]=r[n]}};Rt.NAME=_9;Rt.VALUE=S9;SC=class{static toTextObject(e){let r=new Rt("Algorithm Identifier",{},Ii.toString(e.algorithm));if(e.parameters)if(e.algorithm===Ud){let s=new N0().toWebAlgorithm(e);s&&"namedCurve"in s?r["Named Curve"]=s.namedCurve:r.Parameters=e.parameters}else r.Parameters=e.parameters;return r}},Ii=class{static toString(e){let r=this.items[e];return r||e}};Ii.items={[jd]:"sha1",[cx]:"sha224",[$d]:"sha256",[Fd]:"sha384",[Hd]:"sha512",[Ei]:"rsaEncryption",[Vu]:"sha1WithRSAEncryption",[yD]:"sha224WithRSAEncryption",[ax]:"sha256WithRSAEncryption",[zu]:"sha384WithRSAEncryption",[Wu]:"sha512WithRSAEncryption",[Ud]:"ecPublicKey",[e0]:"ecdsaWithSHA1",[ox]:"ecdsaWithSHA224",[t0]:"ecdsaWithSHA256",[r0]:"ecdsaWithSHA384",[s0]:"ecdsaWithSHA512",[aP]:"TLS WWW server authentication",[cP]:"TLS WWW client authentication",[dP]:"Code Signing",[lP]:"E-mail Protection",[uP]:"Time Stamping",[hP]:"OCSP Signing",[rD]:"Signed Data"};So=class{static serialize(e){return this.serializeObj(e).join(`
|
|
34
|
-
`)}static pad(e=0){return"".padStart(2*e," ")}static serializeObj(e,r=0){let s=[],n=this.pad(r++),i="",o=e[Rt.VALUE];o&&(i=` ${o}`),s.push(`${n}${e[Rt.NAME]}:${i}`),n=this.pad(r);for(let a in e){if(typeof a=="symbol")continue;let c=e[a],d=a?`${a}: `:"";if(typeof c=="string"||typeof c=="number"||typeof c=="boolean")s.push(`${n}${d}${c}`);else if(c instanceof Date)s.push(`${n}${d}${c.toUTCString()}`);else if(Array.isArray(c))for(let u of c)u[Rt.NAME]=a,s.push(...this.serializeObj(u,r));else if(c instanceof Rt)c[Rt.NAME]=a,s.push(...this.serializeObj(c,r));else if(ke.isBufferSource(c))a?(s.push(`${n}${d}`),s.push(...this.serializeBufferSource(c,r+1))):s.push(...this.serializeBufferSource(c,r));else if("toTextObject"in c){let u=c.toTextObject();u[Rt.NAME]=a,s.push(...this.serializeObj(u,r))}else throw new TypeError("Cannot serialize data in text format. Unsupported type.")}return s}static serializeBufferSource(e,r=0){let s=this.pad(r),n=ke.toUint8Array(e),i=[];for(let o=0;o<n.length;){let a=[];for(let c=0;c<16&&o<n.length;c++){c===8&&a.push("");let d=n[o++].toString(16).padStart(2,"0");a.push(d)}i.push(`${s}${a.join(" ")}`)}return i}static serializeAlgorithm(e){return this.algorithmSerializer.toTextObject(e)}};So.oidSerializer=Ii;So.algorithmSerializer=SC;Ka=class t{get rawData(){return gt(this,th,"f")||Yt(this,th,Ee.serialize(this.asn),"f"),gt(this,th,"f")}constructor(...e){th.set(this,void 0),ke.isBufferSource(e[0])?(this.asn=Ee.parse(e[0],e[1]),Yt(this,th,ke.toArrayBuffer(e[0]),"f"),this.onInit(this.asn)):(this.asn=e[0],this.onInit(this.asn))}equal(e){return e instanceof t?B8(e.rawData,this.rawData):!1}toString(e="text"){switch(e){case"asn":return Ee.toString(this.rawData);case"text":return So.serialize(this.toTextObject());case"hex":return We.ToHex(this.rawData);case"base64":return We.ToBase64(this.rawData);case"base64url":return We.ToBase64Url(this.rawData);default:throw TypeError("Argument 'format' is unsupported value")}}getTextName(){return this.constructor.NAME}toTextObject(){let e=this.toTextObjectEmpty();return e[""]=this.rawData,e}toTextObjectEmpty(e){return new Rt(this.getTextName(),{},e)}};th=new WeakMap;Ka.NAME="ASN";zs=class t extends Ka{constructor(...e){let r;ke.isBufferSource(e[0])?r=ke.toArrayBuffer(e[0]):r=Ee.serialize(new as({extnID:e[0],critical:e[1],extnValue:new Xe(ke.toArrayBuffer(e[2]))})),super(r,as)}onInit(e){this.type=e.extnID,this.critical=e.critical,this.value=e.extnValue.buffer}toTextObject(){let e=this.toTextObjectWithoutValue();return e[""]=this.value,e}toTextObjectWithoutValue(){let e=this.toTextObjectEmpty(this.critical?"critical":void 0);return e[Rt.NAME]===t.NAME&&(e[Rt.NAME]=Ii.toString(this.type)),e}},
|
|
35
|
-
`).replace(/\\0d/ig,"\r").replace(/\\0g/ig," ").replace(/\\(.)/g,"$1")}toArrayBuffer(){return Ee.serialize(this.asn)}async getThumbprint(...e){var r;let s,n="SHA-1";return e.length>=1&&!(!((r=e[0])===null||r===void 0)&&r.subtle)?(n=e[0]||n,s=e[1]||Sr.get()):s=e[0]||Sr.get(),await s.subtle.digest(n,this.toArrayBuffer())}},C9="Cannot initialize GeneralName from ASN.1 data.",h9=`${C9} Unsupported string format in use.`,vY=`${C9} Value doesn't match to GUID regular expression.`,f9=/^([0-9a-f]{8})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{12})$/i,p9="1.3.6.1.4.1.311.25.1",m9="1.3.6.1.4.1.311.20.2.3",fC="dns",pC="dn",mC="email",gC="ip",yC="url",bC="guid",xC="upn",Ax="id",Ai=class extends Ka{constructor(...e){let r;if(e.length===2)switch(e[0]){case pC:{let s=new On(e[1]).toArrayBuffer(),n=Ee.parse(s,Vt);r=new et({directoryName:n});break}case fC:r=new et({dNSName:e[1]});break;case mC:r=new et({rfc822Name:e[1]});break;case bC:{let s=new RegExp(f9,"i").exec(e[1]);if(!s)throw new Error("Cannot parse GUID value. Value doesn't match to regular expression");let n=s.slice(1).map((i,o)=>o<3?We.ToHex(new Uint8Array(We.FromHex(i)).reverse()):i).join("");r=new et({otherName:new Aa({typeId:p9,value:Ee.serialize(new Xe(We.FromHex(n)))})});break}case gC:r=new et({iPAddress:e[1]});break;case Ax:r=new et({registeredID:e[1]});break;case xC:{r=new et({otherName:new Aa({typeId:m9,value:Ee.serialize(FS.toASN(e[1]))})});break}case yC:r=new et({uniformResourceIdentifier:e[1]});break;default:throw new Error("Cannot create GeneralName. Unsupported type of the name")}else ke.isBufferSource(e[0])?r=Ee.parse(e[0],et):r=e[0];super(r)}onInit(e){if(e.dNSName!=null)this.type=fC,this.value=e.dNSName;else if(e.rfc822Name!=null)this.type=mC,this.value=e.rfc822Name;else if(e.iPAddress!=null)this.type=gC,this.value=e.iPAddress;else if(e.uniformResourceIdentifier!=null)this.type=yC,this.value=e.uniformResourceIdentifier;else if(e.registeredID!=null)this.type=Ax,this.value=e.registeredID;else if(e.directoryName!=null)this.type=pC,this.value=new On(e.directoryName).toString();else if(e.otherName!=null)if(e.otherName.typeId===p9){this.type=bC;let r=Ee.parse(e.otherName.value,Xe),s=new RegExp(f9,"i").exec(We.ToHex(r));if(!s)throw new Error(vY);this.value=s.slice(1).map((n,i)=>i<3?We.ToHex(new Uint8Array(We.FromHex(n)).reverse()):n).join("-")}else if(e.otherName.typeId===m9)this.type=xC,this.value=Ee.parse(e.otherName.value,_r).toString();else throw new Error(h9);else throw new Error(h9)}toJSON(){return{type:this.type,value:this.value}}toTextObject(){let e;switch(this.type){case pC:case fC:case bC:case gC:case Ax:case xC:case yC:e=this.type.toUpperCase();break;case mC:e="Email";break;default:throw new Error("Unsupported GeneralName type")}let r=this.value;return this.type===Ax&&(r=Ii.toString(r)),new Rt(e,void 0,r)}},Eo=class extends Ka{constructor(e){let r;if(e instanceof Jt)r=e;else if(Array.isArray(e)){let s=[];for(let n of e)if(n instanceof et)s.push(n);else{let i=Ee.parse(new Ai(n.type,n.value).rawData,et);s.push(i)}r=new Jt(s)}else if(ke.isBufferSource(e))r=Ee.parse(e,Jt);else throw new Error("Cannot initialize GeneralNames. Incorrect incoming arguments");super(r)}onInit(e){let r=[];for(let s of e){let n=null;try{n=new Ai(s)}catch{continue}r.push(n)}this.items=r}toJSON(){return this.items.map(e=>e.toJSON())}toTextObject(){let e=super.toTextObjectEmpty();for(let r of this.items){let s=r.toTextObject(),n=e[s[Rt.NAME]];Array.isArray(n)||(n=[],e[s[Rt.NAME]]=n),n.push(s)}return e}};Eo.NAME="GeneralNames";
|
|
33
|
+
`)}function jE(t,e,r){var s=Yu(t.toString().match(/constructor\(([\w, ]+)\)/)||[],2),n=s[1],i=n===void 0?null:n,o=nY(i,e);return iY("Cannot inject the dependency "+o+' of "'+t.name+'" constructor. Reason:',r)}var $E=V(()=>{"use strict";g();y();Ju()});function UD(t){if(typeof t.dispose!="function")return!1;var e=t.dispose;return!(e.length>0)}var MD=V(()=>{"use strict";g();y()});var oY,aY,cY,jD,$D=V(()=>{"use strict";g();y();Ju();ME();oY=(function(t){am(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e})(lm),aY=(function(t){am(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e})(lm),cY=(function(){function t(){this.preResolution=new oY,this.postResolution=new aY}return t})(),jD=cY});var FE,dY,Gt,Fa=V(()=>{"use strict";g();y();Ju();UE();BD();gx();OD();IE();ND();$E();px();MD();$D();FE=new Map,dY=(function(){function t(e){this.parent=e,this._registry=new LD,this.interceptors=new jD,this.disposed=!1,this.disposables=new Set}return t.prototype.register=function(e,r,s){s===void 0&&(s={lifecycle:zr.Transient}),this.ensureNotDisposed();var n;if(DD(r)?n=r:n={useClass:r},zd(n))for(var i=[e],o=n;o!=null;){var a=o.useToken;if(i.includes(a))throw new Error("Token registration cycle detected! "+Ti(i,[a]).join(" -> "));i.push(a);var c=this._registry.get(a);c&&zd(c.provider)?o=c.provider:o=null}if((s.lifecycle===zr.Singleton||s.lifecycle==zr.ContainerScoped||s.lifecycle==zr.ResolutionScoped)&&(Wd(n)||Qu(n)))throw new Error('Cannot use lifecycle "'+zr[s.lifecycle]+'" with ValueProviders or FactoryProviders');return this._registry.set(e,{provider:n,options:s}),this},t.prototype.registerType=function(e,r){return this.ensureNotDisposed(),$a(r)?this.register(e,{useToken:r}):this.register(e,{useClass:r})},t.prototype.registerInstance=function(e,r){return this.ensureNotDisposed(),this.register(e,{useValue:r})},t.prototype.registerSingleton=function(e,r){if(this.ensureNotDisposed(),$a(e)){if($a(r))return this.register(e,{useToken:r},{lifecycle:zr.Singleton});if(r)return this.register(e,{useClass:r},{lifecycle:zr.Singleton});throw new Error('Cannot register a type name as a singleton without a "to" token')}var s=e;return r&&!$a(r)&&(s=r),this.register(e,{useClass:s},{lifecycle:zr.Singleton})},t.prototype.resolve=function(e,r,s){r===void 0&&(r=new um),s===void 0&&(s=!1),this.ensureNotDisposed();var n=this.getRegistration(e);if(!n&&$a(e)){if(s)return;throw new Error('Attempted to resolve unregistered dependency token: "'+e.toString()+'"')}if(this.executePreResolutionInterceptor(e,"Single"),n){var i=this.resolveRegistration(n,r);return this.executePostResolutionInterceptor(e,i,"Single"),i}if(PD(e)){var i=this.construct(e,r);return this.executePostResolutionInterceptor(e,i,"Single"),i}throw new Error("Attempted to construct an undefined constructor. Could mean a circular dependency problem. Try using `delay` function.")},t.prototype.executePreResolutionInterceptor=function(e,r){var s,n;if(this.interceptors.preResolution.has(e)){var i=[];try{for(var o=cm(this.interceptors.preResolution.getAll(e)),a=o.next();!a.done;a=o.next()){var c=a.value;c.options.frequency!="Once"&&i.push(c),c.callback(e,r)}}catch(d){s={error:d}}finally{try{a&&!a.done&&(n=o.return)&&n.call(o)}finally{if(s)throw s.error}}this.interceptors.preResolution.setAll(e,i)}},t.prototype.executePostResolutionInterceptor=function(e,r,s){var n,i;if(this.interceptors.postResolution.has(e)){var o=[];try{for(var a=cm(this.interceptors.postResolution.getAll(e)),c=a.next();!c.done;c=a.next()){var d=c.value;d.options.frequency!="Once"&&o.push(d),d.callback(e,r,s)}}catch(u){n={error:u}}finally{try{c&&!c.done&&(i=a.return)&&i.call(a)}finally{if(n)throw n.error}}this.interceptors.postResolution.setAll(e,o)}},t.prototype.resolveRegistration=function(e,r){if(this.ensureNotDisposed(),e.options.lifecycle===zr.ResolutionScoped&&r.scopedResolutions.has(e))return r.scopedResolutions.get(e);var s=e.options.lifecycle===zr.Singleton,n=e.options.lifecycle===zr.ContainerScoped,i=s||n,o;return Wd(e.provider)?o=e.provider.useValue:zd(e.provider)?o=i?e.instance||(e.instance=this.resolve(e.provider.useToken,r)):this.resolve(e.provider.useToken,r):dm(e.provider)?o=i?e.instance||(e.instance=this.construct(e.provider.useClass,r)):this.construct(e.provider.useClass,r):Qu(e.provider)?o=e.provider.useFactory(this):o=this.construct(e.provider,r),e.options.lifecycle===zr.ResolutionScoped&&r.scopedResolutions.set(e,o),o},t.prototype.resolveAll=function(e,r,s){var n=this;r===void 0&&(r=new um),s===void 0&&(s=!1),this.ensureNotDisposed();var i=this.getAllRegistrations(e);if(!i&&$a(e)){if(s)return[];throw new Error('Attempted to resolve unregistered dependency token: "'+e.toString()+'"')}if(this.executePreResolutionInterceptor(e,"All"),i){var o=i.map(function(c){return n.resolveRegistration(c,r)});return this.executePostResolutionInterceptor(e,o,"All"),o}var a=[this.construct(e,r)];return this.executePostResolutionInterceptor(e,a,"All"),a},t.prototype.isRegistered=function(e,r){return r===void 0&&(r=!1),this.ensureNotDisposed(),this._registry.has(e)||r&&(this.parent||!1)&&this.parent.isRegistered(e,!0)},t.prototype.reset=function(){this.ensureNotDisposed(),this._registry.clear(),this.interceptors.preResolution.clear(),this.interceptors.postResolution.clear()},t.prototype.clearInstances=function(){var e,r;this.ensureNotDisposed();try{for(var s=cm(this._registry.entries()),n=s.next();!n.done;n=s.next()){var i=Yu(n.value,2),o=i[0],a=i[1];this._registry.setAll(o,a.filter(function(c){return!Wd(c.provider)}).map(function(c){return c.instance=void 0,c}))}}catch(c){e={error:c}}finally{try{n&&!n.done&&(r=s.return)&&r.call(s)}finally{if(e)throw e.error}}},t.prototype.createChildContainer=function(){var e,r;this.ensureNotDisposed();var s=new t(this);try{for(var n=cm(this._registry.entries()),i=n.next();!i.done;i=n.next()){var o=Yu(i.value,2),a=o[0],c=o[1];c.some(function(d){var u=d.options;return u.lifecycle===zr.ContainerScoped})&&s._registry.setAll(a,c.map(function(d){return d.options.lifecycle===zr.ContainerScoped?{provider:d.provider,options:d.options}:d}))}}catch(d){e={error:d}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(e)throw e.error}}return s},t.prototype.beforeResolution=function(e,r,s){s===void 0&&(s={frequency:"Always"}),this.interceptors.preResolution.set(e,{callback:r,options:s})},t.prototype.afterResolution=function(e,r,s){s===void 0&&(s={frequency:"Always"}),this.interceptors.postResolution.set(e,{callback:r,options:s})},t.prototype.dispose=function(){return ID(this,void 0,void 0,function(){var e;return RD(this,function(r){switch(r.label){case 0:return this.disposed=!0,e=[],this.disposables.forEach(function(s){var n=s.dispose();n&&e.push(n)}),[4,Promise.all(e)];case 1:return r.sent(),[2]}})})},t.prototype.getRegistration=function(e){return this.isRegistered(e)?this._registry.get(e):this.parent?this.parent.getRegistration(e):null},t.prototype.getAllRegistrations=function(e){return this.isRegistered(e)?this._registry.getAll(e):this.parent?this.parent.getAllRegistrations(e):null},t.prototype.construct=function(e,r){var s=this;if(e instanceof fx)return e.createProxy(function(i){return s.resolve(i,r)});var n=(function(){var i=FE.get(e);if(!i||i.length===0){if(e.length===0)return new e;throw new Error('TypeInfo not known for "'+e.name+'"')}var o=i.map(s.resolveParams(r,e));return new(e.bind.apply(e,Ti([void 0],o)))})();return UD(n)&&this.disposables.add(n),n},t.prototype.resolveParams=function(e,r){var s=this;return function(n,i){var o,a,c;try{return LE(n)?mx(n)?n.multiple?(o=s.resolve(n.transform)).transform.apply(o,Ti([s.resolveAll(n.token,new um,n.isOptional)],n.transformArgs)):(a=s.resolve(n.transform)).transform.apply(a,Ti([s.resolve(n.token,e,n.isOptional)],n.transformArgs)):n.multiple?s.resolveAll(n.token,new um,n.isOptional):s.resolve(n.token,e,n.isOptional):mx(n)?(c=s.resolve(n.transform,e)).transform.apply(c,Ti([s.resolve(n.token,e)],n.transformArgs)):s.resolve(n,e)}catch(d){throw new Error(jE(r,i,d))}}},t.prototype.ensureNotDisposed=function(){if(this.disposed)throw new Error("This container has been disposed, you cannot interact with a disposed container")},t})(),Gt=new dY});var FD=V(()=>{"use strict";g();y();Vd();Fa();gx();$E()});var HD=V(()=>{"use strict";g();y();Vd()});function lY(t){return function(e){FE.set(e,PE(e)),t&&t.token&&(Array.isArray(t.token)?t.token.forEach(function(r){Gt.register(r,e)}):Gt.register(t.token,e))}}var Ha,yx=V(()=>{"use strict";g();y();Vd();Fa();Fa();Ha=lY});var qD=V(()=>{"use strict";g();y();Fa()});var VD=V(()=>{"use strict";g();y();yx();Fa()});var zD=V(()=>{"use strict";g();y();Vd()});var WD=V(()=>{"use strict";g();y();Vd()});var KD=V(()=>{"use strict";g();y();Vd()});var GD=V(()=>{"use strict";g();y();yx();Fa()});var XD=V(()=>{"use strict";g();y();FD();HD();yx();qD();VD();zD();WD();KD();GD()});var YD=V(()=>{"use strict";g();y()});var JD=V(()=>{"use strict";g();y()});var QD=V(()=>{"use strict";g();y()});var ZD=V(()=>{"use strict";g();y();YD();JD();QD()});var eB=V(()=>{"use strict";g();y();AD();XD();ZD();UE();px();Fa();if(typeof Reflect>"u"||!Reflect.getMetadata)throw new Error(`tsyringe requires a reflect polyfill. Please add 'import "reflect-metadata"' to the top of your entry point.`)});var qE,Kd,tB,VE=V(()=>{"use strict";g();y();ge();pe();Kd=class{attrId="";attrValues=[];constructor(e={}){Object.assign(e)}};v([A({type:$.ObjectIdentifier})],Kd.prototype,"attrId",void 0);v([A({type:$.Any,repeated:"set"})],Kd.prototype,"attrValues",void 0);tB=qE=class extends Ke{constructor(e){super(e),Object.setPrototypeOf(this,qE.prototype)}};tB=qE=v([ie({type:re.Sequence,itemType:Kd})],tB)});var zE,rB,sB=V(()=>{"use strict";g();y();ge();pe();Zp();rB=zE=class extends Ke{constructor(e){super(e),Object.setPrototypeOf(this,zE.prototype)}};rB=zE=v([ie({type:re.Sequence,itemType:yn})],rB)});var uY,hY,nB,Zu,eRe,tRe,rRe,sRe,nRe,iRe,Gd,WE=V(()=>{"use strict";g();y();uY="1.2.840.113549",hY=`${uY}.1`,nB=`${hY}.12`,Zu=`${nB}.1`,eRe=`${Zu}.1`,tRe=`${Zu}.2`,rRe=`${Zu}.3`,sRe=`${Zu}.4`,nRe=`${Zu}.5`,iRe=`${Zu}.6`,Gd=`${nB}.10.1`});var lRe,uRe,hRe,fRe,pRe,mRe,bx,xx=V(()=>{"use strict";g();y();WE();lRe=`${Gd}.1`,uRe=`${Gd}.2`,hRe=`${Gd}.3`,fRe=`${Gd}.4`,pRe=`${Gd}.5`,mRe=`${Gd}.6`,bx="1.2.840.113549.1.9"});var wx,iB,_Re,SRe,oB=V(()=>{"use strict";g();y();ge();pe();xx();wx=class{certId="";certValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};v([A({type:$.ObjectIdentifier})],wx.prototype,"certId",void 0);v([A({type:$.Any,context:0})],wx.prototype,"certValue",void 0);iB=`${bx}.22`,_Re=`${iB}.1`,SRe=`${iB}.2`});var vx,fY,RRe,aB=V(()=>{"use strict";g();y();ge();pe();xx();vx=class{crlId="";crltValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};v([A({type:$.ObjectIdentifier})],vx.prototype,"crlId",void 0);v([A({type:$.Any,context:0})],vx.prototype,"crltValue",void 0);fY=`${bx}.23`,RRe=`${fY}.1`});var _x,qa,cB=V(()=>{"use strict";g();y();ge();pe();kt();_x=class extends Xe{},qa=class{encryptionAlgorithm=new _e;encryptedData=new _x;constructor(e={}){Object.assign(this,e)}};v([A({type:_e})],qa.prototype,"encryptionAlgorithm",void 0);v([A({type:_x})],qa.prototype,"encryptedData",void 0)});var KE,GE,Sx,XE,Va,dB=V(()=>{"use strict";g();y();ge();pe();kt();(function(t){t[t.v1=0]="v1"})(GE||(GE={}));Sx=class extends Xe{},XE=KE=class extends Ke{constructor(e){super(e),Object.setPrototypeOf(this,KE.prototype)}};XE=KE=v([ie({type:re.Sequence,itemType:Fr})],XE);Va=class{version=GE.v1;privateKeyAlgorithm=new _e;privateKey=new Sx;attributes;constructor(e={}){Object.assign(this,e)}};v([A({type:$.Integer})],Va.prototype,"version",void 0);v([A({type:_e})],Va.prototype,"privateKeyAlgorithm",void 0);v([A({type:Sx})],Va.prototype,"privateKey",void 0);v([A({type:XE,implicit:!0,context:0,optional:!0})],Va.prototype,"attributes",void 0)});var Ex=V(()=>{"use strict";g();y();cB();dB()});var lB,uB=V(()=>{"use strict";g();y();ge();Ex();pe();lB=class extends Va{};lB=v([ie({type:re.Sequence})],lB)});var hB,fB=V(()=>{"use strict";g();y();ge();Ex();pe();hB=class extends qa{};hB=v([ie({type:re.Sequence})],hB)});var Cx,pB=V(()=>{"use strict";g();y();ge();pe();Cx=class{secretTypeId="";secretValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};v([A({type:$.ObjectIdentifier})],Cx.prototype,"secretTypeId",void 0);v([A({type:$.Any,context:0})],Cx.prototype,"secretValue",void 0)});var mB=V(()=>{"use strict";g();y();oB();aB();uB();fB();pB();xx()});var za,YE=V(()=>{"use strict";g();y();ge();hx();pe();za=class{mac=new qd;macSalt=new Xe;iterations=1;constructor(e={}){Object.assign(this,e)}};v([A({type:qd})],za.prototype,"mac",void 0);v([A({type:Xe})],za.prototype,"macSalt",void 0);v([A({type:$.Integer,defaultValue:1})],za.prototype,"iterations",void 0)});var Xd,gB=V(()=>{"use strict";g();y();ge();pe();Zp();YE();Xd=class{version=3;authSafe=new yn;macData=new za;constructor(e={}){Object.assign(this,e)}};v([A({type:$.Integer})],Xd.prototype,"version",void 0);v([A({type:yn})],Xd.prototype,"authSafe",void 0);v([A({type:za,optional:!0})],Xd.prototype,"macData",void 0)});var JE,eh,yB,bB=V(()=>{"use strict";g();y();ge();pe();VE();eh=class{bagId="";bagValue=new ArrayBuffer(0);bagAttributes;constructor(e={}){Object.assign(this,e)}};v([A({type:$.ObjectIdentifier})],eh.prototype,"bagId",void 0);v([A({type:$.Any,context:0})],eh.prototype,"bagValue",void 0);v([A({type:Kd,repeated:"set",optional:!0})],eh.prototype,"bagAttributes",void 0);yB=JE=class extends Ke{constructor(e){super(e),Object.setPrototypeOf(this,JE.prototype)}};yB=JE=v([ie({type:re.Sequence,itemType:eh})],yB)});var xB=V(()=>{"use strict";g();y();VE();sB();mB();YE();WE();gB();bB()});var QE,ZE,eC,hr,r6e,BB,fm,LB,OB,s6e,n6e,i6e,o6e,a6e,c6e,d6e,l6e,cC,u6e,h6e,f6e,pm,p6e,m6e,g6e,y6e,b6e,x6e,w6e,v6e,mm,_6e,S6e,E6e,C6e,T6e,k6e,A6e,I6e,R6e,P6e,D6e,B6e,L6e,Tx,wB,vB,_B,tC,SB,EB,rC,CB,sC,kx,TB,kB,nC,AB,iC,IB,hm,RB,PB,oC,aC,DB,dC=V(()=>{"use strict";g();y();ge();pe();Zp();xB();Ex();kt();Y2();hr="1.2.840.113549.1.9",r6e=`${hr}.0`,BB=`${hr}.24`,fm=`${hr}.25`,LB=`${hr}.26`,OB=`${hr}.27`,s6e=`${BB}.1`,n6e=`${BB}.2`,i6e=`${hr}.1`,o6e=`${hr}.2`,a6e=`${hr}.3`,c6e=`${hr}.4`,d6e=`${hr}.5`,l6e=`${hr}.6`,cC=`${hr}.7`,u6e=`${hr}.8`,h6e=`${hr}.9`,f6e=`${hr}.13`,pm=`${hr}.14`,p6e=`${hr}.15`,m6e=`${hr}.20`,g6e=`${hr}.21`,y6e=`${fm}.1`,b6e=`${fm}.2`,x6e=`${fm}.3`,w6e=`${fm}.4`,v6e=`${fm}.5`,mm="1.3.6.1.5.5.7.9",_6e=`${mm}.1`,S6e=`${mm}.2`,E6e=`${mm}.3`,C6e=`${mm}.4`,T6e=`${mm}.5`,k6e=`${LB}.1`,A6e=`${LB}.2`,I6e=`${OB}.1`,R6e=`${OB}.2`,P6e=`${hr}.16`,D6e=`${hr}.22`,B6e=`${hr}.23`,L6e=`${W2}.65`,Tx=class extends _r{ia5String;constructor(e={}){super(e)}toString(){return{}.toString(),this.ia5String||super.toString()}};v([A({type:$.IA5String})],Tx.prototype,"ia5String",void 0);Tx=v([ie({type:re.Choice})],Tx);wB=class extends yn{};wB=v([ie({type:re.Sequence})],wB);vB=class extends Xd{};vB=v([ie({type:re.Sequence})],vB);_B=class extends qa{};_B=v([ie({type:re.Sequence})],_B);tC=class{value;constructor(e=""){this.value=e}toString(){return this.value}};v([A({type:$.IA5String})],tC.prototype,"value",void 0);tC=v([ie({type:re.Choice})],tC);SB=class extends Tx{};SB=v([ie({type:re.Choice})],SB);EB=class extends _r{};EB=v([ie({type:re.Choice})],EB);rC=class{value;constructor(e=new Date){this.value=e}};v([A({type:$.GeneralizedTime})],rC.prototype,"value",void 0);rC=v([ie({type:re.Choice})],rC);CB=class extends _r{};CB=v([ie({type:re.Choice})],CB);sC=class{value;constructor(e="M"){this.value=e}toString(){return this.value}};v([A({type:$.PrintableString})],sC.prototype,"value",void 0);sC=v([ie({type:re.Choice})],sC);kx=class{value;constructor(e=""){this.value=e}toString(){return this.value}};v([A({type:$.PrintableString})],kx.prototype,"value",void 0);kx=v([ie({type:re.Choice})],kx);TB=class extends kx{};TB=v([ie({type:re.Choice})],TB);kB=class extends _r{};kB=v([ie({type:re.Choice})],kB);nC=class{value;constructor(e=""){this.value=e}toString(){return this.value}};v([A({type:$.ObjectIdentifier})],nC.prototype,"value",void 0);nC=v([ie({type:re.Choice})],nC);AB=class extends ur{};AB=v([ie({type:re.Choice})],AB);iC=class{value;constructor(e=0){this.value=e}toString(){return this.value.toString()}};v([A({type:$.Integer})],iC.prototype,"value",void 0);iC=v([ie({type:re.Choice})],iC);IB=class extends Ts{};IB=v([ie({type:re.Sequence})],IB);hm=class extends _r{};hm=v([ie({type:re.Choice})],hm);RB=QE=class extends qs{constructor(e){super(e),Object.setPrototypeOf(this,QE.prototype)}};RB=QE=v([ie({type:re.Sequence})],RB);PB=ZE=class extends Ke{constructor(e){super(e),Object.setPrototypeOf(this,ZE.prototype)}};PB=ZE=v([ie({type:re.Set,itemType:Ln})],PB);oC=class{value;constructor(e=""){this.value=e}toString(){return this.value}};v([A({type:$.BmpString})],oC.prototype,"value",void 0);oC=v([ie({type:re.Choice})],oC);aC=class extends _e{};aC=v([ie({type:re.Sequence})],aC);DB=eC=class extends Ke{constructor(e){super(e),Object.setPrototypeOf(this,eC.prototype)}};DB=eC=v([ie({type:re.Sequence,itemType:aC})],DB)});var lC,gm,uC=V(()=>{"use strict";g();y();ge();pe();kt();gm=lC=class extends Ke{constructor(e){super(e),Object.setPrototypeOf(this,lC.prototype)}};gm=lC=v([ie({type:re.Sequence,itemType:Fr})],gm)});var ki,hC=V(()=>{"use strict";g();y();ge();pe();kt();uC();ki=class{version=0;subject=new Vt;subjectPKInfo=new Hr;attributes=new gm;constructor(e={}){Object.assign(this,e)}};v([A({type:$.Integer})],ki.prototype,"version",void 0);v([A({type:Vt})],ki.prototype,"subject",void 0);v([A({type:Hr})],ki.prototype,"subjectPKInfo",void 0);v([A({type:gm,implicit:!0,context:0,optional:!0})],ki.prototype,"attributes",void 0)});var Wa,NB=V(()=>{"use strict";g();y();ge();pe();kt();hC();Wa=class{certificationRequestInfo=new ki;certificationRequestInfoRaw;signatureAlgorithm=new _e;signature=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};v([A({type:ki,raw:!0})],Wa.prototype,"certificationRequestInfo",void 0);v([A({type:_e})],Wa.prototype,"signatureAlgorithm",void 0);v([A({type:$.BitString})],Wa.prototype,"signature",void 0)});var UB=V(()=>{"use strict";g();y();uC();NB();hC()});function bY(t){return new RegExp(yY).test(t)}function xY(t,e){return`\\${We.ToHex(We.FromUtf8String(e)).toUpperCase()}`}function wY(t){return t.replace(/([,+"\\<>;])/g,"\\$1").replace(/^([ #])/,"\\$1").replace(/([ ]$)/,"\\$1").replace(/([\r\n\t])/,xY)}function IY(t,e){return t.algorithm=new _e({algorithm:Ei,parameters:null}),e=Ee.serialize(t),e}function Ix(t,e,r){if(r.length===1)t[e]=r[0].toTextObject();else{let s=new Rt("");r.forEach((n,i)=>{let o=n.toTextObject(),a=`${o[Rt.NAME]} ${i+1}`,c=s[a];Array.isArray(c)||(c=[],s[a]=c),c.push(o)}),t[e]=s}}function Rx(t,e,r,s){let n=e[s];n&&(Array.isArray(n)?n:[n]).forEach(o=>{typeof o=="string"&&(o=new Ai("url",o)),t.push(new po({accessMethod:r,accessLocation:Ee.parse(o.rawData,et)}))})}function RY(t,e=Sr.get()){let r=ke.toUint8Array(We.FromHex(t||"")),s=r&&r.length&&r.some(i=>i>0)?new Uint8Array(r):void 0;s||(s=e.getRandomValues(new Uint8Array(16)));let n=0;for(;n<s.length-1&&s[n]===0;)n++;if(s=s.slice(n),s[0]>127){let i=new Uint8Array(s.length+1);i[0]=0,i.set(s,1),s=i}return s.buffer}var L4e,$m,_C,Yd,Px,Rs,MB,jB,$B,FB,HB,qB,VB,zB,WB,KB,GB,XB,YB,JB,QB,ZB,e9,t9,r9,s9,n9,i9,o9,a9,c9,d9,l9,u9,or,Nm,_9,S9,Rt,SC,Ii,So,th,Ka,zs,E9,Um,Sr,yY,Bx,Is,On,C9,h9,vY,f9,p9,m9,fC,pC,mC,gC,yC,bC,xC,Ax,Ai,Eo,Om,Mm,_Y,SY,EY,nh,CY,TY,kY,AY,g9,Wr,Ga,_o,Lx,Ox,y9,Nx,b9,Ux,Mx,jx,ms,$x,Fx,Hx,qx,ih,Vx,jm,oh,Fm,EC,Dx,CC,TC,Co,wC,x9,vC,w9,kC,ym,bm,xm,wm,vm,_m,Sm,rh,AC,Em,Cm,Tm,km,Am,Im,Rm,Pm,Dm,Bm,sh,Lm,zx,Wx,PY,DY,BY,LY,OY,v9,NY,UY,MY,jY,$Y,FY,HY,T9=V(()=>{"use strict";g();y();L4e=Le(Tv());pe();kt();kt();RS();ge();Zp();_E();_E();hx();hx();eB();dC();dC();UB();$m="crypto.algorithm",_C=class{getAlgorithms(){return Gt.resolveAll($m)}toAsnAlgorithm(e){({...e});for(let r of this.getAlgorithms()){let s=r.toAsnAlgorithm(e);if(s)return s}if(/^[0-9.]+$/.test(e.name)){let r=new _e({algorithm:e.name});if("parameters"in e){let s=e;r.parameters=s.parameters}return r}throw new Error("Cannot convert WebCrypto algorithm to ASN.1 algorithm")}toWebAlgorithm(e){for(let s of this.getAlgorithms()){let n=s.toWebAlgorithm(e);if(n)return n}return{name:e.algorithm,parameters:e.parameters}}},Yd="crypto.algorithmProvider";Gt.registerSingleton(Yd,_C);Rs="1.3.36.3.3.2.8.1.1",MB=`${Rs}.1`,jB=`${Rs}.2`,$B=`${Rs}.3`,FB=`${Rs}.4`,HB=`${Rs}.5`,qB=`${Rs}.6`,VB=`${Rs}.7`,zB=`${Rs}.8`,WB=`${Rs}.9`,KB=`${Rs}.10`,GB=`${Rs}.11`,XB=`${Rs}.12`,YB=`${Rs}.13`,JB=`${Rs}.14`,QB="brainpoolP160r1",ZB="brainpoolP160t1",e9="brainpoolP192r1",t9="brainpoolP192t1",r9="brainpoolP224r1",s9="brainpoolP224t1",n9="brainpoolP256r1",i9="brainpoolP256t1",o9="brainpoolP320r1",a9="brainpoolP320t1",c9="brainpoolP384r1",d9="brainpoolP384t1",l9="brainpoolP512r1",u9="brainpoolP512t1",or="ECDSA",Nm=Px=class{toAsnAlgorithm(e){switch(e.name.toLowerCase()){case or.toLowerCase():if("hash"in e)switch((typeof e.hash=="string"?e.hash:e.hash.name).toLowerCase()){case"sha-1":return oD;case"sha-256":return aD;case"sha-384":return cD;case"sha-512":return dD}else if("namedCurve"in e){let r="";switch(e.namedCurve){case"P-256":r=pE;break;case"K-256":r=Px.SECP256K1;break;case"P-384":r=mE;break;case"P-521":r=gE;break;case QB:r=MB;break;case ZB:r=jB;break;case e9:r=$B;break;case t9:r=FB;break;case r9:r=HB;break;case s9:r=qB;break;case n9:r=VB;break;case i9:r=zB;break;case o9:r=WB;break;case a9:r=KB;break;case c9:r=GB;break;case d9:r=XB;break;case l9:r=YB;break;case u9:r=JB;break}if(r)return new _e({algorithm:Ud,parameters:Ee.serialize(new Si({namedCurve:r}))})}}return null}toWebAlgorithm(e){switch(e.algorithm){case em:return{name:or,hash:{name:"SHA-1"}};case tm:return{name:or,hash:{name:"SHA-256"}};case rm:return{name:or,hash:{name:"SHA-384"}};case sm:return{name:or,hash:{name:"SHA-512"}};case Ud:{if(!e.parameters)throw new TypeError("Cannot get required parameters from EC algorithm");switch(Ee.parse(e.parameters,Si).namedCurve){case pE:return{name:or,namedCurve:"P-256"};case Px.SECP256K1:return{name:or,namedCurve:"K-256"};case mE:return{name:or,namedCurve:"P-384"};case gE:return{name:or,namedCurve:"P-521"};case MB:return{name:or,namedCurve:QB};case jB:return{name:or,namedCurve:ZB};case $B:return{name:or,namedCurve:e9};case FB:return{name:or,namedCurve:t9};case HB:return{name:or,namedCurve:r9};case qB:return{name:or,namedCurve:s9};case VB:return{name:or,namedCurve:n9};case zB:return{name:or,namedCurve:i9};case WB:return{name:or,namedCurve:o9};case KB:return{name:or,namedCurve:a9};case GB:return{name:or,namedCurve:c9};case XB:return{name:or,namedCurve:d9};case YB:return{name:or,namedCurve:l9};case JB:return{name:or,namedCurve:u9}}}}return null}};Nm.SECP256K1="1.3.132.0.10";Nm=Px=v([Ha()],Nm);Gt.registerSingleton($m,Nm);_9=Symbol("name"),S9=Symbol("value"),Rt=class{constructor(e,r={},s=""){this[_9]=e,this[S9]=s;for(let n in r)this[n]=r[n]}};Rt.NAME=_9;Rt.VALUE=S9;SC=class{static toTextObject(e){let r=new Rt("Algorithm Identifier",{},Ii.toString(e.algorithm));if(e.parameters)if(e.algorithm===Ud){let s=new Nm().toWebAlgorithm(e);s&&"namedCurve"in s?r["Named Curve"]=s.namedCurve:r.Parameters=e.parameters}else r.Parameters=e.parameters;return r}},Ii=class{static toString(e){let r=this.items[e];return r||e}};Ii.items={[jd]:"sha1",[cx]:"sha224",[$d]:"sha256",[Fd]:"sha384",[Hd]:"sha512",[Ei]:"rsaEncryption",[Vu]:"sha1WithRSAEncryption",[yD]:"sha224WithRSAEncryption",[ax]:"sha256WithRSAEncryption",[zu]:"sha384WithRSAEncryption",[Wu]:"sha512WithRSAEncryption",[Ud]:"ecPublicKey",[em]:"ecdsaWithSHA1",[ox]:"ecdsaWithSHA224",[tm]:"ecdsaWithSHA256",[rm]:"ecdsaWithSHA384",[sm]:"ecdsaWithSHA512",[aP]:"TLS WWW server authentication",[cP]:"TLS WWW client authentication",[dP]:"Code Signing",[lP]:"E-mail Protection",[uP]:"Time Stamping",[hP]:"OCSP Signing",[rD]:"Signed Data"};So=class{static serialize(e){return this.serializeObj(e).join(`
|
|
34
|
+
`)}static pad(e=0){return"".padStart(2*e," ")}static serializeObj(e,r=0){let s=[],n=this.pad(r++),i="",o=e[Rt.VALUE];o&&(i=` ${o}`),s.push(`${n}${e[Rt.NAME]}:${i}`),n=this.pad(r);for(let a in e){if(typeof a=="symbol")continue;let c=e[a],d=a?`${a}: `:"";if(typeof c=="string"||typeof c=="number"||typeof c=="boolean")s.push(`${n}${d}${c}`);else if(c instanceof Date)s.push(`${n}${d}${c.toUTCString()}`);else if(Array.isArray(c))for(let u of c)u[Rt.NAME]=a,s.push(...this.serializeObj(u,r));else if(c instanceof Rt)c[Rt.NAME]=a,s.push(...this.serializeObj(c,r));else if(ke.isBufferSource(c))a?(s.push(`${n}${d}`),s.push(...this.serializeBufferSource(c,r+1))):s.push(...this.serializeBufferSource(c,r));else if("toTextObject"in c){let u=c.toTextObject();u[Rt.NAME]=a,s.push(...this.serializeObj(u,r))}else throw new TypeError("Cannot serialize data in text format. Unsupported type.")}return s}static serializeBufferSource(e,r=0){let s=this.pad(r),n=ke.toUint8Array(e),i=[];for(let o=0;o<n.length;){let a=[];for(let c=0;c<16&&o<n.length;c++){c===8&&a.push("");let d=n[o++].toString(16).padStart(2,"0");a.push(d)}i.push(`${s}${a.join(" ")}`)}return i}static serializeAlgorithm(e){return this.algorithmSerializer.toTextObject(e)}};So.oidSerializer=Ii;So.algorithmSerializer=SC;Ka=class t{get rawData(){return gt(this,th,"f")||Yt(this,th,Ee.serialize(this.asn),"f"),gt(this,th,"f")}constructor(...e){th.set(this,void 0),ke.isBufferSource(e[0])?(this.asn=Ee.parse(e[0],e[1]),Yt(this,th,ke.toArrayBuffer(e[0]),"f"),this.onInit(this.asn)):(this.asn=e[0],this.onInit(this.asn))}equal(e){return e instanceof t?B8(e.rawData,this.rawData):!1}toString(e="text"){switch(e){case"asn":return Ee.toString(this.rawData);case"text":return So.serialize(this.toTextObject());case"hex":return We.ToHex(this.rawData);case"base64":return We.ToBase64(this.rawData);case"base64url":return We.ToBase64Url(this.rawData);default:throw TypeError("Argument 'format' is unsupported value")}}getTextName(){return this.constructor.NAME}toTextObject(){let e=this.toTextObjectEmpty();return e[""]=this.rawData,e}toTextObjectEmpty(e){return new Rt(this.getTextName(),{},e)}};th=new WeakMap;Ka.NAME="ASN";zs=class t extends Ka{constructor(...e){let r;ke.isBufferSource(e[0])?r=ke.toArrayBuffer(e[0]):r=Ee.serialize(new as({extnID:e[0],critical:e[1],extnValue:new Xe(ke.toArrayBuffer(e[2]))})),super(r,as)}onInit(e){this.type=e.extnID,this.critical=e.critical,this.value=e.extnValue.buffer}toTextObject(){let e=this.toTextObjectWithoutValue();return e[""]=this.value,e}toTextObjectWithoutValue(){let e=this.toTextObjectEmpty(this.critical?"critical":void 0);return e[Rt.NAME]===t.NAME&&(e[Rt.NAME]=Ii.toString(this.type)),e}},Um=class t{static isCryptoKeyPair(e){return e&&e.privateKey&&e.publicKey}static isCryptoKey(e){return e&&e.usages&&e.type&&e.algorithm&&e.extractable!==void 0}constructor(){this.items=new Map,this[E9]="CryptoProvider",typeof self<"u"&&typeof crypto<"u"?this.set(t.DEFAULT,crypto):typeof global<"u"&&global.crypto&&global.crypto.subtle&&this.set(t.DEFAULT,global.crypto)}clear(){this.items.clear()}delete(e){return this.items.delete(e)}forEach(e,r){return this.items.forEach(e,r)}has(e){return this.items.has(e)}get size(){return this.items.size}entries(){return this.items.entries()}keys(){return this.items.keys()}values(){return this.items.values()}[Symbol.iterator](){return this.items[Symbol.iterator]()}get(e=t.DEFAULT){let r=this.items.get(e.toLowerCase());if(!r)throw new Error(`Cannot get Crypto by name '${e}'`);return r}set(e,r){if(typeof e=="string"){if(!r)throw new TypeError("Argument 'value' is required");this.items.set(e.toLowerCase(),r)}else this.items.set(t.DEFAULT,e);return this}};E9=Symbol.toStringTag;Um.DEFAULT="default";Sr=new Um,yY=/^[0-2](?:\.[1-9][0-9]*)+$/;Bx=class{constructor(e={}){this.items={};for(let r in e)this.register(r,e[r])}get(e){return this.items[e]||null}findId(e){return bY(e)?e:this.get(e)}register(e,r){this.items[e]=r,this.items[r]=e}},Is=new Bx;Is.register("CN","2.5.4.3");Is.register("L","2.5.4.7");Is.register("ST","2.5.4.8");Is.register("O","2.5.4.10");Is.register("OU","2.5.4.11");Is.register("C","2.5.4.6");Is.register("DC","0.9.2342.19200300.100.1.25");Is.register("E","1.2.840.113549.1.9.1");Is.register("G","2.5.4.42");Is.register("I","2.5.4.43");Is.register("SN","2.5.4.4");Is.register("T","2.5.4.12");On=class t{static isASCII(e){for(let r=0;r<e.length;r++)if(e.charCodeAt(r)>255)return!1;return!0}static isPrintableString(e){return/^[A-Za-z0-9 '()+,-./:=?]*$/g.test(e)}constructor(e,r={}){this.extraNames=new Bx,this.asn=new Vt;for(let s in r)if(Object.prototype.hasOwnProperty.call(r,s)){let n=r[s];this.extraNames.register(s,n)}typeof e=="string"?this.asn=this.fromString(e):e instanceof Vt?this.asn=e:ke.isBufferSource(e)?this.asn=Ee.parse(e,Vt):this.asn=this.fromJSON(e)}getField(e){let r=this.extraNames.findId(e)||Is.findId(e),s=[];for(let n of this.asn)for(let i of n)i.type===r&&s.push(i.value.toString());return s}getName(e){return this.extraNames.get(e)||Is.get(e)}toString(){return this.asn.map(e=>e.map(r=>{let s=this.getName(r.type)||r.type,n=r.value.anyValue?`#${We.ToHex(r.value.anyValue)}`:wY(r.value.toString());return`${s}=${n}`}).join("+")).join(", ")}toJSON(){var e;let r=[];for(let s of this.asn){let n={};for(let i of s){let o=this.getName(i.type)||i.type;(e=n[o])!==null&&e!==void 0||(n[o]=[]),n[o].push(i.value.anyValue?`#${We.ToHex(i.value.anyValue)}`:i.value.toString())}r.push(n)}return r}fromString(e){let r=new Vt,s=/(\d\.[\d.]*\d|[A-Za-z]+)=((?:"")|(?:".*?[^\\]")|(?:[^,+"\\](?=[,+]|$))|(?:[^,+].*?(?:[^\\][,+]))|(?:))([,+])?/g,n=null,i=",";for(;n=s.exec(`${e},`);){let[,o,a]=n,c=a[a.length-1];(c===","||c==="+")&&(a=a.slice(0,a.length-1),n[3]=c);let d=n[3];o=this.getTypeOid(o);let u=this.createAttribute(o,a);i==="+"?r[r.length-1].push(u):r.push(new ka([u])),i=d}return r}fromJSON(e){let r=new Vt;for(let s of e){let n=new ka;for(let i in s){let o=this.getTypeOid(i),a=s[i];for(let c of a){let d=this.createAttribute(o,c);n.push(d)}}r.push(n)}return r}getTypeOid(e){if(/[\d.]+/.test(e)||(e=this.getName(e)||""),!e)throw new Error(`Cannot get OID for name type '${e}'`);return e}createAttribute(e,r){let s=new md({type:e});if(typeof r=="object")for(let n in r)switch(n){case"ia5String":s.value.ia5String=r[n];break;case"utf8String":s.value.utf8String=r[n];break;case"universalString":s.value.universalString=r[n];break;case"bmpString":s.value.bmpString=r[n];break;case"printableString":s.value.printableString=r[n];break}else if(r[0]==="#")s.value.anyValue=We.FromHex(r.slice(1));else{let n=this.processStringValue(r);e===this.getName("E")||e===this.getName("DC")?s.value.ia5String=n:t.isPrintableString(n)?s.value.printableString=n:s.value.utf8String=n}return s}processStringValue(e){let r=/"(.*?[^\\])?"/.exec(e);return r&&(e=r[1]),e.replace(/\\0a/ig,`
|
|
35
|
+
`).replace(/\\0d/ig,"\r").replace(/\\0g/ig," ").replace(/\\(.)/g,"$1")}toArrayBuffer(){return Ee.serialize(this.asn)}async getThumbprint(...e){var r;let s,n="SHA-1";return e.length>=1&&!(!((r=e[0])===null||r===void 0)&&r.subtle)?(n=e[0]||n,s=e[1]||Sr.get()):s=e[0]||Sr.get(),await s.subtle.digest(n,this.toArrayBuffer())}},C9="Cannot initialize GeneralName from ASN.1 data.",h9=`${C9} Unsupported string format in use.`,vY=`${C9} Value doesn't match to GUID regular expression.`,f9=/^([0-9a-f]{8})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{12})$/i,p9="1.3.6.1.4.1.311.25.1",m9="1.3.6.1.4.1.311.20.2.3",fC="dns",pC="dn",mC="email",gC="ip",yC="url",bC="guid",xC="upn",Ax="id",Ai=class extends Ka{constructor(...e){let r;if(e.length===2)switch(e[0]){case pC:{let s=new On(e[1]).toArrayBuffer(),n=Ee.parse(s,Vt);r=new et({directoryName:n});break}case fC:r=new et({dNSName:e[1]});break;case mC:r=new et({rfc822Name:e[1]});break;case bC:{let s=new RegExp(f9,"i").exec(e[1]);if(!s)throw new Error("Cannot parse GUID value. Value doesn't match to regular expression");let n=s.slice(1).map((i,o)=>o<3?We.ToHex(new Uint8Array(We.FromHex(i)).reverse()):i).join("");r=new et({otherName:new Aa({typeId:p9,value:Ee.serialize(new Xe(We.FromHex(n)))})});break}case gC:r=new et({iPAddress:e[1]});break;case Ax:r=new et({registeredID:e[1]});break;case xC:{r=new et({otherName:new Aa({typeId:m9,value:Ee.serialize(FS.toASN(e[1]))})});break}case yC:r=new et({uniformResourceIdentifier:e[1]});break;default:throw new Error("Cannot create GeneralName. Unsupported type of the name")}else ke.isBufferSource(e[0])?r=Ee.parse(e[0],et):r=e[0];super(r)}onInit(e){if(e.dNSName!=null)this.type=fC,this.value=e.dNSName;else if(e.rfc822Name!=null)this.type=mC,this.value=e.rfc822Name;else if(e.iPAddress!=null)this.type=gC,this.value=e.iPAddress;else if(e.uniformResourceIdentifier!=null)this.type=yC,this.value=e.uniformResourceIdentifier;else if(e.registeredID!=null)this.type=Ax,this.value=e.registeredID;else if(e.directoryName!=null)this.type=pC,this.value=new On(e.directoryName).toString();else if(e.otherName!=null)if(e.otherName.typeId===p9){this.type=bC;let r=Ee.parse(e.otherName.value,Xe),s=new RegExp(f9,"i").exec(We.ToHex(r));if(!s)throw new Error(vY);this.value=s.slice(1).map((n,i)=>i<3?We.ToHex(new Uint8Array(We.FromHex(n)).reverse()):n).join("-")}else if(e.otherName.typeId===m9)this.type=xC,this.value=Ee.parse(e.otherName.value,_r).toString();else throw new Error(h9);else throw new Error(h9)}toJSON(){return{type:this.type,value:this.value}}toTextObject(){let e;switch(this.type){case pC:case fC:case bC:case gC:case Ax:case xC:case yC:e=this.type.toUpperCase();break;case mC:e="Email";break;default:throw new Error("Unsupported GeneralName type")}let r=this.value;return this.type===Ax&&(r=Ii.toString(r)),new Rt(e,void 0,r)}},Eo=class extends Ka{constructor(e){let r;if(e instanceof Jt)r=e;else if(Array.isArray(e)){let s=[];for(let n of e)if(n instanceof et)s.push(n);else{let i=Ee.parse(new Ai(n.type,n.value).rawData,et);s.push(i)}r=new Jt(s)}else if(ke.isBufferSource(e))r=Ee.parse(e,Jt);else throw new Error("Cannot initialize GeneralNames. Incorrect incoming arguments");super(r)}onInit(e){let r=[];for(let s of e){let n=null;try{n=new Ai(s)}catch{continue}r.push(n)}this.items=r}toJSON(){return this.items.map(e=>e.toJSON())}toTextObject(){let e=super.toTextObjectEmpty();for(let r of this.items){let s=r.toTextObject(),n=e[s[Rt.NAME]];Array.isArray(n)||(n=[],e[s[Rt.NAME]]=n),n.push(s)}return e}};Eo.NAME="GeneralNames";Om="-{5}",Mm="\\n",_Y=`[^${Mm}]+`,SY=`${Om}BEGIN (${_Y}(?=${Om}))${Om}`,EY=`${Om}END \\1${Om}`,nh="\\n",CY=`[^:${Mm}]+`,TY=`(?:[^${Mm}]+${nh}(?: +[^${Mm}]+${nh})*)`,kY="[a-zA-Z0-9=+/]+",AY=`(?:${kY}${nh})+`,g9=`${SY}${nh}(?:((?:${CY}: ${TY})+))?${nh}?(${AY})${EY}`,Wr=class{static isPem(e){return typeof e=="string"&&new RegExp(g9,"g").test(e.replace(/\r/g,""))}static decodeWithHeaders(e){e=e.replace(/\r/g,"");let r=new RegExp(g9,"g"),s=[],n=null;for(;n=r.exec(e);){let i=n[3].replace(new RegExp(`[${Mm}]+`,"g"),""),o={type:n[1],headers:[],rawData:We.FromBase64(i)},a=n[2];if(a){let c=a.split(new RegExp(nh,"g")),d=null;for(let u of c){let[l,h]=u.split(/:(.*)/);if(h===void 0){if(!d)throw new Error("Cannot parse PEM string. Incorrect header value");d.value+=l.trim()}else d&&o.headers.push(d),d={key:l,value:h.trim()}}d&&o.headers.push(d)}s.push(o)}return s}static decode(e){return this.decodeWithHeaders(e).map(s=>s.rawData)}static decodeFirst(e){let r=this.decode(e);if(!r.length)throw new RangeError("PEM string doesn't contain any objects");return r[0]}static encode(e,r){if(Array.isArray(e)){let s=new Array;return r?e.forEach(n=>{if(!ke.isBufferSource(n))throw new TypeError("Cannot encode array of BufferSource in PEM format. Not all items of the array are BufferSource");s.push(this.encodeStruct({type:r,rawData:ke.toArrayBuffer(n)}))}):e.forEach(n=>{if(!("type"in n))throw new TypeError("Cannot encode array of PemStruct in PEM format. Not all items of the array are PemStrut");s.push(this.encodeStruct(n))}),s.join(`
|
|
36
36
|
`)}else{if(!r)throw new Error("Required argument 'tag' is missed");return this.encodeStruct({type:r,rawData:ke.toArrayBuffer(e)})}}static encodeStruct(e){var r;let s=e.type.toLocaleUpperCase(),n=[];if(n.push(`-----BEGIN ${s}-----`),!((r=e.headers)===null||r===void 0)&&r.length){for(let d of e.headers)n.push(`${d.key}: ${d.value}`);n.push("")}let i=We.ToBase64(e.rawData),o,a=0,c=Array();for(;a<i.length&&(i.length-a<64?o=i.substring(a):(o=i.substring(a,a+64),a+=64),o.length!==0);)if(c.push(o),o.length<64)break;return n.push(...c),n.push(`-----END ${s}-----`),n.join(`
|
|
37
|
-
`)}};Wr.CertificateTag="CERTIFICATE";Wr.CrlTag="CRL";Wr.CertificateRequestTag="CERTIFICATE REQUEST";Wr.PublicKeyTag="PUBLIC KEY";Wr.PrivateKeyTag="PRIVATE KEY";Ga=class t extends Ka{static isAsnEncoded(e){return ke.isBufferSource(e)||typeof e=="string"}static toArrayBuffer(e){if(typeof e=="string"){if(Wr.isPem(e))return Wr.decode(e)[0];if(We.isHex(e))return We.FromHex(e);if(We.isBase64(e))return We.FromBase64(e);if(We.isBase64Url(e))return We.FromBase64Url(e);throw new TypeError("Unsupported format of 'raw' argument. Must be one of DER, PEM, HEX, Base64, or Base4Url")}else{let r=ke.toUint8Array(e);if(r.length>0&&r[0]===48)return ke.toArrayBuffer(e);let s=We.ToBinary(e);if(Wr.isPem(s))return Wr.decode(s)[0];if(We.isHex(s))return We.FromHex(s);if(We.isBase64(s))return We.FromBase64(s);if(We.isBase64Url(s))return We.FromBase64Url(s);throw new TypeError("Unsupported format of 'raw' argument. Must be one of DER, PEM, HEX, Base64, or Base4Url")}}constructor(...e){t.isAsnEncoded(e[0])?super(t.toArrayBuffer(e[0]),e[1]):super(e[0])}toString(e="pem"){return e==="pem"?Wr.encode(this.rawData,this.tag):super.toString(e)}},_o=class t extends Ga{static async create(e,r=Sr.get()){if(e instanceof t)return e;if(U0.isCryptoKey(e)){if(e.type!=="public")throw new TypeError("Public key is required");let s=await r.subtle.exportKey("spki",e);return new t(s)}else{if(e.publicKey)return e.publicKey;if(ke.isBufferSource(e))return new t(e);throw new TypeError("Unsupported PublicKeyType")}}constructor(e){Ga.isAsnEncoded(e)?super(e,Hr):super(e),this.tag=Wr.PublicKeyTag}async export(...e){let r,s=["verify"],n={hash:"SHA-256",...this.algorithm};e.length>1?(n=e[0]||n,s=e[1]||s,r=e[2]||Sr.get()):r=e[0]||Sr.get();let i=this.rawData,o=Ee.parse(this.rawData,Hr);return o.algorithm.algorithm===Ma&&(i=IY(o,i)),r.subtle.importKey("spki",i,n,!0,s)}onInit(e){let r=Gt.resolve(Yd),s=this.algorithm=r.toWebAlgorithm(e.algorithm);if(e.algorithm.algorithm===Ei){let n=Ee.parse(e.subjectPublicKey,Xu),i=ke.toUint8Array(n.modulus);s.publicExponent=ke.toUint8Array(n.publicExponent),s.modulusLength=(i[0]?i:i.slice(1)).byteLength<<3}}async getThumbprint(...e){var r;let s,n="SHA-1";return e.length>=1&&!(!((r=e[0])===null||r===void 0)&&r.subtle)?(n=e[0]||n,s=e[1]||Sr.get()):s=e[0]||Sr.get(),await s.subtle.digest(n,this.rawData)}async getKeyIdentifier(...e){let r,s="SHA-1";e.length===1?typeof e[0]=="string"?(s=e[0],r=Sr.get()):r=e[0]:e.length===2?(s=e[0],r=e[1]):r=Sr.get();let n=Ee.parse(this.rawData,Hr);return await r.subtle.digest(s,n.subjectPublicKey)}toTextObject(){let e=this.toTextObjectEmpty(),r=Ee.parse(this.rawData,Hr);switch(e.Algorithm=So.serializeAlgorithm(r.algorithm),r.algorithm.algorithm){case Ud:e["EC Point"]=r.subjectPublicKey;break;case Ei:default:e["Raw Data"]=r.subjectPublicKey}return e}};Lx=class t extends zs{static async create(e,r=!1,s=Sr.get()){if("name"in e&&"serialNumber"in e)return new t(e,r);let i=await(await _o.create(e,s)).getKeyIdentifier(s);return new t(We.ToHex(i),r)}constructor(...e){if(ke.isBufferSource(e[0]))super(e[0]);else if(typeof e[0]=="string"){let r=new bi({keyIdentifier:new xd(We.FromHex(e[0]))});super(Db,e[1],Ee.serialize(r))}else{let r=e[0],s=r.name instanceof Eo?Ee.parse(r.name.rawData,Jt):r.name,n=new bi({authorityCertIssuer:s,authorityCertSerialNumber:We.FromHex(r.serialNumber)});super(Db,e[1],Ee.serialize(n))}}onInit(e){super.onInit(e);let r=Ee.parse(e.extnValue,bi);r.keyIdentifier&&(this.keyId=We.ToHex(r.keyIdentifier)),(r.authorityCertIssuer||r.authorityCertSerialNumber)&&(this.certId={name:r.authorityCertIssuer||[],serialNumber:r.authorityCertSerialNumber?We.ToHex(r.authorityCertSerialNumber):""})}toTextObject(){let e=this.toTextObjectWithoutValue(),r=Ee.parse(this.value,bi);return r.authorityCertIssuer&&(e["Authority Issuer"]=new Eo(r.authorityCertIssuer).toTextObject()),r.authorityCertSerialNumber&&(e["Authority Serial Number"]=r.authorityCertSerialNumber),r.keyIdentifier&&(e[""]=r.keyIdentifier),e}};Lx.NAME="Authority Key Identifier";Ox=class extends zs{constructor(...e){if(ke.isBufferSource(e[0])){super(e[0]);let r=Ee.parse(this.value,wd);this.ca=r.cA,this.pathLength=r.pathLenConstraint}else{let r=new wd({cA:e[0],pathLenConstraint:e[1]});super(Bb,e[2],Ee.serialize(r)),this.ca=e[0],this.pathLength=e[1]}}toTextObject(){let e=this.toTextObjectWithoutValue();return this.ca&&(e.CA=this.ca),this.pathLength!==void 0&&(e["Path Length"]=this.pathLength),e}};Ox.NAME="Basic Constraints";(function(t){t.serverAuth="1.3.6.1.5.5.7.3.1",t.clientAuth="1.3.6.1.5.5.7.3.2",t.codeSigning="1.3.6.1.5.5.7.3.3",t.emailProtection="1.3.6.1.5.5.7.3.4",t.timeStamping="1.3.6.1.5.5.7.3.8",t.ocspSigning="1.3.6.1.5.5.7.3.9"})(y9||(y9={}));Nx=class extends zs{constructor(...e){if(ke.isBufferSource(e[0])){super(e[0]);let r=Ee.parse(this.value,Pp);this.usages=r.map(s=>s)}else{let r=new Pp(e[0]);super(Mb,e[1],Ee.serialize(r)),this.usages=e[0]}}toTextObject(){let e=this.toTextObjectWithoutValue();return e[""]=this.usages.map(r=>Ii.toString(r)).join(", "),e}};Nx.NAME="Extended Key Usages";(function(t){t[t.digitalSignature=1]="digitalSignature",t[t.nonRepudiation=2]="nonRepudiation",t[t.keyEncipherment=4]="keyEncipherment",t[t.dataEncipherment=8]="dataEncipherment",t[t.keyAgreement=16]="keyAgreement",t[t.keyCertSign=32]="keyCertSign",t[t.cRLSign=64]="cRLSign",t[t.encipherOnly=128]="encipherOnly",t[t.decipherOnly=256]="decipherOnly"})(b9||(b9={}));Ux=class extends zs{constructor(...e){if(ke.isBufferSource(e[0])){super(e[0]);let r=Ee.parse(this.value,ku);this.usages=r.toNumber()}else{let r=new ku(e[0]);super(jb,e[1],Ee.serialize(r)),this.usages=e[0]}}toTextObject(){let e=this.toTextObjectWithoutValue(),r=Ee.parse(this.value,ku);return e[""]=r.toJSON().join(", "),e}};Ux.NAME="Key Usages";Mx=class t extends zs{static async create(e,r=!1,s=Sr.get()){let i=await(await _o.create(e,s)).getKeyIdentifier(s);return new t(We.ToHex(i),r)}constructor(...e){if(ke.isBufferSource(e[0])){super(e[0]);let r=Ee.parse(this.value,Es);this.keyId=We.ToHex(r)}else{let r=typeof e[0]=="string"?We.FromHex(e[0]):e[0],s=new Es(r);super(C2,e[1],Ee.serialize(s)),this.keyId=We.ToHex(r)}}toTextObject(){let e=this.toTextObjectWithoutValue(),r=Ee.parse(this.value,Es);return e[""]=r,e}};Mx.NAME="Subject Key Identifier";jx=class extends zs{constructor(...e){ke.isBufferSource(e[0])?super(e[0]):super(_2,e[1],new Eo(e[0]||[]).rawData)}onInit(e){super.onInit(e);let r=Ee.parse(e.extnValue,qb);this.names=new Eo(r)}toTextObject(){let e=this.toTextObjectWithoutValue(),r=this.names.toTextObject();for(let s in r)e[s]=r[s];return e}};jx.NAME="Subject Alternative Name";ms=class{static register(e,r){this.items.set(e,r)}static create(e){let r=new zs(e),s=this.items.get(r.type);return s?new s(e):r}};ms.items=new Map;$x=class extends zs{constructor(...e){var r;if(ke.isBufferSource(e[0])){super(e[0]);let s=Ee.parse(this.value,Tp);this.policies=s.map(n=>n.policyIdentifier)}else{let s=e[0],n=(r=e[1])!==null&&r!==void 0?r:!1,i=new Tp(s.map(o=>new vd({policyIdentifier:o})));super(Ob,n,Ee.serialize(i)),this.policies=s}}toTextObject(){let e=this.toTextObjectWithoutValue();return e.Policy=this.policies.map(r=>new Rt("",{},Ii.toString(r))),e}};$x.NAME="Certificate Policies";ms.register(Ob,$x);Fx=class extends zs{constructor(...e){var r;if(ke.isBufferSource(e[0]))super(e[0]);else if(Array.isArray(e[0])&&typeof e[0][0]=="string"){let n=e[0].map(o=>new xi({distributionPoint:new go({fullName:[new et({uniformResourceIdentifier:o})]})})),i=new Pa(n);super(Nb,e[1],Ee.serialize(i))}else{let s=new Pa(e[0]);super(Nb,e[1],Ee.serialize(s))}(r=this.distributionPoints)!==null&&r!==void 0||(this.distributionPoints=[])}onInit(e){super.onInit(e);let r=Ee.parse(e.extnValue,Pa);this.distributionPoints=r}toTextObject(){let e=this.toTextObjectWithoutValue();return e["Distribution Point"]=this.distributionPoints.map(r=>{var s;let n={};return r.distributionPoint&&(n[""]=(s=r.distributionPoint.fullName)===null||s===void 0?void 0:s.map(i=>new Ai(i).toString()).join(", ")),r.reasons&&(n.Reasons=r.reasons.toString()),r.cRLIssuer&&(n["CRL Issuer"]=r.cRLIssuer.map(i=>i.toString()).join(", ")),n}),e}};Fx.NAME="CRL Distribution Points";Hx=class extends zs{constructor(...e){var r,s,n,i;if(ke.isBufferSource(e[0]))super(e[0]);else if(e[0]instanceof bd){let o=new bd(e[0]);super(Pb,e[1],Ee.serialize(o))}else{let o=e[0],a=new bd;Rx(a,o,r2,"ocsp"),Rx(a,o,s2,"caIssuers"),Rx(a,o,n2,"timeStamping"),Rx(a,o,i2,"caRepository"),super(Pb,e[1],Ee.serialize(a))}(r=this.ocsp)!==null&&r!==void 0||(this.ocsp=[]),(s=this.caIssuers)!==null&&s!==void 0||(this.caIssuers=[]),(n=this.timeStamping)!==null&&n!==void 0||(this.timeStamping=[]),(i=this.caRepository)!==null&&i!==void 0||(this.caRepository=[])}onInit(e){super.onInit(e),this.ocsp=[],this.caIssuers=[],this.timeStamping=[],this.caRepository=[],Ee.parse(e.extnValue,bd).forEach(s=>{switch(s.accessMethod){case r2:this.ocsp.push(new Ai(s.accessLocation));break;case s2:this.caIssuers.push(new Ai(s.accessLocation));break;case n2:this.timeStamping.push(new Ai(s.accessLocation));break;case i2:this.caRepository.push(new Ai(s.accessLocation));break}})}toTextObject(){let e=this.toTextObjectWithoutValue();return this.ocsp.length&&Ix(e,"OCSP",this.ocsp),this.caIssuers.length&&Ix(e,"CA Issuers",this.caIssuers),this.timeStamping.length&&Ix(e,"Time Stamping",this.timeStamping),this.caRepository.length&&Ix(e,"CA Repository",this.caRepository),e}};Hx.NAME="Authority Info Access";qx=class extends zs{constructor(...e){ke.isBufferSource(e[0])?super(e[0]):super(b2,e[1],new Eo(e[0]||[]).rawData)}onInit(e){super.onInit(e);let r=Ee.parse(e.extnValue,Jt);this.names=new Eo(r)}toTextObject(){let e=this.toTextObjectWithoutValue(),r=this.names.toTextObject();for(let s in r)e[s]=r[s];return e}};qx.NAME="Issuer Alternative Name";ih=class t extends Ka{constructor(...e){let r;if(ke.isBufferSource(e[0]))r=ke.toArrayBuffer(e[0]);else{let s=e[0],n=Array.isArray(e[1])?e[1].map(i=>ke.toArrayBuffer(i)):[];r=Ee.serialize(new Fr({type:s,values:n}))}super(r,Fr)}onInit(e){this.type=e.type,this.values=e.values}toTextObject(){let e=this.toTextObjectWithoutValue();return e.Value=this.values.map(r=>new Rt("",{"":r})),e}toTextObjectWithoutValue(){let e=this.toTextObjectEmpty();return e[Rt.NAME]===t.NAME&&(e[Rt.NAME]=Ii.toString(this.type)),e}};ih.NAME="Attribute";Vx=class extends ih{constructor(...e){var r;if(ke.isBufferSource(e[0]))super(e[0]);else{let s=new h0({printableString:e[0]});super(cC,[Ee.serialize(s)])}(r=this.password)!==null&&r!==void 0||(this.password="")}onInit(e){if(super.onInit(e),this.values[0]){let r=Ee.parse(this.values[0],h0);this.password=r.toString()}}toTextObject(){let e=this.toTextObjectWithoutValue();return e[Rt.VALUE]=this.password,e}};Vx.NAME="Challenge Password";j0=class extends ih{constructor(...e){var r;if(ke.isBufferSource(e[0]))super(e[0]);else{let s=e[0],n=new qs;for(let i of s)n.push(Ee.parse(i.rawData,as));super(p0,[Ee.serialize(n)])}(r=this.items)!==null&&r!==void 0||(this.items=[])}onInit(e){if(super.onInit(e),this.values[0]){let r=Ee.parse(this.values[0],qs);this.items=r.map(s=>ms.create(Ee.serialize(s)))}}toTextObject(){let e=this.toTextObjectWithoutValue(),r=this.items.map(s=>s.toTextObject());for(let s of r)e[s[Rt.NAME]]=s;return e}};j0.NAME="Extensions";oh=class{static register(e,r){this.items.set(e,r)}static create(e){let r=new ih(e),s=this.items.get(r.type);return s?new s(e):r}};oh.items=new Map;F0="crypto.signatureFormatter",EC=class{toAsnSignature(e,r){return ke.toArrayBuffer(r)}toWebSignature(e,r){return ke.toArrayBuffer(r)}},CC=Dx=class{static createPssParams(e,r){let s=Dx.getHashAlgorithm(e);return s?new Ci({hashAlgorithm:s,maskGenAlgorithm:new _e({algorithm:ja,parameters:Ee.serialize(s)}),saltLength:r}):null}static getHashAlgorithm(e){let r=Gt.resolve(Yd);return typeof e=="string"?r.toAsnAlgorithm({name:e}):typeof e=="object"&&e&&"name"in e?r.toAsnAlgorithm(e):null}toAsnAlgorithm(e){switch(e.name.toLowerCase()){case"rsassa-pkcs1-v1_5":if("hash"in e){let r;if(typeof e.hash=="string")r=e.hash;else if(e.hash&&typeof e.hash=="object"&&"name"in e.hash&&typeof e.hash.name=="string")r=e.hash.name.toUpperCase();else throw new Error("Cannot get hash algorithm name");switch(r.toLowerCase()){case"sha-1":return new _e({algorithm:Vu,parameters:null});case"sha-256":return new _e({algorithm:ax,parameters:null});case"sha-384":return new _e({algorithm:zu,parameters:null});case"sha-512":return new _e({algorithm:Wu,parameters:null})}}else return new _e({algorithm:Ei,parameters:null});break;case"rsa-pss":if("hash"in e){if(!("saltLength"in e&&typeof e.saltLength=="number"))throw new Error("Cannot get 'saltLength' from 'alg' argument");let r=Dx.createPssParams(e.hash,e.saltLength);if(!r)throw new Error("Cannot create PSS parameters");return new _e({algorithm:Ma,parameters:Ee.serialize(r)})}else return new _e({algorithm:Ma,parameters:null})}return null}toWebAlgorithm(e){switch(e.algorithm){case Ei:return{name:"RSASSA-PKCS1-v1_5"};case Vu:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-1"}};case ax:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case zu:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-384"}};case Wu:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-512"}};case Ma:if(e.parameters){let r=Ee.parse(e.parameters,Ci);return{name:"RSA-PSS",hash:Gt.resolve(Yd).toWebAlgorithm(r.hashAlgorithm),saltLength:r.saltLength}}else return{name:"RSA-PSS"}}return null}};CC=Dx=v([Ha()],CC);Gt.registerSingleton($0,CC);TC=class{toAsnAlgorithm(e){switch(e.name.toLowerCase()){case"sha-1":return new _e({algorithm:jd});case"sha-256":return new _e({algorithm:$d});case"sha-384":return new _e({algorithm:Fd});case"sha-512":return new _e({algorithm:Hd})}return null}toWebAlgorithm(e){switch(e.algorithm){case jd:return{name:"SHA-1"};case $d:return{name:"SHA-256"};case Fd:return{name:"SHA-384"};case Hd:return{name:"SHA-512"}}return null}};TC=v([Ha()],TC);Gt.registerSingleton($0,TC);Co=class t{addPadding(e,r){let s=ke.toUint8Array(r),n=new Uint8Array(e);return n.set(s,e-s.length),n.buffer}removePadding(e,r=!1){let s=ke.toUint8Array(e);for(let n=0;n<s.length;n++)if(s[n]){s=s.slice(n);break}if(r&&s[0]>127){let n=new Uint8Array(s.length+1);return n.set(s,1),n.buffer}return s.buffer}toAsnSignature(e,r){if(e.name==="ECDSA"){let s=e.namedCurve,n=t.namedCurveSize.get(s)||t.defaultNamedCurveSize,i=new Md,o=ke.toUint8Array(r);return i.r=this.removePadding(o.slice(0,n),!0),i.s=this.removePadding(o.slice(n,n+n),!0),Ee.serialize(i)}return null}toWebSignature(e,r){if(e.name==="ECDSA"){let s=Ee.parse(r,Md),n=e.namedCurve,i=t.namedCurveSize.get(n)||t.defaultNamedCurveSize,o=this.addPadding(i,this.removePadding(s.r)),a=this.addPadding(i,this.removePadding(s.s));return D8(o,a)}return null}};Co.namedCurveSize=new Map;Co.defaultNamedCurveSize=32;wC="1.3.101.110",x9="1.3.101.111",vC="1.3.101.112",w9="1.3.101.113",kC=class{toAsnAlgorithm(e){let r=null;switch(e.name.toLowerCase()){case"ed25519":r=vC;break;case"x25519":r=wC;break;case"eddsa":switch(e.namedCurve.toLowerCase()){case"ed25519":r=vC;break;case"ed448":r=w9;break}break;case"ecdh-es":switch(e.namedCurve.toLowerCase()){case"x25519":r=wC;break;case"x448":r=x9;break}}return r?new _e({algorithm:r}):null}toWebAlgorithm(e){switch(e.algorithm){case vC:return{name:"Ed25519"};case w9:return{name:"EdDSA",namedCurve:"Ed448"};case wC:return{name:"X25519"};case x9:return{name:"ECDH-ES",namedCurve:"X448"}}return null}};kC=v([Ha()],kC);Gt.registerSingleton($0,kC);AC=class extends Ga{get subjectName(){return gt(this,b0,"f")||Yt(this,b0,new On(this.asn.certificationRequestInfo.subject),"f"),gt(this,b0,"f")}get subject(){return gt(this,x0,"f")||Yt(this,x0,this.subjectName.toString(),"f"),gt(this,x0,"f")}get signatureAlgorithm(){if(!gt(this,w0,"f")){let e=Gt.resolve(Yd);Yt(this,w0,e.toWebAlgorithm(this.asn.signatureAlgorithm),"f")}return gt(this,w0,"f")}get signature(){return gt(this,v0,"f")||Yt(this,v0,this.asn.signature,"f"),gt(this,v0,"f")}get publicKey(){return gt(this,_0,"f")||Yt(this,_0,new _o(this.asn.certificationRequestInfo.subjectPKInfo),"f"),gt(this,_0,"f")}get attributes(){return gt(this,S0,"f")||Yt(this,S0,this.asn.certificationRequestInfo.attributes.map(e=>oh.create(Ee.serialize(e))),"f"),gt(this,S0,"f")}get extensions(){if(!gt(this,rh,"f")){Yt(this,rh,[],"f");let e=this.getAttribute(p0);e instanceof j0&&Yt(this,rh,e.items,"f")}return gt(this,rh,"f")}get tbs(){return gt(this,y0,"f")||Yt(this,y0,this.asn.certificationRequestInfoRaw||Ee.serialize(this.asn.certificationRequestInfo),"f"),gt(this,y0,"f")}constructor(e){let r=Ga.isAsnEncoded(e)?[e,Wa]:[e];super(r[0],r[1]),y0.set(this,void 0),b0.set(this,void 0),x0.set(this,void 0),w0.set(this,void 0),v0.set(this,void 0),_0.set(this,void 0),S0.set(this,void 0),rh.set(this,void 0),this.tag=Wr.CertificateRequestTag}onInit(e){}getAttribute(e){for(let r of this.attributes)if(r.type===e)return r;return null}getAttributes(e){return this.attributes.filter(r=>r.type===e)}getExtension(e){for(let r of this.extensions)if(r.type===e)return r;return null}getExtensions(e){return this.extensions.filter(r=>r.type===e)}async verify(e=Sr.get()){let r={...this.publicKey.algorithm,...this.signatureAlgorithm},s=await this.publicKey.export(r,["verify"],e),n=Gt.resolveAll(F0).reverse(),i=null;for(let a of n)if(i=a.toWebSignature(r,this.signature),i)break;if(!i)throw Error("Cannot convert WebCrypto signature value to ASN.1 format");return await e.subtle.verify(this.signatureAlgorithm,s,i,this.tbs)}toTextObject(){let e=this.toTextObjectEmpty(),r=Ee.parse(this.rawData,Wa),s=r.certificationRequestInfo,n=new Rt("",{Version:`${wi[s.version]} (${s.version})`,Subject:this.subject,"Subject Public Key Info":this.publicKey});if(this.attributes.length){let i=new Rt("");for(let o of this.attributes){let a=o.toTextObject();i[a[Rt.NAME]]=a}n.Attributes=i}return e.Data=n,e.Signature=new Rt("",{Algorithm:So.serializeAlgorithm(r.signatureAlgorithm),"":r.signature}),e}};y0=new WeakMap,b0=new WeakMap,x0=new WeakMap,w0=new WeakMap,v0=new WeakMap,_0=new WeakMap,S0=new WeakMap,rh=new WeakMap;AC.NAME="PKCS#10 Certificate Request";zx=class extends Ga{get publicKey(){return gt(this,L0,"f")||Yt(this,L0,new _o(this.asn.tbsCertificate.subjectPublicKeyInfo),"f"),gt(this,L0,"f")}get serialNumber(){if(!gt(this,C0,"f")){let e=this.asn.tbsCertificate,r=new Uint8Array(e.serialNumber);r.length>1&&r[0]===0&&r[1]>127&&(r=r.slice(1)),Yt(this,C0,We.ToHex(r),"f")}return gt(this,C0,"f")}get subjectName(){return gt(this,T0,"f")||Yt(this,T0,new On(this.asn.tbsCertificate.subject),"f"),gt(this,T0,"f")}get subject(){return gt(this,k0,"f")||Yt(this,k0,this.subjectName.toString(),"f"),gt(this,k0,"f")}get issuerName(){return gt(this,A0,"f")||Yt(this,A0,new On(this.asn.tbsCertificate.issuer),"f"),gt(this,A0,"f")}get issuer(){return gt(this,I0,"f")||Yt(this,I0,this.issuerName.toString(),"f"),gt(this,I0,"f")}get notBefore(){if(!gt(this,R0,"f")){let e=this.asn.tbsCertificate.validity.notBefore.utcTime||this.asn.tbsCertificate.validity.notBefore.generalTime;if(!e)throw new Error("Cannot get 'notBefore' value");Yt(this,R0,e,"f")}return gt(this,R0,"f")}get notAfter(){if(!gt(this,P0,"f")){let e=this.asn.tbsCertificate.validity.notAfter.utcTime||this.asn.tbsCertificate.validity.notAfter.generalTime;if(!e)throw new Error("Cannot get 'notAfter' value");Yt(this,P0,e,"f")}return gt(this,P0,"f")}get signatureAlgorithm(){if(!gt(this,D0,"f")){let e=Gt.resolve(Yd);Yt(this,D0,e.toWebAlgorithm(this.asn.signatureAlgorithm),"f")}return gt(this,D0,"f")}get signature(){return gt(this,B0,"f")||Yt(this,B0,this.asn.signatureValue,"f"),gt(this,B0,"f")}get extensions(){return gt(this,sh,"f")||(Yt(this,sh,[],"f"),this.asn.tbsCertificate.extensions&&Yt(this,sh,this.asn.tbsCertificate.extensions.map(e=>ms.create(Ee.serialize(e))),"f")),gt(this,sh,"f")}get tbs(){return gt(this,E0,"f")||Yt(this,E0,this.asn.tbsCertificateRaw||Ee.serialize(this.asn.tbsCertificate),"f"),gt(this,E0,"f")}constructor(e){let r=Ga.isAsnEncoded(e)?[e,pn]:[e];super(r[0],r[1]),E0.set(this,void 0),C0.set(this,void 0),T0.set(this,void 0),k0.set(this,void 0),A0.set(this,void 0),I0.set(this,void 0),R0.set(this,void 0),P0.set(this,void 0),D0.set(this,void 0),B0.set(this,void 0),sh.set(this,void 0),L0.set(this,void 0),this.tag=Wr.CertificateTag}onInit(e){}getExtension(e){for(let r of this.extensions)if(typeof e=="string"){if(r.type===e)return r}else if(r instanceof e)return r;return null}getExtensions(e){return this.extensions.filter(r=>typeof e=="string"?r.type===e:r instanceof e)}async verify(e={},r=Sr.get()){let s,n,i=e.publicKey;try{if(!i)s={...this.publicKey.algorithm,...this.signatureAlgorithm},n=await this.publicKey.export(s,["verify"],r);else if("publicKey"in i)s={...i.publicKey.algorithm,...this.signatureAlgorithm},n=await i.publicKey.export(s,["verify"],r);else if(i instanceof _o)s={...i.algorithm,...this.signatureAlgorithm},n=await i.export(s,["verify"],r);else if(ke.isBufferSource(i)){let d=new _o(i);s={...d.algorithm,...this.signatureAlgorithm},n=await d.export(s,["verify"],r)}else s={...i.algorithm,...this.signatureAlgorithm},n=i}catch{return!1}let o=Gt.resolveAll(F0).reverse(),a=null;for(let d of o)if(a=d.toWebSignature(s,this.signature),a)break;if(!a)throw Error("Cannot convert ASN.1 signature value to WebCrypto format");let c=await r.subtle.verify(this.signatureAlgorithm,n,a,this.tbs);if(e.signatureOnly)return c;{let u=(e.date||new Date).getTime();return c&&this.notBefore.getTime()<u&&u<this.notAfter.getTime()}}async getThumbprint(...e){let r,s="SHA-1";return e[0]&&(e[0].subtle?r=e[0]:(s=e[0]||s,r=e[1])),r??(r=Sr.get()),await r.subtle.digest(s,this.rawData)}async isSelfSigned(e=Sr.get()){return this.subject===this.issuer&&await this.verify({signatureOnly:!0},e)}toTextObject(){let e=this.toTextObjectEmpty(),r=Ee.parse(this.rawData,pn),s=r.tbsCertificate,n=new Rt("",{Version:`${wi[s.version]} (${s.version})`,"Serial Number":s.serialNumber,"Signature Algorithm":So.serializeAlgorithm(s.signature),Issuer:this.issuer,Validity:new Rt("",{"Not Before":s.validity.notBefore.getTime(),"Not After":s.validity.notAfter.getTime()}),Subject:this.subject,"Subject Public Key Info":this.publicKey});if(s.issuerUniqueID&&(n["Issuer Unique ID"]=s.issuerUniqueID),s.subjectUniqueID&&(n["Subject Unique ID"]=s.subjectUniqueID),this.extensions.length){let i=new Rt("");for(let o of this.extensions){let a=o.toTextObject();i[a[Rt.NAME]]=a}n.Extensions=i}return e.Data=n,e.Signature=new Rt("",{Algorithm:So.serializeAlgorithm(r.signatureAlgorithm),"":r.signatureValue}),e}};E0=new WeakMap,C0=new WeakMap,T0=new WeakMap,k0=new WeakMap,A0=new WeakMap,I0=new WeakMap,R0=new WeakMap,P0=new WeakMap,D0=new WeakMap,B0=new WeakMap,sh=new WeakMap,L0=new WeakMap;zx.NAME="Certificate";Wx=class{static async createSelfSigned(e,r=Sr.get()){if(!e.keys.privateKey)throw new Error("Bad field 'keys' in 'params' argument. 'privateKey' is empty");if(!e.keys.publicKey)throw new Error("Bad field 'keys' in 'params' argument. 'publicKey' is empty");return this.create({serialNumber:e.serialNumber,subject:e.name,issuer:e.name,notBefore:e.notBefore,notAfter:e.notAfter,publicKey:e.keys.publicKey,signingKey:e.keys.privateKey,signingAlgorithm:e.signingAlgorithm,extensions:e.extensions},r)}static async create(e,r=Sr.get()){var s;let n;e.publicKey instanceof _o?n=e.publicKey.rawData:"publicKey"in e.publicKey?n=e.publicKey.publicKey.rawData:ke.isBufferSource(e.publicKey)?n=e.publicKey:n=await r.subtle.exportKey("spki",e.publicKey);let i=RY(e.serialNumber,r),o=e.notBefore||new Date,a=e.notAfter||new Date(o.getTime()+31536e6),c=new pn({tbsCertificate:new qr({version:wi.v3,serialNumber:i,validity:new yo({notBefore:o,notAfter:a}),extensions:new qs(((s=e.extensions)===null||s===void 0?void 0:s.map(f=>Ee.parse(f.rawData,as)))||[]),subjectPublicKeyInfo:Ee.parse(n,Hr)})});if(e.subject){let f=e.subject instanceof On?e.subject:new On(e.subject);c.tbsCertificate.subject=Ee.parse(f.toArrayBuffer(),Vt)}if(e.issuer){let f=e.issuer instanceof On?e.issuer:new On(e.issuer);c.tbsCertificate.issuer=Ee.parse(f.toArrayBuffer(),Vt)}let d={hash:"SHA-256"},u="signingKey"in e?{...d,...e.signingAlgorithm,...e.signingKey.algorithm}:{...d,...e.signingAlgorithm},l=Gt.resolve(Yd);c.tbsCertificate.signature=c.signatureAlgorithm=l.toAsnAlgorithm(u);let h=Ee.serialize(c.tbsCertificate),p="signingKey"in e?await r.subtle.sign(u,e.signingKey,h):e.signature,m=Gt.resolveAll(F0).reverse(),_=null;for(let f of m)if(_=f.toAsnSignature(u,p),_)break;if(!_)throw Error("Cannot convert ASN.1 signature value to WebCrypto format");return c.signatureValue=_,new zx(Ee.serialize(c))}};(function(t){t[t.unspecified=0]="unspecified",t[t.keyCompromise=1]="keyCompromise",t[t.cACompromise=2]="cACompromise",t[t.affiliationChanged=3]="affiliationChanged",t[t.superseded=4]="superseded",t[t.cessationOfOperation=5]="cessationOfOperation",t[t.certificateHold=6]="certificateHold",t[t.removeFromCRL=8]="removeFromCRL",t[t.privilegeWithdrawn=9]="privilegeWithdrawn",t[t.aACompromise=10]="aACompromise"})(v9||(v9={}));PY=new WeakMap,DY=new WeakMap,BY=new WeakMap,LY=new WeakMap,OY=new WeakMap;NY=new WeakMap,UY=new WeakMap,MY=new WeakMap,jY=new WeakMap,$Y=new WeakMap,FY=new WeakMap,HY=new WeakMap;ms.register(Bb,Ox);ms.register(Mb,Nx);ms.register(jb,Ux);ms.register(C2,Mx);ms.register(Db,Lx);ms.register(_2,jx);ms.register(Nb,Fx);ms.register(Pb,Hx);ms.register(b2,qx);oh.register(cC,Vx);oh.register(p0,j0);Gt.registerSingleton(F0,EC);Gt.registerSingleton(F0,Co);Co.namedCurveSize.set("P-256",32);Co.namedCurveSize.set("K-256",32);Co.namedCurveSize.set("P-384",48);Co.namedCurveSize.set("P-521",66)});var A9=Me((Y4e,k9)=>{"use strict";g();y();function VY(t){return/^[$A-Z\_a-z\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa80-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc][$A-Z\_a-z\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa80-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc0-9\u0300-\u036f\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08e4-\u08fe\u0900-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c01-\u0c03\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c82\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0d02\u0d03\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d82\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19b0-\u19c0\u19c8\u19c9\u19d0-\u19d9\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf2-\u1cf4\u1dc0-\u1de6\u1dfc-\u1dff\u200c\u200d\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua880\ua881\ua8b4-\ua8c4\ua8d0-\ua8d9\ua8e0-\ua8f1\ua900-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f]*$/.test(t)}k9.exports=VY});var H0=Me((Z4e,U9)=>{"use strict";g();y();var I9=require("util"),B9=A9(),R9=/[\{\[]/,P9=/[\}\]]/,D9=["do","if","in","for","let","new","try","var","case","else","enum","eval","null","this","true","void","with","await","break","catch","class","const","false","super","throw","while","yield","delete","export","import","public","return","static","switch","typeof","default","extends","finally","package","private","continue","debugger","function","arguments","interface","protected","implements","instanceof","NaN","undefined"],L9={};for(Kx=0;Kx<D9.length;Kx++)L9[D9[Kx]]=!0;var Kx,zY=function(t){return B9(t)&&!L9.hasOwnProperty(t)},O9={s:function(t){return""+t},d:function(t){return""+Number(t)},o:function(t){return JSON.stringify(t)}},N9=function(){var t=[],e=0,r={},s=function(o){for(var a="";a.length<e*2;)a+=" ";t.push(a+o)},n=function(o){if(P9.test(o.trim()[0])&&R9.test(o[o.length-1])){e--,s(o),e++;return}if(R9.test(o[o.length-1])){s(o),e++;return}if(P9.test(o.trim()[0])){e--,s(o);return}s(o)},i=function(o){if(!o)return i;if(arguments.length===1&&o.indexOf(`
|
|
37
|
+
`)}};Wr.CertificateTag="CERTIFICATE";Wr.CrlTag="CRL";Wr.CertificateRequestTag="CERTIFICATE REQUEST";Wr.PublicKeyTag="PUBLIC KEY";Wr.PrivateKeyTag="PRIVATE KEY";Ga=class t extends Ka{static isAsnEncoded(e){return ke.isBufferSource(e)||typeof e=="string"}static toArrayBuffer(e){if(typeof e=="string"){if(Wr.isPem(e))return Wr.decode(e)[0];if(We.isHex(e))return We.FromHex(e);if(We.isBase64(e))return We.FromBase64(e);if(We.isBase64Url(e))return We.FromBase64Url(e);throw new TypeError("Unsupported format of 'raw' argument. Must be one of DER, PEM, HEX, Base64, or Base4Url")}else{let r=ke.toUint8Array(e);if(r.length>0&&r[0]===48)return ke.toArrayBuffer(e);let s=We.ToBinary(e);if(Wr.isPem(s))return Wr.decode(s)[0];if(We.isHex(s))return We.FromHex(s);if(We.isBase64(s))return We.FromBase64(s);if(We.isBase64Url(s))return We.FromBase64Url(s);throw new TypeError("Unsupported format of 'raw' argument. Must be one of DER, PEM, HEX, Base64, or Base4Url")}}constructor(...e){t.isAsnEncoded(e[0])?super(t.toArrayBuffer(e[0]),e[1]):super(e[0])}toString(e="pem"){return e==="pem"?Wr.encode(this.rawData,this.tag):super.toString(e)}},_o=class t extends Ga{static async create(e,r=Sr.get()){if(e instanceof t)return e;if(Um.isCryptoKey(e)){if(e.type!=="public")throw new TypeError("Public key is required");let s=await r.subtle.exportKey("spki",e);return new t(s)}else{if(e.publicKey)return e.publicKey;if(ke.isBufferSource(e))return new t(e);throw new TypeError("Unsupported PublicKeyType")}}constructor(e){Ga.isAsnEncoded(e)?super(e,Hr):super(e),this.tag=Wr.PublicKeyTag}async export(...e){let r,s=["verify"],n={hash:"SHA-256",...this.algorithm};e.length>1?(n=e[0]||n,s=e[1]||s,r=e[2]||Sr.get()):r=e[0]||Sr.get();let i=this.rawData,o=Ee.parse(this.rawData,Hr);return o.algorithm.algorithm===Ma&&(i=IY(o,i)),r.subtle.importKey("spki",i,n,!0,s)}onInit(e){let r=Gt.resolve(Yd),s=this.algorithm=r.toWebAlgorithm(e.algorithm);if(e.algorithm.algorithm===Ei){let n=Ee.parse(e.subjectPublicKey,Xu),i=ke.toUint8Array(n.modulus);s.publicExponent=ke.toUint8Array(n.publicExponent),s.modulusLength=(i[0]?i:i.slice(1)).byteLength<<3}}async getThumbprint(...e){var r;let s,n="SHA-1";return e.length>=1&&!(!((r=e[0])===null||r===void 0)&&r.subtle)?(n=e[0]||n,s=e[1]||Sr.get()):s=e[0]||Sr.get(),await s.subtle.digest(n,this.rawData)}async getKeyIdentifier(...e){let r,s="SHA-1";e.length===1?typeof e[0]=="string"?(s=e[0],r=Sr.get()):r=e[0]:e.length===2?(s=e[0],r=e[1]):r=Sr.get();let n=Ee.parse(this.rawData,Hr);return await r.subtle.digest(s,n.subjectPublicKey)}toTextObject(){let e=this.toTextObjectEmpty(),r=Ee.parse(this.rawData,Hr);switch(e.Algorithm=So.serializeAlgorithm(r.algorithm),r.algorithm.algorithm){case Ud:e["EC Point"]=r.subjectPublicKey;break;case Ei:default:e["Raw Data"]=r.subjectPublicKey}return e}};Lx=class t extends zs{static async create(e,r=!1,s=Sr.get()){if("name"in e&&"serialNumber"in e)return new t(e,r);let i=await(await _o.create(e,s)).getKeyIdentifier(s);return new t(We.ToHex(i),r)}constructor(...e){if(ke.isBufferSource(e[0]))super(e[0]);else if(typeof e[0]=="string"){let r=new bi({keyIdentifier:new xd(We.FromHex(e[0]))});super(Db,e[1],Ee.serialize(r))}else{let r=e[0],s=r.name instanceof Eo?Ee.parse(r.name.rawData,Jt):r.name,n=new bi({authorityCertIssuer:s,authorityCertSerialNumber:We.FromHex(r.serialNumber)});super(Db,e[1],Ee.serialize(n))}}onInit(e){super.onInit(e);let r=Ee.parse(e.extnValue,bi);r.keyIdentifier&&(this.keyId=We.ToHex(r.keyIdentifier)),(r.authorityCertIssuer||r.authorityCertSerialNumber)&&(this.certId={name:r.authorityCertIssuer||[],serialNumber:r.authorityCertSerialNumber?We.ToHex(r.authorityCertSerialNumber):""})}toTextObject(){let e=this.toTextObjectWithoutValue(),r=Ee.parse(this.value,bi);return r.authorityCertIssuer&&(e["Authority Issuer"]=new Eo(r.authorityCertIssuer).toTextObject()),r.authorityCertSerialNumber&&(e["Authority Serial Number"]=r.authorityCertSerialNumber),r.keyIdentifier&&(e[""]=r.keyIdentifier),e}};Lx.NAME="Authority Key Identifier";Ox=class extends zs{constructor(...e){if(ke.isBufferSource(e[0])){super(e[0]);let r=Ee.parse(this.value,wd);this.ca=r.cA,this.pathLength=r.pathLenConstraint}else{let r=new wd({cA:e[0],pathLenConstraint:e[1]});super(Bb,e[2],Ee.serialize(r)),this.ca=e[0],this.pathLength=e[1]}}toTextObject(){let e=this.toTextObjectWithoutValue();return this.ca&&(e.CA=this.ca),this.pathLength!==void 0&&(e["Path Length"]=this.pathLength),e}};Ox.NAME="Basic Constraints";(function(t){t.serverAuth="1.3.6.1.5.5.7.3.1",t.clientAuth="1.3.6.1.5.5.7.3.2",t.codeSigning="1.3.6.1.5.5.7.3.3",t.emailProtection="1.3.6.1.5.5.7.3.4",t.timeStamping="1.3.6.1.5.5.7.3.8",t.ocspSigning="1.3.6.1.5.5.7.3.9"})(y9||(y9={}));Nx=class extends zs{constructor(...e){if(ke.isBufferSource(e[0])){super(e[0]);let r=Ee.parse(this.value,Pp);this.usages=r.map(s=>s)}else{let r=new Pp(e[0]);super(Mb,e[1],Ee.serialize(r)),this.usages=e[0]}}toTextObject(){let e=this.toTextObjectWithoutValue();return e[""]=this.usages.map(r=>Ii.toString(r)).join(", "),e}};Nx.NAME="Extended Key Usages";(function(t){t[t.digitalSignature=1]="digitalSignature",t[t.nonRepudiation=2]="nonRepudiation",t[t.keyEncipherment=4]="keyEncipherment",t[t.dataEncipherment=8]="dataEncipherment",t[t.keyAgreement=16]="keyAgreement",t[t.keyCertSign=32]="keyCertSign",t[t.cRLSign=64]="cRLSign",t[t.encipherOnly=128]="encipherOnly",t[t.decipherOnly=256]="decipherOnly"})(b9||(b9={}));Ux=class extends zs{constructor(...e){if(ke.isBufferSource(e[0])){super(e[0]);let r=Ee.parse(this.value,ku);this.usages=r.toNumber()}else{let r=new ku(e[0]);super(jb,e[1],Ee.serialize(r)),this.usages=e[0]}}toTextObject(){let e=this.toTextObjectWithoutValue(),r=Ee.parse(this.value,ku);return e[""]=r.toJSON().join(", "),e}};Ux.NAME="Key Usages";Mx=class t extends zs{static async create(e,r=!1,s=Sr.get()){let i=await(await _o.create(e,s)).getKeyIdentifier(s);return new t(We.ToHex(i),r)}constructor(...e){if(ke.isBufferSource(e[0])){super(e[0]);let r=Ee.parse(this.value,Es);this.keyId=We.ToHex(r)}else{let r=typeof e[0]=="string"?We.FromHex(e[0]):e[0],s=new Es(r);super(C2,e[1],Ee.serialize(s)),this.keyId=We.ToHex(r)}}toTextObject(){let e=this.toTextObjectWithoutValue(),r=Ee.parse(this.value,Es);return e[""]=r,e}};Mx.NAME="Subject Key Identifier";jx=class extends zs{constructor(...e){ke.isBufferSource(e[0])?super(e[0]):super(_2,e[1],new Eo(e[0]||[]).rawData)}onInit(e){super.onInit(e);let r=Ee.parse(e.extnValue,qb);this.names=new Eo(r)}toTextObject(){let e=this.toTextObjectWithoutValue(),r=this.names.toTextObject();for(let s in r)e[s]=r[s];return e}};jx.NAME="Subject Alternative Name";ms=class{static register(e,r){this.items.set(e,r)}static create(e){let r=new zs(e),s=this.items.get(r.type);return s?new s(e):r}};ms.items=new Map;$x=class extends zs{constructor(...e){var r;if(ke.isBufferSource(e[0])){super(e[0]);let s=Ee.parse(this.value,Tp);this.policies=s.map(n=>n.policyIdentifier)}else{let s=e[0],n=(r=e[1])!==null&&r!==void 0?r:!1,i=new Tp(s.map(o=>new vd({policyIdentifier:o})));super(Ob,n,Ee.serialize(i)),this.policies=s}}toTextObject(){let e=this.toTextObjectWithoutValue();return e.Policy=this.policies.map(r=>new Rt("",{},Ii.toString(r))),e}};$x.NAME="Certificate Policies";ms.register(Ob,$x);Fx=class extends zs{constructor(...e){var r;if(ke.isBufferSource(e[0]))super(e[0]);else if(Array.isArray(e[0])&&typeof e[0][0]=="string"){let n=e[0].map(o=>new xi({distributionPoint:new go({fullName:[new et({uniformResourceIdentifier:o})]})})),i=new Pa(n);super(Nb,e[1],Ee.serialize(i))}else{let s=new Pa(e[0]);super(Nb,e[1],Ee.serialize(s))}(r=this.distributionPoints)!==null&&r!==void 0||(this.distributionPoints=[])}onInit(e){super.onInit(e);let r=Ee.parse(e.extnValue,Pa);this.distributionPoints=r}toTextObject(){let e=this.toTextObjectWithoutValue();return e["Distribution Point"]=this.distributionPoints.map(r=>{var s;let n={};return r.distributionPoint&&(n[""]=(s=r.distributionPoint.fullName)===null||s===void 0?void 0:s.map(i=>new Ai(i).toString()).join(", ")),r.reasons&&(n.Reasons=r.reasons.toString()),r.cRLIssuer&&(n["CRL Issuer"]=r.cRLIssuer.map(i=>i.toString()).join(", ")),n}),e}};Fx.NAME="CRL Distribution Points";Hx=class extends zs{constructor(...e){var r,s,n,i;if(ke.isBufferSource(e[0]))super(e[0]);else if(e[0]instanceof bd){let o=new bd(e[0]);super(Pb,e[1],Ee.serialize(o))}else{let o=e[0],a=new bd;Rx(a,o,r2,"ocsp"),Rx(a,o,s2,"caIssuers"),Rx(a,o,n2,"timeStamping"),Rx(a,o,i2,"caRepository"),super(Pb,e[1],Ee.serialize(a))}(r=this.ocsp)!==null&&r!==void 0||(this.ocsp=[]),(s=this.caIssuers)!==null&&s!==void 0||(this.caIssuers=[]),(n=this.timeStamping)!==null&&n!==void 0||(this.timeStamping=[]),(i=this.caRepository)!==null&&i!==void 0||(this.caRepository=[])}onInit(e){super.onInit(e),this.ocsp=[],this.caIssuers=[],this.timeStamping=[],this.caRepository=[],Ee.parse(e.extnValue,bd).forEach(s=>{switch(s.accessMethod){case r2:this.ocsp.push(new Ai(s.accessLocation));break;case s2:this.caIssuers.push(new Ai(s.accessLocation));break;case n2:this.timeStamping.push(new Ai(s.accessLocation));break;case i2:this.caRepository.push(new Ai(s.accessLocation));break}})}toTextObject(){let e=this.toTextObjectWithoutValue();return this.ocsp.length&&Ix(e,"OCSP",this.ocsp),this.caIssuers.length&&Ix(e,"CA Issuers",this.caIssuers),this.timeStamping.length&&Ix(e,"Time Stamping",this.timeStamping),this.caRepository.length&&Ix(e,"CA Repository",this.caRepository),e}};Hx.NAME="Authority Info Access";qx=class extends zs{constructor(...e){ke.isBufferSource(e[0])?super(e[0]):super(b2,e[1],new Eo(e[0]||[]).rawData)}onInit(e){super.onInit(e);let r=Ee.parse(e.extnValue,Jt);this.names=new Eo(r)}toTextObject(){let e=this.toTextObjectWithoutValue(),r=this.names.toTextObject();for(let s in r)e[s]=r[s];return e}};qx.NAME="Issuer Alternative Name";ih=class t extends Ka{constructor(...e){let r;if(ke.isBufferSource(e[0]))r=ke.toArrayBuffer(e[0]);else{let s=e[0],n=Array.isArray(e[1])?e[1].map(i=>ke.toArrayBuffer(i)):[];r=Ee.serialize(new Fr({type:s,values:n}))}super(r,Fr)}onInit(e){this.type=e.type,this.values=e.values}toTextObject(){let e=this.toTextObjectWithoutValue();return e.Value=this.values.map(r=>new Rt("",{"":r})),e}toTextObjectWithoutValue(){let e=this.toTextObjectEmpty();return e[Rt.NAME]===t.NAME&&(e[Rt.NAME]=Ii.toString(this.type)),e}};ih.NAME="Attribute";Vx=class extends ih{constructor(...e){var r;if(ke.isBufferSource(e[0]))super(e[0]);else{let s=new hm({printableString:e[0]});super(cC,[Ee.serialize(s)])}(r=this.password)!==null&&r!==void 0||(this.password="")}onInit(e){if(super.onInit(e),this.values[0]){let r=Ee.parse(this.values[0],hm);this.password=r.toString()}}toTextObject(){let e=this.toTextObjectWithoutValue();return e[Rt.VALUE]=this.password,e}};Vx.NAME="Challenge Password";jm=class extends ih{constructor(...e){var r;if(ke.isBufferSource(e[0]))super(e[0]);else{let s=e[0],n=new qs;for(let i of s)n.push(Ee.parse(i.rawData,as));super(pm,[Ee.serialize(n)])}(r=this.items)!==null&&r!==void 0||(this.items=[])}onInit(e){if(super.onInit(e),this.values[0]){let r=Ee.parse(this.values[0],qs);this.items=r.map(s=>ms.create(Ee.serialize(s)))}}toTextObject(){let e=this.toTextObjectWithoutValue(),r=this.items.map(s=>s.toTextObject());for(let s of r)e[s[Rt.NAME]]=s;return e}};jm.NAME="Extensions";oh=class{static register(e,r){this.items.set(e,r)}static create(e){let r=new ih(e),s=this.items.get(r.type);return s?new s(e):r}};oh.items=new Map;Fm="crypto.signatureFormatter",EC=class{toAsnSignature(e,r){return ke.toArrayBuffer(r)}toWebSignature(e,r){return ke.toArrayBuffer(r)}},CC=Dx=class{static createPssParams(e,r){let s=Dx.getHashAlgorithm(e);return s?new Ci({hashAlgorithm:s,maskGenAlgorithm:new _e({algorithm:ja,parameters:Ee.serialize(s)}),saltLength:r}):null}static getHashAlgorithm(e){let r=Gt.resolve(Yd);return typeof e=="string"?r.toAsnAlgorithm({name:e}):typeof e=="object"&&e&&"name"in e?r.toAsnAlgorithm(e):null}toAsnAlgorithm(e){switch(e.name.toLowerCase()){case"rsassa-pkcs1-v1_5":if("hash"in e){let r;if(typeof e.hash=="string")r=e.hash;else if(e.hash&&typeof e.hash=="object"&&"name"in e.hash&&typeof e.hash.name=="string")r=e.hash.name.toUpperCase();else throw new Error("Cannot get hash algorithm name");switch(r.toLowerCase()){case"sha-1":return new _e({algorithm:Vu,parameters:null});case"sha-256":return new _e({algorithm:ax,parameters:null});case"sha-384":return new _e({algorithm:zu,parameters:null});case"sha-512":return new _e({algorithm:Wu,parameters:null})}}else return new _e({algorithm:Ei,parameters:null});break;case"rsa-pss":if("hash"in e){if(!("saltLength"in e&&typeof e.saltLength=="number"))throw new Error("Cannot get 'saltLength' from 'alg' argument");let r=Dx.createPssParams(e.hash,e.saltLength);if(!r)throw new Error("Cannot create PSS parameters");return new _e({algorithm:Ma,parameters:Ee.serialize(r)})}else return new _e({algorithm:Ma,parameters:null})}return null}toWebAlgorithm(e){switch(e.algorithm){case Ei:return{name:"RSASSA-PKCS1-v1_5"};case Vu:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-1"}};case ax:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case zu:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-384"}};case Wu:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-512"}};case Ma:if(e.parameters){let r=Ee.parse(e.parameters,Ci);return{name:"RSA-PSS",hash:Gt.resolve(Yd).toWebAlgorithm(r.hashAlgorithm),saltLength:r.saltLength}}else return{name:"RSA-PSS"}}return null}};CC=Dx=v([Ha()],CC);Gt.registerSingleton($m,CC);TC=class{toAsnAlgorithm(e){switch(e.name.toLowerCase()){case"sha-1":return new _e({algorithm:jd});case"sha-256":return new _e({algorithm:$d});case"sha-384":return new _e({algorithm:Fd});case"sha-512":return new _e({algorithm:Hd})}return null}toWebAlgorithm(e){switch(e.algorithm){case jd:return{name:"SHA-1"};case $d:return{name:"SHA-256"};case Fd:return{name:"SHA-384"};case Hd:return{name:"SHA-512"}}return null}};TC=v([Ha()],TC);Gt.registerSingleton($m,TC);Co=class t{addPadding(e,r){let s=ke.toUint8Array(r),n=new Uint8Array(e);return n.set(s,e-s.length),n.buffer}removePadding(e,r=!1){let s=ke.toUint8Array(e);for(let n=0;n<s.length;n++)if(s[n]){s=s.slice(n);break}if(r&&s[0]>127){let n=new Uint8Array(s.length+1);return n.set(s,1),n.buffer}return s.buffer}toAsnSignature(e,r){if(e.name==="ECDSA"){let s=e.namedCurve,n=t.namedCurveSize.get(s)||t.defaultNamedCurveSize,i=new Md,o=ke.toUint8Array(r);return i.r=this.removePadding(o.slice(0,n),!0),i.s=this.removePadding(o.slice(n,n+n),!0),Ee.serialize(i)}return null}toWebSignature(e,r){if(e.name==="ECDSA"){let s=Ee.parse(r,Md),n=e.namedCurve,i=t.namedCurveSize.get(n)||t.defaultNamedCurveSize,o=this.addPadding(i,this.removePadding(s.r)),a=this.addPadding(i,this.removePadding(s.s));return D8(o,a)}return null}};Co.namedCurveSize=new Map;Co.defaultNamedCurveSize=32;wC="1.3.101.110",x9="1.3.101.111",vC="1.3.101.112",w9="1.3.101.113",kC=class{toAsnAlgorithm(e){let r=null;switch(e.name.toLowerCase()){case"ed25519":r=vC;break;case"x25519":r=wC;break;case"eddsa":switch(e.namedCurve.toLowerCase()){case"ed25519":r=vC;break;case"ed448":r=w9;break}break;case"ecdh-es":switch(e.namedCurve.toLowerCase()){case"x25519":r=wC;break;case"x448":r=x9;break}}return r?new _e({algorithm:r}):null}toWebAlgorithm(e){switch(e.algorithm){case vC:return{name:"Ed25519"};case w9:return{name:"EdDSA",namedCurve:"Ed448"};case wC:return{name:"X25519"};case x9:return{name:"ECDH-ES",namedCurve:"X448"}}return null}};kC=v([Ha()],kC);Gt.registerSingleton($m,kC);AC=class extends Ga{get subjectName(){return gt(this,bm,"f")||Yt(this,bm,new On(this.asn.certificationRequestInfo.subject),"f"),gt(this,bm,"f")}get subject(){return gt(this,xm,"f")||Yt(this,xm,this.subjectName.toString(),"f"),gt(this,xm,"f")}get signatureAlgorithm(){if(!gt(this,wm,"f")){let e=Gt.resolve(Yd);Yt(this,wm,e.toWebAlgorithm(this.asn.signatureAlgorithm),"f")}return gt(this,wm,"f")}get signature(){return gt(this,vm,"f")||Yt(this,vm,this.asn.signature,"f"),gt(this,vm,"f")}get publicKey(){return gt(this,_m,"f")||Yt(this,_m,new _o(this.asn.certificationRequestInfo.subjectPKInfo),"f"),gt(this,_m,"f")}get attributes(){return gt(this,Sm,"f")||Yt(this,Sm,this.asn.certificationRequestInfo.attributes.map(e=>oh.create(Ee.serialize(e))),"f"),gt(this,Sm,"f")}get extensions(){if(!gt(this,rh,"f")){Yt(this,rh,[],"f");let e=this.getAttribute(pm);e instanceof jm&&Yt(this,rh,e.items,"f")}return gt(this,rh,"f")}get tbs(){return gt(this,ym,"f")||Yt(this,ym,this.asn.certificationRequestInfoRaw||Ee.serialize(this.asn.certificationRequestInfo),"f"),gt(this,ym,"f")}constructor(e){let r=Ga.isAsnEncoded(e)?[e,Wa]:[e];super(r[0],r[1]),ym.set(this,void 0),bm.set(this,void 0),xm.set(this,void 0),wm.set(this,void 0),vm.set(this,void 0),_m.set(this,void 0),Sm.set(this,void 0),rh.set(this,void 0),this.tag=Wr.CertificateRequestTag}onInit(e){}getAttribute(e){for(let r of this.attributes)if(r.type===e)return r;return null}getAttributes(e){return this.attributes.filter(r=>r.type===e)}getExtension(e){for(let r of this.extensions)if(r.type===e)return r;return null}getExtensions(e){return this.extensions.filter(r=>r.type===e)}async verify(e=Sr.get()){let r={...this.publicKey.algorithm,...this.signatureAlgorithm},s=await this.publicKey.export(r,["verify"],e),n=Gt.resolveAll(Fm).reverse(),i=null;for(let a of n)if(i=a.toWebSignature(r,this.signature),i)break;if(!i)throw Error("Cannot convert WebCrypto signature value to ASN.1 format");return await e.subtle.verify(this.signatureAlgorithm,s,i,this.tbs)}toTextObject(){let e=this.toTextObjectEmpty(),r=Ee.parse(this.rawData,Wa),s=r.certificationRequestInfo,n=new Rt("",{Version:`${wi[s.version]} (${s.version})`,Subject:this.subject,"Subject Public Key Info":this.publicKey});if(this.attributes.length){let i=new Rt("");for(let o of this.attributes){let a=o.toTextObject();i[a[Rt.NAME]]=a}n.Attributes=i}return e.Data=n,e.Signature=new Rt("",{Algorithm:So.serializeAlgorithm(r.signatureAlgorithm),"":r.signature}),e}};ym=new WeakMap,bm=new WeakMap,xm=new WeakMap,wm=new WeakMap,vm=new WeakMap,_m=new WeakMap,Sm=new WeakMap,rh=new WeakMap;AC.NAME="PKCS#10 Certificate Request";zx=class extends Ga{get publicKey(){return gt(this,Lm,"f")||Yt(this,Lm,new _o(this.asn.tbsCertificate.subjectPublicKeyInfo),"f"),gt(this,Lm,"f")}get serialNumber(){if(!gt(this,Cm,"f")){let e=this.asn.tbsCertificate,r=new Uint8Array(e.serialNumber);r.length>1&&r[0]===0&&r[1]>127&&(r=r.slice(1)),Yt(this,Cm,We.ToHex(r),"f")}return gt(this,Cm,"f")}get subjectName(){return gt(this,Tm,"f")||Yt(this,Tm,new On(this.asn.tbsCertificate.subject),"f"),gt(this,Tm,"f")}get subject(){return gt(this,km,"f")||Yt(this,km,this.subjectName.toString(),"f"),gt(this,km,"f")}get issuerName(){return gt(this,Am,"f")||Yt(this,Am,new On(this.asn.tbsCertificate.issuer),"f"),gt(this,Am,"f")}get issuer(){return gt(this,Im,"f")||Yt(this,Im,this.issuerName.toString(),"f"),gt(this,Im,"f")}get notBefore(){if(!gt(this,Rm,"f")){let e=this.asn.tbsCertificate.validity.notBefore.utcTime||this.asn.tbsCertificate.validity.notBefore.generalTime;if(!e)throw new Error("Cannot get 'notBefore' value");Yt(this,Rm,e,"f")}return gt(this,Rm,"f")}get notAfter(){if(!gt(this,Pm,"f")){let e=this.asn.tbsCertificate.validity.notAfter.utcTime||this.asn.tbsCertificate.validity.notAfter.generalTime;if(!e)throw new Error("Cannot get 'notAfter' value");Yt(this,Pm,e,"f")}return gt(this,Pm,"f")}get signatureAlgorithm(){if(!gt(this,Dm,"f")){let e=Gt.resolve(Yd);Yt(this,Dm,e.toWebAlgorithm(this.asn.signatureAlgorithm),"f")}return gt(this,Dm,"f")}get signature(){return gt(this,Bm,"f")||Yt(this,Bm,this.asn.signatureValue,"f"),gt(this,Bm,"f")}get extensions(){return gt(this,sh,"f")||(Yt(this,sh,[],"f"),this.asn.tbsCertificate.extensions&&Yt(this,sh,this.asn.tbsCertificate.extensions.map(e=>ms.create(Ee.serialize(e))),"f")),gt(this,sh,"f")}get tbs(){return gt(this,Em,"f")||Yt(this,Em,this.asn.tbsCertificateRaw||Ee.serialize(this.asn.tbsCertificate),"f"),gt(this,Em,"f")}constructor(e){let r=Ga.isAsnEncoded(e)?[e,pn]:[e];super(r[0],r[1]),Em.set(this,void 0),Cm.set(this,void 0),Tm.set(this,void 0),km.set(this,void 0),Am.set(this,void 0),Im.set(this,void 0),Rm.set(this,void 0),Pm.set(this,void 0),Dm.set(this,void 0),Bm.set(this,void 0),sh.set(this,void 0),Lm.set(this,void 0),this.tag=Wr.CertificateTag}onInit(e){}getExtension(e){for(let r of this.extensions)if(typeof e=="string"){if(r.type===e)return r}else if(r instanceof e)return r;return null}getExtensions(e){return this.extensions.filter(r=>typeof e=="string"?r.type===e:r instanceof e)}async verify(e={},r=Sr.get()){let s,n,i=e.publicKey;try{if(!i)s={...this.publicKey.algorithm,...this.signatureAlgorithm},n=await this.publicKey.export(s,["verify"],r);else if("publicKey"in i)s={...i.publicKey.algorithm,...this.signatureAlgorithm},n=await i.publicKey.export(s,["verify"],r);else if(i instanceof _o)s={...i.algorithm,...this.signatureAlgorithm},n=await i.export(s,["verify"],r);else if(ke.isBufferSource(i)){let d=new _o(i);s={...d.algorithm,...this.signatureAlgorithm},n=await d.export(s,["verify"],r)}else s={...i.algorithm,...this.signatureAlgorithm},n=i}catch{return!1}let o=Gt.resolveAll(Fm).reverse(),a=null;for(let d of o)if(a=d.toWebSignature(s,this.signature),a)break;if(!a)throw Error("Cannot convert ASN.1 signature value to WebCrypto format");let c=await r.subtle.verify(this.signatureAlgorithm,n,a,this.tbs);if(e.signatureOnly)return c;{let u=(e.date||new Date).getTime();return c&&this.notBefore.getTime()<u&&u<this.notAfter.getTime()}}async getThumbprint(...e){let r,s="SHA-1";return e[0]&&(e[0].subtle?r=e[0]:(s=e[0]||s,r=e[1])),r??(r=Sr.get()),await r.subtle.digest(s,this.rawData)}async isSelfSigned(e=Sr.get()){return this.subject===this.issuer&&await this.verify({signatureOnly:!0},e)}toTextObject(){let e=this.toTextObjectEmpty(),r=Ee.parse(this.rawData,pn),s=r.tbsCertificate,n=new Rt("",{Version:`${wi[s.version]} (${s.version})`,"Serial Number":s.serialNumber,"Signature Algorithm":So.serializeAlgorithm(s.signature),Issuer:this.issuer,Validity:new Rt("",{"Not Before":s.validity.notBefore.getTime(),"Not After":s.validity.notAfter.getTime()}),Subject:this.subject,"Subject Public Key Info":this.publicKey});if(s.issuerUniqueID&&(n["Issuer Unique ID"]=s.issuerUniqueID),s.subjectUniqueID&&(n["Subject Unique ID"]=s.subjectUniqueID),this.extensions.length){let i=new Rt("");for(let o of this.extensions){let a=o.toTextObject();i[a[Rt.NAME]]=a}n.Extensions=i}return e.Data=n,e.Signature=new Rt("",{Algorithm:So.serializeAlgorithm(r.signatureAlgorithm),"":r.signatureValue}),e}};Em=new WeakMap,Cm=new WeakMap,Tm=new WeakMap,km=new WeakMap,Am=new WeakMap,Im=new WeakMap,Rm=new WeakMap,Pm=new WeakMap,Dm=new WeakMap,Bm=new WeakMap,sh=new WeakMap,Lm=new WeakMap;zx.NAME="Certificate";Wx=class{static async createSelfSigned(e,r=Sr.get()){if(!e.keys.privateKey)throw new Error("Bad field 'keys' in 'params' argument. 'privateKey' is empty");if(!e.keys.publicKey)throw new Error("Bad field 'keys' in 'params' argument. 'publicKey' is empty");return this.create({serialNumber:e.serialNumber,subject:e.name,issuer:e.name,notBefore:e.notBefore,notAfter:e.notAfter,publicKey:e.keys.publicKey,signingKey:e.keys.privateKey,signingAlgorithm:e.signingAlgorithm,extensions:e.extensions},r)}static async create(e,r=Sr.get()){var s;let n;e.publicKey instanceof _o?n=e.publicKey.rawData:"publicKey"in e.publicKey?n=e.publicKey.publicKey.rawData:ke.isBufferSource(e.publicKey)?n=e.publicKey:n=await r.subtle.exportKey("spki",e.publicKey);let i=RY(e.serialNumber,r),o=e.notBefore||new Date,a=e.notAfter||new Date(o.getTime()+31536e6),c=new pn({tbsCertificate:new qr({version:wi.v3,serialNumber:i,validity:new yo({notBefore:o,notAfter:a}),extensions:new qs(((s=e.extensions)===null||s===void 0?void 0:s.map(f=>Ee.parse(f.rawData,as)))||[]),subjectPublicKeyInfo:Ee.parse(n,Hr)})});if(e.subject){let f=e.subject instanceof On?e.subject:new On(e.subject);c.tbsCertificate.subject=Ee.parse(f.toArrayBuffer(),Vt)}if(e.issuer){let f=e.issuer instanceof On?e.issuer:new On(e.issuer);c.tbsCertificate.issuer=Ee.parse(f.toArrayBuffer(),Vt)}let d={hash:"SHA-256"},u="signingKey"in e?{...d,...e.signingAlgorithm,...e.signingKey.algorithm}:{...d,...e.signingAlgorithm},l=Gt.resolve(Yd);c.tbsCertificate.signature=c.signatureAlgorithm=l.toAsnAlgorithm(u);let h=Ee.serialize(c.tbsCertificate),p="signingKey"in e?await r.subtle.sign(u,e.signingKey,h):e.signature,m=Gt.resolveAll(Fm).reverse(),_=null;for(let f of m)if(_=f.toAsnSignature(u,p),_)break;if(!_)throw Error("Cannot convert ASN.1 signature value to WebCrypto format");return c.signatureValue=_,new zx(Ee.serialize(c))}};(function(t){t[t.unspecified=0]="unspecified",t[t.keyCompromise=1]="keyCompromise",t[t.cACompromise=2]="cACompromise",t[t.affiliationChanged=3]="affiliationChanged",t[t.superseded=4]="superseded",t[t.cessationOfOperation=5]="cessationOfOperation",t[t.certificateHold=6]="certificateHold",t[t.removeFromCRL=8]="removeFromCRL",t[t.privilegeWithdrawn=9]="privilegeWithdrawn",t[t.aACompromise=10]="aACompromise"})(v9||(v9={}));PY=new WeakMap,DY=new WeakMap,BY=new WeakMap,LY=new WeakMap,OY=new WeakMap;NY=new WeakMap,UY=new WeakMap,MY=new WeakMap,jY=new WeakMap,$Y=new WeakMap,FY=new WeakMap,HY=new WeakMap;ms.register(Bb,Ox);ms.register(Mb,Nx);ms.register(jb,Ux);ms.register(C2,Mx);ms.register(Db,Lx);ms.register(_2,jx);ms.register(Nb,Fx);ms.register(Pb,Hx);ms.register(b2,qx);oh.register(cC,Vx);oh.register(pm,jm);Gt.registerSingleton(Fm,EC);Gt.registerSingleton(Fm,Co);Co.namedCurveSize.set("P-256",32);Co.namedCurveSize.set("K-256",32);Co.namedCurveSize.set("P-384",48);Co.namedCurveSize.set("P-521",66)});var A9=Me((Y4e,k9)=>{"use strict";g();y();function VY(t){return/^[$A-Z\_a-z\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa80-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc][$A-Z\_a-z\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa80-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc0-9\u0300-\u036f\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08e4-\u08fe\u0900-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c01-\u0c03\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c82\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0d02\u0d03\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d82\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19b0-\u19c0\u19c8\u19c9\u19d0-\u19d9\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf2-\u1cf4\u1dc0-\u1de6\u1dfc-\u1dff\u200c\u200d\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua880\ua881\ua8b4-\ua8c4\ua8d0-\ua8d9\ua8e0-\ua8f1\ua900-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f]*$/.test(t)}k9.exports=VY});var Hm=Me((Z4e,U9)=>{"use strict";g();y();var I9=require("util"),B9=A9(),R9=/[\{\[]/,P9=/[\}\]]/,D9=["do","if","in","for","let","new","try","var","case","else","enum","eval","null","this","true","void","with","await","break","catch","class","const","false","super","throw","while","yield","delete","export","import","public","return","static","switch","typeof","default","extends","finally","package","private","continue","debugger","function","arguments","interface","protected","implements","instanceof","NaN","undefined"],L9={};for(Kx=0;Kx<D9.length;Kx++)L9[D9[Kx]]=!0;var Kx,zY=function(t){return B9(t)&&!L9.hasOwnProperty(t)},O9={s:function(t){return""+t},d:function(t){return""+Number(t)},o:function(t){return JSON.stringify(t)}},N9=function(){var t=[],e=0,r={},s=function(o){for(var a="";a.length<e*2;)a+=" ";t.push(a+o)},n=function(o){if(P9.test(o.trim()[0])&&R9.test(o[o.length-1])){e--,s(o),e++;return}if(R9.test(o[o.length-1])){s(o),e++;return}if(P9.test(o.trim()[0])){e--,s(o);return}s(o)},i=function(o){if(!o)return i;if(arguments.length===1&&o.indexOf(`
|
|
38
38
|
`)>-1)for(var a=o.trim().split(`
|
|
39
39
|
`),c=0;c<a.length;c++)n(a[c].trim());else n(I9.format.apply(I9,arguments));return i};return i.scope={},i.formats=O9,i.sym=function(o){return(!o||!zY(o))&&(o="tmp"),r[o]||(r[o]=0),o+(r[o]++||"")},i.property=function(o,a){return arguments.length===1&&(a=o,o=""),a=a+"",B9(a)?o?o+"."+a:a:o?o+"["+JSON.stringify(a)+"]":JSON.stringify(a)},i.toString=function(){return t.join(`
|
|
40
|
-
`)},i.toFunction=function(o){o||(o={});var a="return ("+i.toString()+")";Object.keys(i.scope).forEach(function(u){o[u]||(o[u]=i.scope[u])});var c=Object.keys(o).map(function(u){return u}),d=c.map(function(u){return o[u]});return Function.apply(null,c.concat(a)).apply(null,d)},arguments.length&&i.apply(null,arguments),i};N9.formats=O9;U9.exports=N9});var j9=Me((r8e,M9)=>{"use strict";g();y();var Xx=class{constructor(){this.next=null,this.buffer=null}};M9.exports=class Gx{constructor(){this.head=null,this.tail=null,this.length=0,this.count=0}push(e){let r=new Xx;r.buffer=e,this.length>0?this.tail.next=r:this.head=r,this.tail=r,this.length+=e.length,this.count+=1}unshift(e){let r=new Xx;r.buffer=e,r.next=this.head,this.isEmpty()&&(this.tail=r),this.head=r,this.length+=e.length,this.count+=1}shift(){if(this.isEmpty())return null;let e=this.head.buffer;return this.head===this.tail?(this.head=null,this.tail=null):this.head=this.head.next,this.length-=e.length,this.length=Math.max(this.length,0),this.count-=1,e}get first(){return this.isEmpty()?null:this.head.buffer}get last(){return this.isEmpty()?null:this.tail.buffer}isEmpty(){return this.length===0}clear(){this.head=null,this.tail=null,this.length=0,this.count=0}slice(e,r){if(e<0||e>=this.length)return new Gx;if(r<0||r>this.length||r<e)return new Gx;let s=new Gx,n=this.head,i=e,o=r;for(;n;){if(n.buffer.length>i){i===0&&n.buffer.length<=o?s.push(n.buffer):n.buffer.length>=o?s.push(n.buffer.slice(i,o)):s.push(n.buffer.slice(i));break}i-=n.buffer.length,o-=n.buffer.length,n=n.next}if(n.buffer.length<o)for(;n;){if(n.buffer.length===o){s.push(n.buffer);break}else if(n.buffer.length>o){s.push(n.buffer.slice(0,o));break}else i<0&&n.buffer.length<o&&s.push(n.buffer);i-=n.buffer.length,o-=n.buffer.length,n=n.next}return s}}});var q9=Me((i8e,H9)=>{"use strict";g();y();var Yx=
|
|
40
|
+
`)},i.toFunction=function(o){o||(o={});var a="return ("+i.toString()+")";Object.keys(i.scope).forEach(function(u){o[u]||(o[u]=i.scope[u])});var c=Object.keys(o).map(function(u){return u}),d=c.map(function(u){return o[u]});return Function.apply(null,c.concat(a)).apply(null,d)},arguments.length&&i.apply(null,arguments),i};N9.formats=O9;U9.exports=N9});var j9=Me((r8e,M9)=>{"use strict";g();y();var Xx=class{constructor(){this.next=null,this.buffer=null}};M9.exports=class Gx{constructor(){this.head=null,this.tail=null,this.length=0,this.count=0}push(e){let r=new Xx;r.buffer=e,this.length>0?this.tail.next=r:this.head=r,this.tail=r,this.length+=e.length,this.count+=1}unshift(e){let r=new Xx;r.buffer=e,r.next=this.head,this.isEmpty()&&(this.tail=r),this.head=r,this.length+=e.length,this.count+=1}shift(){if(this.isEmpty())return null;let e=this.head.buffer;return this.head===this.tail?(this.head=null,this.tail=null):this.head=this.head.next,this.length-=e.length,this.length=Math.max(this.length,0),this.count-=1,e}get first(){return this.isEmpty()?null:this.head.buffer}get last(){return this.isEmpty()?null:this.tail.buffer}isEmpty(){return this.length===0}clear(){this.head=null,this.tail=null,this.length=0,this.count=0}slice(e,r){if(e<0||e>=this.length)return new Gx;if(r<0||r>this.length||r<e)return new Gx;let s=new Gx,n=this.head,i=e,o=r;for(;n;){if(n.buffer.length>i){i===0&&n.buffer.length<=o?s.push(n.buffer):n.buffer.length>=o?s.push(n.buffer.slice(i,o)):s.push(n.buffer.slice(i));break}i-=n.buffer.length,o-=n.buffer.length,n=n.next}if(n.buffer.length<o)for(;n;){if(n.buffer.length===o){s.push(n.buffer);break}else if(n.buffer.length>o){s.push(n.buffer.slice(0,o));break}else i<0&&n.buffer.length<o&&s.push(n.buffer);i-=n.buffer.length,o-=n.buffer.length,n=n.next}return s}}});var q9=Me((i8e,H9)=>{"use strict";g();y();var Yx=Hm(),WY=j9(),Jd=class t{constructor(){this.queue=new WY,this.offset=0}get length(){return this.queue.length-this.offset}append(e){if(Buffer.isBuffer(e)){if(this.offset>0){let r=this.queue.shift();this.queue.unshift(r.slice(this.offset)),this.offset=0}this.queue.push(e)}else if(Array.isArray(e))for(let r=0;r<e.length;r+=1)this.append(e[r]);else if(e instanceof t){if(this.offset>0){let s=this.queue.shift();this.queue.unshift(s.slice(this.offset)),this.offset=0}if(e.offset>0){let s=e.queue.shift();e.queue.unshift(s.slice(e.offset)),e.offset=0}let r=e.queue.head;for(;r;)this.queue.push(r.buffer),r=r.next}}get(e){let r=e;for(;r>=this.length;)r-=this.length;for(;r<0;)r+=this.length;let s=this.queue.head,{offset:n}=this;for(;s;){if(s.buffer.length-n>r)return s.buffer[r+n];r-=s.buffer.length-n,n=0,s=s.next}}slice(e,r){for(typeof e!="number"&&(e=0),typeof r!="number"&&(r=this.length);e<0;)e+=this.length;for(;r<0;)r+=this.length;if(r=Math.min(r,this.length),e>=this.length||r===0)return Buffer.alloc(0);let s=e;e=Math.min(s,r),r=Math.max(s,r);let n=this.queue.slice(e+this.offset,r+this.offset);if(n.count===1)return n.first;let i=n.head,o=Buffer.allocUnsafe(n.length),a=0;for(let c=0;c<n.count;c+=1)o.set(i.buffer,a),a+=i.buffer.length,i=i.next;return o}toString(e,r,s){return this.slice(r,s).toString(e)}consume(e){let r=e;for(;this.length>0;){let s=this.queue.first.length-this.offset;if(r>=s)this.queue.shift(),r-=s,this.offset=0;else{this.offset+=r;break}}}indexOf(e,r=0){if(!Number.isInteger(e))throw new TypeError("Invalid argument 1");if(e<0||e>255)throw new Error("Invalid argument 1");for(Number.isInteger(r)||(r=0);r>=this.length;)r-=this.length;for(;r<0;)r+=this.length;let s=this.queue.head,n=0,i=()=>{n+=s.buffer.length,s=s.next};for(;s;){let o=0;if(s===this.queue.head&&(o+=this.offset),r>=s.buffer.length-o){r-=s.buffer.length-o,i();continue}r<s.buffer.length&&(o+=r);let a=s.buffer.indexOf(e,o);if(a>-1)return a+n-this.offset;i(),o>this.offset&&(r=0)}return-1}},$9={readDoubleBE:8,readDoubleLE:8,readFloatBE:4,readFloatLE:4,readInt32BE:4,readInt32LE:4,readUInt32BE:4,readUInt32LE:4,readInt16BE:2,readInt16LE:2,readUInt16BE:2,readUInt16LE:2,readInt8:1,readUInt8:1};Object.keys($9).forEach(t=>{let e=Yx();e(`
|
|
41
41
|
function bufferlist_${t}(offset = 0) {
|
|
42
42
|
const start = offset + this.offset;
|
|
43
43
|
const head = this.queue.first;
|
|
@@ -71,7 +71,7 @@ ${e.join(`
|
|
|
71
71
|
buf.${t}(value, 0, size);
|
|
72
72
|
this.append(buf);
|
|
73
73
|
}
|
|
74
|
-
`),Jd.prototype[t]=e.toFunction()});H9.exports=Jd});var ah=Me((d8e,V9)=>{"use strict";g();y();V9.exports=class extends Error{constructor(e,r){let s=`requested ${e} bytes but only ${r} available`;super(s),this.name="NotEnoughDataError"}}});var
|
|
74
|
+
`),Jd.prototype[t]=e.toFunction()});H9.exports=Jd});var ah=Me((d8e,V9)=>{"use strict";g();y();V9.exports=class extends Error{constructor(e,r){let s=`requested ${e} bytes but only ${r} available`;super(s),this.name="NotEnoughDataError"}}});var qm=Me((h8e,K9)=>{"use strict";g();y();var{Transform:XY}=require("stream"),Jx=Hm(),YY=q9(),JY=ah(),z9=Symbol("buffer"),Qd=class extends XY{constructor(e={}){super(e),this[z9]=new YY}get buffer(){return this[z9]}get length(){return this.buffer.length}append(e){this.buffer.append(e)}get(e){return this.buffer.get(e)}slice(e,r){return this.buffer.slice(e,r)}consume(e){this.buffer.consume(e)}toString(e,r,s){return this.buffer.toString(e,r,s)}indexOf(e,r=0){return this.buffer.indexOf(e,r)}readBuffer(e){IC(e,this.length);let r=this.slice(0,e);return this.consume(e),r}writeBuffer(e){this.append(e)}},W9={readDoubleBE:8,readDoubleLE:8,readFloatBE:4,readFloatLE:4,readInt32BE:4,readInt32LE:4,readUInt32BE:4,readUInt32LE:4,readInt16BE:2,readInt16LE:2,readUInt16BE:2,readUInt16LE:2,readInt8:1,readUInt8:1},QY=["readIntBE","readIntLE","readUIntBE","readUIntLE"];Object.keys(W9).forEach(t=>{let e=Jx();e(`
|
|
75
75
|
function binary_${t}() {
|
|
76
76
|
const bytes = ${e.formats.d(W9[t])};
|
|
77
77
|
assertSize(bytes, this.length);
|
|
@@ -97,7 +97,7 @@ ${e.join(`
|
|
|
97
97
|
function binary_${t}(value, size) {
|
|
98
98
|
this.buffer.${t}(value, size);
|
|
99
99
|
}
|
|
100
|
-
`),Qd.prototype[t]=e.toFunction()});function IC(t,e){if(t>e)throw new JY(t,e)}K9.exports=Qd});var X9=Me((m8e,G9)=>{"use strict";g();y();G9.exports=function(e){return e!=null&&typeof e=="object"&&Array.isArray(e)===!1}});var Q9=Me((b8e,J9)=>{"use strict";g();y();var tJ=X9();function Y9(t){return tJ(t)===!0&&Object.prototype.toString.call(t)==="[object Object]"}J9.exports=function(e){var r,s;return!(Y9(e)===!1||(r=e.constructor,typeof r!="function")||(s=r.prototype,Y9(s)===!1)||s.hasOwnProperty("isPrototypeOf")===!1)}});var Ri=Me((v8e,Z9)=>{"use strict";g();y();var rJ=Q9();Z9.exports={isType:sJ,isUserType:rJ,isFunction:V0,isDecodeType:nJ,isEncodeType:iJ};function sJ(t){return RC(t)&&V0(t.encode)&&V0(t.decode)}function V0(t){return typeof t=="function"}function RC(t){return typeof t=="object"&&t!==null}function nJ(t){return RC(t)&&V0(t.decode)}function iJ(t){return RC(t)&&V0(t.encode)}});var Xa=Me((E8e,eL)=>{"use strict";g();y();var oJ=Symbol("skip"),aJ=Symbol("bytes");eL.exports={skip:oJ,bytes:aJ}});var Ya=Me((k8e,rL)=>{"use strict";g();y();var tL=Xa();rL.exports=class Qx{constructor(){this[tL.bytes]=0,this.node=void 0,this.current=void 0}get bytes(){return this[tL.bytes]}static clone(e){let r=new Qx;return e instanceof Qx&&(r.node=e.node,r.current=e.current),r}static clean(e){e instanceof Qx&&(e.node=void 0,e.current=void 0)}}});var ch=Me((R8e,aL)=>{"use strict";g();y();var{isType:cJ,isUserType:dJ,isDecodeType:lJ}=Ri(),uJ=q0(),PC=Xa(),sL=Ya();aL.exports={decode:nL,decodeCommon:iL};function nL(t,e){let r=t;Buffer.isBuffer(t)&&(r=new uJ,r.append(t));let s=new sL,n=iL(r,e,s);return nL.bytes=s.bytes,sL.clean(s),n}function iL(t,e,r){if(cJ(e)){let s=e.decode.call(r,t);return r[PC.bytes]+=e.decode.bytes,s}return oL(t,e,r)}function oL(t,e,r){hJ(e);let s=Object.create(null);r.node===void 0&&(r.node=s),r.current=s;let n=Object.keys(e);for(let i=0;i<n.length;i+=1){let o=n[i],a=e[o];if(!lJ(a)){s[o]=oL(t,a,r),r.current=s;continue}let c=a.decode.call(r,t);r[PC.bytes]+=a.decode.bytes,a[PC.skip]!==!0&&(s[o]=c)}return s}function hJ(t){if(!dJ(t))throw new TypeError("Argument #2 should be a plain object.")}});var z0=Me((B8e,fL)=>{"use strict";g();y();var{isUserType:fJ,isEncodeType:pJ,isType:mJ}=Ri(),dL=Xa(),cL=Ya(),DC=q0();fL.exports={encode:lL,encodeCommon:uL};function lL(t,e,r){let s=new cL;if(e instanceof DC){let n=r;r=e,e=n}return r instanceof DC||(r=new DC),uL(t,r,e,s),lL.bytes=s.bytes,cL.clean(s),r}function uL(t,e,r,s){mJ(r)?(r.encode.call(s,t,e),s[dL.bytes]+=r.encode.bytes):hL(t,e,r,s)}function hL(t,e,r,s){gJ(r),s.node===void 0&&(s.node=t),s.current=t;let n=Object.keys(r);for(let i=0;i<n.length;i+=1){let o=n[i],a=r[o],c=t[o];if(!pJ(a)){hL(c,e,a,s),s.current=t;continue}a.encode.call(s,c,e),s[dL.bytes]+=a.encode.bytes}}function gJ(t){if(!fJ(t))throw new TypeError("Argument `schema` should be a plain object.")}});var W0=Me((N8e,xL)=>{"use strict";g();y();var{isUserType:yJ,isType:mL}=Ri(),pL=Ya(),gL=Xa();xL.exports={encodingLength:bJ,encodingLengthCommon:yL};function bJ(t,e){let r=new pL;return yL(t,e,r),pL.clean(r),r.bytes}function yL(t,e,r){mL(e)?r[gL.bytes]+=e.encodingLength.call(r,t):bL(t,e,r)}function bL(t,e,r){if(!yJ(e))throw new TypeError("Argument `schema` should be a plain object.");r.node===void 0&&(r.node=t),r.current=t;let s=Object.keys(e);for(let n=0;n<s.length;n+=1){let i=s[n],o=e[i],a=t[i];if(!mL(o)){bL(a,o,r),r.current=t;continue}r[gL.bytes]+=o.encodingLength.call(r,a)}}});var kL=Me((j8e,TL)=>{"use strict";g();y();var{decodeCommon:CL}=ch(),{encodeCommon:xJ}=z0(),{encodingLengthCommon:wL}=W0(),{isType:vL,isUserType:wJ,isFunction:vJ}=Ri(),Ja=Ya();TL.exports=_J;function _J(t,e,r="count"){if(!vL(t)&&!wJ(t))throw new TypeError("Argument #1 should be a valid type.");let s=r==="bytes",n=typeof e=="number",i=vL(e),o=vJ(e);if(!n&&!i&&!o)throw new TypeError("Unknown type of argument #1.");return{encode:a,decode:c,encodingLength:d};function a(u,l){_L(u);let h=Ja.clone(this);a.bytes=0;let p=0;if(i?p=u.length:n?p=e:o&&(p=e(h),SL(p)),s||EL(p,u.length),s){let m=Ja.clone(h);for(let _ of u)wL(_,t,m);i&&(p=m.bytes),EL(m.bytes,p),Ja.clean(m)}i&&(e.encode.call(h,p,l),a.bytes+=e.encode.bytes),u.forEach(m=>{xJ(m,l,t,h)}),a.bytes+=h.bytes,Ja.clean(h)}function c(u){let l=0;c.bytes=0;let h=Ja.clone(this);n?l=e:i?(l=e.decode.call(h,u),c.bytes+=e.decode.bytes):o&&(l=e(h)),SL(l);let p;return s?p=SJ(t,l,u,h):p=EJ(t,l,u,h),c.bytes+=h.bytes,Ja.clean(h),p}function d(u){_L(u);let l=Ja.clone(this),h=0;if(n&&s)return e;i&&!s&&(h=e.encodingLength(u.length));for(let p of u)wL(p,t,l);return Ja.clean(l),h+=l.bytes,i&&s&&(h+=e.encodingLength(h)),h}}function _L(t){if(!Array.isArray(t))throw new TypeError("Argument #1 should be an Array.")}function SL(t){if(typeof t!="number")throw new TypeError("Length of an array should be a number.")}function EL(t,e){if(t!==e)throw new Error(`Argument #1 required length ${t} instead of ${e}`)}function SJ(t,e,r,s){let n=[],i=s.bytes,o=0;for(;o<e;)n.push(CL(r,t,s)),o=s.bytes-i;if(o>e)throw new Error("Incorrect length of an array.");return n}function EJ(t,e,r,s){let n=new Array(e);for(let i=0;i<e;i+=1)n[i]=CL(r,t,s);return n}});var PL=Me((H8e,RL)=>{"use strict";g();y();var{isType:CJ,isFunction:TJ}=Ri(),kJ=ah(),AJ=q0();RL.exports=IJ;function IJ(t){let e=typeof t=="number",r=CJ(t),s=TJ(t),n=t===null;if(!e&&!r&&!s&&!n)throw new TypeError("Unknown type of argument #1.");return{encode:i,decode:o,encodingLength:a};function i(c,d){AL(c),i.bytes=0;let u=this;if(e&&IL(t,c.length),r&&(t.encode.call(u,c.length,d),i.bytes+=t.encode.bytes),s){let l=t(u);BC(l),IL(l,c.length)}d.writeBuffer(Buffer.isBuffer(c)?c:c.buffer),i.bytes+=c.length,n&&(d.writeUInt8(0),i.bytes+=1)}function o(c){let d=0;o.bytes=0;let u=this;if(e)d=t;else if(r)d=t.decode.call(u,c),o.bytes+=t.decode.bytes,BC(d);else if(s)d=t(u),BC(d);else if(n&&(d=c.indexOf(0),d===-1))throw new kJ(c.length+1,c.length);let l=c.readBuffer(d);return o.bytes+=d,n&&(o.bytes+=1,c.consume(1)),l}function a(c){AL(c);let d=0;return e?t:(n?d=1:r&&(d=t.encodingLength(c.length)),d+c.length)}}function AL(t){if(!Buffer.isBuffer(t)&&!(t instanceof AJ))throw new TypeError("Argument 1 should be a Buffer or a BinaryStream.")}function IL(t,e){if(t!==e)throw new Error(`Buffer required length ${t} instead of ${e}`)}function BC(t){if(typeof t!="number")throw new TypeError("Length of a buffer should be a number.")}});var BL=Me((z8e,DL)=>{"use strict";g();y();var{isType:RJ}=Ri();DL.exports=PJ;function PJ(t){if(!RJ(t))throw new TypeError("Argument #1 should be valid type.");function e(s){let n=this,i=t.decode.call(n,s);return e.bytes=t.decode.bytes,!!i}function r(s,n){let i=this;t.encode.call(i,s?1:0,n),r.bytes=t.encode.bytes}return{encode:r,decode:e,encodingLength:t.encodingLength}}});var OL=Me((G8e,LL)=>{"use strict";g();y();var{decodeCommon:DJ}=ch(),{encodeCommon:BJ}=z0(),{encodingLengthCommon:LJ}=W0(),{isType:OJ,isFunction:Zx}=Ri(),NJ=Xa(),Qa=Ya();LL.exports=UJ;function UJ(t,e=1){if(!OJ(t))throw new TypeError("Invalid data type.");if(!Number.isInteger(e)&&!Zx(e))throw new TypeError("Argument #2 should be a valid integer or function.");return{[NJ.skip]:!0,encodingLength:r,decode:s,encode:n};function r(i){let o=Qa.clone(this),a=Zx(e)?e(o):e;return LJ(i,t,o),Qa.clean(o),o.bytes*a}function s(i){let o=Qa.clone(this);s.bytes=0;let a=Zx(e)?e(o):e;if(a===0){Qa.clean(o);return}for(let c=a;c>0;c-=1)DJ(i,t,o);s.bytes=o.bytes,Qa.clean(o)}function n(i,o){n.bytes=0;let a=Qa.clone(this),c=Zx(e)?e(a):e;if(c===0){Qa.clean(a);return}for(let d=c;d>0;d-=1)BJ(0,o,t,a);n.bytes=a.bytes,Qa.clean(a)}}});var ML=Me((J8e,UL)=>{"use strict";g();y();var{isType:MJ}=Ri(),jJ=ah();UL.exports=$J;function $J(t,e="ascii"){if(!Buffer.isEncoding(e))throw new Error("Argument #2 should be an encoding name.");if(typeof t=="number")return{encode:qJ(t,e),decode:VJ(t,e),encodingLength:()=>t};if(MJ(t))return{encode:zJ(t,e),decode:WJ(t,e),encodingLength:KJ(t,e)};if(t===null)return{encode:FJ(e),decode:HJ(e),encodingLength(r){return Buffer.byteLength(r,e)+1}};if(typeof t=="function")return{encode:GJ(t,e),decode:XJ(t,e),encodingLength(r){return Buffer.byteLength(r,e)}};throw new TypeError("Unknown type of argument #1.")}function FJ(t){return function e(r,s){let n=Buffer.from(r.toString(),t);s.writeBuffer(n),s.writeInt8(0),e.bytes=n.length+1}}function HJ(t){return function e(r){let s=r.indexOf(0);if(s===-1)throw new jJ(r.length+1,r.length);let n=s+1,i=r.readBuffer(n);return e.bytes=n,i.toString(t,0,s)}}function qJ(t,e){return function r(s,n){if(s=s.toString(),Buffer.byteLength(s,e)!==t)throw new Error(`Size of string should be ${t} in bytes.`);let i=Buffer.from(s,e);n.writeBuffer(i),r.bytes=i.length}}function VJ(t,e){return function r(s){let n=s.readBuffer(t);return r.bytes=t,n.toString(e)}}function zJ(t,e){return function r(s,n){s=s.toString();let i=this;t.encode.call(i,Buffer.byteLength(s,e),n),r.bytes=t.encode.bytes;let o=Buffer.from(s,e);n.writeBuffer(o),r.bytes+=o.length}}function WJ(t,e){return function r(s){let n=t.decode.call(this,s);if(typeof n!="number")throw new TypeError("Size of a string should be a number.");let i=s.readBuffer(n);return r.bytes=t.decode.bytes+i.length,i.toString(e)}}function KJ(t,e){return function(s){let n=Buffer.byteLength(s,e);return t.encodingLength(n)+n}}function GJ(t,e){return function r(s,n){r.bytes=0;let o=t(this),a=Buffer.from(s.toString(),e);NL(o),YJ(o,a.length),n.writeBuffer(a),r.bytes+=a.length}}function XJ(t,e){return function r(s){let n=t(this);NL(n);let i=s.readBuffer(n);return r.bytes=n,i.toString(e)}}function NL(t){if(typeof t!="number")throw new TypeError("Length of a buffer should be a number.")}function YJ(t,e){if(t!==e)throw new Error(`Buffer required length ${t} instead of ${e}`)}});var $L=Me((e5e,jL)=>{"use strict";g();y();var ew=H0();jL.exports={doublebe:Ps(8,"writeDoubleBE","readDoubleBE"),doublele:Ps(8,"writeDoubleLE","readDoubleLE"),floatbe:Ps(4,"writeFloatBE","readFloatBE"),floatle:Ps(4,"writeFloatLE","readFloatLE"),int8:Ps(1,"writeInt8","readInt8"),uint8:Ps(1,"writeUInt8","readUInt8"),int16be:Ps(2,"writeInt16BE","readInt16BE"),uint16be:Ps(2,"writeUInt16BE","readUInt16BE"),int16le:Ps(2,"writeInt16LE","readInt16LE"),uint16le:Ps(2,"writeUInt16LE","readUInt16LE"),int32be:Ps(4,"writeInt32BE","readInt32BE"),uint32be:Ps(4,"writeUInt32BE","readUInt32BE"),int32le:Ps(4,"writeInt32LE","readInt32LE"),uint32le:Ps(4,"writeUInt32LE","readUInt32LE"),int24be:xn(3,"writeIntBE","readIntBE"),uint24be:xn(3,"writeUIntBE","readUIntBE"),int24le:xn(3,"writeIntLE","readIntLE"),uint24le:xn(3,"writeUIntLE","readUIntLE"),int40be:xn(5,"writeIntBE","readIntBE"),uint40be:xn(5,"writeUIntBE","readUIntBE"),int40le:xn(5,"writeIntLE","readIntLE"),uint40le:xn(5,"writeUIntLE","readUIntLE"),int48be:xn(6,"writeIntBE","readIntBE"),uint48be:xn(6,"writeUIntBE","readUIntBE"),int48le:xn(6,"writeIntLE","readIntLE"),uint48le:xn(6,"writeUIntLE","readUIntLE")};function Ps(t,e,r){let s=ew(),n=ew();return s(`
|
|
100
|
+
`),Qd.prototype[t]=e.toFunction()});function IC(t,e){if(t>e)throw new JY(t,e)}K9.exports=Qd});var X9=Me((m8e,G9)=>{"use strict";g();y();G9.exports=function(e){return e!=null&&typeof e=="object"&&Array.isArray(e)===!1}});var Q9=Me((b8e,J9)=>{"use strict";g();y();var tJ=X9();function Y9(t){return tJ(t)===!0&&Object.prototype.toString.call(t)==="[object Object]"}J9.exports=function(e){var r,s;return!(Y9(e)===!1||(r=e.constructor,typeof r!="function")||(s=r.prototype,Y9(s)===!1)||s.hasOwnProperty("isPrototypeOf")===!1)}});var Ri=Me((v8e,Z9)=>{"use strict";g();y();var rJ=Q9();Z9.exports={isType:sJ,isUserType:rJ,isFunction:Vm,isDecodeType:nJ,isEncodeType:iJ};function sJ(t){return RC(t)&&Vm(t.encode)&&Vm(t.decode)}function Vm(t){return typeof t=="function"}function RC(t){return typeof t=="object"&&t!==null}function nJ(t){return RC(t)&&Vm(t.decode)}function iJ(t){return RC(t)&&Vm(t.encode)}});var Xa=Me((E8e,eL)=>{"use strict";g();y();var oJ=Symbol("skip"),aJ=Symbol("bytes");eL.exports={skip:oJ,bytes:aJ}});var Ya=Me((k8e,rL)=>{"use strict";g();y();var tL=Xa();rL.exports=class Qx{constructor(){this[tL.bytes]=0,this.node=void 0,this.current=void 0}get bytes(){return this[tL.bytes]}static clone(e){let r=new Qx;return e instanceof Qx&&(r.node=e.node,r.current=e.current),r}static clean(e){e instanceof Qx&&(e.node=void 0,e.current=void 0)}}});var ch=Me((R8e,aL)=>{"use strict";g();y();var{isType:cJ,isUserType:dJ,isDecodeType:lJ}=Ri(),uJ=qm(),PC=Xa(),sL=Ya();aL.exports={decode:nL,decodeCommon:iL};function nL(t,e){let r=t;Buffer.isBuffer(t)&&(r=new uJ,r.append(t));let s=new sL,n=iL(r,e,s);return nL.bytes=s.bytes,sL.clean(s),n}function iL(t,e,r){if(cJ(e)){let s=e.decode.call(r,t);return r[PC.bytes]+=e.decode.bytes,s}return oL(t,e,r)}function oL(t,e,r){hJ(e);let s=Object.create(null);r.node===void 0&&(r.node=s),r.current=s;let n=Object.keys(e);for(let i=0;i<n.length;i+=1){let o=n[i],a=e[o];if(!lJ(a)){s[o]=oL(t,a,r),r.current=s;continue}let c=a.decode.call(r,t);r[PC.bytes]+=a.decode.bytes,a[PC.skip]!==!0&&(s[o]=c)}return s}function hJ(t){if(!dJ(t))throw new TypeError("Argument #2 should be a plain object.")}});var zm=Me((B8e,fL)=>{"use strict";g();y();var{isUserType:fJ,isEncodeType:pJ,isType:mJ}=Ri(),dL=Xa(),cL=Ya(),DC=qm();fL.exports={encode:lL,encodeCommon:uL};function lL(t,e,r){let s=new cL;if(e instanceof DC){let n=r;r=e,e=n}return r instanceof DC||(r=new DC),uL(t,r,e,s),lL.bytes=s.bytes,cL.clean(s),r}function uL(t,e,r,s){mJ(r)?(r.encode.call(s,t,e),s[dL.bytes]+=r.encode.bytes):hL(t,e,r,s)}function hL(t,e,r,s){gJ(r),s.node===void 0&&(s.node=t),s.current=t;let n=Object.keys(r);for(let i=0;i<n.length;i+=1){let o=n[i],a=r[o],c=t[o];if(!pJ(a)){hL(c,e,a,s),s.current=t;continue}a.encode.call(s,c,e),s[dL.bytes]+=a.encode.bytes}}function gJ(t){if(!fJ(t))throw new TypeError("Argument `schema` should be a plain object.")}});var Wm=Me((N8e,xL)=>{"use strict";g();y();var{isUserType:yJ,isType:mL}=Ri(),pL=Ya(),gL=Xa();xL.exports={encodingLength:bJ,encodingLengthCommon:yL};function bJ(t,e){let r=new pL;return yL(t,e,r),pL.clean(r),r.bytes}function yL(t,e,r){mL(e)?r[gL.bytes]+=e.encodingLength.call(r,t):bL(t,e,r)}function bL(t,e,r){if(!yJ(e))throw new TypeError("Argument `schema` should be a plain object.");r.node===void 0&&(r.node=t),r.current=t;let s=Object.keys(e);for(let n=0;n<s.length;n+=1){let i=s[n],o=e[i],a=t[i];if(!mL(o)){bL(a,o,r),r.current=t;continue}r[gL.bytes]+=o.encodingLength.call(r,a)}}});var kL=Me((j8e,TL)=>{"use strict";g();y();var{decodeCommon:CL}=ch(),{encodeCommon:xJ}=zm(),{encodingLengthCommon:wL}=Wm(),{isType:vL,isUserType:wJ,isFunction:vJ}=Ri(),Ja=Ya();TL.exports=_J;function _J(t,e,r="count"){if(!vL(t)&&!wJ(t))throw new TypeError("Argument #1 should be a valid type.");let s=r==="bytes",n=typeof e=="number",i=vL(e),o=vJ(e);if(!n&&!i&&!o)throw new TypeError("Unknown type of argument #1.");return{encode:a,decode:c,encodingLength:d};function a(u,l){_L(u);let h=Ja.clone(this);a.bytes=0;let p=0;if(i?p=u.length:n?p=e:o&&(p=e(h),SL(p)),s||EL(p,u.length),s){let m=Ja.clone(h);for(let _ of u)wL(_,t,m);i&&(p=m.bytes),EL(m.bytes,p),Ja.clean(m)}i&&(e.encode.call(h,p,l),a.bytes+=e.encode.bytes),u.forEach(m=>{xJ(m,l,t,h)}),a.bytes+=h.bytes,Ja.clean(h)}function c(u){let l=0;c.bytes=0;let h=Ja.clone(this);n?l=e:i?(l=e.decode.call(h,u),c.bytes+=e.decode.bytes):o&&(l=e(h)),SL(l);let p;return s?p=SJ(t,l,u,h):p=EJ(t,l,u,h),c.bytes+=h.bytes,Ja.clean(h),p}function d(u){_L(u);let l=Ja.clone(this),h=0;if(n&&s)return e;i&&!s&&(h=e.encodingLength(u.length));for(let p of u)wL(p,t,l);return Ja.clean(l),h+=l.bytes,i&&s&&(h+=e.encodingLength(h)),h}}function _L(t){if(!Array.isArray(t))throw new TypeError("Argument #1 should be an Array.")}function SL(t){if(typeof t!="number")throw new TypeError("Length of an array should be a number.")}function EL(t,e){if(t!==e)throw new Error(`Argument #1 required length ${t} instead of ${e}`)}function SJ(t,e,r,s){let n=[],i=s.bytes,o=0;for(;o<e;)n.push(CL(r,t,s)),o=s.bytes-i;if(o>e)throw new Error("Incorrect length of an array.");return n}function EJ(t,e,r,s){let n=new Array(e);for(let i=0;i<e;i+=1)n[i]=CL(r,t,s);return n}});var PL=Me((H8e,RL)=>{"use strict";g();y();var{isType:CJ,isFunction:TJ}=Ri(),kJ=ah(),AJ=qm();RL.exports=IJ;function IJ(t){let e=typeof t=="number",r=CJ(t),s=TJ(t),n=t===null;if(!e&&!r&&!s&&!n)throw new TypeError("Unknown type of argument #1.");return{encode:i,decode:o,encodingLength:a};function i(c,d){AL(c),i.bytes=0;let u=this;if(e&&IL(t,c.length),r&&(t.encode.call(u,c.length,d),i.bytes+=t.encode.bytes),s){let l=t(u);BC(l),IL(l,c.length)}d.writeBuffer(Buffer.isBuffer(c)?c:c.buffer),i.bytes+=c.length,n&&(d.writeUInt8(0),i.bytes+=1)}function o(c){let d=0;o.bytes=0;let u=this;if(e)d=t;else if(r)d=t.decode.call(u,c),o.bytes+=t.decode.bytes,BC(d);else if(s)d=t(u),BC(d);else if(n&&(d=c.indexOf(0),d===-1))throw new kJ(c.length+1,c.length);let l=c.readBuffer(d);return o.bytes+=d,n&&(o.bytes+=1,c.consume(1)),l}function a(c){AL(c);let d=0;return e?t:(n?d=1:r&&(d=t.encodingLength(c.length)),d+c.length)}}function AL(t){if(!Buffer.isBuffer(t)&&!(t instanceof AJ))throw new TypeError("Argument 1 should be a Buffer or a BinaryStream.")}function IL(t,e){if(t!==e)throw new Error(`Buffer required length ${t} instead of ${e}`)}function BC(t){if(typeof t!="number")throw new TypeError("Length of a buffer should be a number.")}});var BL=Me((z8e,DL)=>{"use strict";g();y();var{isType:RJ}=Ri();DL.exports=PJ;function PJ(t){if(!RJ(t))throw new TypeError("Argument #1 should be valid type.");function e(s){let n=this,i=t.decode.call(n,s);return e.bytes=t.decode.bytes,!!i}function r(s,n){let i=this;t.encode.call(i,s?1:0,n),r.bytes=t.encode.bytes}return{encode:r,decode:e,encodingLength:t.encodingLength}}});var OL=Me((G8e,LL)=>{"use strict";g();y();var{decodeCommon:DJ}=ch(),{encodeCommon:BJ}=zm(),{encodingLengthCommon:LJ}=Wm(),{isType:OJ,isFunction:Zx}=Ri(),NJ=Xa(),Qa=Ya();LL.exports=UJ;function UJ(t,e=1){if(!OJ(t))throw new TypeError("Invalid data type.");if(!Number.isInteger(e)&&!Zx(e))throw new TypeError("Argument #2 should be a valid integer or function.");return{[NJ.skip]:!0,encodingLength:r,decode:s,encode:n};function r(i){let o=Qa.clone(this),a=Zx(e)?e(o):e;return LJ(i,t,o),Qa.clean(o),o.bytes*a}function s(i){let o=Qa.clone(this);s.bytes=0;let a=Zx(e)?e(o):e;if(a===0){Qa.clean(o);return}for(let c=a;c>0;c-=1)DJ(i,t,o);s.bytes=o.bytes,Qa.clean(o)}function n(i,o){n.bytes=0;let a=Qa.clone(this),c=Zx(e)?e(a):e;if(c===0){Qa.clean(a);return}for(let d=c;d>0;d-=1)BJ(0,o,t,a);n.bytes=a.bytes,Qa.clean(a)}}});var ML=Me((J8e,UL)=>{"use strict";g();y();var{isType:MJ}=Ri(),jJ=ah();UL.exports=$J;function $J(t,e="ascii"){if(!Buffer.isEncoding(e))throw new Error("Argument #2 should be an encoding name.");if(typeof t=="number")return{encode:qJ(t,e),decode:VJ(t,e),encodingLength:()=>t};if(MJ(t))return{encode:zJ(t,e),decode:WJ(t,e),encodingLength:KJ(t,e)};if(t===null)return{encode:FJ(e),decode:HJ(e),encodingLength(r){return Buffer.byteLength(r,e)+1}};if(typeof t=="function")return{encode:GJ(t,e),decode:XJ(t,e),encodingLength(r){return Buffer.byteLength(r,e)}};throw new TypeError("Unknown type of argument #1.")}function FJ(t){return function e(r,s){let n=Buffer.from(r.toString(),t);s.writeBuffer(n),s.writeInt8(0),e.bytes=n.length+1}}function HJ(t){return function e(r){let s=r.indexOf(0);if(s===-1)throw new jJ(r.length+1,r.length);let n=s+1,i=r.readBuffer(n);return e.bytes=n,i.toString(t,0,s)}}function qJ(t,e){return function r(s,n){if(s=s.toString(),Buffer.byteLength(s,e)!==t)throw new Error(`Size of string should be ${t} in bytes.`);let i=Buffer.from(s,e);n.writeBuffer(i),r.bytes=i.length}}function VJ(t,e){return function r(s){let n=s.readBuffer(t);return r.bytes=t,n.toString(e)}}function zJ(t,e){return function r(s,n){s=s.toString();let i=this;t.encode.call(i,Buffer.byteLength(s,e),n),r.bytes=t.encode.bytes;let o=Buffer.from(s,e);n.writeBuffer(o),r.bytes+=o.length}}function WJ(t,e){return function r(s){let n=t.decode.call(this,s);if(typeof n!="number")throw new TypeError("Size of a string should be a number.");let i=s.readBuffer(n);return r.bytes=t.decode.bytes+i.length,i.toString(e)}}function KJ(t,e){return function(s){let n=Buffer.byteLength(s,e);return t.encodingLength(n)+n}}function GJ(t,e){return function r(s,n){r.bytes=0;let o=t(this),a=Buffer.from(s.toString(),e);NL(o),YJ(o,a.length),n.writeBuffer(a),r.bytes+=a.length}}function XJ(t,e){return function r(s){let n=t(this);NL(n);let i=s.readBuffer(n);return r.bytes=n,i.toString(e)}}function NL(t){if(typeof t!="number")throw new TypeError("Length of a buffer should be a number.")}function YJ(t,e){if(t!==e)throw new Error(`Buffer required length ${t} instead of ${e}`)}});var $L=Me((e5e,jL)=>{"use strict";g();y();var ew=Hm();jL.exports={doublebe:Ps(8,"writeDoubleBE","readDoubleBE"),doublele:Ps(8,"writeDoubleLE","readDoubleLE"),floatbe:Ps(4,"writeFloatBE","readFloatBE"),floatle:Ps(4,"writeFloatLE","readFloatLE"),int8:Ps(1,"writeInt8","readInt8"),uint8:Ps(1,"writeUInt8","readUInt8"),int16be:Ps(2,"writeInt16BE","readInt16BE"),uint16be:Ps(2,"writeUInt16BE","readUInt16BE"),int16le:Ps(2,"writeInt16LE","readInt16LE"),uint16le:Ps(2,"writeUInt16LE","readUInt16LE"),int32be:Ps(4,"writeInt32BE","readInt32BE"),uint32be:Ps(4,"writeUInt32BE","readUInt32BE"),int32le:Ps(4,"writeInt32LE","readInt32LE"),uint32le:Ps(4,"writeUInt32LE","readUInt32LE"),int24be:xn(3,"writeIntBE","readIntBE"),uint24be:xn(3,"writeUIntBE","readUIntBE"),int24le:xn(3,"writeIntLE","readIntLE"),uint24le:xn(3,"writeUIntLE","readUIntLE"),int40be:xn(5,"writeIntBE","readIntBE"),uint40be:xn(5,"writeUIntBE","readUIntBE"),int40le:xn(5,"writeIntLE","readIntLE"),uint40le:xn(5,"writeUIntLE","readUIntLE"),int48be:xn(6,"writeIntBE","readIntBE"),uint48be:xn(6,"writeUIntBE","readUIntBE"),int48le:xn(6,"writeIntLE","readIntLE"),uint48le:xn(6,"writeUIntLE","readUIntLE")};function Ps(t,e,r){let s=ew(),n=ew();return s(`
|
|
101
101
|
function decode_${r}(rstream) {
|
|
102
102
|
decode_${r}.bytes = ${s.formats.d(t)};
|
|
103
103
|
return rstream.${r}()
|
|
@@ -117,34 +117,34 @@ ${e.join(`
|
|
|
117
117
|
wstream.${e}(value, ${s.formats.d(t)});
|
|
118
118
|
encode_${e}.bytes = ${s.formats.d(t)};
|
|
119
119
|
}
|
|
120
|
-
`),{encodingLength:()=>t,encode:n.toFunction(),decode:s.toFunction()}}});var HL=Me((s5e,FL)=>{"use strict";g();y();var{isType:JJ,isFunction:LC,isUserType:QJ}=Ri(),OC=Xa(),{decodeCommon:ZJ}=ch(),{encodeCommon:eQ}=
|
|
120
|
+
`),{encodingLength:()=>t,encode:n.toFunction(),decode:s.toFunction()}}});var HL=Me((s5e,FL)=>{"use strict";g();y();var{isType:JJ,isFunction:LC,isUserType:QJ}=Ri(),OC=Xa(),{decodeCommon:ZJ}=ch(),{encodeCommon:eQ}=zm(),{encodingLengthCommon:tQ}=Wm(),Za=Ya();FL.exports=rQ;function rQ(t,e){if(!JJ(e)&&!QJ(e))throw new TypeError("Argument #2 should be a valid type.");let r={encode:s,decode:n,encodingLength:i,[OC.skip]:!1};return r;function s(o,a){let c=Za.clone(this);s.bytes=0;let d=LC(t)?!!t(c):!!t;if(r[OC.skip]=!d,!d){Za.clean(c);return}eQ(o,a,e,c),s.bytes=c.bytes,Za.clean(c)}function n(o){let a=Za.clone(this);n.bytes=0;let c=LC(t)?!!t(a):!!t;if(r[OC.skip]=!c,!c){Za.clean(a);return}let d=ZJ(o,e,a);return n.bytes=a.bytes,Za.clean(a),d}function i(o){let a=Za.clone(this);return(LC(t)?t(a):t)&&tQ(o,e,a),Za.clean(a),a.bytes}}});var zL=Me((o5e,VL)=>{"use strict";g();y();var tw=Xa(),{decodeCommon:sQ}=ch(),qL=Ya();VL.exports=nQ;function nQ(...t){if(t.length===0)throw new TypeError("You should set at least one condition type.");let e={decode:r,encode:()=>{},[tw.skip]:!0};return e;function r(s){r.bytes=0;let n=qL.clone(this);for(let i of t){let o=sQ(s,i,n);if(i[tw.skip]!==!0)return r.bytes=n.bytes,qL.clean(n),e[tw.skip]=!1,o}e[tw.skip]=!0}}});var XL=Me((d5e,GL)=>{"use strict";g();y();var KL=Hm(),iQ=ah(),Km=class{constructor(e){this.stream=e,this.index=0}append(e){this.stream.append(e)}commit(){this.stream.consume(this.index)}get(e=0){return this.stream.get(this.index+e)}get length(){return this.stream.length}slice(e,r){return this.stream.slice(e,r)}toString(e,r,s){return this.stream.toString(e,r,s)}readBuffer(e){NC(this.index+e,this.length);let r=this.stream.slice(this.index,this.index+e);return this.index+=e,r}indexOf(e,r=0){return this.stream.indexOf(e,this.index+r)-this.index}},WL={readDoubleBE:8,readDoubleLE:8,readFloatBE:4,readFloatLE:4,readInt32BE:4,readInt32LE:4,readUInt32BE:4,readUInt32LE:4,readInt16BE:2,readInt16LE:2,readUInt16BE:2,readUInt16LE:2,readInt8:1,readUInt8:1};Object.keys(WL).forEach(t=>{let e=KL(),r=WL[t];e(`
|
|
121
121
|
function transaction_${t}() {
|
|
122
122
|
assertSize(this.index + ${e.formats.d(r)}, this.length);
|
|
123
123
|
const value = this.stream.buffer.${t}(this.index);
|
|
124
124
|
this.index += ${e.formats.d(r)};
|
|
125
125
|
return value;
|
|
126
126
|
}
|
|
127
|
-
`),
|
|
127
|
+
`),Km.prototype[t]=e.toFunction({assertSize:NC})});["readIntBE","readIntLE","readUIntBE","readUIntLE"].forEach(t=>{let e=KL();e(`
|
|
128
128
|
function transaction_${t}(bytes) {
|
|
129
129
|
assertSize(this.index + bytes, this.length);
|
|
130
130
|
const value = this.stream.buffer.${t}(bytes, this.index);
|
|
131
131
|
this.index += bytes;
|
|
132
132
|
return value;
|
|
133
133
|
}
|
|
134
|
-
`),K0.prototype[t]=e.toFunction({assertSize:NC})});GL.exports=K0;function NC(t,e){if(t>e)throw new iQ(t,e)}});var sr=Me((h5e,sO)=>{"use strict";g();y();var UC=q0(),oQ=kL(),aQ=PL(),cQ=BL(),dQ=OL(),lQ=ML(),YL=$L(),uQ=HL(),hQ=zL(),{encode:ZL}=z0(),{decode:eO}=ch(),{encodingLength:fQ}=W0(),pQ=XL(),tO=ah(),rO={array:oQ,bool:cQ,buffer:aQ,reserved:dQ,string:lQ,when:uQ,select:hQ};for(let t of Object.keys(YL))rO[t]=YL[t];var rw=Symbol("schema");function JL(t){let e=new UC({readableObjectMode:!1,writableObjectMode:!0,transform:mQ});return e[rw]=t,e}function QL(t){let e=null,r=Buffer.isBuffer(t);r||(e=t);let s=new UC({transform:gQ,readableObjectMode:!0,writableObjectMode:!1});return s[rw]=e,r&&s.append(t),s}function mQ(t,e,r){try{ZL(t,this[rw],this);let s=this.slice();this.consume(s.length),r(null,s)}catch(s){r(s)}}function gQ(t,e,r){this.append(t);try{for(;this.length>0;){let s=new pQ(this),n=eO(s,this[rw]);s.commit(),this.push(n)}r()}catch(s){s instanceof tO?r():r(s)}}sO.exports={createEncodeStream:JL,createDecodeStream:QL,encode:ZL,decode:eO,encodingLength:fQ,createEncode:JL,createDecode:QL,types:rO,BinaryStream:UC,NotEnoughDataError:tO}});var To,Zd,nO=V(()=>{"use strict";g();y();To=Le(require("crypto"),1),Zd=To&&typeof To=="object"&&"webcrypto"in To?To.webcrypto:To&&typeof To=="object"&&"randomBytes"in To?To:void 0});function el(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function G0(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function Nn(t,...e){if(!el(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function sw(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");G0(t.outputLen),G0(t.blockLen)}function lh(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function oO(t,e){Nn(t);let r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function Ao(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function nw(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function Un(t,e){return t<<32-e|t>>>e}function Io(t){if(Nn(t),aO)return t.toHex();let e="";for(let r=0;r<t.length;r++)e+=yQ[t[r]];return e}function iO(t){if(t>=ko._0&&t<=ko._9)return t-ko._0;if(t>=ko.A&&t<=ko.F)return t-(ko.A-10);if(t>=ko.a&&t<=ko.f)return t-(ko.a-10)}function tl(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(aO)return Uint8Array.fromHex(t);let e=t.length,r=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);let s=new Uint8Array(r);for(let n=0,i=0;n<r;n++,i+=2){let o=iO(t.charCodeAt(i)),a=iO(t.charCodeAt(i+1));if(o===void 0||a===void 0){let c=t[i]+t[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}s[n]=o*16+a}return s}function cO(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function X0(t){return typeof t=="string"&&(t=cO(t)),Nn(t),t}function Mn(...t){let e=0;for(let s=0;s<t.length;s++){let n=t[s];Nn(n),e+=n.length}let r=new Uint8Array(e);for(let s=0,n=0;s<t.length;s++){let i=t[s];r.set(i,n),n+=i.length}return r}function iw(t){let e=s=>t().update(X0(s)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function ow(t=32){if(Zd&&typeof Zd.getRandomValues=="function")return Zd.getRandomValues(new Uint8Array(t));if(Zd&&typeof Zd.randomBytes=="function")return Uint8Array.from(Zd.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}var aO,yQ,ko,dh,rl=V(()=>{"use strict";g();y();nO();aO=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",yQ=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));ko={_0:48,_9:57,A:65,F:70,a:97,f:102};dh=class{}});function Y0(t,e=""){if(typeof t!="boolean"){let r=e&&`"${e}"`;throw new Error(r+"expected boolean, got type="+typeof t)}return t}function ec(t,e,r=""){let s=el(t),n=t?.length,i=e!==void 0;if(!s||i&&n!==e){let o=r&&`"${r}" `,a=i?` of length ${e}`:"",c=s?`length=${n}`:`type=${typeof t}`;throw new Error(o+"expected Uint8Array"+a+", got "+c)}return t}function J0(t){let e=t.toString(16);return e.length&1?"0"+e:e}function dO(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?$C:BigInt("0x"+t)}function uh(t){return dO(Io(t))}function FC(t){return Nn(t),dO(Io(Uint8Array.from(t).reverse()))}function aw(t,e){return tl(t.toString(16).padStart(e*2,"0"))}function HC(t,e){return aw(t,e).reverse()}function cs(t,e,r){let s;if(typeof e=="string")try{s=tl(e)}catch(i){throw new Error(t+" must be hex string or Uint8Array, cause: "+i)}else if(el(e))s=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");let n=s.length;if(typeof r=="number"&&n!==r)throw new Error(t+" of length "+r+" expected, got "+n);return s}function lO(t,e,r){return MC(t)&&MC(e)&&MC(r)&&e<=t&&t<r}function uO(t,e,r,s){if(!lO(e,r,s))throw new Error("expected valid "+t+": "+r+" <= n < "+s+", got "+e)}function cw(t){let e;for(e=0;t>$C;t>>=jC,e+=1);return e}function hO(t,e,r){if(typeof t!="number"||t<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof r!="function")throw new Error("hmacFn must be a function");let s=p=>new Uint8Array(p),n=p=>Uint8Array.of(p),i=s(t),o=s(t),a=0,c=()=>{i.fill(1),o.fill(0),a=0},d=(...p)=>r(o,i,...p),u=(p=s(0))=>{o=d(n(0),p),i=d(),p.length!==0&&(o=d(n(1),p),i=d())},l=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let p=0,m=[];for(;p<e;){i=d();let _=i.slice();m.push(_),p+=i.length}return Mn(...m)};return(p,m)=>{c(),u(p);let _;for(;!(_=m(l()));)u();return c(),_}}function Q0(t,e,r={}){if(!t||typeof t!="object")throw new Error("expected valid options object");function s(n,i,o){let a=t[n];if(o&&a===void 0)return;let c=typeof a;if(c!==i||a===null)throw new Error(`param "${n}" is invalid: expected ${i}, got ${c}`)}Object.entries(e).forEach(([n,i])=>s(n,i,!1)),Object.entries(r).forEach(([n,i])=>s(n,i,!0))}function qC(t){let e=new WeakMap;return(r,...s)=>{let n=e.get(r);if(n!==void 0)return n;let i=t(r,...s);return e.set(r,i),i}}var $C,jC,MC,tc,dw=V(()=>{"use strict";g();y();rl();rl();$C=BigInt(0),jC=BigInt(1);MC=t=>typeof t=="bigint"&&$C<=t;tc=t=>(jC<<BigInt(t))-jC});function jn(t,e){let r=t%e;return r>=Ds?r:e+r}function fO(t,e){if(t===Ds)throw new Error("invert: expected non-zero number");if(e<=Ds)throw new Error("invert: expected positive modulus, got "+e);let r=jn(t,e),s=e,n=Ds,i=ds,o=ds,a=Ds;for(;r!==Ds;){let d=s/r,u=s%r,l=n-o*d,h=i-a*d;s=r,r=u,n=o,i=a,o=l,a=h}if(s!==ds)throw new Error("invert: does not exist");return jn(n,e)}function VC(t,e,r){if(!t.eql(t.sqr(e),r))throw new Error("Cannot find square root")}function wO(t,e){let r=(t.ORDER+ds)/gO,s=t.pow(e,r);return VC(t,s,e),s}function wQ(t,e){let r=(t.ORDER-yO)/bO,s=t.mul(e,sl),n=t.pow(s,r),i=t.mul(e,n),o=t.mul(t.mul(i,sl),n),a=t.mul(i,t.sub(o,t.ONE));return VC(t,a,e),a}function vQ(t){let e=Pi(t),r=vO(t),s=r(e,e.neg(e.ONE)),n=r(e,s),i=r(e,e.neg(s)),o=(t+bQ)/xO;return(a,c)=>{let d=a.pow(c,o),u=a.mul(d,s),l=a.mul(d,n),h=a.mul(d,i),p=a.eql(a.sqr(u),c),m=a.eql(a.sqr(l),c);d=a.cmov(d,u,p),u=a.cmov(h,l,m);let _=a.eql(a.sqr(u),c),f=a.cmov(d,u,_);return VC(a,f,c),f}}function vO(t){if(t<mO)throw new Error("sqrt is not defined for small field");let e=t-ds,r=0;for(;e%sl===Ds;)e/=sl,r++;let s=sl,n=Pi(t);for(;pO(n,s)===1;)if(s++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return wO;let i=n.pow(s,e),o=(e+ds)/sl;return function(c,d){if(c.is0(d))return d;if(pO(c,d)!==1)throw new Error("Cannot find square root");let u=r,l=c.mul(c.ONE,i),h=c.pow(d,e),p=c.pow(d,o);for(;!c.eql(h,c.ONE);){if(c.is0(h))return c.ZERO;let m=1,_=c.sqr(h);for(;!c.eql(_,c.ONE);)if(m++,_=c.sqr(_),m===u)throw new Error("Cannot find square root");let f=ds<<BigInt(u-m-1),b=c.pow(l,f);u=m,l=c.sqr(b),h=c.mul(h,l),p=c.mul(p,b)}return p}}function _Q(t){return t%gO===mO?wO:t%bO===yO?wQ:t%xO===xQ?vQ(t):vO(t)}function zC(t){let e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},r=SQ.reduce((s,n)=>(s[n]="function",s),e);return Q0(t,r),t}function EQ(t,e,r){if(r<Ds)throw new Error("invalid exponent, negatives unsupported");if(r===Ds)return t.ONE;if(r===ds)return e;let s=t.ONE,n=e;for(;r>Ds;)r&ds&&(s=t.mul(s,n)),n=t.sqr(n),r>>=ds;return s}function lw(t,e,r=!1){let s=new Array(e.length).fill(r?t.ZERO:void 0),n=e.reduce((o,a,c)=>t.is0(a)?o:(s[c]=o,t.mul(o,a)),t.ONE),i=t.inv(n);return e.reduceRight((o,a,c)=>t.is0(a)?o:(s[c]=t.mul(o,s[c]),t.mul(o,a)),i),s}function pO(t,e){let r=(t.ORDER-ds)/sl,s=t.pow(e,r),n=t.eql(s,t.ONE),i=t.eql(s,t.ZERO),o=t.eql(s,t.neg(t.ONE));if(!n&&!i&&!o)throw new Error("invalid Legendre symbol result");return n?1:i?0:-1}function uw(t,e){e!==void 0&&G0(e);let r=e!==void 0?e:t.toString(2).length,s=Math.ceil(r/8);return{nBitLength:r,nByteLength:s}}function Pi(t,e,r=!1,s={}){if(t<=Ds)throw new Error("invalid field: expected ORDER > 0, got "+t);let n,i,o=!1,a;if(typeof e=="object"&&e!=null){if(s.sqrt||r)throw new Error("cannot specify opts in two arguments");let h=e;h.BITS&&(n=h.BITS),h.sqrt&&(i=h.sqrt),typeof h.isLE=="boolean"&&(r=h.isLE),typeof h.modFromBytes=="boolean"&&(o=h.modFromBytes),a=h.allowedLengths}else typeof e=="number"&&(n=e),s.sqrt&&(i=s.sqrt);let{nBitLength:c,nByteLength:d}=uw(t,n);if(d>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let u,l=Object.freeze({ORDER:t,isLE:r,BITS:c,BYTES:d,MASK:tc(c),ZERO:Ds,ONE:ds,allowedLengths:a,create:h=>jn(h,t),isValid:h=>{if(typeof h!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof h);return Ds<=h&&h<t},is0:h=>h===Ds,isValidNot0:h=>!l.is0(h)&&l.isValid(h),isOdd:h=>(h&ds)===ds,neg:h=>jn(-h,t),eql:(h,p)=>h===p,sqr:h=>jn(h*h,t),add:(h,p)=>jn(h+p,t),sub:(h,p)=>jn(h-p,t),mul:(h,p)=>jn(h*p,t),pow:(h,p)=>EQ(l,h,p),div:(h,p)=>jn(h*fO(p,t),t),sqrN:h=>h*h,addN:(h,p)=>h+p,subN:(h,p)=>h-p,mulN:(h,p)=>h*p,inv:h=>fO(h,t),sqrt:i||(h=>(u||(u=_Q(t)),u(l,h))),toBytes:h=>r?HC(h,d):aw(h,d),fromBytes:(h,p=!0)=>{if(a){if(!a.includes(h.length)||h.length>d)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+h.length);let _=new Uint8Array(d);_.set(h,r?0:_.length-h.length),h=_}if(h.length!==d)throw new Error("Field.fromBytes: expected "+d+" bytes, got "+h.length);let m=r?FC(h):uh(h);if(o&&(m=jn(m,t)),!p&&!l.isValid(m))throw new Error("invalid field element: outside of range 0..ORDER");return m},invertBatch:h=>lw(l,h),cmov:(h,p,m)=>m?p:h});return Object.freeze(l)}function _O(t){if(typeof t!="bigint")throw new Error("field order must be bigint");let e=t.toString(2).length;return Math.ceil(e/8)}function WC(t){let e=_O(t);return e+Math.ceil(e/2)}function SO(t,e,r=!1){let s=t.length,n=_O(e),i=WC(e);if(s<16||s<i||s>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+s);let o=r?FC(t):uh(t),a=jn(o,e-ds)+ds;return r?HC(a,n):aw(a,n)}var Ds,ds,sl,mO,gO,yO,bQ,bO,xQ,xO,SQ,hw=V(()=>{"use strict";g();y();dw();Ds=BigInt(0),ds=BigInt(1),sl=BigInt(2),mO=BigInt(3),gO=BigInt(4),yO=BigInt(5),bQ=BigInt(7),bO=BigInt(8),xQ=BigInt(9),xO=BigInt(16);SQ=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"]});function CQ(t,e,r,s){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,s);let n=BigInt(32),i=BigInt(4294967295),o=Number(r>>n&i),a=Number(r&i),c=s?4:0,d=s?0:4;t.setUint32(e+c,o,s),t.setUint32(e+d,a,s)}function EO(t,e,r){return t&e^~t&r}function CO(t,e,r){return t&e^t&r^e&r}var Z0,Ro,Kr,Gr,TO=V(()=>{"use strict";g();y();rl();Z0=class extends dh{constructor(e,r,s,n){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=r,this.padOffset=s,this.isLE=n,this.buffer=new Uint8Array(e),this.view=nw(this.buffer)}update(e){lh(this),e=X0(e),Nn(e);let{view:r,buffer:s,blockLen:n}=this,i=e.length;for(let o=0;o<i;){let a=Math.min(n-this.pos,i-o);if(a===n){let c=nw(e);for(;n<=i-o;o+=n)this.process(c,o);continue}s.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===n&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){lh(this),oO(e,this),this.finished=!0;let{buffer:r,view:s,blockLen:n,isLE:i}=this,{pos:o}=this;r[o++]=128,Ao(this.buffer.subarray(o)),this.padOffset>n-o&&(this.process(s,0),o=0);for(let l=o;l<n;l++)r[l]=0;CQ(s,n-8,BigInt(this.length*8),i),this.process(s,0);let a=nw(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let d=c/4,u=this.get();if(d>u.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;l<d;l++)a.setUint32(4*l,u[l],i)}digest(){let{buffer:e,outputLen:r}=this;this.digestInto(e);let s=e.slice(0,r);return this.destroy(),s}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:r,buffer:s,length:n,finished:i,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=i,e.length=n,e.pos=a,n%r&&e.buffer.set(s),e}clone(){return this._cloneInto()}},Ro=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Kr=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]),Gr=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209])});function TQ(t,e=!1){return e?{h:Number(t&fw),l:Number(t>>kO&fw)}:{h:Number(t>>kO&fw)|0,l:Number(t&fw)|0}}function AO(t,e=!1){let r=t.length,s=new Uint32Array(r),n=new Uint32Array(r);for(let i=0;i<r;i++){let{h:o,l:a}=TQ(t[i],e);[s[i],n[i]]=[o,a]}return[s,n]}function Di(t,e,r,s){let n=(e>>>0)+(s>>>0);return{h:t+r+(n/2**32|0)|0,l:n|0}}var fw,kO,KC,GC,nl,il,em,tm,IO,RO,PO,DO,BO,LO,OO=V(()=>{"use strict";g();y();fw=BigInt(4294967295),kO=BigInt(32);KC=(t,e,r)=>t>>>r,GC=(t,e,r)=>t<<32-r|e>>>r,nl=(t,e,r)=>t>>>r|e<<32-r,il=(t,e,r)=>t<<32-r|e>>>r,em=(t,e,r)=>t<<64-r|e>>>r-32,tm=(t,e,r)=>t>>>r-32|e<<64-r;IO=(t,e,r)=>(t>>>0)+(e>>>0)+(r>>>0),RO=(t,e,r,s)=>e+r+s+(t/2**32|0)|0,PO=(t,e,r,s)=>(t>>>0)+(e>>>0)+(r>>>0)+(s>>>0),DO=(t,e,r,s,n)=>e+r+s+n+(t/2**32|0)|0,BO=(t,e,r,s,n)=>(t>>>0)+(e>>>0)+(r>>>0)+(s>>>0)+(n>>>0),LO=(t,e,r,s,n,i)=>e+r+s+n+i+(t/2**32|0)|0});var AQ,rc,XC,NO,IQ,RQ,sc,nc,pw,YC,UO,MO,jO,$O=V(()=>{"use strict";g();y();TO();OO();rl();AQ=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),rc=new Uint32Array(64),XC=class extends Z0{constructor(e=32){super(64,e,8,!1),this.A=Ro[0]|0,this.B=Ro[1]|0,this.C=Ro[2]|0,this.D=Ro[3]|0,this.E=Ro[4]|0,this.F=Ro[5]|0,this.G=Ro[6]|0,this.H=Ro[7]|0}get(){let{A:e,B:r,C:s,D:n,E:i,F:o,G:a,H:c}=this;return[e,r,s,n,i,o,a,c]}set(e,r,s,n,i,o,a,c){this.A=e|0,this.B=r|0,this.C=s|0,this.D=n|0,this.E=i|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,r){for(let l=0;l<16;l++,r+=4)rc[l]=e.getUint32(r,!1);for(let l=16;l<64;l++){let h=rc[l-15],p=rc[l-2],m=Un(h,7)^Un(h,18)^h>>>3,_=Un(p,17)^Un(p,19)^p>>>10;rc[l]=_+rc[l-7]+m+rc[l-16]|0}let{A:s,B:n,C:i,D:o,E:a,F:c,G:d,H:u}=this;for(let l=0;l<64;l++){let h=Un(a,6)^Un(a,11)^Un(a,25),p=u+h+EO(a,c,d)+AQ[l]+rc[l]|0,_=(Un(s,2)^Un(s,13)^Un(s,22))+CO(s,n,i)|0;u=d,d=c,c=a,a=o+p|0,o=i,i=n,n=s,s=p+_|0}s=s+this.A|0,n=n+this.B|0,i=i+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,d=d+this.G|0,u=u+this.H|0,this.set(s,n,i,o,a,c,d,u)}roundClean(){Ao(rc)}destroy(){this.set(0,0,0,0,0,0,0,0),Ao(this.buffer)}},NO=AO(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(t=>BigInt(t))),IQ=NO[0],RQ=NO[1],sc=new Uint32Array(80),nc=new Uint32Array(80),pw=class extends Z0{constructor(e=64){super(128,e,16,!1),this.Ah=Gr[0]|0,this.Al=Gr[1]|0,this.Bh=Gr[2]|0,this.Bl=Gr[3]|0,this.Ch=Gr[4]|0,this.Cl=Gr[5]|0,this.Dh=Gr[6]|0,this.Dl=Gr[7]|0,this.Eh=Gr[8]|0,this.El=Gr[9]|0,this.Fh=Gr[10]|0,this.Fl=Gr[11]|0,this.Gh=Gr[12]|0,this.Gl=Gr[13]|0,this.Hh=Gr[14]|0,this.Hl=Gr[15]|0}get(){let{Ah:e,Al:r,Bh:s,Bl:n,Ch:i,Cl:o,Dh:a,Dl:c,Eh:d,El:u,Fh:l,Fl:h,Gh:p,Gl:m,Hh:_,Hl:f}=this;return[e,r,s,n,i,o,a,c,d,u,l,h,p,m,_,f]}set(e,r,s,n,i,o,a,c,d,u,l,h,p,m,_,f){this.Ah=e|0,this.Al=r|0,this.Bh=s|0,this.Bl=n|0,this.Ch=i|0,this.Cl=o|0,this.Dh=a|0,this.Dl=c|0,this.Eh=d|0,this.El=u|0,this.Fh=l|0,this.Fl=h|0,this.Gh=p|0,this.Gl=m|0,this.Hh=_|0,this.Hl=f|0}process(e,r){for(let S=0;S<16;S++,r+=4)sc[S]=e.getUint32(r),nc[S]=e.getUint32(r+=4);for(let S=16;S<80;S++){let O=sc[S-15]|0,j=nc[S-15]|0,P=nl(O,j,1)^nl(O,j,8)^KC(O,j,7),k=il(O,j,1)^il(O,j,8)^GC(O,j,7),C=sc[S-2]|0,D=nc[S-2]|0,H=nl(C,D,19)^em(C,D,61)^KC(C,D,6),W=il(C,D,19)^tm(C,D,61)^GC(C,D,6),J=PO(k,W,nc[S-7],nc[S-16]),F=DO(J,P,H,sc[S-7],sc[S-16]);sc[S]=F|0,nc[S]=J|0}let{Ah:s,Al:n,Bh:i,Bl:o,Ch:a,Cl:c,Dh:d,Dl:u,Eh:l,El:h,Fh:p,Fl:m,Gh:_,Gl:f,Hh:b,Hl:w}=this;for(let S=0;S<80;S++){let O=nl(l,h,14)^nl(l,h,18)^em(l,h,41),j=il(l,h,14)^il(l,h,18)^tm(l,h,41),P=l&p^~l&_,k=h&m^~h&f,C=BO(w,j,k,RQ[S],nc[S]),D=LO(C,b,O,P,IQ[S],sc[S]),H=C|0,W=nl(s,n,28)^em(s,n,34)^em(s,n,39),J=il(s,n,28)^tm(s,n,34)^tm(s,n,39),F=s&i^s&a^i&a,q=n&o^n&c^o&c;b=_|0,w=f|0,_=p|0,f=m|0,p=l|0,m=h|0,{h:l,l:h}=Di(d|0,u|0,D|0,H|0),d=a|0,u=c|0,a=i|0,c=o|0,i=s|0,o=n|0;let Q=IO(H,J,q);s=RO(Q,D,W,F),n=Q|0}({h:s,l:n}=Di(this.Ah|0,this.Al|0,s|0,n|0)),{h:i,l:o}=Di(this.Bh|0,this.Bl|0,i|0,o|0),{h:a,l:c}=Di(this.Ch|0,this.Cl|0,a|0,c|0),{h:d,l:u}=Di(this.Dh|0,this.Dl|0,d|0,u|0),{h:l,l:h}=Di(this.Eh|0,this.El|0,l|0,h|0),{h:p,l:m}=Di(this.Fh|0,this.Fl|0,p|0,m|0),{h:_,l:f}=Di(this.Gh|0,this.Gl|0,_|0,f|0),{h:b,l:w}=Di(this.Hh|0,this.Hl|0,b|0,w|0),this.set(s,n,i,o,a,c,d,u,l,h,p,m,_,f,b,w)}roundClean(){Ao(sc,nc)}destroy(){Ao(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},YC=class extends pw{constructor(){super(48),this.Ah=Kr[0]|0,this.Al=Kr[1]|0,this.Bh=Kr[2]|0,this.Bl=Kr[3]|0,this.Ch=Kr[4]|0,this.Cl=Kr[5]|0,this.Dh=Kr[6]|0,this.Dl=Kr[7]|0,this.Eh=Kr[8]|0,this.El=Kr[9]|0,this.Fh=Kr[10]|0,this.Fl=Kr[11]|0,this.Gh=Kr[12]|0,this.Gl=Kr[13]|0,this.Hh=Kr[14]|0,this.Hl=Kr[15]|0}},UO=iw(()=>new XC),MO=iw(()=>new pw),jO=iw(()=>new YC)});var mw,JC,FO=V(()=>{"use strict";g();y();rl();mw=class extends dh{constructor(e,r){super(),this.finished=!1,this.destroyed=!1,sw(e);let s=X0(r);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,i=new Uint8Array(n);i.set(s.length>n?e.create().update(s).digest():s);for(let o=0;o<i.length;o++)i[o]^=54;this.iHash.update(i),this.oHash=e.create();for(let o=0;o<i.length;o++)i[o]^=106;this.oHash.update(i),Ao(i)}update(e){return lh(this),this.iHash.update(e),this}digestInto(e){lh(this),Nn(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));let{oHash:r,iHash:s,finished:n,destroyed:i,blockLen:o,outputLen:a}=this;return e=e,e.finished=n,e.destroyed=i,e.blockLen=o,e.outputLen=a,e.oHash=r._cloneInto(e.oHash),e.iHash=s._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},JC=(t,e,r)=>new mw(t,e).update(r).digest();JC.create=(t,e)=>new mw(t,e)});function rm(t,e){let r=e.negate();return t?r:e}function yw(t,e){let r=lw(t.Fp,e.map(s=>s.Z));return e.map((s,n)=>t.fromAffine(s.toAffine(r[n])))}function zO(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function QC(t,e){zO(t,e);let r=Math.ceil(e/t)+1,s=2**(t-1),n=2**t,i=tc(t),o=BigInt(t);return{windows:r,windowSize:s,mask:i,maxNumber:n,shiftBy:o}}function HO(t,e,r){let{windowSize:s,mask:n,maxNumber:i,shiftBy:o}=r,a=Number(t&n),c=t>>o;a>s&&(a-=i,c+=ol);let d=e*s,u=d+Math.abs(a)-1,l=a===0,h=a<0,p=e%2!==0;return{nextN:c,offset:u,isZero:l,isNeg:h,isNegF:p,offsetF:d}}function PQ(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((r,s)=>{if(!(r instanceof e))throw new Error("invalid point at index "+s)})}function DQ(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((r,s)=>{if(!e.isValid(r))throw new Error("invalid scalar at index "+s)})}function eT(t){return WO.get(t)||1}function qO(t){if(t!==hh)throw new Error("invalid wNAF")}function KO(t,e,r,s){let n=e,i=t.ZERO,o=t.ZERO;for(;r>hh||s>hh;)r&ol&&(i=i.add(n)),s&ol&&(o=o.add(n)),n=n.double(),r>>=ol,s>>=ol;return{p1:i,p2:o}}function GO(t,e,r,s){PQ(r,t),DQ(s,e);let n=r.length,i=s.length;if(n!==i)throw new Error("arrays of points and scalars must have equal length");let o=t.ZERO,a=cw(BigInt(n)),c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);let d=tc(c),u=new Array(Number(d)+1).fill(o),l=Math.floor((e.BITS-1)/c)*c,h=o;for(let p=l;p>=0;p-=c){u.fill(o);for(let _=0;_<i;_++){let f=s[_],b=Number(f>>BigInt(p)&d);u[b]=u[b].add(r[_])}let m=o;for(let _=u.length-1,f=o;_>0;_--)f=f.add(u[_]),m=m.add(f);if(h=h.add(m),p!==0)for(let _=0;_<c;_++)h=h.double()}return h}function VO(t,e,r){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return zC(e),e}else return Pi(t,{isLE:r})}function XO(t,e,r={},s){if(s===void 0&&(s=t==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);for(let c of["p","n","h"]){let d=e[c];if(!(typeof d=="bigint"&&d>hh))throw new Error(`CURVE.${c} must be positive bigint`)}let n=VO(e.p,r.Fp,s),i=VO(e.n,r.Fn,s),a=["Gx","Gy","a",t==="weierstrass"?"b":"d"];for(let c of a)if(!n.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:n,Fn:i}}var hh,ol,ZC,WO,gw,YO=V(()=>{"use strict";g();y();dw();hw();hh=BigInt(0),ol=BigInt(1);ZC=new WeakMap,WO=new WeakMap;gw=class{constructor(e,r){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=r}_unsafeLadder(e,r,s=this.ZERO){let n=e;for(;r>hh;)r&ol&&(s=s.add(n)),n=n.double(),r>>=ol;return s}precomputeWindow(e,r){let{windows:s,windowSize:n}=QC(r,this.bits),i=[],o=e,a=o;for(let c=0;c<s;c++){a=o,i.push(a);for(let d=1;d<n;d++)a=a.add(o),i.push(a);o=a.double()}return i}wNAF(e,r,s){if(!this.Fn.isValid(s))throw new Error("invalid scalar");let n=this.ZERO,i=this.BASE,o=QC(e,this.bits);for(let a=0;a<o.windows;a++){let{nextN:c,offset:d,isZero:u,isNeg:l,isNegF:h,offsetF:p}=HO(s,a,o);s=c,u?i=i.add(rm(h,r[p])):n=n.add(rm(l,r[d]))}return qO(s),{p:n,f:i}}wNAFUnsafe(e,r,s,n=this.ZERO){let i=QC(e,this.bits);for(let o=0;o<i.windows&&s!==hh;o++){let{nextN:a,offset:c,isZero:d,isNeg:u}=HO(s,o,i);if(s=a,!d){let l=r[c];n=n.add(u?l.negate():l)}}return qO(s),n}getPrecomputes(e,r,s){let n=ZC.get(r);return n||(n=this.precomputeWindow(r,e),e!==1&&(typeof s=="function"&&(n=s(n)),ZC.set(r,n))),n}cached(e,r,s){let n=eT(e);return this.wNAF(n,this.getPrecomputes(n,e,s),r)}unsafe(e,r,s,n){let i=eT(e);return i===1?this._unsafeLadder(e,r,n):this.wNAFUnsafe(i,this.getPrecomputes(i,e,s),r,n)}createCache(e,r){zO(r,this.bits),WO.set(e,r),ZC.delete(e)}hasCache(e){return eT(e)!==1}}});function BQ(t,e,r){let[[s,n],[i,o]]=e,a=JO(o*t,r),c=JO(-n*t,r),d=t-a*s-c*i,u=-a*n-c*o,l=d<Do,h=u<Do;l&&(d=-d),h&&(u=-u);let p=tc(Math.ceil(cw(r)/2))+ph;if(d<Do||d>=p||u<Do||u>=p)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:l,k1:d,k2neg:h,k2:u}}function rT(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function tT(t,e){let r={};for(let s of Object.keys(e))r[s]=t[s]===void 0?e[s]:t[s];return Y0(r.lowS,"lowS"),Y0(r.prehash,"prehash"),r.format!==void 0&&rT(r.format),r}function fh(t,e){let{BYTES:r}=t,s;if(typeof e=="bigint")s=e;else{let n=cs("private key",e);try{s=t.fromBytes(n)}catch{throw new Error(`invalid private key: expected ui8a of size ${r}, got ${typeof e}`)}}if(!t.isValidNot0(s))throw new Error("invalid private key: out of range [1..N-1]");return s}function OQ(t,e={}){let r=XO("weierstrass",t,e),{Fp:s,Fn:n}=r,i=r.CURVE,{h:o,n:a}=i;Q0(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});let{endo:c}=e;if(c&&(!s.is0(i.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let d=eN(s,n);function u(){if(!s.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function l(J,F,q){let{x:Q,y:R}=F.toAffine(),Y=s.toBytes(Q);if(Y0(q,"isCompressed"),q){u();let Z=!s.isOdd(R);return Mn(ZO(Z),Y)}else return Mn(Uint8Array.of(4),Y,s.toBytes(R))}function h(J){ec(J,void 0,"Point");let{publicKey:F,publicKeyUncompressed:q}=d,Q=J.length,R=J[0],Y=J.subarray(1);if(Q===F&&(R===2||R===3)){let Z=s.fromBytes(Y);if(!s.isValid(Z))throw new Error("bad point: is not on curve, wrong x");let I=_(Z),U;try{U=s.sqrt(I)}catch(G){let de=G instanceof Error?": "+G.message:"";throw new Error("bad point: is not on curve, sqrt error"+de)}u();let K=s.isOdd(U);return(R&1)===1!==K&&(U=s.neg(U)),{x:Z,y:U}}else if(Q===q&&R===4){let Z=s.BYTES,I=s.fromBytes(Y.subarray(0,Z)),U=s.fromBytes(Y.subarray(Z,Z*2));if(!f(I,U))throw new Error("bad point: is not on curve");return{x:I,y:U}}else throw new Error(`bad point: got length ${Q}, expected compressed=${F} or uncompressed=${q}`)}let p=e.toBytes||l,m=e.fromBytes||h;function _(J){let F=s.sqr(J),q=s.mul(F,J);return s.add(s.add(q,s.mul(J,i.a)),i.b)}function f(J,F){let q=s.sqr(F),Q=_(J);return s.eql(q,Q)}if(!f(i.Gx,i.Gy))throw new Error("bad curve params: generator point");let b=s.mul(s.pow(i.a,bw),LQ),w=s.mul(s.sqr(i.b),BigInt(27));if(s.is0(s.add(b,w)))throw new Error("bad curve params: a or b");function S(J,F,q=!1){if(!s.isValid(F)||q&&s.is0(F))throw new Error(`bad point coordinate ${J}`);return F}function O(J){if(!(J instanceof D))throw new Error("ProjectivePoint expected")}function j(J){if(!c||!c.basises)throw new Error("no endo");return BQ(J,c.basises,n.ORDER)}let P=qC((J,F)=>{let{X:q,Y:Q,Z:R}=J;if(s.eql(R,s.ONE))return{x:q,y:Q};let Y=J.is0();F==null&&(F=Y?s.ONE:s.inv(R));let Z=s.mul(q,F),I=s.mul(Q,F),U=s.mul(R,F);if(Y)return{x:s.ZERO,y:s.ZERO};if(!s.eql(U,s.ONE))throw new Error("invZ was invalid");return{x:Z,y:I}}),k=qC(J=>{if(J.is0()){if(e.allowInfinityPoint&&!s.is0(J.Y))return;throw new Error("bad point: ZERO")}let{x:F,y:q}=J.toAffine();if(!s.isValid(F)||!s.isValid(q))throw new Error("bad point: x or y not field elements");if(!f(F,q))throw new Error("bad point: equation left != right");if(!J.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function C(J,F,q,Q,R){return q=new D(s.mul(q.X,J),q.Y,q.Z),F=rm(Q,F),q=rm(R,q),F.add(q)}class D{constructor(F,q,Q){this.X=S("x",F),this.Y=S("y",q,!0),this.Z=S("z",Q),Object.freeze(this)}static CURVE(){return i}static fromAffine(F){let{x:q,y:Q}=F||{};if(!F||!s.isValid(q)||!s.isValid(Q))throw new Error("invalid affine point");if(F instanceof D)throw new Error("projective point not allowed");return s.is0(q)&&s.is0(Q)?D.ZERO:new D(q,Q,s.ONE)}static fromBytes(F){let q=D.fromAffine(m(ec(F,void 0,"point")));return q.assertValidity(),q}static fromHex(F){return D.fromBytes(cs("pointHex",F))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(F=8,q=!0){return W.createCache(this,F),q||this.multiply(bw),this}assertValidity(){k(this)}hasEvenY(){let{y:F}=this.toAffine();if(!s.isOdd)throw new Error("Field doesn't support isOdd");return!s.isOdd(F)}equals(F){O(F);let{X:q,Y:Q,Z:R}=this,{X:Y,Y:Z,Z:I}=F,U=s.eql(s.mul(q,I),s.mul(Y,R)),K=s.eql(s.mul(Q,I),s.mul(Z,R));return U&&K}negate(){return new D(this.X,s.neg(this.Y),this.Z)}double(){let{a:F,b:q}=i,Q=s.mul(q,bw),{X:R,Y,Z}=this,I=s.ZERO,U=s.ZERO,K=s.ZERO,z=s.mul(R,R),G=s.mul(Y,Y),de=s.mul(Z,Z),ce=s.mul(R,Y);return ce=s.add(ce,ce),K=s.mul(R,Z),K=s.add(K,K),I=s.mul(F,K),U=s.mul(Q,de),U=s.add(I,U),I=s.sub(G,U),U=s.add(G,U),U=s.mul(I,U),I=s.mul(ce,I),K=s.mul(Q,K),de=s.mul(F,de),ce=s.sub(z,de),ce=s.mul(F,ce),ce=s.add(ce,K),K=s.add(z,z),z=s.add(K,z),z=s.add(z,de),z=s.mul(z,ce),U=s.add(U,z),de=s.mul(Y,Z),de=s.add(de,de),z=s.mul(de,ce),I=s.sub(I,z),K=s.mul(de,G),K=s.add(K,K),K=s.add(K,K),new D(I,U,K)}add(F){O(F);let{X:q,Y:Q,Z:R}=this,{X:Y,Y:Z,Z:I}=F,U=s.ZERO,K=s.ZERO,z=s.ZERO,G=i.a,de=s.mul(i.b,bw),ce=s.mul(q,Y),Je=s.mul(Q,Z),tt=s.mul(R,I),Ot=s.add(q,Q),Et=s.add(Y,Z);Ot=s.mul(Ot,Et),Et=s.add(ce,Je),Ot=s.sub(Ot,Et),Et=s.add(q,R);let Ut=s.add(Y,I);return Et=s.mul(Et,Ut),Ut=s.add(ce,tt),Et=s.sub(Et,Ut),Ut=s.add(Q,R),U=s.add(Z,I),Ut=s.mul(Ut,U),U=s.add(Je,tt),Ut=s.sub(Ut,U),z=s.mul(G,Et),U=s.mul(de,tt),z=s.add(U,z),U=s.sub(Je,z),z=s.add(Je,z),K=s.mul(U,z),Je=s.add(ce,ce),Je=s.add(Je,ce),tt=s.mul(G,tt),Et=s.mul(de,Et),Je=s.add(Je,tt),tt=s.sub(ce,tt),tt=s.mul(G,tt),Et=s.add(Et,tt),ce=s.mul(Je,Et),K=s.add(K,ce),ce=s.mul(Ut,Et),U=s.mul(Ot,U),U=s.sub(U,ce),ce=s.mul(Ot,Je),z=s.mul(Ut,z),z=s.add(z,ce),new D(U,K,z)}subtract(F){return this.add(F.negate())}is0(){return this.equals(D.ZERO)}multiply(F){let{endo:q}=e;if(!n.isValidNot0(F))throw new Error("invalid scalar: out of range");let Q,R,Y=Z=>W.cached(this,Z,I=>yw(D,I));if(q){let{k1neg:Z,k1:I,k2neg:U,k2:K}=j(F),{p:z,f:G}=Y(I),{p:de,f:ce}=Y(K);R=G.add(ce),Q=C(q.beta,z,de,Z,U)}else{let{p:Z,f:I}=Y(F);Q=Z,R=I}return yw(D,[Q,R])[0]}multiplyUnsafe(F){let{endo:q}=e,Q=this;if(!n.isValid(F))throw new Error("invalid scalar: out of range");if(F===Do||Q.is0())return D.ZERO;if(F===ph)return Q;if(W.hasCache(this))return this.multiply(F);if(q){let{k1neg:R,k1:Y,k2neg:Z,k2:I}=j(F),{p1:U,p2:K}=KO(D,Q,Y,I);return C(q.beta,U,K,R,Z)}else return W.unsafe(Q,F)}multiplyAndAddUnsafe(F,q,Q){let R=this.multiplyUnsafe(q).add(F.multiplyUnsafe(Q));return R.is0()?void 0:R}toAffine(F){return P(this,F)}isTorsionFree(){let{isTorsionFree:F}=e;return o===ph?!0:F?F(D,this):W.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:F}=e;return o===ph?this:F?F(D,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(F=!0){return Y0(F,"isCompressed"),this.assertValidity(),p(D,this,F)}toHex(F=!0){return Io(this.toBytes(F))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(F=!0){return this.toBytes(F)}_setWindowSize(F){this.precompute(F)}static normalizeZ(F){return yw(D,F)}static msm(F,q){return GO(D,n,F,q)}static fromPrivateKey(F){return D.BASE.multiply(fh(n,F))}}D.BASE=new D(i.Gx,i.Gy,s.ONE),D.ZERO=new D(s.ZERO,s.ONE,s.ZERO),D.Fp=s,D.Fn=n;let H=n.BITS,W=new gw(D,e.endo?Math.ceil(H/2):H);return D.BASE.precompute(8),D}function ZO(t){return Uint8Array.of(t?2:3)}function eN(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function NQ(t,e={}){let{Fn:r}=t,s=e.randomBytes||ow,n=Object.assign(eN(t.Fp,r),{seed:WC(r.ORDER)});function i(p){try{return!!fh(r,p)}catch{return!1}}function o(p,m){let{publicKey:_,publicKeyUncompressed:f}=n;try{let b=p.length;return m===!0&&b!==_||m===!1&&b!==f?!1:!!t.fromBytes(p)}catch{return!1}}function a(p=s(n.seed)){return SO(ec(p,n.seed,"seed"),r.ORDER)}function c(p,m=!0){return t.BASE.multiply(fh(r,p)).toBytes(m)}function d(p){let m=a(p);return{secretKey:m,publicKey:c(m)}}function u(p){if(typeof p=="bigint")return!1;if(p instanceof t)return!0;let{secretKey:m,publicKey:_,publicKeyUncompressed:f}=n;if(r.allowedLengths||m===_)return;let b=cs("key",p).length;return b===_||b===f}function l(p,m,_=!0){if(u(p)===!0)throw new Error("first arg must be private key");if(u(m)===!1)throw new Error("second arg must be public key");let f=fh(r,p);return t.fromHex(m).multiply(f).toBytes(_)}return Object.freeze({getPublicKey:c,getSharedSecret:l,keygen:d,Point:t,utils:{isValidSecretKey:i,isValidPublicKey:o,randomSecretKey:a,isValidPrivateKey:i,randomPrivateKey:a,normPrivateKeyToScalar:p=>fh(r,p),precompute(p=8,m=t.BASE){return m.precompute(p,!1)}},lengths:n})}function UQ(t,e,r={}){sw(e),Q0(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let s=r.randomBytes||ow,n=r.hmac||((q,...Q)=>JC(e,q,Mn(...Q))),{Fp:i,Fn:o}=t,{ORDER:a,BITS:c}=o,{keygen:d,getPublicKey:u,getSharedSecret:l,utils:h,lengths:p}=NQ(t,r),m={prehash:!1,lowS:typeof r.lowS=="boolean"?r.lowS:!1,format:void 0,extraEntropy:!1},_="compact";function f(q){let Q=a>>ph;return q>Q}function b(q,Q){if(!o.isValidNot0(Q))throw new Error(`invalid signature ${q}: out of range 1..Point.Fn.ORDER`);return Q}function w(q,Q){rT(Q);let R=p.signature,Y=Q==="compact"?R:Q==="recovered"?R+1:void 0;return ec(q,Y,`${Q} signature`)}class S{constructor(Q,R,Y){this.r=b("r",Q),this.s=b("s",R),Y!=null&&(this.recovery=Y),Object.freeze(this)}static fromBytes(Q,R=_){w(Q,R);let Y;if(R==="der"){let{r:K,s:z}=Po.toSig(ec(Q));return new S(K,z)}R==="recovered"&&(Y=Q[0],R="compact",Q=Q.subarray(1));let Z=o.BYTES,I=Q.subarray(0,Z),U=Q.subarray(Z,Z*2);return new S(o.fromBytes(I),o.fromBytes(U),Y)}static fromHex(Q,R){return this.fromBytes(tl(Q),R)}addRecoveryBit(Q){return new S(this.r,this.s,Q)}recoverPublicKey(Q){let R=i.ORDER,{r:Y,s:Z,recovery:I}=this;if(I==null||![0,1,2,3].includes(I))throw new Error("recovery id invalid");if(a*QO<R&&I>1)throw new Error("recovery id is ambiguous for h>1 curve");let K=I===2||I===3?Y+a:Y;if(!i.isValid(K))throw new Error("recovery id 2 or 3 invalid");let z=i.toBytes(K),G=t.fromBytes(Mn(ZO((I&1)===0),z)),de=o.inv(K),ce=j(cs("msgHash",Q)),Je=o.create(-ce*de),tt=o.create(Z*de),Ot=t.BASE.multiplyUnsafe(Je).add(G.multiplyUnsafe(tt));if(Ot.is0())throw new Error("point at infinify");return Ot.assertValidity(),Ot}hasHighS(){return f(this.s)}toBytes(Q=_){if(rT(Q),Q==="der")return tl(Po.hexFromSig(this));let R=o.toBytes(this.r),Y=o.toBytes(this.s);if(Q==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return Mn(Uint8Array.of(this.recovery),R,Y)}return Mn(R,Y)}toHex(Q){return Io(this.toBytes(Q))}assertValidity(){}static fromCompact(Q){return S.fromBytes(cs("sig",Q),"compact")}static fromDER(Q){return S.fromBytes(cs("sig",Q),"der")}normalizeS(){return this.hasHighS()?new S(this.r,o.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return Io(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return Io(this.toBytes("compact"))}}let O=r.bits2int||function(Q){if(Q.length>8192)throw new Error("input is too large");let R=uh(Q),Y=Q.length*8-c;return Y>0?R>>BigInt(Y):R},j=r.bits2int_modN||function(Q){return o.create(O(Q))},P=tc(c);function k(q){return uO("num < 2^"+c,q,Do,P),o.toBytes(q)}function C(q,Q){return ec(q,void 0,"message"),Q?ec(e(q),void 0,"prehashed message"):q}function D(q,Q,R){if(["recovered","canonical"].some(Je=>Je in R))throw new Error("sign() legacy options not supported");let{lowS:Y,prehash:Z,extraEntropy:I}=tT(R,m);q=C(q,Z);let U=j(q),K=fh(o,Q),z=[k(K),k(U)];if(I!=null&&I!==!1){let Je=I===!0?s(p.secretKey):I;z.push(cs("extraEntropy",Je))}let G=Mn(...z),de=U;function ce(Je){let tt=O(Je);if(!o.isValidNot0(tt))return;let Ot=o.inv(tt),Et=t.BASE.multiply(tt).toAffine(),Ut=o.create(Et.x);if(Ut===Do)return;let Js=o.create(Ot*o.create(de+Ut*K));if(Js===Do)return;let Qs=(Et.x===Ut?0:2)|Number(Et.y&ph),_c=Js;return Y&&f(Js)&&(_c=o.neg(Js),Qs^=1),new S(Ut,_c,Qs)}return{seed:G,k2sig:ce}}function H(q,Q,R={}){q=cs("message",q);let{seed:Y,k2sig:Z}=D(q,Q,R);return hO(e.outputLen,o.BYTES,n)(Y,Z)}function W(q){let Q,R=typeof q=="string"||el(q),Y=!R&&q!==null&&typeof q=="object"&&typeof q.r=="bigint"&&typeof q.s=="bigint";if(!R&&!Y)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(Y)Q=new S(q.r,q.s);else if(R){try{Q=S.fromBytes(cs("sig",q),"der")}catch(Z){if(!(Z instanceof Po.Err))throw Z}if(!Q)try{Q=S.fromBytes(cs("sig",q),"compact")}catch{return!1}}return Q||!1}function J(q,Q,R,Y={}){let{lowS:Z,prehash:I,format:U}=tT(Y,m);if(R=cs("publicKey",R),Q=C(cs("message",Q),I),"strict"in Y)throw new Error("options.strict was renamed to lowS");let K=U===void 0?W(q):S.fromBytes(cs("sig",q),U);if(K===!1)return!1;try{let z=t.fromBytes(R);if(Z&&K.hasHighS())return!1;let{r:G,s:de}=K,ce=j(Q),Je=o.inv(de),tt=o.create(ce*Je),Ot=o.create(G*Je),Et=t.BASE.multiplyUnsafe(tt).add(z.multiplyUnsafe(Ot));return Et.is0()?!1:o.create(Et.x)===G}catch{return!1}}function F(q,Q,R={}){let{prehash:Y}=tT(R,m);return Q=C(Q,Y),S.fromBytes(q,"recovered").recoverPublicKey(Q).toBytes()}return Object.freeze({keygen:d,getPublicKey:u,getSharedSecret:l,utils:h,lengths:p,Point:t,sign:H,verify:J,recoverPublicKey:F,Signature:S,hash:e})}function MQ(t){let e={a:t.a,b:t.b,p:t.Fp.ORDER,n:t.n,h:t.h,Gx:t.Gx,Gy:t.Gy},r=t.Fp,s=t.allowedPrivateKeyLengths?Array.from(new Set(t.allowedPrivateKeyLengths.map(o=>Math.ceil(o/2)))):void 0,n=Pi(e.n,{BITS:t.nBitLength,allowedLengths:s,modFromBytes:t.wrapPrivateKey}),i={Fp:r,Fn:n,allowInfinityPoint:t.allowInfinityPoint,endo:t.endo,isTorsionFree:t.isTorsionFree,clearCofactor:t.clearCofactor,fromBytes:t.fromBytes,toBytes:t.toBytes};return{CURVE:e,curveOpts:i}}function jQ(t){let{CURVE:e,curveOpts:r}=MQ(t),s={hmac:t.hmac,randomBytes:t.randomBytes,lowS:t.lowS,bits2int:t.bits2int,bits2int_modN:t.bits2int_modN};return{CURVE:e,curveOpts:r,hash:t.hash,ecdsaOpts:s}}function $Q(t,e){let r=e.Point;return Object.assign({},e,{ProjectivePoint:r,CURVE:Object.assign({},t,uw(r.Fn.ORDER,r.Fn.BITS))})}function tN(t){let{CURVE:e,curveOpts:r,hash:s,ecdsaOpts:n}=jQ(t),i=OQ(e,r),o=UQ(i,s,n);return $Q(t,o)}var JO,sT,Po,Do,ph,QO,bw,LQ,rN=V(()=>{"use strict";g();y();FO();rl();dw();YO();hw();JO=(t,e)=>(t+(t>=0?e:-e)/QO)/e;sT=class extends Error{constructor(e=""){super(e)}},Po={Err:sT,_tlv:{encode:(t,e)=>{let{Err:r}=Po;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length&1)throw new r("tlv.encode: unpadded data");let s=e.length/2,n=J0(s);if(n.length/2&128)throw new r("tlv.encode: long form length too big");let i=s>127?J0(n.length/2|128):"";return J0(t)+i+n+e},decode(t,e){let{Err:r}=Po,s=0;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length<2||e[s++]!==t)throw new r("tlv.decode: wrong tlv");let n=e[s++],i=!!(n&128),o=0;if(!i)o=n;else{let c=n&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");let d=e.subarray(s,s+c);if(d.length!==c)throw new r("tlv.decode: length bytes not complete");if(d[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(let u of d)o=o<<8|u;if(s+=c,o<128)throw new r("tlv.decode(long): not minimal encoding")}let a=e.subarray(s,s+o);if(a.length!==o)throw new r("tlv.decode: wrong value length");return{v:a,l:e.subarray(s+o)}}},_int:{encode(t){let{Err:e}=Po;if(t<Do)throw new e("integer: negative integers are not allowed");let r=J0(t);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return r},decode(t){let{Err:e}=Po;if(t[0]&128)throw new e("invalid signature integer: negative");if(t[0]===0&&!(t[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return uh(t)}},toSig(t){let{Err:e,_int:r,_tlv:s}=Po,n=cs("signature",t),{v:i,l:o}=s.decode(48,n);if(o.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=s.decode(2,i),{v:d,l:u}=s.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(d)}},hexFromSig(t){let{_tlv:e,_int:r}=Po,s=e.encode(2,r.encode(t.r)),n=e.encode(2,r.encode(t.s)),i=s+n;return e.encode(48,i)}},Do=BigInt(0),ph=BigInt(1),QO=BigInt(2),bw=BigInt(3),LQ=BigInt(4)});function xw(t,e){let r=s=>tN({...t,hash:s});return{...r(e),create:r}}var sN=V(()=>{"use strict";g();y();rN();});var nN,iN,oN,FQ,HQ,qQ,aN,mPe,gPe,cN=V(()=>{"use strict";g();y();$O();sN();hw();nN={p:BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),h:BigInt(1),a:BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")},iN={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff"),n:BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),h:BigInt(1),a:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc"),b:BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"),Gx:BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"),Gy:BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f")},oN={p:BigInt("0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),n:BigInt("0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409"),h:BigInt(1),a:BigInt("0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc"),b:BigInt("0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00"),Gx:BigInt("0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66"),Gy:BigInt("0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650")},FQ=Pi(nN.p),HQ=Pi(iN.p),qQ=Pi(oN.p),aN=xw({...nN,Fp:FQ,lowS:!1},UO),mPe=xw({...iN,Fp:HQ,lowS:!1},jO),gPe=xw({...oN,Fp:qQ,lowS:!1,allowedPrivateKeyLengths:[130,131,132]},MO)});var ww,dN=V(()=>{"use strict";g();y();cN();ww=aN});var uN=Me(ic=>{"use strict";g();y();Object.defineProperty(ic,"__esModule",{value:!0});ic.LEB128=ic.SignedLEB128=ic.UnsignedLEB128=void 0;var mh;(function(t){t[t.LOWER_7=127]="LOWER_7",t[t.UPPER_1=128]="UPPER_1"})(mh||(mh={}));var lN=t=>Number.isSafeInteger(t),al=class{static decode(e,r=0){let s=this.$scanForNullBytes(e,r),n=0,i=0;for(let o=0;o<=s-r;o++){let a=e[r+o]&mh.LOWER_7;n|=a<<i,i+=7}return n}static encode(e){if(this.check(e),e<0)throw new Error(`An unsigned number must NOT be negative, ${e} is!`);let r=[],s=e;do{let n=s&mh.LOWER_7;s>>=7,s&&(n=n|mh.UPPER_1),r.push(n)}while(s);return Uint8Array.from(r)}static check(e){if(!lN(e))throw new Error(`${e} is not a safe integer!`)}static $scanForNullBytes(e,r=0){let s=r,n=0;do{if(s>=e.byteLength)throw new Error("This is not a LEB128-encoded Uint8Array, no ending found!");n=e.slice(s,s+1)[0],s++}while(n&mh.UPPER_1);return s-1}static getLength(e,r=0){return this.$scanForNullBytes(e,r)-r}};ic.UnsignedLEB128=al;var sm=class{static $ceil7mul(e){let r=e;for(;r%7;)r++;return r}static check(e){if(!lN(e))throw new Error(`${e} is not a safe integer!`)}static encode(e){if(this.check(e),e>=0)throw new Error(`A signed number must be negative, ${e} isn't!`);let r=Math.ceil(Math.log2(-e));return al.encode((1<<this.$ceil7mul(r))+e)}static decode(e,r=0){let s=al.decode(e,r);return-((1<<Math.ceil(Math.log2(s)))-s)}};ic.SignedLEB128=sm;var nm=class{};ic.LEB128=nm;nm.encode=t=>(t>=0?al:sm).encode(t);nm.decode=(t,e=0,r=!1)=>(r?sm:al).decode(t,e)});var fN=Me((nT,hN)=>{"use strict";g();y();(function(t){"use strict";function e(I){return parseInt(I)===I}function r(I){if(!e(I.length))return!1;for(var U=0;U<I.length;U++)if(!e(I[U])||I[U]<0||I[U]>255)return!1;return!0}function s(I,U){if(I.buffer&&I.name==="Uint8Array")return U&&(I.slice?I=I.slice():I=Array.prototype.slice.call(I)),I;if(Array.isArray(I)){if(!r(I))throw new Error("Array contains invalid value: "+I);return new Uint8Array(I)}if(e(I.length)&&r(I))return new Uint8Array(I);throw new Error("unsupported array-like object")}function n(I){return new Uint8Array(I)}function i(I,U,K,z,G){(z!=null||G!=null)&&(I.slice?I=I.slice(z,G):I=Array.prototype.slice.call(I,z,G)),U.set(I,K)}var o=(function(){function I(K){var z=[],G=0;for(K=encodeURI(K);G<K.length;){var de=K.charCodeAt(G++);de===37?(z.push(parseInt(K.substr(G,2),16)),G+=2):z.push(de)}return s(z)}function U(K){for(var z=[],G=0;G<K.length;){var de=K[G];de<128?(z.push(String.fromCharCode(de)),G++):de>191&&de<224?(z.push(String.fromCharCode((de&31)<<6|K[G+1]&63)),G+=2):(z.push(String.fromCharCode((de&15)<<12|(K[G+1]&63)<<6|K[G+2]&63)),G+=3)}return z.join("")}return{toBytes:I,fromBytes:U}})(),a=(function(){function I(z){for(var G=[],de=0;de<z.length;de+=2)G.push(parseInt(z.substr(de,2),16));return G}var U="0123456789abcdef";function K(z){for(var G=[],de=0;de<z.length;de++){var ce=z[de];G.push(U[(ce&240)>>4]+U[ce&15])}return G.join("")}return{toBytes:I,fromBytes:K}})(),c={16:10,24:12,32:14},d=[1,2,4,8,16,32,64,128,27,54,108,216,171,77,154,47,94,188,99,198,151,53,106,212,179,125,250,239,197,145],u=[99,124,119,123,242,107,111,197,48,1,103,43,254,215,171,118,202,130,201,125,250,89,71,240,173,212,162,175,156,164,114,192,183,253,147,38,54,63,247,204,52,165,229,241,113,216,49,21,4,199,35,195,24,150,5,154,7,18,128,226,235,39,178,117,9,131,44,26,27,110,90,160,82,59,214,179,41,227,47,132,83,209,0,237,32,252,177,91,106,203,190,57,74,76,88,207,208,239,170,251,67,77,51,133,69,249,2,127,80,60,159,168,81,163,64,143,146,157,56,245,188,182,218,33,16,255,243,210,205,12,19,236,95,151,68,23,196,167,126,61,100,93,25,115,96,129,79,220,34,42,144,136,70,238,184,20,222,94,11,219,224,50,58,10,73,6,36,92,194,211,172,98,145,149,228,121,231,200,55,109,141,213,78,169,108,86,244,234,101,122,174,8,186,120,37,46,28,166,180,198,232,221,116,31,75,189,139,138,112,62,181,102,72,3,246,14,97,53,87,185,134,193,29,158,225,248,152,17,105,217,142,148,155,30,135,233,206,85,40,223,140,161,137,13,191,230,66,104,65,153,45,15,176,84,187,22],l=[82,9,106,213,48,54,165,56,191,64,163,158,129,243,215,251,124,227,57,130,155,47,255,135,52,142,67,68,196,222,233,203,84,123,148,50,166,194,35,61,238,76,149,11,66,250,195,78,8,46,161,102,40,217,36,178,118,91,162,73,109,139,209,37,114,248,246,100,134,104,152,22,212,164,92,204,93,101,182,146,108,112,72,80,253,237,185,218,94,21,70,87,167,141,157,132,144,216,171,0,140,188,211,10,247,228,88,5,184,179,69,6,208,44,30,143,202,63,15,2,193,175,189,3,1,19,138,107,58,145,17,65,79,103,220,234,151,242,207,206,240,180,230,115,150,172,116,34,231,173,53,133,226,249,55,232,28,117,223,110,71,241,26,113,29,41,197,137,111,183,98,14,170,24,190,27,252,86,62,75,198,210,121,32,154,219,192,254,120,205,90,244,31,221,168,51,136,7,199,49,177,18,16,89,39,128,236,95,96,81,127,169,25,181,74,13,45,229,122,159,147,201,156,239,160,224,59,77,174,42,245,176,200,235,187,60,131,83,153,97,23,43,4,126,186,119,214,38,225,105,20,99,85,33,12,125],h=[3328402341,4168907908,4000806809,4135287693,4294111757,3597364157,3731845041,2445657428,1613770832,33620227,3462883241,1445669757,3892248089,3050821474,1303096294,3967186586,2412431941,528646813,2311702848,4202528135,4026202645,2992200171,2387036105,4226871307,1101901292,3017069671,1604494077,1169141738,597466303,1403299063,3832705686,2613100635,1974974402,3791519004,1033081774,1277568618,1815492186,2118074177,4126668546,2211236943,1748251740,1369810420,3521504564,4193382664,3799085459,2883115123,1647391059,706024767,134480908,2512897874,1176707941,2646852446,806885416,932615841,168101135,798661301,235341577,605164086,461406363,3756188221,3454790438,1311188841,2142417613,3933566367,302582043,495158174,1479289972,874125870,907746093,3698224818,3025820398,1537253627,2756858614,1983593293,3084310113,2108928974,1378429307,3722699582,1580150641,327451799,2790478837,3117535592,0,3253595436,1075847264,3825007647,2041688520,3059440621,3563743934,2378943302,1740553945,1916352843,2487896798,2555137236,2958579944,2244988746,3151024235,3320835882,1336584933,3992714006,2252555205,2588757463,1714631509,293963156,2319795663,3925473552,67240454,4269768577,2689618160,2017213508,631218106,1269344483,2723238387,1571005438,2151694528,93294474,1066570413,563977660,1882732616,4059428100,1673313503,2008463041,2950355573,1109467491,537923632,3858759450,4260623118,3218264685,2177748300,403442708,638784309,3287084079,3193921505,899127202,2286175436,773265209,2479146071,1437050866,4236148354,2050833735,3362022572,3126681063,840505643,3866325909,3227541664,427917720,2655997905,2749160575,1143087718,1412049534,999329963,193497219,2353415882,3354324521,1807268051,672404540,2816401017,3160301282,369822493,2916866934,3688947771,1681011286,1949973070,336202270,2454276571,201721354,1210328172,3093060836,2680341085,3184776046,1135389935,3294782118,965841320,831886756,3554993207,4068047243,3588745010,2345191491,1849112409,3664604599,26054028,2983581028,2622377682,1235855840,3630984372,2891339514,4092916743,3488279077,3395642799,4101667470,1202630377,268961816,1874508501,4034427016,1243948399,1546530418,941366308,1470539505,1941222599,2546386513,3421038627,2715671932,3899946140,1042226977,2521517021,1639824860,227249030,260737669,3765465232,2084453954,1907733956,3429263018,2420656344,100860677,4160157185,470683154,3261161891,1781871967,2924959737,1773779408,394692241,2579611992,974986535,664706745,3655459128,3958962195,731420851,571543859,3530123707,2849626480,126783113,865375399,765172662,1008606754,361203602,3387549984,2278477385,2857719295,1344809080,2782912378,59542671,1503764984,160008576,437062935,1707065306,3622233649,2218934982,3496503480,2185314755,697932208,1512910199,504303377,2075177163,2824099068,1841019862,739644986],p=[2781242211,2230877308,2582542199,2381740923,234877682,3184946027,2984144751,1418839493,1348481072,50462977,2848876391,2102799147,434634494,1656084439,3863849899,2599188086,1167051466,2636087938,1082771913,2281340285,368048890,3954334041,3381544775,201060592,3963727277,1739838676,4250903202,3930435503,3206782108,4149453988,2531553906,1536934080,3262494647,484572669,2923271059,1783375398,1517041206,1098792767,49674231,1334037708,1550332980,4098991525,886171109,150598129,2481090929,1940642008,1398944049,1059722517,201851908,1385547719,1699095331,1587397571,674240536,2704774806,252314885,3039795866,151914247,908333586,2602270848,1038082786,651029483,1766729511,3447698098,2682942837,454166793,2652734339,1951935532,775166490,758520603,3000790638,4004797018,4217086112,4137964114,1299594043,1639438038,3464344499,2068982057,1054729187,1901997871,2534638724,4121318227,1757008337,0,750906861,1614815264,535035132,3363418545,3988151131,3201591914,1183697867,3647454910,1265776953,3734260298,3566750796,3903871064,1250283471,1807470800,717615087,3847203498,384695291,3313910595,3617213773,1432761139,2484176261,3481945413,283769337,100925954,2180939647,4037038160,1148730428,3123027871,3813386408,4087501137,4267549603,3229630528,2315620239,2906624658,3156319645,1215313976,82966005,3747855548,3245848246,1974459098,1665278241,807407632,451280895,251524083,1841287890,1283575245,337120268,891687699,801369324,3787349855,2721421207,3431482436,959321879,1469301956,4065699751,2197585534,1199193405,2898814052,3887750493,724703513,2514908019,2696962144,2551808385,3516813135,2141445340,1715741218,2119445034,2872807568,2198571144,3398190662,700968686,3547052216,1009259540,2041044702,3803995742,487983883,1991105499,1004265696,1449407026,1316239930,504629770,3683797321,168560134,1816667172,3837287516,1570751170,1857934291,4014189740,2797888098,2822345105,2754712981,936633572,2347923833,852879335,1133234376,1500395319,3084545389,2348912013,1689376213,3533459022,3762923945,3034082412,4205598294,133428468,634383082,2949277029,2398386810,3913789102,403703816,3580869306,2297460856,1867130149,1918643758,607656988,4049053350,3346248884,1368901318,600565992,2090982877,2632479860,557719327,3717614411,3697393085,2249034635,2232388234,2430627952,1115438654,3295786421,2865522278,3633334344,84280067,33027830,303828494,2747425121,1600795957,4188952407,3496589753,2434238086,1486471617,658119965,3106381470,953803233,334231800,3005978776,857870609,3151128937,1890179545,2298973838,2805175444,3056442267,574365214,2450884487,550103529,1233637070,4289353045,2018519080,2057691103,2399374476,4166623649,2148108681,387583245,3664101311,836232934,3330556482,3100665960,3280093505,2955516313,2002398509,287182607,3413881008,4238890068,3597515707,975967766],m=[1671808611,2089089148,2006576759,2072901243,4061003762,1807603307,1873927791,3310653893,810573872,16974337,1739181671,729634347,4263110654,3613570519,2883997099,1989864566,3393556426,2191335298,3376449993,2106063485,4195741690,1508618841,1204391495,4027317232,2917941677,3563566036,2734514082,2951366063,2629772188,2767672228,1922491506,3227229120,3082974647,4246528509,2477669779,644500518,911895606,1061256767,4144166391,3427763148,878471220,2784252325,3845444069,4043897329,1905517169,3631459288,827548209,356461077,67897348,3344078279,593839651,3277757891,405286936,2527147926,84871685,2595565466,118033927,305538066,2157648768,3795705826,3945188843,661212711,2999812018,1973414517,152769033,2208177539,745822252,439235610,455947803,1857215598,1525593178,2700827552,1391895634,994932283,3596728278,3016654259,695947817,3812548067,795958831,2224493444,1408607827,3513301457,0,3979133421,543178784,4229948412,2982705585,1542305371,1790891114,3410398667,3201918910,961245753,1256100938,1289001036,1491644504,3477767631,3496721360,4012557807,2867154858,4212583931,1137018435,1305975373,861234739,2241073541,1171229253,4178635257,33948674,2139225727,1357946960,1011120188,2679776671,2833468328,1374921297,2751356323,1086357568,2408187279,2460827538,2646352285,944271416,4110742005,3168756668,3066132406,3665145818,560153121,271589392,4279952895,4077846003,3530407890,3444343245,202643468,322250259,3962553324,1608629855,2543990167,1154254916,389623319,3294073796,2817676711,2122513534,1028094525,1689045092,1575467613,422261273,1939203699,1621147744,2174228865,1339137615,3699352540,577127458,712922154,2427141008,2290289544,1187679302,3995715566,3100863416,339486740,3732514782,1591917662,186455563,3681988059,3762019296,844522546,978220090,169743370,1239126601,101321734,611076132,1558493276,3260915650,3547250131,2901361580,1655096418,2443721105,2510565781,3828863972,2039214713,3878868455,3359869896,928607799,1840765549,2374762893,3580146133,1322425422,2850048425,1823791212,1459268694,4094161908,3928346602,1706019429,2056189050,2934523822,135794696,3134549946,2022240376,628050469,779246638,472135708,2800834470,3032970164,3327236038,3894660072,3715932637,1956440180,522272287,1272813131,3185336765,2340818315,2323976074,1888542832,1044544574,3049550261,1722469478,1222152264,50660867,4127324150,236067854,1638122081,895445557,1475980887,3117443513,2257655686,3243809217,489110045,2662934430,3778599393,4162055160,2561878936,288563729,1773916777,3648039385,2391345038,2493985684,2612407707,505560094,2274497927,3911240169,3460925390,1442818645,678973480,3749357023,2358182796,2717407649,2306869641,219617805,3218761151,3862026214,1120306242,1756942440,1103331905,2578459033,762796589,252780047,2966125488,1425844308,3151392187,372911126],_=[1667474886,2088535288,2004326894,2071694838,4075949567,1802223062,1869591006,3318043793,808472672,16843522,1734846926,724270422,4278065639,3621216949,2880169549,1987484396,3402253711,2189597983,3385409673,2105378810,4210693615,1499065266,1195886990,4042263547,2913856577,3570689971,2728590687,2947541573,2627518243,2762274643,1920112356,3233831835,3082273397,4261223649,2475929149,640051788,909531756,1061110142,4160160501,3435941763,875846760,2779116625,3857003729,4059105529,1903268834,3638064043,825316194,353713962,67374088,3351728789,589522246,3284360861,404236336,2526454071,84217610,2593830191,117901582,303183396,2155911963,3806477791,3958056653,656894286,2998062463,1970642922,151591698,2206440989,741110872,437923380,454765878,1852748508,1515908788,2694904667,1381168804,993742198,3604373943,3014905469,690584402,3823320797,791638366,2223281939,1398011302,3520161977,0,3991743681,538992704,4244381667,2981218425,1532751286,1785380564,3419096717,3200178535,960056178,1246420628,1280103576,1482221744,3486468741,3503319995,4025428677,2863326543,4227536621,1128514950,1296947098,859002214,2240123921,1162203018,4193849577,33687044,2139062782,1347481760,1010582648,2678045221,2829640523,1364325282,2745433693,1077985408,2408548869,2459086143,2644360225,943212656,4126475505,3166494563,3065430391,3671750063,555836226,269496352,4294908645,4092792573,3537006015,3452783745,202118168,320025894,3974901699,1600119230,2543297077,1145359496,387397934,3301201811,2812801621,2122220284,1027426170,1684319432,1566435258,421079858,1936954854,1616945344,2172753945,1330631070,3705438115,572679748,707427924,2425400123,2290647819,1179044492,4008585671,3099120491,336870440,3739122087,1583276732,185277718,3688593069,3772791771,842159716,976899700,168435220,1229577106,101059084,606366792,1549591736,3267517855,3553849021,2897014595,1650632388,2442242105,2509612081,3840161747,2038008818,3890688725,3368567691,926374254,1835907034,2374863873,3587531953,1313788572,2846482505,1819063512,1448540844,4109633523,3941213647,1701162954,2054852340,2930698567,134748176,3132806511,2021165296,623210314,774795868,471606328,2795958615,3031746419,3334885783,3907527627,3722280097,1953799400,522133822,1263263126,3183336545,2341176845,2324333839,1886425312,1044267644,3048588401,1718004428,1212733584,50529542,4143317495,235803164,1633788866,892690282,1465383342,3115962473,2256965911,3250673817,488449850,2661202215,3789633753,4177007595,2560144171,286339874,1768537042,3654906025,2391705863,2492770099,2610673197,505291324,2273808917,3924369609,3469625735,1431699370,673740880,3755965093,2358021891,2711746649,2307489801,218961690,3217021541,3873845719,1111672452,1751693520,1094828930,2576986153,757954394,252645662,2964376443,1414855848,3149649517,370555436],f=[1374988112,2118214995,437757123,975658646,1001089995,530400753,2902087851,1273168787,540080725,2910219766,2295101073,4110568485,1340463100,3307916247,641025152,3043140495,3736164937,632953703,1172967064,1576976609,3274667266,2169303058,2370213795,1809054150,59727847,361929877,3211623147,2505202138,3569255213,1484005843,1239443753,2395588676,1975683434,4102977912,2572697195,666464733,3202437046,4035489047,3374361702,2110667444,1675577880,3843699074,2538681184,1649639237,2976151520,3144396420,4269907996,4178062228,1883793496,2403728665,2497604743,1383856311,2876494627,1917518562,3810496343,1716890410,3001755655,800440835,2261089178,3543599269,807962610,599762354,33778362,3977675356,2328828971,2809771154,4077384432,1315562145,1708848333,101039829,3509871135,3299278474,875451293,2733856160,92987698,2767645557,193195065,1080094634,1584504582,3178106961,1042385657,2531067453,3711829422,1306967366,2438237621,1908694277,67556463,1615861247,429456164,3602770327,2302690252,1742315127,2968011453,126454664,3877198648,2043211483,2709260871,2084704233,4169408201,0,159417987,841739592,504459436,1817866830,4245618683,260388950,1034867998,908933415,168810852,1750902305,2606453969,607530554,202008497,2472011535,3035535058,463180190,2160117071,1641816226,1517767529,470948374,3801332234,3231722213,1008918595,303765277,235474187,4069246893,766945465,337553864,1475418501,2943682380,4003061179,2743034109,4144047775,1551037884,1147550661,1543208500,2336434550,3408119516,3069049960,3102011747,3610369226,1113818384,328671808,2227573024,2236228733,3535486456,2935566865,3341394285,496906059,3702665459,226906860,2009195472,733156972,2842737049,294930682,1206477858,2835123396,2700099354,1451044056,573804783,2269728455,3644379585,2362090238,2564033334,2801107407,2776292904,3669462566,1068351396,742039012,1350078989,1784663195,1417561698,4136440770,2430122216,775550814,2193862645,2673705150,1775276924,1876241833,3475313331,3366754619,270040487,3902563182,3678124923,3441850377,1851332852,3969562369,2203032232,3868552805,2868897406,566021896,4011190502,3135740889,1248802510,3936291284,699432150,832877231,708780849,3332740144,899835584,1951317047,4236429990,3767586992,866637845,4043610186,1106041591,2144161806,395441711,1984812685,1139781709,3433712980,3835036895,2664543715,1282050075,3240894392,1181045119,2640243204,25965917,4203181171,4211818798,3009879386,2463879762,3910161971,1842759443,2597806476,933301370,1509430414,3943906441,3467192302,3076639029,3776767469,2051518780,2631065433,1441952575,404016761,1942435775,1408749034,1610459739,3745345300,2017778566,3400528769,3110650942,941896748,3265478751,371049330,3168937228,675039627,4279080257,967311729,135050206,3635733660,1683407248,2076935265,3576870512,1215061108,3501741890],b=[1347548327,1400783205,3273267108,2520393566,3409685355,4045380933,2880240216,2471224067,1428173050,4138563181,2441661558,636813900,4233094615,3620022987,2149987652,2411029155,1239331162,1730525723,2554718734,3781033664,46346101,310463728,2743944855,3328955385,3875770207,2501218972,3955191162,3667219033,768917123,3545789473,692707433,1150208456,1786102409,2029293177,1805211710,3710368113,3065962831,401639597,1724457132,3028143674,409198410,2196052529,1620529459,1164071807,3769721975,2226875310,486441376,2499348523,1483753576,428819965,2274680428,3075636216,598438867,3799141122,1474502543,711349675,129166120,53458370,2592523643,2782082824,4063242375,2988687269,3120694122,1559041666,730517276,2460449204,4042459122,2706270690,3446004468,3573941694,533804130,2328143614,2637442643,2695033685,839224033,1973745387,957055980,2856345839,106852767,1371368976,4181598602,1033297158,2933734917,1179510461,3046200461,91341917,1862534868,4284502037,605657339,2547432937,3431546947,2003294622,3182487618,2282195339,954669403,3682191598,1201765386,3917234703,3388507166,0,2198438022,1211247597,2887651696,1315723890,4227665663,1443857720,507358933,657861945,1678381017,560487590,3516619604,975451694,2970356327,261314535,3535072918,2652609425,1333838021,2724322336,1767536459,370938394,182621114,3854606378,1128014560,487725847,185469197,2918353863,3106780840,3356761769,2237133081,1286567175,3152976349,4255350624,2683765030,3160175349,3309594171,878443390,1988838185,3704300486,1756818940,1673061617,3403100636,272786309,1075025698,545572369,2105887268,4174560061,296679730,1841768865,1260232239,4091327024,3960309330,3497509347,1814803222,2578018489,4195456072,575138148,3299409036,446754879,3629546796,4011996048,3347532110,3252238545,4270639778,915985419,3483825537,681933534,651868046,2755636671,3828103837,223377554,2607439820,1649704518,3270937875,3901806776,1580087799,4118987695,3198115200,2087309459,2842678573,3016697106,1003007129,2802849917,1860738147,2077965243,164439672,4100872472,32283319,2827177882,1709610350,2125135846,136428751,3874428392,3652904859,3460984630,3572145929,3593056380,2939266226,824852259,818324884,3224740454,930369212,2801566410,2967507152,355706840,1257309336,4148292826,243256656,790073846,2373340630,1296297904,1422699085,3756299780,3818836405,457992840,3099667487,2135319889,77422314,1560382517,1945798516,788204353,1521706781,1385356242,870912086,325965383,2358957921,2050466060,2388260884,2313884476,4006521127,901210569,3990953189,1014646705,1503449823,1062597235,2031621326,3212035895,3931371469,1533017514,350174575,2256028891,2177544179,1052338372,741876788,1606591296,1914052035,213705253,2334669897,1107234197,1899603969,3725069491,2631447780,2422494913,1635502980,1893020342,1950903388,1120974935],w=[2807058932,1699970625,2764249623,1586903591,1808481195,1173430173,1487645946,59984867,4199882800,1844882806,1989249228,1277555970,3623636965,3419915562,1149249077,2744104290,1514790577,459744698,244860394,3235995134,1963115311,4027744588,2544078150,4190530515,1608975247,2627016082,2062270317,1507497298,2200818878,567498868,1764313568,3359936201,2305455554,2037970062,1047239e3,1910319033,1337376481,2904027272,2892417312,984907214,1243112415,830661914,861968209,2135253587,2011214180,2927934315,2686254721,731183368,1750626376,4246310725,1820824798,4172763771,3542330227,48394827,2404901663,2871682645,671593195,3254988725,2073724613,145085239,2280796200,2779915199,1790575107,2187128086,472615631,3029510009,4075877127,3802222185,4107101658,3201631749,1646252340,4270507174,1402811438,1436590835,3778151818,3950355702,3963161475,4020912224,2667994737,273792366,2331590177,104699613,95345982,3175501286,2377486676,1560637892,3564045318,369057872,4213447064,3919042237,1137477952,2658625497,1119727848,2340947849,1530455833,4007360968,172466556,266959938,516552836,0,2256734592,3980931627,1890328081,1917742170,4294704398,945164165,3575528878,958871085,3647212047,2787207260,1423022939,775562294,1739656202,3876557655,2530391278,2443058075,3310321856,547512796,1265195639,437656594,3121275539,719700128,3762502690,387781147,218828297,3350065803,2830708150,2848461854,428169201,122466165,3720081049,1627235199,648017665,4122762354,1002783846,2117360635,695634755,3336358691,4234721005,4049844452,3704280881,2232435299,574624663,287343814,612205898,1039717051,840019705,2708326185,793451934,821288114,1391201670,3822090177,376187827,3113855344,1224348052,1679968233,2361698556,1058709744,752375421,2431590963,1321699145,3519142200,2734591178,188127444,2177869557,3727205754,2384911031,3215212461,2648976442,2450346104,3432737375,1180849278,331544205,3102249176,4150144569,2952102595,2159976285,2474404304,766078933,313773861,2570832044,2108100632,1668212892,3145456443,2013908262,418672217,3070356634,2594734927,1852171925,3867060991,3473416636,3907448597,2614737639,919489135,164948639,2094410160,2997825956,590424639,2486224549,1723872674,3157750862,3399941250,3501252752,3625268135,2555048196,3673637356,1343127501,4130281361,3599595085,2957853679,1297403050,81781910,3051593425,2283490410,532201772,1367295589,3926170974,895287692,1953757831,1093597963,492483431,3528626907,1446242576,1192455638,1636604631,209336225,344873464,1015671571,669961897,3375740769,3857572124,2973530695,3747192018,1933530610,3464042516,935293895,3454686199,2858115069,1863638845,3683022916,4085369519,3292445032,875313188,1080017571,3279033885,621591778,1233856572,2504130317,24197544,3017672716,3835484340,3247465558,2220981195,3060847922,1551124588,1463996600],S=[4104605777,1097159550,396673818,660510266,2875968315,2638606623,4200115116,3808662347,821712160,1986918061,3430322568,38544885,3856137295,718002117,893681702,1654886325,2975484382,3122358053,3926825029,4274053469,796197571,1290801793,1184342925,3556361835,2405426947,2459735317,1836772287,1381620373,3196267988,1948373848,3764988233,3385345166,3263785589,2390325492,1480485785,3111247143,3780097726,2293045232,548169417,3459953789,3746175075,439452389,1362321559,1400849762,1685577905,1806599355,2174754046,137073913,1214797936,1174215055,3731654548,2079897426,1943217067,1258480242,529487843,1437280870,3945269170,3049390895,3313212038,923313619,679998e3,3215307299,57326082,377642221,3474729866,2041877159,133361907,1776460110,3673476453,96392454,878845905,2801699524,777231668,4082475170,2330014213,4142626212,2213296395,1626319424,1906247262,1846563261,562755902,3708173718,1040559837,3871163981,1418573201,3294430577,114585348,1343618912,2566595609,3186202582,1078185097,3651041127,3896688048,2307622919,425408743,3371096953,2081048481,1108339068,2216610296,0,2156299017,736970802,292596766,1517440620,251657213,2235061775,2933202493,758720310,265905162,1554391400,1532285339,908999204,174567692,1474760595,4002861748,2610011675,3234156416,3693126241,2001430874,303699484,2478443234,2687165888,585122620,454499602,151849742,2345119218,3064510765,514443284,4044981591,1963412655,2581445614,2137062819,19308535,1928707164,1715193156,4219352155,1126790795,600235211,3992742070,3841024952,836553431,1669664834,2535604243,3323011204,1243905413,3141400786,4180808110,698445255,2653899549,2989552604,2253581325,3252932727,3004591147,1891211689,2487810577,3915653703,4237083816,4030667424,2100090966,865136418,1229899655,953270745,3399679628,3557504664,4118925222,2061379749,3079546586,2915017791,983426092,2022837584,1607244650,2118541908,2366882550,3635996816,972512814,3283088770,1568718495,3499326569,3576539503,621982671,2895723464,410887952,2623762152,1002142683,645401037,1494807662,2595684844,1335535747,2507040230,4293295786,3167684641,367585007,3885750714,1865862730,2668221674,2960971305,2763173681,1059270954,2777952454,2724642869,1320957812,2194319100,2429595872,2815956275,77089521,3973773121,3444575871,2448830231,1305906550,4021308739,2857194700,2516901860,3518358430,1787304780,740276417,1699839814,1592394909,2352307457,2272556026,188821243,1729977011,3687994002,274084841,3594982253,3613494426,2701949495,4162096729,322734571,2837966542,1640576439,484830689,1202797690,3537852828,4067639125,349075736,3342319475,4157467219,4255800159,1030690015,1155237496,2951971274,1757691577,607398968,2738905026,499347990,3794078908,1011452712,227885567,2818666809,213114376,3034881240,1455525988,3414450555,850817237,1817998408,3092726480],O=[0,235474187,470948374,303765277,941896748,908933415,607530554,708780849,1883793496,2118214995,1817866830,1649639237,1215061108,1181045119,1417561698,1517767529,3767586992,4003061179,4236429990,4069246893,3635733660,3602770327,3299278474,3400528769,2430122216,2664543715,2362090238,2193862645,2835123396,2801107407,3035535058,3135740889,3678124923,3576870512,3341394285,3374361702,3810496343,3977675356,4279080257,4043610186,2876494627,2776292904,3076639029,3110650942,2472011535,2640243204,2403728665,2169303058,1001089995,899835584,666464733,699432150,59727847,226906860,530400753,294930682,1273168787,1172967064,1475418501,1509430414,1942435775,2110667444,1876241833,1641816226,2910219766,2743034109,2976151520,3211623147,2505202138,2606453969,2302690252,2269728455,3711829422,3543599269,3240894392,3475313331,3843699074,3943906441,4178062228,4144047775,1306967366,1139781709,1374988112,1610459739,1975683434,2076935265,1775276924,1742315127,1034867998,866637845,566021896,800440835,92987698,193195065,429456164,395441711,1984812685,2017778566,1784663195,1683407248,1315562145,1080094634,1383856311,1551037884,101039829,135050206,437757123,337553864,1042385657,807962610,573804783,742039012,2531067453,2564033334,2328828971,2227573024,2935566865,2700099354,3001755655,3168937228,3868552805,3902563182,4203181171,4102977912,3736164937,3501741890,3265478751,3433712980,1106041591,1340463100,1576976609,1408749034,2043211483,2009195472,1708848333,1809054150,832877231,1068351396,766945465,599762354,159417987,126454664,361929877,463180190,2709260871,2943682380,3178106961,3009879386,2572697195,2538681184,2236228733,2336434550,3509871135,3745345300,3441850377,3274667266,3910161971,3877198648,4110568485,4211818798,2597806476,2497604743,2261089178,2295101073,2733856160,2902087851,3202437046,2968011453,3936291284,3835036895,4136440770,4169408201,3535486456,3702665459,3467192302,3231722213,2051518780,1951317047,1716890410,1750902305,1113818384,1282050075,1584504582,1350078989,168810852,67556463,371049330,404016761,841739592,1008918595,775550814,540080725,3969562369,3801332234,4035489047,4269907996,3569255213,3669462566,3366754619,3332740144,2631065433,2463879762,2160117071,2395588676,2767645557,2868897406,3102011747,3069049960,202008497,33778362,270040487,504459436,875451293,975658646,675039627,641025152,2084704233,1917518562,1615861247,1851332852,1147550661,1248802510,1484005843,1451044056,933301370,967311729,733156972,632953703,260388950,25965917,328671808,496906059,1206477858,1239443753,1543208500,1441952575,2144161806,1908694277,1675577880,1842759443,3610369226,3644379585,3408119516,3307916247,4011190502,3776767469,4077384432,4245618683,2809771154,2842737049,3144396420,3043140495,2673705150,2438237621,2203032232,2370213795],j=[0,185469197,370938394,487725847,741876788,657861945,975451694,824852259,1483753576,1400783205,1315723890,1164071807,1950903388,2135319889,1649704518,1767536459,2967507152,3152976349,2801566410,2918353863,2631447780,2547432937,2328143614,2177544179,3901806776,3818836405,4270639778,4118987695,3299409036,3483825537,3535072918,3652904859,2077965243,1893020342,1841768865,1724457132,1474502543,1559041666,1107234197,1257309336,598438867,681933534,901210569,1052338372,261314535,77422314,428819965,310463728,3409685355,3224740454,3710368113,3593056380,3875770207,3960309330,4045380933,4195456072,2471224067,2554718734,2237133081,2388260884,3212035895,3028143674,2842678573,2724322336,4138563181,4255350624,3769721975,3955191162,3667219033,3516619604,3431546947,3347532110,2933734917,2782082824,3099667487,3016697106,2196052529,2313884476,2499348523,2683765030,1179510461,1296297904,1347548327,1533017514,1786102409,1635502980,2087309459,2003294622,507358933,355706840,136428751,53458370,839224033,957055980,605657339,790073846,2373340630,2256028891,2607439820,2422494913,2706270690,2856345839,3075636216,3160175349,3573941694,3725069491,3273267108,3356761769,4181598602,4063242375,4011996048,3828103837,1033297158,915985419,730517276,545572369,296679730,446754879,129166120,213705253,1709610350,1860738147,1945798516,2029293177,1239331162,1120974935,1606591296,1422699085,4148292826,4233094615,3781033664,3931371469,3682191598,3497509347,3446004468,3328955385,2939266226,2755636671,3106780840,2988687269,2198438022,2282195339,2501218972,2652609425,1201765386,1286567175,1371368976,1521706781,1805211710,1620529459,2105887268,1988838185,533804130,350174575,164439672,46346101,870912086,954669403,636813900,788204353,2358957921,2274680428,2592523643,2441661558,2695033685,2880240216,3065962831,3182487618,3572145929,3756299780,3270937875,3388507166,4174560061,4091327024,4006521127,3854606378,1014646705,930369212,711349675,560487590,272786309,457992840,106852767,223377554,1678381017,1862534868,1914052035,2031621326,1211247597,1128014560,1580087799,1428173050,32283319,182621114,401639597,486441376,768917123,651868046,1003007129,818324884,1503449823,1385356242,1333838021,1150208456,1973745387,2125135846,1673061617,1756818940,2970356327,3120694122,2802849917,2887651696,2637442643,2520393566,2334669897,2149987652,3917234703,3799141122,4284502037,4100872472,3309594171,3460984630,3545789473,3629546796,2050466060,1899603969,1814803222,1730525723,1443857720,1560382517,1075025698,1260232239,575138148,692707433,878443390,1062597235,243256656,91341917,409198410,325965383,3403100636,3252238545,3704300486,3620022987,3874428392,3990953189,4042459122,4227665663,2460449204,2578018489,2226875310,2411029155,3198115200,3046200461,2827177882,2743944855],P=[0,218828297,437656594,387781147,875313188,958871085,775562294,590424639,1750626376,1699970625,1917742170,2135253587,1551124588,1367295589,1180849278,1265195639,3501252752,3720081049,3399941250,3350065803,3835484340,3919042237,4270507174,4085369519,3102249176,3051593425,2734591178,2952102595,2361698556,2177869557,2530391278,2614737639,3145456443,3060847922,2708326185,2892417312,2404901663,2187128086,2504130317,2555048196,3542330227,3727205754,3375740769,3292445032,3876557655,3926170974,4246310725,4027744588,1808481195,1723872674,1910319033,2094410160,1608975247,1391201670,1173430173,1224348052,59984867,244860394,428169201,344873464,935293895,984907214,766078933,547512796,1844882806,1627235199,2011214180,2062270317,1507497298,1423022939,1137477952,1321699145,95345982,145085239,532201772,313773861,830661914,1015671571,731183368,648017665,3175501286,2957853679,2807058932,2858115069,2305455554,2220981195,2474404304,2658625497,3575528878,3625268135,3473416636,3254988725,3778151818,3963161475,4213447064,4130281361,3599595085,3683022916,3432737375,3247465558,3802222185,4020912224,4172763771,4122762354,3201631749,3017672716,2764249623,2848461854,2331590177,2280796200,2431590963,2648976442,104699613,188127444,472615631,287343814,840019705,1058709744,671593195,621591778,1852171925,1668212892,1953757831,2037970062,1514790577,1463996600,1080017571,1297403050,3673637356,3623636965,3235995134,3454686199,4007360968,3822090177,4107101658,4190530515,2997825956,3215212461,2830708150,2779915199,2256734592,2340947849,2627016082,2443058075,172466556,122466165,273792366,492483431,1047239e3,861968209,612205898,695634755,1646252340,1863638845,2013908262,1963115311,1446242576,1530455833,1277555970,1093597963,1636604631,1820824798,2073724613,1989249228,1436590835,1487645946,1337376481,1119727848,164948639,81781910,331544205,516552836,1039717051,821288114,669961897,719700128,2973530695,3157750862,2871682645,2787207260,2232435299,2283490410,2667994737,2450346104,3647212047,3564045318,3279033885,3464042516,3980931627,3762502690,4150144569,4199882800,3070356634,3121275539,2904027272,2686254721,2200818878,2384911031,2570832044,2486224549,3747192018,3528626907,3310321856,3359936201,3950355702,3867060991,4049844452,4234721005,1739656202,1790575107,2108100632,1890328081,1402811438,1586903591,1233856572,1149249077,266959938,48394827,369057872,418672217,1002783846,919489135,567498868,752375421,209336225,24197544,376187827,459744698,945164165,895287692,574624663,793451934,1679968233,1764313568,2117360635,1933530610,1343127501,1560637892,1243112415,1192455638,3704280881,3519142200,3336358691,3419915562,3907448597,3857572124,4075877127,4294704398,3029510009,3113855344,2927934315,2744104290,2159976285,2377486676,2594734927,2544078150],k=[0,151849742,303699484,454499602,607398968,758720310,908999204,1059270954,1214797936,1097159550,1517440620,1400849762,1817998408,1699839814,2118541908,2001430874,2429595872,2581445614,2194319100,2345119218,3034881240,3186202582,2801699524,2951971274,3635996816,3518358430,3399679628,3283088770,4237083816,4118925222,4002861748,3885750714,1002142683,850817237,698445255,548169417,529487843,377642221,227885567,77089521,1943217067,2061379749,1640576439,1757691577,1474760595,1592394909,1174215055,1290801793,2875968315,2724642869,3111247143,2960971305,2405426947,2253581325,2638606623,2487810577,3808662347,3926825029,4044981591,4162096729,3342319475,3459953789,3576539503,3693126241,1986918061,2137062819,1685577905,1836772287,1381620373,1532285339,1078185097,1229899655,1040559837,923313619,740276417,621982671,439452389,322734571,137073913,19308535,3871163981,4021308739,4104605777,4255800159,3263785589,3414450555,3499326569,3651041127,2933202493,2815956275,3167684641,3049390895,2330014213,2213296395,2566595609,2448830231,1305906550,1155237496,1607244650,1455525988,1776460110,1626319424,2079897426,1928707164,96392454,213114376,396673818,514443284,562755902,679998e3,865136418,983426092,3708173718,3557504664,3474729866,3323011204,4180808110,4030667424,3945269170,3794078908,2507040230,2623762152,2272556026,2390325492,2975484382,3092726480,2738905026,2857194700,3973773121,3856137295,4274053469,4157467219,3371096953,3252932727,3673476453,3556361835,2763173681,2915017791,3064510765,3215307299,2156299017,2307622919,2459735317,2610011675,2081048481,1963412655,1846563261,1729977011,1480485785,1362321559,1243905413,1126790795,878845905,1030690015,645401037,796197571,274084841,425408743,38544885,188821243,3613494426,3731654548,3313212038,3430322568,4082475170,4200115116,3780097726,3896688048,2668221674,2516901860,2366882550,2216610296,3141400786,2989552604,2837966542,2687165888,1202797690,1320957812,1437280870,1554391400,1669664834,1787304780,1906247262,2022837584,265905162,114585348,499347990,349075736,736970802,585122620,972512814,821712160,2595684844,2478443234,2293045232,2174754046,3196267988,3079546586,2895723464,2777952454,3537852828,3687994002,3234156416,3385345166,4142626212,4293295786,3841024952,3992742070,174567692,57326082,410887952,292596766,777231668,660510266,1011452712,893681702,1108339068,1258480242,1343618912,1494807662,1715193156,1865862730,1948373848,2100090966,2701949495,2818666809,3004591147,3122358053,2235061775,2352307457,2535604243,2653899549,3915653703,3764988233,4219352155,4067639125,3444575871,3294430577,3746175075,3594982253,836553431,953270745,600235211,718002117,367585007,484830689,133361907,251657213,2041877159,1891211689,1806599355,1654886325,1568718495,1418573201,1335535747,1184342925];function C(I){for(var U=[],K=0;K<I.length;K+=4)U.push(I[K]<<24|I[K+1]<<16|I[K+2]<<8|I[K+3]);return U}var D=function(I){if(!(this instanceof D))throw Error("AES must be instanitated with `new`");Object.defineProperty(this,"key",{value:s(I,!0)}),this._prepare()};D.prototype._prepare=function(){var I=c[this.key.length];if(I==null)throw new Error("invalid key size (must be 16, 24 or 32 bytes)");this._Ke=[],this._Kd=[];for(var U=0;U<=I;U++)this._Ke.push([0,0,0,0]),this._Kd.push([0,0,0,0]);for(var K=(I+1)*4,z=this.key.length/4,G=C(this.key),de,U=0;U<z;U++)de=U>>2,this._Ke[de][U%4]=G[U],this._Kd[I-de][U%4]=G[U];for(var ce=0,Je=z,tt;Je<K;){if(tt=G[z-1],G[0]^=u[tt>>16&255]<<24^u[tt>>8&255]<<16^u[tt&255]<<8^u[tt>>24&255]^d[ce]<<24,ce+=1,z!=8)for(var U=1;U<z;U++)G[U]^=G[U-1];else{for(var U=1;U<z/2;U++)G[U]^=G[U-1];tt=G[z/2-1],G[z/2]^=u[tt&255]^u[tt>>8&255]<<8^u[tt>>16&255]<<16^u[tt>>24&255]<<24;for(var U=z/2+1;U<z;U++)G[U]^=G[U-1]}for(var U=0,Ot,Et;U<z&&Je<K;)Ot=Je>>2,Et=Je%4,this._Ke[Ot][Et]=G[U],this._Kd[I-Ot][Et]=G[U++],Je++}for(var Ot=1;Ot<I;Ot++)for(var Et=0;Et<4;Et++)tt=this._Kd[Ot][Et],this._Kd[Ot][Et]=O[tt>>24&255]^j[tt>>16&255]^P[tt>>8&255]^k[tt&255]},D.prototype.encrypt=function(I){if(I.length!=16)throw new Error("invalid plaintext size (must be 16 bytes)");for(var U=this._Ke.length-1,K=[0,0,0,0],z=C(I),G=0;G<4;G++)z[G]^=this._Ke[0][G];for(var de=1;de<U;de++){for(var G=0;G<4;G++)K[G]=h[z[G]>>24&255]^p[z[(G+1)%4]>>16&255]^m[z[(G+2)%4]>>8&255]^_[z[(G+3)%4]&255]^this._Ke[de][G];z=K.slice()}for(var ce=n(16),Je,G=0;G<4;G++)Je=this._Ke[U][G],ce[4*G]=(u[z[G]>>24&255]^Je>>24)&255,ce[4*G+1]=(u[z[(G+1)%4]>>16&255]^Je>>16)&255,ce[4*G+2]=(u[z[(G+2)%4]>>8&255]^Je>>8)&255,ce[4*G+3]=(u[z[(G+3)%4]&255]^Je)&255;return ce},D.prototype.decrypt=function(I){if(I.length!=16)throw new Error("invalid ciphertext size (must be 16 bytes)");for(var U=this._Kd.length-1,K=[0,0,0,0],z=C(I),G=0;G<4;G++)z[G]^=this._Kd[0][G];for(var de=1;de<U;de++){for(var G=0;G<4;G++)K[G]=f[z[G]>>24&255]^b[z[(G+3)%4]>>16&255]^w[z[(G+2)%4]>>8&255]^S[z[(G+1)%4]&255]^this._Kd[de][G];z=K.slice()}for(var ce=n(16),Je,G=0;G<4;G++)Je=this._Kd[U][G],ce[4*G]=(l[z[G]>>24&255]^Je>>24)&255,ce[4*G+1]=(l[z[(G+3)%4]>>16&255]^Je>>16)&255,ce[4*G+2]=(l[z[(G+2)%4]>>8&255]^Je>>8)&255,ce[4*G+3]=(l[z[(G+1)%4]&255]^Je)&255;return ce};var H=function(I){if(!(this instanceof H))throw Error("AES must be instanitated with `new`");this.description="Electronic Code Block",this.name="ecb",this._aes=new D(I)};H.prototype.encrypt=function(I){if(I=s(I),I.length%16!==0)throw new Error("invalid plaintext size (must be multiple of 16 bytes)");for(var U=n(I.length),K=n(16),z=0;z<I.length;z+=16)i(I,K,0,z,z+16),K=this._aes.encrypt(K),i(K,U,z);return U},H.prototype.decrypt=function(I){if(I=s(I),I.length%16!==0)throw new Error("invalid ciphertext size (must be multiple of 16 bytes)");for(var U=n(I.length),K=n(16),z=0;z<I.length;z+=16)i(I,K,0,z,z+16),K=this._aes.decrypt(K),i(K,U,z);return U};var W=function(I,U){if(!(this instanceof W))throw Error("AES must be instanitated with `new`");if(this.description="Cipher Block Chaining",this.name="cbc",!U)U=n(16);else if(U.length!=16)throw new Error("invalid initialation vector size (must be 16 bytes)");this._lastCipherblock=s(U,!0),this._aes=new D(I)};W.prototype.encrypt=function(I){if(I=s(I),I.length%16!==0)throw new Error("invalid plaintext size (must be multiple of 16 bytes)");for(var U=n(I.length),K=n(16),z=0;z<I.length;z+=16){i(I,K,0,z,z+16);for(var G=0;G<16;G++)K[G]^=this._lastCipherblock[G];this._lastCipherblock=this._aes.encrypt(K),i(this._lastCipherblock,U,z)}return U},W.prototype.decrypt=function(I){if(I=s(I),I.length%16!==0)throw new Error("invalid ciphertext size (must be multiple of 16 bytes)");for(var U=n(I.length),K=n(16),z=0;z<I.length;z+=16){i(I,K,0,z,z+16),K=this._aes.decrypt(K);for(var G=0;G<16;G++)U[z+G]=K[G]^this._lastCipherblock[G];i(I,this._lastCipherblock,0,z,z+16)}return U};var J=function(I,U,K){if(!(this instanceof J))throw Error("AES must be instanitated with `new`");if(this.description="Cipher Feedback",this.name="cfb",!U)U=n(16);else if(U.length!=16)throw new Error("invalid initialation vector size (must be 16 size)");K||(K=1),this.segmentSize=K,this._shiftRegister=s(U,!0),this._aes=new D(I)};J.prototype.encrypt=function(I){if(I.length%this.segmentSize!=0)throw new Error("invalid plaintext size (must be segmentSize bytes)");for(var U=s(I,!0),K,z=0;z<U.length;z+=this.segmentSize){K=this._aes.encrypt(this._shiftRegister);for(var G=0;G<this.segmentSize;G++)U[z+G]^=K[G];i(this._shiftRegister,this._shiftRegister,0,this.segmentSize),i(U,this._shiftRegister,16-this.segmentSize,z,z+this.segmentSize)}return U},J.prototype.decrypt=function(I){if(I.length%this.segmentSize!=0)throw new Error("invalid ciphertext size (must be segmentSize bytes)");for(var U=s(I,!0),K,z=0;z<U.length;z+=this.segmentSize){K=this._aes.encrypt(this._shiftRegister);for(var G=0;G<this.segmentSize;G++)U[z+G]^=K[G];i(this._shiftRegister,this._shiftRegister,0,this.segmentSize),i(I,this._shiftRegister,16-this.segmentSize,z,z+this.segmentSize)}return U};var F=function(I,U){if(!(this instanceof F))throw Error("AES must be instanitated with `new`");if(this.description="Output Feedback",this.name="ofb",!U)U=n(16);else if(U.length!=16)throw new Error("invalid initialation vector size (must be 16 bytes)");this._lastPrecipher=s(U,!0),this._lastPrecipherIndex=16,this._aes=new D(I)};F.prototype.encrypt=function(I){for(var U=s(I,!0),K=0;K<U.length;K++)this._lastPrecipherIndex===16&&(this._lastPrecipher=this._aes.encrypt(this._lastPrecipher),this._lastPrecipherIndex=0),U[K]^=this._lastPrecipher[this._lastPrecipherIndex++];return U},F.prototype.decrypt=F.prototype.encrypt;var q=function(I){if(!(this instanceof q))throw Error("Counter must be instanitated with `new`");I!==0&&!I&&(I=1),typeof I=="number"?(this._counter=n(16),this.setValue(I)):this.setBytes(I)};q.prototype.setValue=function(I){if(typeof I!="number"||parseInt(I)!=I)throw new Error("invalid counter value (must be an integer)");if(I>Number.MAX_SAFE_INTEGER)throw new Error("integer value out of safe range");for(var U=15;U>=0;--U)this._counter[U]=I%256,I=parseInt(I/256)},q.prototype.setBytes=function(I){if(I=s(I,!0),I.length!=16)throw new Error("invalid counter bytes size (must be 16 bytes)");this._counter=I},q.prototype.increment=function(){for(var I=15;I>=0;I--)if(this._counter[I]===255)this._counter[I]=0;else{this._counter[I]++;break}};var Q=function(I,U){if(!(this instanceof Q))throw Error("AES must be instanitated with `new`");this.description="Counter",this.name="ctr",U instanceof q||(U=new q(U)),this._counter=U,this._remainingCounter=null,this._remainingCounterIndex=16,this._aes=new D(I)};Q.prototype.encrypt=function(I){for(var U=s(I,!0),K=0;K<U.length;K++)this._remainingCounterIndex===16&&(this._remainingCounter=this._aes.encrypt(this._counter._counter),this._remainingCounterIndex=0,this._counter.increment()),U[K]^=this._remainingCounter[this._remainingCounterIndex++];return U},Q.prototype.decrypt=Q.prototype.encrypt;function R(I){I=s(I,!0);var U=16-I.length%16,K=n(I.length+U);i(I,K);for(var z=I.length;z<K.length;z++)K[z]=U;return K}function Y(I){if(I=s(I,!0),I.length<16)throw new Error("PKCS#7 invalid length");var U=I[I.length-1];if(U>16)throw new Error("PKCS#7 padding byte out of range");for(var K=I.length-U,z=0;z<U;z++)if(I[K+z]!==U)throw new Error("PKCS#7 invalid padding byte");var G=n(K);return i(I,G,0,0,K),G}var Z={AES:D,Counter:q,ModeOfOperation:{ecb:H,cbc:W,cfb:J,ofb:F,ctr:Q},utils:{hex:a,utf8:o},padding:{pkcs7:{pad:R,strip:Y}},_arrayTest:{coerceArray:s,createArray:n,copyArray:i}};typeof nT<"u"?hN.exports=Z:typeof define=="function"&&define.amd?define([],function(){return Z}):(t.aesjs&&(Z._aesjs=t.aesjs),t.aesjs=Z)})(nT)});function gN(t,e,r){var s=e?0:4,n=e?4:0,i=e?0:3,o=e?1:2,a=e?2:1,c=e?3:0,d=e?GQ:YQ,u=e?XQ:JQ,l=m.prototype,h="is"+t,p="_"+h;return l.buffer=void 0,l.offset=0,l[p]=!0,l.toNumber=w,l.toString=S,l.toJSON=w,l.toArray=WQ,bh&&(l.toBuffer=KQ),yh&&(l.toArrayBuffer=yN),m[h]=_,m;function m(P,k,C,D){return this instanceof m?f(this,P,k,C,D):new m(P,k,C,D)}function _(P){return!!(P&&P[p])}function f(P,k,C,D,H){if(yh&&vw&&(k instanceof vw&&(k=new yh(k)),D instanceof vw&&(D=new yh(D))),!k&&!C&&!D&&!xh){P.buffer=bN(pN,0);return}if(!mN(k,C)){var W=xh||Array;H=C,D=k,C=0,k=xh===bh?bh.alloc(8):new W(8)}P.buffer=k,P.offset=C|=0,_w!==typeof D&&(typeof D=="string"?b(k,C,D,H||10):mN(D,H)?iT(k,C,D,H):typeof H=="number"?(O(k,C+s,D),O(k,C+n,H)):D>0?d(k,C,D):D<0?u(k,C,D):iT(k,C,pN,0))}function b(P,k,C,D){var H=0,W=C.length,J=0,F=0;C[0]==="-"&&H++;for(var q=H;H<W;){var Q=parseInt(C[H++],D);if(!(Q>=0))break;F=F*D+Q,J=J*D+Math.floor(F/gh),F%=gh}q&&(J=~J,F?F=gh-F:J++),O(P,k+s,J),O(P,k+n,F)}function w(){var P=this.buffer,k=this.offset,C=j(P,k+s),D=j(P,k+n);return r||(C|=0),C?C*gh+D:D}function S(P){var k=this.buffer,C=this.offset,D=j(k,C+s),H=j(k,C+n),W="",J=!r&&D&2147483648;for(J&&(D=~D,H=gh-H),P=P||10;;){var F=D%P*gh+H;if(D=Math.floor(D/P),H=Math.floor(F/P),W=(F%P).toString(P)+W,!D&&!H)break}return J&&(W="-"+W),W}function O(P,k,C){P[k+c]=C&255,C=C>>8,P[k+a]=C&255,C=C>>8,P[k+o]=C&255,C=C>>8,P[k+i]=C&255}function j(P,k){return P[k+i]*zQ+(P[k+o]<<16)+(P[k+a]<<8)+P[k+c]}}function WQ(t){var e=this.buffer,r=this.offset;return xh=null,t!==!1&&VQ(e)?e.length===8?e:e.slice(r,r+8):bN(e,r)}function KQ(t){var e=this.buffer,r=this.offset;return xh=bh,t!==!1&&bh.isBuffer(e)?e.length===8?e:e.slice(r,r+8):bh.from(yN.call(this,t))}function yN(t){var e=this.buffer,r=this.offset,s=e.buffer;if(xh=yh,t!==!1&&!e.offset&&s instanceof vw)return s.byteLength===8?s:s.slice(r,r+8);var n=new yh(8);return iT(n,0,e,r),n.buffer}function mN(t,e){var r=t&&t.length;return e|=0,r&&e+8<=r&&typeof t[e]!="string"}function iT(t,e,r,s){e|=0,s|=0;for(var n=0;n<8;n++)t[e++]=r[s++]&255}function bN(t,e){return Array.prototype.slice.call(t,e,e+8)}function GQ(t,e,r){for(var s=e+8;s>e;)t[--s]=r&255,r/=256}function XQ(t,e,r){var s=e+8;for(r++;s>e;)t[--s]=-r&255^255,r/=256}function YQ(t,e,r){for(var s=e+8;e<s;)t[e++]=r&255,r/=256}function JQ(t,e,r){var s=e+8;for(r++;e<s;)t[e++]=-r&255^255,r/=256}function QQ(t){return!!t&&Object.prototype.toString.call(t)=="[object Array]"}var _w,bh,yh,vw,pN,VQ,gh,zQ,xh,Sw,oT,Ew=V(()=>{"use strict";g();y();_w="undefined",bh=_w!==typeof Buffer&&Buffer,yh=_w!==typeof Uint8Array&&Uint8Array,vw=_w!==typeof ArrayBuffer&&ArrayBuffer,pN=[0,0,0,0,0,0,0,0],VQ=Array.isArray||QQ,gh=4294967296,zQ=16777216,Sw=gN("Uint64BE",!0,!0),oT=gN("Int64BE",!0,!1)});var cT=Me(xN=>{"use strict";g();y();var Ye=xN,{Buffer:Cw}=require("buffer"),ZQ=require("os");Ye.toBuffer=function(t,e,r){r=~~r;let s;if(this.isV4Format(t))s=e||Cw.alloc(r+4),t.split(/\./g).map(n=>{s[r++]=parseInt(n,10)&255});else if(this.isV6Format(t)){let n=t.split(":",8),i;for(i=0;i<n.length;i++){let o=this.isV4Format(n[i]),a;o&&(a=this.toBuffer(n[i]),n[i]=a.slice(0,2).toString("hex")),a&&++i<8&&n.splice(i,0,a.slice(2,4).toString("hex"))}if(n[0]==="")for(;n.length<8;)n.unshift("0");else if(n[n.length-1]==="")for(;n.length<8;)n.push("0");else if(n.length<8){for(i=0;i<n.length&&n[i]!=="";i++);let o=[i,1];for(i=9-n.length;i>0;i--)o.push("0");n.splice(...o)}for(s=e||Cw.alloc(r+16),i=0;i<n.length;i++){let o=parseInt(n[i],16);s[r++]=o>>8&255,s[r++]=o&255}}if(!s)throw Error(`Invalid ip address: ${t}`);return s};Ye.toString=function(t,e,r){e=~~e,r=r||t.length-e;let s=[];if(r===4){for(let n=0;n<r;n++)s.push(t[e+n]);s=s.join(".")}else if(r===16){for(let n=0;n<r;n+=2)s.push(t.readUInt16BE(e+n).toString(16));s=s.join(":"),s=s.replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3"),s=s.replace(/:{3,4}/,"::")}return s};var eZ=/^(\d{1,3}\.){3,3}\d{1,3}$/,tZ=/^(::)?(((\d{1,3}\.){3}(\d{1,3}){1})?([0-9a-f]){0,4}:{0,2}){1,8}(::)?$/i;Ye.isV4Format=function(t){return eZ.test(t)};Ye.isV6Format=function(t){return tZ.test(t)};function im(t){return t===4?"ipv4":t===6?"ipv6":t?t.toLowerCase():"ipv4"}Ye.fromPrefixLen=function(t,e){t>32?e="ipv6":e=im(e);let r=4;e==="ipv6"&&(r=16);let s=Cw.alloc(r);for(let n=0,i=s.length;n<i;++n){let o=8;t<8&&(o=t),t-=o,s[n]=~(255>>o)&255}return Ye.toString(s)};Ye.mask=function(t,e){t=Ye.toBuffer(t),e=Ye.toBuffer(e);let r=Cw.alloc(Math.max(t.length,e.length)),s;if(t.length===e.length)for(s=0;s<t.length;s++)r[s]=t[s]&e[s];else if(e.length===4)for(s=0;s<e.length;s++)r[s]=t[t.length-4+s]&e[s];else{for(s=0;s<r.length-6;s++)r[s]=0;for(r[10]=255,r[11]=255,s=0;s<t.length;s++)r[s+12]=t[s]&e[s+12];s+=12}for(;s<r.length;s++)r[s]=0;return Ye.toString(r)};Ye.cidr=function(t){let e=t.split("/"),r=e[0];if(e.length!==2)throw new Error(`invalid CIDR subnet: ${r}`);let s=Ye.fromPrefixLen(parseInt(e[1],10));return Ye.mask(r,s)};Ye.subnet=function(t,e){let r=Ye.toLong(Ye.mask(t,e)),s=Ye.toBuffer(e),n=0;for(let o=0;o<s.length;o++)if(s[o]===255)n+=8;else{let a=s[o]&255;for(;a;)a=a<<1&255,n++}let i=2**(32-n);return{networkAddress:Ye.fromLong(r),firstAddress:i<=2?Ye.fromLong(r):Ye.fromLong(r+1),lastAddress:i<=2?Ye.fromLong(r+i-1):Ye.fromLong(r+i-2),broadcastAddress:Ye.fromLong(r+i-1),subnetMask:e,subnetMaskLength:n,numHosts:i<=2?i:i-2,length:i,contains(o){return r===Ye.toLong(Ye.mask(o,e))}}};Ye.cidrSubnet=function(t){let e=t.split("/"),r=e[0];if(e.length!==2)throw new Error(`invalid CIDR subnet: ${r}`);let s=Ye.fromPrefixLen(parseInt(e[1],10));return Ye.subnet(r,s)};Ye.not=function(t){let e=Ye.toBuffer(t);for(let r=0;r<e.length;r++)e[r]=255^e[r];return Ye.toString(e)};Ye.or=function(t,e){if(t=Ye.toBuffer(t),e=Ye.toBuffer(e),t.length===e.length){for(let i=0;i<t.length;++i)t[i]|=e[i];return Ye.toString(t)}let r=t,s=e;e.length>t.length&&(r=e,s=t);let n=r.length-s.length;for(let i=n;i<r.length;++i)r[i]|=s[i-n];return Ye.toString(r)};Ye.isEqual=function(t,e){if(t=Ye.toBuffer(t),e=Ye.toBuffer(e),t.length===e.length){for(let s=0;s<t.length;s++)if(t[s]!==e[s])return!1;return!0}if(e.length===4){let s=e;e=t,t=s}for(let s=0;s<10;s++)if(e[s]!==0)return!1;let r=e.readUInt16BE(10);if(r!==0&&r!==65535)return!1;for(let s=0;s<4;s++)if(t[s]!==e[s+12])return!1;return!0};Ye.isPrivate=function(t){if(Ye.isLoopback(t))return!0;if(!Ye.isV6Format(t)){let e=Ye.normalizeToLong(t);if(e<0)throw new Error("invalid ipv4 address");t=Ye.fromLong(e)}return/^(::f{4}:)?10\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(t)||/^(::f{4}:)?192\.168\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(t)||/^(::f{4}:)?172\.(1[6-9]|2\d|30|31)\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(t)||/^(::f{4}:)?169\.254\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(t)||/^f[cd][0-9a-f]{2}:/i.test(t)||/^fe80:/i.test(t)||/^::1$/.test(t)||/^::$/.test(t)};Ye.isPublic=function(t){return!Ye.isPrivate(t)};Ye.isLoopback=function(t){return!/\./.test(t)&&!/:/.test(t)&&(t=Ye.fromLong(Number(t))),/^(::f{4}:)?127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})/.test(t)||/^0177\./.test(t)||/^0x7f\./i.test(t)||/^fe80::1$/i.test(t)||/^::1$/.test(t)||/^::$/.test(t)};Ye.loopback=function(t){if(t=im(t),t!=="ipv4"&&t!=="ipv6")throw new Error("family must be ipv4 or ipv6");return t==="ipv4"?"127.0.0.1":"fe80::1"};Ye.address=function(t,e){let r=ZQ.networkInterfaces();if(e=im(e),t&&t!=="private"&&t!=="public"){let n=r[t].filter(i=>im(i.family)===e);return n.length===0?void 0:n[0].address}let s=Object.keys(r).map(n=>{let i=r[n].filter(o=>(o.family=im(o.family),o.family!==e||Ye.isLoopback(o.address)?!1:t?t==="public"?Ye.isPrivate(o.address):Ye.isPublic(o.address):!0));return i.length?i[0].address:void 0}).filter(Boolean);return s.length?s[0]:Ye.loopback(e)};Ye.toLong=function(t){let e=0;return t.split(".").forEach(r=>{e<<=8,e+=parseInt(r)}),e>>>0};Ye.fromLong=function(t){return`${t>>>24}.${t>>16&255}.${t>>8&255}.${t&255}`};Ye.normalizeToLong=function(t){let e=t.split(".").map(n=>n.startsWith("0x")||n.startsWith("0X")?parseInt(n,16):n.startsWith("0")&&n!=="0"&&/^[0-7]+$/.test(n)?parseInt(n,8):/^[1-9]\d*$/.test(n)||n==="0"?parseInt(n,10):NaN);if(e.some(isNaN))return-1;let r=0;switch(e.length){case 1:r=e[0];break;case 2:if(e[0]>255||e[1]>16777215)return-1;r=e[0]<<24|e[1]&16777215;break;case 3:if(e[0]>255||e[1]>255||e[2]>65535)return-1;r=e[0]<<24|e[1]<<16|e[2]&65535;break;case 4:if(e.some(n=>n>255))return-1;r=e[0]<<24|e[1]<<16|e[2]<<8|e[3];break;default:return-1}return r>>>0}});var vN=Me((OPe,wN)=>{"use strict";g();y();wN.exports=function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var s,n,i;if(Array.isArray(e)){if(s=e.length,s!=r.length)return!1;for(n=s;n--!==0;)if(!t(e[n],r[n]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(i=Object.keys(e),s=i.length,s!==Object.keys(r).length)return!1;for(n=s;n--!==0;)if(!Object.prototype.hasOwnProperty.call(r,i[n]))return!1;for(n=s;n--!==0;){var o=i[n];if(!t(e[o],r[o]))return!1}return!0}return e!==e&&r!==r}});var _N=Me(dT=>{"use strict";g();y();dT.toString=function(t){switch(t){case 1:return"A";case 10:return"NULL";case 28:return"AAAA";case 18:return"AFSDB";case 42:return"APL";case 257:return"CAA";case 60:return"CDNSKEY";case 59:return"CDS";case 37:return"CERT";case 5:return"CNAME";case 49:return"DHCID";case 32769:return"DLV";case 39:return"DNAME";case 48:return"DNSKEY";case 43:return"DS";case 55:return"HIP";case 13:return"HINFO";case 45:return"IPSECKEY";case 25:return"KEY";case 36:return"KX";case 29:return"LOC";case 15:return"MX";case 35:return"NAPTR";case 2:return"NS";case 47:return"NSEC";case 50:return"NSEC3";case 51:return"NSEC3PARAM";case 12:return"PTR";case 46:return"RRSIG";case 17:return"RP";case 24:return"SIG";case 6:return"SOA";case 99:return"SPF";case 33:return"SRV";case 44:return"SSHFP";case 32768:return"TA";case 249:return"TKEY";case 52:return"TLSA";case 250:return"TSIG";case 16:return"TXT";case 252:return"AXFR";case 251:return"IXFR";case 41:return"OPT";case 255:return"ANY"}return"UNKNOWN_"+t};dT.toType=function(t){switch(t.toUpperCase()){case"A":return 1;case"NULL":return 10;case"AAAA":return 28;case"AFSDB":return 18;case"APL":return 42;case"CAA":return 257;case"CDNSKEY":return 60;case"CDS":return 59;case"CERT":return 37;case"CNAME":return 5;case"DHCID":return 49;case"DLV":return 32769;case"DNAME":return 39;case"DNSKEY":return 48;case"DS":return 43;case"HIP":return 55;case"HINFO":return 13;case"IPSECKEY":return 45;case"KEY":return 25;case"KX":return 36;case"LOC":return 29;case"MX":return 15;case"NAPTR":return 35;case"NS":return 2;case"NSEC":return 47;case"NSEC3":return 50;case"NSEC3PARAM":return 51;case"PTR":return 12;case"RRSIG":return 46;case"RP":return 17;case"SIG":return 24;case"SOA":return 6;case"SPF":return 99;case"SRV":return 33;case"SSHFP":return 44;case"TA":return 32768;case"TKEY":return 249;case"TLSA":return 52;case"TSIG":return 250;case"TXT":return 16;case"AXFR":return 252;case"IXFR":return 251;case"OPT":return 41;case"ANY":return 255;case"*":return 255}return t.toUpperCase().startsWith("UNKNOWN_")?parseInt(t.slice(8)):0}});var SN=Me(lT=>{"use strict";g();y();lT.toString=function(t){switch(t){case 0:return"NOERROR";case 1:return"FORMERR";case 2:return"SERVFAIL";case 3:return"NXDOMAIN";case 4:return"NOTIMP";case 5:return"REFUSED";case 6:return"YXDOMAIN";case 7:return"YXRRSET";case 8:return"NXRRSET";case 9:return"NOTAUTH";case 10:return"NOTZONE";case 11:return"RCODE_11";case 12:return"RCODE_12";case 13:return"RCODE_13";case 14:return"RCODE_14";case 15:return"RCODE_15"}return"RCODE_"+t};lT.toRcode=function(t){switch(t.toUpperCase()){case"NOERROR":return 0;case"FORMERR":return 1;case"SERVFAIL":return 2;case"NXDOMAIN":return 3;case"NOTIMP":return 4;case"REFUSED":return 5;case"YXDOMAIN":return 6;case"YXRRSET":return 7;case"NXRRSET":return 8;case"NOTAUTH":return 9;case"NOTZONE":return 10;case"RCODE_11":return 11;case"RCODE_12":return 12;case"RCODE_13":return 13;case"RCODE_14":return 14;case"RCODE_15":return 15}return 0}});var EN=Me(uT=>{"use strict";g();y();uT.toString=function(t){switch(t){case 0:return"QUERY";case 1:return"IQUERY";case 2:return"STATUS";case 3:return"OPCODE_3";case 4:return"NOTIFY";case 5:return"UPDATE";case 6:return"OPCODE_6";case 7:return"OPCODE_7";case 8:return"OPCODE_8";case 9:return"OPCODE_9";case 10:return"OPCODE_10";case 11:return"OPCODE_11";case 12:return"OPCODE_12";case 13:return"OPCODE_13";case 14:return"OPCODE_14";case 15:return"OPCODE_15"}return"OPCODE_"+t};uT.toOpcode=function(t){switch(t.toUpperCase()){case"QUERY":return 0;case"IQUERY":return 1;case"STATUS":return 2;case"OPCODE_3":return 3;case"NOTIFY":return 4;case"UPDATE":return 5;case"OPCODE_6":return 6;case"OPCODE_7":return 7;case"OPCODE_8":return 8;case"OPCODE_9":return 9;case"OPCODE_10":return 10;case"OPCODE_11":return 11;case"OPCODE_12":return 12;case"OPCODE_13":return 13;case"OPCODE_14":return 14;case"OPCODE_15":return 15}return 0}});var CN=Me(hT=>{"use strict";g();y();hT.toString=function(t){switch(t){case 1:return"IN";case 2:return"CS";case 3:return"CH";case 4:return"HS";case 255:return"ANY"}return"UNKNOWN_"+t};hT.toClass=function(t){switch(t.toUpperCase()){case"IN":return 1;case"CS":return 2;case"CH":return 3;case"HS":return 4;case"ANY":return 255}return 0}});var TN=Me(fT=>{"use strict";g();y();fT.toString=function(t){switch(t){case 1:return"LLQ";case 2:return"UL";case 3:return"NSID";case 5:return"DAU";case 6:return"DHU";case 7:return"N3U";case 8:return"CLIENT_SUBNET";case 9:return"EXPIRE";case 10:return"COOKIE";case 11:return"TCP_KEEPALIVE";case 12:return"PADDING";case 13:return"CHAIN";case 14:return"KEY_TAG";case 26946:return"DEVICEID"}return t<0?null:`OPTION_${t}`};fT.toCode=function(t){if(typeof t=="number")return t;if(!t)return-1;switch(t.toUpperCase()){case"OPTION_0":return 0;case"LLQ":return 1;case"UL":return 2;case"NSID":return 3;case"OPTION_4":return 4;case"DAU":return 5;case"DHU":return 6;case"N3U":return 7;case"CLIENT_SUBNET":return 8;case"EXPIRE":return 9;case"COOKIE":return 10;case"TCP_KEEPALIVE":return 11;case"PADDING":return 12;case"CHAIN":return 13;case"KEY_TAG":return 14;case"DEVICEID":return 26946;case"OPTION_65535":return 65535}let e=t.match(/_(\d+)$/);return e?parseInt(e[1],10):-1}});var IN=Me((AN,pT)=>{"use strict";g();y();var kN=(function(t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.decode=l,t.encode=u,t.familyOf=d,t.name=void 0,t.sizeOf=c,t.v6=t.v4=void 0;let e=/^(\d{1,3}\.){3,3}\d{1,3}$/,r=4,s=/^(::)?(((\d{1,3}\.){3}(\d{1,3}){1})?([0-9a-f]){0,4}:{0,2}){1,8}(::)?$/i,n=16,i={name:"v4",size:r,isFormat:h=>e.test(h),encode(h,p,m){m=~~m,p=p||new Uint8Array(m+r);let _=h.length,f=0;for(let b=0;b<_;){let w=h.charCodeAt(b++);w===46?(p[m++]=f,f=0):f=f*10+(w-48)}return p[m]=f,p},decode(h,p){return p=~~p,`${h[p++]}.${h[p++]}.${h[p++]}.${h[p]}`}};t.v4=i;let o={name:"v6",size:n,isFormat:h=>h.length>0&&s.test(h),encode(h,p,m){m=~~m;let _=m+n,f=-1,b=0,w=0,S=!0,O=!1;p=p||new Uint8Array(m+n);for(let j=0;j<h.length;j++){let P=h.charCodeAt(j);P===58?(S?f!==-1?(m<_&&(p[m]=0),m<_-1&&(p[m+1]=0),m+=2):m<_&&(f=m):(O===!0?(m<_&&(p[m]=w),m++):(m<_&&(p[m]=b>>8),m<_-1&&(p[m+1]=b&255),m+=2),b=0,w=0),S=!0,O=!1):P===46?(m<_&&(p[m]=w),m++,w=0,b=0,S=!1,O=!0):(S=!1,P>=97?P-=87:P>=65?P-=55:(P-=48,w=w*10+P),b=(b<<4)+P)}if(S===!1)O===!0?(m<_&&(p[m]=w),m++):(m<_&&(p[m]=b>>8),m<_-1&&(p[m+1]=b&255),m+=2);else if(f===0)m<_&&(p[m]=0),m<_-1&&(p[m+1]=0),m+=2;else if(f!==-1){m+=2;for(let j=Math.min(m-1,_-1);j>=f+2;j--)p[j]=p[j-2];p[f]=0,p[f+1]=0,f=m}if(f!==m&&f!==-1)for(m>_-2&&(m=_-2);_>f;)p[--_]=m<_&&m>f?p[--m]:0;else for(;m<_;)p[m++]=0;return p},decode(h,p){p=~~p;let m="";for(let _=0;_<n;_+=2)_!==0&&(m+=":"),m+=(h[p+_]<<8|h[p+_+1]).toString(16);return m.replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}};t.v6=o;let a="ip";t.name=a;function c(h){if(i.isFormat(h))return i.size;if(o.isFormat(h))return o.size;throw Error(`Invalid ip address: ${h}`)}function d(h){return c(h)===i.size?1:2}function u(h,p,m){m=~~m;let _=c(h);return typeof p=="function"&&(p=p(m+_)),_===i.size?i.encode(h,p,m):o.encode(h,p,m)}function l(h,p,m){if(p=~~p,m=m||h.length-p,m===i.size)return i.decode(h,p,m);if(m===o.size)return o.decode(h,p,m);throw Error(`Invalid buffer size needs to be ${i.size} for v4 or ${o.size} for v6.`)}return"default"in t?t.default:t})({});typeof define=="function"&&define.amd?define([],function(){return kN}):typeof pT=="object"&&typeof AN=="object"&&(pT.exports=kN)});var DN=Me(Qe=>{"use strict";g();y();var Ze=require("buffer").Buffer,Ho=_N(),rZ=SN(),sZ=EN(),kw=CN(),mT=TN(),cl=IN(),nZ=0,RN=32768,gT=32768,iZ=~gT,PN=32768,oZ=~PN,Ie=Qe.name={};Ie.encode=function(t,e,r,{mail:s=!1}={}){e||(e=Ze.alloc(Ie.encodingLength(t))),r||(r=0);let n=r,i=t.replace(/^\.|\.$/gm,"");if(i.length){let o=[];if(s){let a="";i.split(".").forEach(c=>{c.endsWith("\\")?a+=(a.length?".":"")+c.slice(0,-1):o.length===0&&a.length?o.push(a+"."+c):o.push(c)})}else o=i.split(".");for(let a=0;a<o.length;a++){let c=e.write(o[a],r+1);e[r]=c,r+=c+1}}return e[r++]=0,Ie.encode.bytes=r-n,e};Ie.encode.bytes=0;Ie.decode=function(t,e,{mail:r=!1}={}){e||(e=0);let s=[],n=e,i=0,o=0,a=!1;for(;;){if(e>=t.length)throw new Error("Cannot decode name (buffer overflow)");let c=t[e++];if(o+=a?0:1,c===0)break;if((c&192)===0){if(e+c>t.length)throw new Error("Cannot decode name (buffer overflow)");if(i+=c+1,i>254)throw new Error("Cannot decode name (name too long)");let d=t.toString("utf-8",e,e+c);r&&(d=d.replace(/\./g,"\\.")),s.push(d),e+=c,o+=a?0:c}else if((c&192)===192){if(e+1>t.length)throw new Error("Cannot decode name (buffer overflow)");let d=t.readUInt16BE(e-1)-49152;if(d>=n)throw new Error("Cannot decode name (bad pointer)");e=d,n=d,o+=a?0:1,a=!0}else throw new Error("Cannot decode name (bad label)")}return Ie.decode.bytes=o,s.length===0?".":s.join(".")};Ie.decode.bytes=0;Ie.encodingLength=function(t){return t==="."||t===".."?1:Ze.byteLength(t.replace(/^\.|\.$/gm,""))+2};var St={};St.encode=function(t,e,r){e||(e=Ze.alloc(St.encodingLength(t))),r||(r=0);let s=e.write(t,r+1);return e[r]=s,St.encode.bytes=s+1,e};St.encode.bytes=0;St.decode=function(t,e){e||(e=0);let r=t[e],s=t.toString("utf-8",e+1,e+1+r);return St.decode.bytes=r+1,s};St.decode.bytes=0;St.encodingLength=function(t){return Ze.byteLength(t)+1};var Hn={};Hn.encode=function(t,e,r){e||(e=Hn.encodingLength(t)),r||(r=0);let s=(t.flags||0)&32767,n=t.type==="response"?RN:nZ;return e.writeUInt16BE(t.id||0,r),e.writeUInt16BE(s|n,r+2),e.writeUInt16BE(t.questions.length,r+4),e.writeUInt16BE(t.answers.length,r+6),e.writeUInt16BE(t.authorities.length,r+8),e.writeUInt16BE(t.additionals.length,r+10),e};Hn.encode.bytes=12;Hn.decode=function(t,e){if(e||(e=0),t.length<12)throw new Error("Header must be 12 bytes");let r=t.readUInt16BE(e+2);return{id:t.readUInt16BE(e),type:r&RN?"response":"query",flags:r&32767,flag_qr:(r>>15&1)===1,opcode:sZ.toString(r>>11&15),flag_aa:(r>>10&1)===1,flag_tc:(r>>9&1)===1,flag_rd:(r>>8&1)===1,flag_ra:(r>>7&1)===1,flag_z:(r>>6&1)===1,flag_ad:(r>>5&1)===1,flag_cd:(r>>4&1)===1,rcode:rZ.toString(r&15),questions:new Array(t.readUInt16BE(e+4)),answers:new Array(t.readUInt16BE(e+6)),authorities:new Array(t.readUInt16BE(e+8)),additionals:new Array(t.readUInt16BE(e+10))}};Hn.decode.bytes=12;Hn.encodingLength=function(){return 12};var Bo=Qe.unknown={};Bo.encode=function(t,e,r){return e||(e=Ze.alloc(Bo.encodingLength(t))),r||(r=0),e.writeUInt16BE(t.length,r),t.copy(e,r+2),Bo.encode.bytes=t.length+2,e};Bo.encode.bytes=0;Bo.decode=function(t,e){e||(e=0);let r=t.readUInt16BE(e),s=t.slice(e+2,e+2+r);return Bo.decode.bytes=r+2,s};Bo.decode.bytes=0;Bo.encodingLength=function(t){return t.length+2};var Lo=Qe.ns={};Lo.encode=function(t,e,r){return e||(e=Ze.alloc(Lo.encodingLength(t))),r||(r=0),Ie.encode(t,e,r+2),e.writeUInt16BE(Ie.encode.bytes,r),Lo.encode.bytes=Ie.encode.bytes+2,e};Lo.encode.bytes=0;Lo.decode=function(t,e){e||(e=0);let r=t.readUInt16BE(e),s=Ie.decode(t,e+2);return Lo.decode.bytes=r+2,s};Lo.decode.bytes=0;Lo.encodingLength=function(t){return Ie.encodingLength(t)+2};var Oo=Qe.soa={};Oo.encode=function(t,e,r){e||(e=Ze.alloc(Oo.encodingLength(t))),r||(r=0);let s=r;return r+=2,Ie.encode(t.mname,e,r),r+=Ie.encode.bytes,Ie.encode(t.rname,e,r,{mail:!0}),r+=Ie.encode.bytes,e.writeUInt32BE(t.serial||0,r),r+=4,e.writeUInt32BE(t.refresh||0,r),r+=4,e.writeUInt32BE(t.retry||0,r),r+=4,e.writeUInt32BE(t.expire||0,r),r+=4,e.writeUInt32BE(t.minimum||0,r),r+=4,e.writeUInt16BE(r-s-2,s),Oo.encode.bytes=r-s,e};Oo.encode.bytes=0;Oo.decode=function(t,e){e||(e=0);let r=e,s={};return e+=2,s.mname=Ie.decode(t,e),e+=Ie.decode.bytes,s.rname=Ie.decode(t,e,{mail:!0}),e+=Ie.decode.bytes,s.serial=t.readUInt32BE(e),e+=4,s.refresh=t.readUInt32BE(e),e+=4,s.retry=t.readUInt32BE(e),e+=4,s.expire=t.readUInt32BE(e),e+=4,s.minimum=t.readUInt32BE(e),e+=4,Oo.decode.bytes=e-r,s};Oo.decode.bytes=0;Oo.encodingLength=function(t){return 22+Ie.encodingLength(t.mname)+Ie.encodingLength(t.rname)};var No=Qe.txt={};No.encode=function(t,e,r){Array.isArray(t)||(t=[t]);for(let n=0;n<t.length;n++)if(typeof t[n]=="string"&&(t[n]=Ze.from(t[n])),!Ze.isBuffer(t[n]))throw new Error("Must be a Buffer");e||(e=Ze.alloc(No.encodingLength(t))),r||(r=0);let s=r;return r+=2,t.forEach(function(n){e[r++]=n.length,n.copy(e,r,0,n.length),r+=n.length}),e.writeUInt16BE(r-s-2,s),No.encode.bytes=r-s,e};No.encode.bytes=0;No.decode=function(t,e){e||(e=0);let r=e,s=t.readUInt16BE(e);e+=2;let n=[];for(;s>0;){let i=t[e++];if(--s,s<i)throw new Error("Buffer overflow");n.push(t.slice(e,e+i)),e+=i,s-=i}return No.decode.bytes=e-r,n};No.decode.bytes=0;No.encodingLength=function(t){Array.isArray(t)||(t=[t]);let e=2;return t.forEach(function(r){typeof r=="string"?e+=Ze.byteLength(r)+1:e+=r.length+1}),e};var Uo=Qe.null={};Uo.encode=function(t,e,r){e||(e=Ze.alloc(Uo.encodingLength(t))),r||(r=0),typeof t=="string"&&(t=Ze.from(t)),t||(t=Ze.alloc(0));let s=r;r+=2;let n=t.length;return t.copy(e,r,0,n),r+=n,e.writeUInt16BE(r-s-2,s),Uo.encode.bytes=r-s,e};Uo.encode.bytes=0;Uo.decode=function(t,e){e||(e=0);let r=e,s=t.readUInt16BE(e);e+=2;let n=t.slice(e,e+s);return e+=s,Uo.decode.bytes=e-r,n};Uo.decode.bytes=0;Uo.encodingLength=function(t){return t?(Ze.isBuffer(t)?t.length:Ze.byteLength(t))+2:2};var Mo=Qe.hinfo={};Mo.encode=function(t,e,r){e||(e=Ze.alloc(Mo.encodingLength(t))),r||(r=0);let s=r;return r+=2,St.encode(t.cpu,e,r),r+=St.encode.bytes,St.encode(t.os,e,r),r+=St.encode.bytes,e.writeUInt16BE(r-s-2,s),Mo.encode.bytes=r-s,e};Mo.encode.bytes=0;Mo.decode=function(t,e){e||(e=0);let r=e,s={};return e+=2,s.cpu=St.decode(t,e),e+=St.decode.bytes,s.os=St.decode(t,e),e+=St.decode.bytes,Mo.decode.bytes=e-r,s};Mo.decode.bytes=0;Mo.encodingLength=function(t){return St.encodingLength(t.cpu)+St.encodingLength(t.os)+2};var $n=Qe.ptr={},aZ=Qe.cname=$n,cZ=Qe.dname=$n;$n.encode=function(t,e,r){return e||(e=Ze.alloc($n.encodingLength(t))),r||(r=0),Ie.encode(t,e,r+2),e.writeUInt16BE(Ie.encode.bytes,r),$n.encode.bytes=Ie.encode.bytes+2,e};$n.encode.bytes=0;$n.decode=function(t,e){e||(e=0);let r=Ie.decode(t,e+2);return $n.decode.bytes=Ie.decode.bytes+2,r};$n.decode.bytes=0;$n.encodingLength=function(t){return Ie.encodingLength(t)+2};var jo=Qe.srv={};jo.encode=function(t,e,r){e||(e=Ze.alloc(jo.encodingLength(t))),r||(r=0),e.writeUInt16BE(t.priority||0,r+2),e.writeUInt16BE(t.weight||0,r+4),e.writeUInt16BE(t.port||0,r+6),Ie.encode(t.target,e,r+8);let s=Ie.encode.bytes+6;return e.writeUInt16BE(s,r),jo.encode.bytes=s+2,e};jo.encode.bytes=0;jo.decode=function(t,e){e||(e=0);let r=t.readUInt16BE(e),s={};return s.priority=t.readUInt16BE(e+2),s.weight=t.readUInt16BE(e+4),s.port=t.readUInt16BE(e+6),s.target=Ie.decode(t,e+8),jo.decode.bytes=r+2,s};jo.decode.bytes=0;jo.encodingLength=function(t){return 8+Ie.encodingLength(t.target)};var Ws=Qe.caa={};Ws.ISSUER_CRITICAL=128;Ws.encode=function(t,e,r){let s=Ws.encodingLength(t);return e||(e=Ze.alloc(Ws.encodingLength(t))),r||(r=0),t.issuerCritical&&(t.flags=Ws.ISSUER_CRITICAL),e.writeUInt16BE(s-2,r),r+=2,e.writeUInt8(t.flags||0,r),r+=1,St.encode(t.tag,e,r),r+=St.encode.bytes,e.write(t.value,r),r+=Ze.byteLength(t.value),Ws.encode.bytes=s,e};Ws.encode.bytes=0;Ws.decode=function(t,e){e||(e=0);let r=t.readUInt16BE(e);e+=2;let s=e,n={};return n.flags=t.readUInt8(e),e+=1,n.tag=St.decode(t,e),e+=St.decode.bytes,n.value=t.toString("utf-8",e,s+r),n.issuerCritical=!!(n.flags&Ws.ISSUER_CRITICAL),Ws.decode.bytes=r+2,n};Ws.decode.bytes=0;Ws.encodingLength=function(t){return St.encodingLength(t.tag)+St.encodingLength(t.value)+2};var oc=Qe.mx={};oc.encode=function(t,e,r){e||(e=Ze.alloc(oc.encodingLength(t))),r||(r=0);let s=r;return r+=2,e.writeUInt16BE(t.preference||0,r),r+=2,Ie.encode(t.exchange,e,r),r+=Ie.encode.bytes,e.writeUInt16BE(r-s-2,s),oc.encode.bytes=r-s,e};oc.encode.bytes=0;oc.decode=function(t,e){e||(e=0);let r=e,s={};return e+=2,s.preference=t.readUInt16BE(e),e+=2,s.exchange=Ie.decode(t,e),e+=Ie.decode.bytes,oc.decode.bytes=e-r,s};oc.encodingLength=function(t){return 4+Ie.encodingLength(t.exchange)};var $o=Qe.a={};$o.encode=function(t,e,r){return e||(e=Ze.alloc($o.encodingLength(t))),r||(r=0),e.writeUInt16BE(4,r),r+=2,cl.v4.encode(t,e,r),$o.encode.bytes=6,e};$o.encode.bytes=0;$o.decode=function(t,e){e||(e=0),e+=2;let r=cl.v4.decode(t,e);return $o.decode.bytes=6,r};$o.decode.bytes=0;$o.encodingLength=function(){return 6};var Fo=Qe.aaaa={};Fo.encode=function(t,e,r){return e||(e=Ze.alloc(Fo.encodingLength(t))),r||(r=0),e.writeUInt16BE(16,r),r+=2,cl.v6.encode(t,e,r),Fo.encode.bytes=18,e};Fo.encode.bytes=0;Fo.decode=function(t,e){e||(e=0),e+=2;let r=cl.v6.decode(t,e);return Fo.decode.bytes=18,r};Fo.decode.bytes=0;Fo.encodingLength=function(){return 18};var Bs=Qe.option={};Bs.encode=function(t,e,r){e||(e=Ze.alloc(Bs.encodingLength(t))),r||(r=0);let s=r,n=mT.toCode(t.code);if(e.writeUInt16BE(n,r),r+=2,t.data)e.writeUInt16BE(t.data.length,r),r+=2,t.data.copy(e,r),r+=t.data.length;else switch(n){case 8:let i=t.sourcePrefixLength||0,o=t.family||cl.familyOf(t.ip),a=cl.encode(t.ip,Ze.alloc),c=Math.ceil(i/8);e.writeUInt16BE(c+4,r),r+=2,e.writeUInt16BE(o,r),r+=2,e.writeUInt8(i,r++),e.writeUInt8(t.scopePrefixLength||0,r++),a.copy(e,r,0,c),r+=c;break;case 11:t.timeout?(e.writeUInt16BE(2,r),r+=2,e.writeUInt16BE(t.timeout,r),r+=2):(e.writeUInt16BE(0,r),r+=2);break;case 12:let d=t.length||0;e.writeUInt16BE(d,r),r+=2,e.fill(0,r,r+d),r+=d;break;case 14:let u=t.tags.length*2;e.writeUInt16BE(u,r),r+=2;for(let l of t.tags)e.writeUInt16BE(l,r),r+=2;break;default:throw new Error(`Unknown roption code: ${t.code}`)}return Bs.encode.bytes=r-s,e};Bs.encode.bytes=0;Bs.decode=function(t,e){e||(e=0);let r={};r.code=t.readUInt16BE(e),r.type=mT.toString(r.code),e+=2;let s=t.readUInt16BE(e);switch(e+=2,r.data=t.slice(e,e+s),r.code){case 8:r.family=t.readUInt16BE(e),e+=2,r.sourcePrefixLength=t.readUInt8(e++),r.scopePrefixLength=t.readUInt8(e++);let n=Ze.alloc(r.family===1?4:16);t.copy(n,0,e,e+s-4),r.ip=cl.decode(n);break;case 11:s>0&&(r.timeout=t.readUInt16BE(e),e+=2);break;case 14:r.tags=[];for(let i=0;i<s;i+=2)r.tags.push(t.readUInt16BE(e)),e+=2}return Bs.decode.bytes=s+4,r};Bs.decode.bytes=0;Bs.encodingLength=function(t){if(t.data)return t.data.length+4;switch(mT.toCode(t.code)){case 8:let r=t.sourcePrefixLength||0;return Math.ceil(r/8)+8;case 11:return typeof t.timeout=="number"?6:4;case 12:return t.length+4;case 14:return 4+t.tags.length*2}throw new Error(`Unknown roption code: ${t.code}`)};var Gs=Qe.opt={};Gs.encode=function(t,e,r){e||(e=Ze.alloc(Gs.encodingLength(t))),r||(r=0);let s=r,n=wh(t,Bs);return e.writeUInt16BE(n,r),r=om(t,Bs,e,r+2),Gs.encode.bytes=r-s,e};Gs.encode.bytes=0;Gs.decode=function(t,e){e||(e=0);let r=e,s=[],n=t.readUInt16BE(e);e+=2;let i=0;for(;n>0;)s[i++]=Bs.decode(t,e),e+=Bs.decode.bytes,n-=Bs.decode.bytes;return Gs.decode.bytes=e-r,s};Gs.decode.bytes=0;Gs.encodingLength=function(t){return 2+wh(t||[],Bs)};var gs=Qe.dnskey={};gs.PROTOCOL_DNSSEC=3;gs.ZONE_KEY=128;gs.SECURE_ENTRYPOINT=32768;gs.encode=function(t,e,r){e||(e=Ze.alloc(gs.encodingLength(t))),r||(r=0);let s=r,n=t.key;if(!Ze.isBuffer(n))throw new Error("Key must be a Buffer");return r+=2,e.writeUInt16BE(t.flags,r),r+=2,e.writeUInt8(gs.PROTOCOL_DNSSEC,r),r+=1,e.writeUInt8(t.algorithm,r),r+=1,n.copy(e,r,0,n.length),r+=n.length,gs.encode.bytes=r-s,e.writeUInt16BE(gs.encode.bytes-2,s),e};gs.encode.bytes=0;gs.decode=function(t,e){e||(e=0);let r=e;var s={},n=t.readUInt16BE(e);if(e+=2,s.flags=t.readUInt16BE(e),e+=2,t.readUInt8(e)!==gs.PROTOCOL_DNSSEC)throw new Error("Protocol must be 3");return e+=1,s.algorithm=t.readUInt8(e),e+=1,s.key=t.slice(e,r+n+2),e+=s.key.length,gs.decode.bytes=e-r,s};gs.decode.bytes=0;gs.encodingLength=function(t){return 6+Ze.byteLength(t.key)};var Bi=Qe.rrsig={};Bi.encode=function(t,e,r){e||(e=Ze.alloc(Bi.encodingLength(t))),r||(r=0);let s=r,n=t.signature;if(!Ze.isBuffer(n))throw new Error("Signature must be a Buffer");return r+=2,e.writeUInt16BE(Ho.toType(t.typeCovered),r),r+=2,e.writeUInt8(t.algorithm,r),r+=1,e.writeUInt8(t.labels,r),r+=1,e.writeUInt32BE(t.originalTTL,r),r+=4,e.writeUInt32BE(t.expiration,r),r+=4,e.writeUInt32BE(t.inception,r),r+=4,e.writeUInt16BE(t.keyTag,r),r+=2,Ie.encode(t.signersName,e,r),r+=Ie.encode.bytes,n.copy(e,r,0,n.length),r+=n.length,Bi.encode.bytes=r-s,e.writeUInt16BE(Bi.encode.bytes-2,s),e};Bi.encode.bytes=0;Bi.decode=function(t,e){e||(e=0);let r=e;var s={},n=t.readUInt16BE(e);return e+=2,s.typeCovered=Ho.toString(t.readUInt16BE(e)),e+=2,s.algorithm=t.readUInt8(e),e+=1,s.labels=t.readUInt8(e),e+=1,s.originalTTL=t.readUInt32BE(e),e+=4,s.expiration=t.readUInt32BE(e),e+=4,s.inception=t.readUInt32BE(e),e+=4,s.keyTag=t.readUInt16BE(e),e+=2,s.signersName=Ie.decode(t,e),e+=Ie.decode.bytes,s.signature=t.slice(e,r+n+2),e+=s.signature.length,Bi.decode.bytes=e-r,s};Bi.decode.bytes=0;Bi.encodingLength=function(t){return 20+Ie.encodingLength(t.signersName)+Ze.byteLength(t.signature)};var Li=Qe.rp={};Li.encode=function(t,e,r){e||(e=Ze.alloc(Li.encodingLength(t))),r||(r=0);let s=r;return r+=2,Ie.encode(t.mbox||".",e,r,{mail:!0}),r+=Ie.encode.bytes,Ie.encode(t.txt||".",e,r),r+=Ie.encode.bytes,Li.encode.bytes=r-s,e.writeUInt16BE(Li.encode.bytes-2,s),e};Li.encode.bytes=0;Li.decode=function(t,e){e||(e=0);let r=e,s={};return e+=2,s.mbox=Ie.decode(t,e,{mail:!0})||".",e+=Ie.decode.bytes,s.txt=Ie.decode(t,e)||".",e+=Ie.decode.bytes,Li.decode.bytes=e-r,s};Li.decode.bytes=0;Li.encodingLength=function(t){return 2+Ie.encodingLength(t.mbox||".")+Ie.encodingLength(t.txt||".")};var Mr={};Mr.encode=function(t,e,r){e||(e=Ze.alloc(Mr.encodingLength(t))),r||(r=0);let s=r;for(var n=[],i=0;i<t.length;i++){var o=Ho.toType(t[i]);n[o>>8]===void 0&&(n[o>>8]=[]),n[o>>8][o>>3&31]|=1<<7-(o&7)}for(i=0;i<n.length;i++)if(n[i]!==void 0){var a=Ze.from(n[i]);e.writeUInt8(i,r),r+=1,e.writeUInt8(a.length,r),r+=1,a.copy(e,r),r+=a.length}return Mr.encode.bytes=r-s,e};Mr.encode.bytes=0;Mr.decode=function(t,e,r){e||(e=0);let s=e;for(var n=[];e-s<r;){var i=t.readUInt8(e);e+=1;var o=t.readUInt8(e);e+=1;for(var a=0;a<o;a++)for(var c=t.readUInt8(e+a),d=0;d<8;d++)if(c&1<<7-d){var u=Ho.toString(i<<8|a<<3|d);n.push(u)}e+=o}return Mr.decode.bytes=e-s,n};Mr.decode.bytes=0;Mr.encodingLength=function(t){for(var e=[],r=0;r<t.length;r++){var s=Ho.toType(t[r]);e[s>>8]=Math.max(e[s>>8]||0,s&255)}var n=0;for(r=0;r<e.length;r++)e[r]!==void 0&&(n+=2+Math.ceil((e[r]+1)/8));return n};var Oi=Qe.nsec={};Oi.encode=function(t,e,r){e||(e=Ze.alloc(Oi.encodingLength(t))),r||(r=0);let s=r;return r+=2,Ie.encode(t.nextDomain,e,r),r+=Ie.encode.bytes,Mr.encode(t.rrtypes,e,r),r+=Mr.encode.bytes,Oi.encode.bytes=r-s,e.writeUInt16BE(Oi.encode.bytes-2,s),e};Oi.encode.bytes=0;Oi.decode=function(t,e){e||(e=0);let r=e;var s={},n=t.readUInt16BE(e);return e+=2,s.nextDomain=Ie.decode(t,e),e+=Ie.decode.bytes,s.rrtypes=Mr.decode(t,e,n-(e-r)),e+=Mr.decode.bytes,Oi.decode.bytes=e-r,s};Oi.decode.bytes=0;Oi.encodingLength=function(t){return 2+Ie.encodingLength(t.nextDomain)+Mr.encodingLength(t.rrtypes)};var Ni=Qe.nsec3={};Ni.encode=function(t,e,r){e||(e=Ze.alloc(Ni.encodingLength(t))),r||(r=0);let s=r,n=t.salt;if(!Ze.isBuffer(n))throw new Error("salt must be a Buffer");let i=t.nextDomain;if(!Ze.isBuffer(i))throw new Error("nextDomain must be a Buffer");return r+=2,e.writeUInt8(t.algorithm,r),r+=1,e.writeUInt8(t.flags,r),r+=1,e.writeUInt16BE(t.iterations,r),r+=2,e.writeUInt8(n.length,r),r+=1,n.copy(e,r,0,n.length),r+=n.length,e.writeUInt8(i.length,r),r+=1,i.copy(e,r,0,i.length),r+=i.length,Mr.encode(t.rrtypes,e,r),r+=Mr.encode.bytes,Ni.encode.bytes=r-s,e.writeUInt16BE(Ni.encode.bytes-2,s),e};Ni.encode.bytes=0;Ni.decode=function(t,e){e||(e=0);let r=e;var s={},n=t.readUInt16BE(e);e+=2,s.algorithm=t.readUInt8(e),e+=1,s.flags=t.readUInt8(e),e+=1,s.iterations=t.readUInt16BE(e),e+=2;let i=t.readUInt8(e);e+=1,s.salt=t.slice(e,e+i),e+=i;let o=t.readUInt8(e);return e+=1,s.nextDomain=t.slice(e,e+o),e+=o,s.rrtypes=Mr.decode(t,e,n-(e-r)),e+=Mr.decode.bytes,Ni.decode.bytes=e-r,s};Ni.decode.bytes=0;Ni.encodingLength=function(t){return 8+t.salt.length+t.nextDomain.length+Mr.encodingLength(t.rrtypes)};var Ui=Qe.ds={};Ui.encode=function(t,e,r){e||(e=Ze.alloc(Ui.encodingLength(t))),r||(r=0);let s=r,n=t.digest;if(!Ze.isBuffer(n))throw new Error("Digest must be a Buffer");return r+=2,e.writeUInt16BE(t.keyTag,r),r+=2,e.writeUInt8(t.algorithm,r),r+=1,e.writeUInt8(t.digestType,r),r+=1,n.copy(e,r,0,n.length),r+=n.length,Ui.encode.bytes=r-s,e.writeUInt16BE(Ui.encode.bytes-2,s),e};Ui.encode.bytes=0;Ui.decode=function(t,e){e||(e=0);let r=e;var s={},n=t.readUInt16BE(e);return e+=2,s.keyTag=t.readUInt16BE(e),e+=2,s.algorithm=t.readUInt8(e),e+=1,s.digestType=t.readUInt8(e),e+=1,s.digest=t.slice(e,r+n+2),e+=s.digest.length,Ui.decode.bytes=e-r,s};Ui.decode.bytes=0;Ui.encodingLength=function(t){return 6+Ze.byteLength(t.digest)};var Ks=Qe.sshfp={};Ks.getFingerprintLengthForHashType=function(e){switch(e){case 1:return 20;case 2:return 32}};Ks.encode=function(e,r,s){r||(r=Ze.alloc(Ks.encodingLength(e))),s||(s=0);let n=s;s+=2,r[s]=e.algorithm,s+=1,r[s]=e.hash,s+=1;let i=Ze.from(e.fingerprint.toUpperCase(),"hex");if(i.length!==Ks.getFingerprintLengthForHashType(e.hash))throw new Error("Invalid fingerprint length");return i.copy(r,s),s+=i.byteLength,Ks.encode.bytes=s-n,r.writeUInt16BE(Ks.encode.bytes-2,n),r};Ks.encode.bytes=0;Ks.decode=function(e,r){r||(r=0);let s=r,n={};r+=2,n.algorithm=e[r],r+=1,n.hash=e[r],r+=1;let i=Ks.getFingerprintLengthForHashType(n.hash);return n.fingerprint=e.slice(r,r+i).toString("hex").toUpperCase(),r+=i,Ks.decode.bytes=r-s,n};Ks.decode.bytes=0;Ks.encodingLength=function(t){return 4+Ze.from(t.fingerprint,"hex").byteLength};var Mi=Qe.naptr={};Mi.encode=function(t,e,r){e||(e=Ze.alloc(Mi.encodingLength(t))),r||(r=0);let s=r;return r+=2,e.writeUInt16BE(t.order||0,r),r+=2,e.writeUInt16BE(t.preference||0,r),r+=2,St.encode(t.flags,e,r),r+=St.encode.bytes,St.encode(t.services,e,r),r+=St.encode.bytes,St.encode(t.regexp,e,r),r+=St.encode.bytes,Ie.encode(t.replacement,e,r),r+=Ie.encode.bytes,Mi.encode.bytes=r-s,e.writeUInt16BE(Mi.encode.bytes-2,s),e};Mi.encode.bytes=0;Mi.decode=function(t,e){e||(e=0);let r=e,s={};return e+=2,s.order=t.readUInt16BE(e),e+=2,s.preference=t.readUInt16BE(e),e+=2,s.flags=St.decode(t,e),e+=St.decode.bytes,s.services=St.decode(t,e),e+=St.decode.bytes,s.regexp=St.decode(t,e),e+=St.decode.bytes,s.replacement=Ie.decode(t,e),e+=Ie.decode.bytes,Mi.decode.bytes=e-r,s};Mi.decode.bytes=0;Mi.encodingLength=function(t){return St.encodingLength(t.flags)+St.encodingLength(t.services)+St.encodingLength(t.regexp)+Ie.encodingLength(t.replacement)+6};var ji=Qe.tlsa={};ji.encode=function(t,e,r){e||(e=Ze.alloc(ji.encodingLength(t))),r||(r=0);let s=r,n=t.certificate;if(!Ze.isBuffer(n))throw new Error("Certificate must be a Buffer");return r+=2,e.writeUInt8(t.usage,r),r+=1,e.writeUInt8(t.selector,r),r+=1,e.writeUInt8(t.matchingType,r),r+=1,n.copy(e,r,0,n.length),r+=n.length,ji.encode.bytes=r-s,e.writeUInt16BE(ji.encode.bytes-2,s),e};ji.encode.bytes=0;ji.decode=function(t,e){e||(e=0);let r=e,s={},n=t.readUInt16BE(e);return e+=2,s.usage=t.readUInt8(e),e+=1,s.selector=t.readUInt8(e),e+=1,s.matchingType=t.readUInt8(e),e+=1,s.certificate=t.slice(e,r+n+2),e+=s.certificate.length,ji.decode.bytes=e-r,s};ji.decode.bytes=0;ji.encodingLength=function(t){return 5+Ze.byteLength(t.certificate)};var yT=Qe.record=function(t){switch(t.toUpperCase()){case"A":return $o;case"PTR":return $n;case"CNAME":return aZ;case"DNAME":return cZ;case"TXT":return No;case"NULL":return Uo;case"AAAA":return Fo;case"SRV":return jo;case"HINFO":return Mo;case"CAA":return Ws;case"NS":return Lo;case"SOA":return Oo;case"MX":return oc;case"OPT":return Gs;case"DNSKEY":return gs;case"RRSIG":return Bi;case"RP":return Li;case"NSEC":return Oi;case"NSEC3":return Ni;case"SSHFP":return Ks;case"DS":return Ui;case"NAPTR":return Mi;case"TLSA":return ji}return Bo},Xr=Qe.answer={};Xr.encode=function(t,e,r){e||(e=Ze.alloc(Xr.encodingLength(t))),r||(r=0);let s=r;if(Ie.encode(t.name,e,r),r+=Ie.encode.bytes,e.writeUInt16BE(Ho.toType(t.type),r),t.type.toUpperCase()==="OPT"){if(t.name!==".")throw new Error("OPT name must be root.");e.writeUInt16BE(t.udpPayloadSize||4096,r+2),e.writeUInt8(t.extendedRcode||0,r+4),e.writeUInt8(t.ednsVersion||0,r+5),e.writeUInt16BE(t.flags||0,r+6),r+=8,Gs.encode(t.options||[],e,r),r+=Gs.encode.bytes}else{let n=kw.toClass(t.class===void 0?"IN":t.class);t.flush&&(n|=gT),e.writeUInt16BE(n,r+2),e.writeUInt32BE(t.ttl||0,r+4),r+=8;let i=yT(t.type);i.encode(t.data,e,r),r+=i.encode.bytes}return Xr.encode.bytes=r-s,e};Xr.encode.bytes=0;Xr.decode=function(t,e){e||(e=0);let r={},s=e;if(r.name=Ie.decode(t,e),e+=Ie.decode.bytes,r.type=Ho.toString(t.readUInt16BE(e)),r.type==="OPT")r.udpPayloadSize=t.readUInt16BE(e+2),r.extendedRcode=t.readUInt8(e+4),r.ednsVersion=t.readUInt8(e+5),r.flags=t.readUInt16BE(e+6),r.flag_do=(r.flags>>15&1)===1,r.options=Gs.decode(t,e+8),e+=8+Gs.decode.bytes;else{let n=t.readUInt16BE(e+2);r.ttl=t.readUInt32BE(e+4),r.class=kw.toString(n&iZ),r.flush=!!(n&gT);let i=yT(r.type);r.data=i.decode(t,e+8),e+=8+i.decode.bytes}return Xr.decode.bytes=e-s,r};Xr.decode.bytes=0;Xr.encodingLength=function(t){let e=t.data!==null&&t.data!==void 0?t.data:t.options;return Ie.encodingLength(t.name)+8+yT(t.type).encodingLength(e)};var Fn=Qe.question={};Fn.encode=function(t,e,r){e||(e=Ze.alloc(Fn.encodingLength(t))),r||(r=0);let s=r;return Ie.encode(t.name,e,r),r+=Ie.encode.bytes,e.writeUInt16BE(Ho.toType(t.type),r),r+=2,e.writeUInt16BE(kw.toClass(t.class===void 0?"IN":t.class),r),r+=2,Fn.encode.bytes=r-s,t};Fn.encode.bytes=0;Fn.decode=function(t,e){e||(e=0);let r=e,s={};return s.name=Ie.decode(t,e),e+=Ie.decode.bytes,s.type=Ho.toString(t.readUInt16BE(e)),e+=2,s.class=kw.toString(t.readUInt16BE(e)),e+=2,s.class&PN&&(s.class&=oZ),Fn.decode.bytes=e-r,s};Fn.decode.bytes=0;Fn.encodingLength=function(t){return Ie.encodingLength(t.name)+4};Qe.AUTHORITATIVE_ANSWER=1024;Qe.TRUNCATED_RESPONSE=512;Qe.RECURSION_DESIRED=256;Qe.RECURSION_AVAILABLE=128;Qe.AUTHENTIC_DATA=32;Qe.CHECKING_DISABLED=16;Qe.DNSSEC_OK=32768;Qe.encode=function(t,e,r){let s=!e;s&&(e=Ze.alloc(Qe.encodingLength(t))),r||(r=0);let n=r;return t.questions||(t.questions=[]),t.answers||(t.answers=[]),t.authorities||(t.authorities=[]),t.additionals||(t.additionals=[]),Hn.encode(t,e,r),r+=Hn.encode.bytes,r=om(t.questions,Fn,e,r),r=om(t.answers,Xr,e,r),r=om(t.authorities,Xr,e,r),r=om(t.additionals,Xr,e,r),Qe.encode.bytes=r-n,s&&Qe.encode.bytes!==e.length?e.slice(0,Qe.encode.bytes):e};Qe.encode.bytes=0;Qe.decode=function(t,e){e||(e=0);let r=e,s=Hn.decode(t,e);return e+=Hn.decode.bytes,e=Tw(s.questions,Fn,t,e),e=Tw(s.answers,Xr,t,e),e=Tw(s.authorities,Xr,t,e),e=Tw(s.additionals,Xr,t,e),Qe.decode.bytes=e-r,s};Qe.decode.bytes=0;Qe.encodingLength=function(t){return Hn.encodingLength(t)+wh(t.questions||[],Fn)+wh(t.answers||[],Xr)+wh(t.authorities||[],Xr)+wh(t.additionals||[],Xr)};Qe.streamEncode=function(t){let e=Qe.encode(t),r=Ze.alloc(2);r.writeUInt16BE(e.byteLength);let s=Ze.concat([r,e]);return Qe.streamEncode.bytes=s.byteLength,s};Qe.streamEncode.bytes=0;Qe.streamDecode=function(t){let e=t.readUInt16BE(0);if(t.byteLength<e+2)return null;let r=Qe.decode(t.slice(2));return Qe.streamDecode.bytes=Qe.decode.bytes,r};Qe.streamDecode.bytes=0;function wh(t,e){let r=0;for(let s=0;s<t.length;s++)r+=e.encodingLength(t[s]);return r}function om(t,e,r,s){for(let n=0;n<t.length;n++)e.encode(t[n],r,s),s+=e.encode.bytes;return s}function Tw(t,e,r,s){for(let n=0;n<t.length;n++)t[n]=e.decode(r,s),s+=e.decode.bytes;return s}});var ON=Me((nDe,LN)=>{"use strict";g();y();var BN=pZ;process.nextTick(fZ,42);LN.exports=dZ;function dZ(t){var e=s;return r;function r(n){e(n||uZ)}function s(n){var i=[n];e=o,t(a);function o(c){i.push(c)}function a(c){var d=arguments;for(e=lZ(c)?s:u;i.length;)u(i.shift());function u(l){BN(hZ,l,d)}}}}function lZ(t){return Object.prototype.toString.call(t)==="[object Error]"}function uZ(){}function hZ(t,e){t.apply(null,e)}function fZ(t){t===42&&(BN=process.nextTick)}function pZ(t,e,r){process.nextTick(function(){t(e,r)})}});var MN=Me((aDe,UN)=>{"use strict";g();y();var bT=DN(),mZ=require("dgram"),gZ=ON(),yZ=require("events"),wT=require("os"),xT=function(){};UN.exports=function(t){t||(t={});var e=new yZ.EventEmitter,r=typeof t.port=="number"?t.port:5353,s=t.type||"udp4",n=t.ip||t.host||(s==="udp4"?"224.0.0.251":null),i={address:n,port:r},o={},a=!1,c=null;if(s==="udp6"&&(!n||!t.interface))throw new Error("For IPv6 multicast you must specify `ip` and `interface`");var d=t.socket||mZ.createSocket({type:s,reuseAddr:t.reuseAddr!==!1,toString:function(){return s}});d.on("error",function(l){l.code==="EACCES"||l.code==="EADDRINUSE"?e.emit("error",l):e.emit("warning",l)}),d.on("message",function(l,h){try{l=bT.decode(l)}catch(p){e.emit("warning",p);return}e.emit("packet",l,h),l.type==="query"&&e.emit("query",l,h),l.type==="response"&&e.emit("response",l,h)}),d.on("listening",function(){r||(r=i.port=d.address().port),t.multicast!==!1&&(e.update(),c=setInterval(e.update,5e3),d.setMulticastTTL(t.ttl||255),d.setMulticastLoopback(t.loopback!==!1))});var u=gZ(function(l){if(!r||t.bind===!1)return l(null);d.once("error",l),d.bind(r,t.bind||t.interface,function(){d.removeListener("error",l),l(null)})});return u(function(l){if(l)return e.emit("error",l);e.emit("ready")}),e.send=function(l,h,p){if(typeof h=="function")return e.send(l,null,h);p||(p=xT),h?!h.host&&!h.address&&(h.address=i.address):h=i,u(m);function m(_){if(a)return p();if(_)return p(_);var f=bT.encode(l);d.send(f,0,f.length,h.port,h.address||h.host,p)}},e.response=e.respond=function(l,h,p){Array.isArray(l)&&(l={answers:l}),l.type="response",l.flags=(l.flags||0)|bT.AUTHORITATIVE_ANSWER,e.send(l,h,p)},e.query=function(l,h,p,m){if(typeof h=="function")return e.query(l,null,null,h);if(typeof h=="object"&&h&&h.port)return e.query(l,null,h,p);if(typeof p=="function")return e.query(l,h,null,p);m||(m=xT),typeof l=="string"&&(l=[{name:l,type:h||"ANY"}]),Array.isArray(l)&&(l={type:"query",questions:l}),l.type="query",e.send(l,p,m)},e.destroy=function(l){if(l||(l=xT),a)return process.nextTick(l);a=!0,clearInterval(c);for(var h in o)try{d.dropMembership(n,h)}catch{}o={},d.close(l)},e.update=function(){for(var l=t.interface?[].concat(t.interface):xZ(),h=!1,p=0;p<l.length;p++){var m=l[p];if(!o[m])try{d.addMembership(n,m),o[m]=!0,h=!0}catch(_){e.emit("warning",_)}}if(h){if(d.setMulticastInterface)try{d.setMulticastInterface(t.interface||bZ())}catch(_){e.emit("warning",_)}e.emit("networkInterface")}},e};function bZ(){for(var t=wT.networkInterfaces(),e=Object.keys(t),r=0;r<e.length;r++)for(var s=t[e[r]],n=0;n<s.length;n++){var i=s[n];if(NN(i.family)&&!i.internal)return wT.platform()==="darwin"&&e[r]==="en0"?i.address:"0.0.0.0"}return"127.0.0.1"}function xZ(){for(var t=wT.networkInterfaces(),e=Object.keys(t),r=[],s=0;s<e.length;s++)for(var n=t[e[s]],i=0;i<n.length;i++){var o=n[i];if(NN(o.family)){r.push(o.address);break}}return r}function NN(t){return t===4||t==="IPv4"}});var U$={};sa(U$,{AV1Obu:()=>U7,AV1RtpPayload:()=>qT,AttributeKeys:()=>Fee,BitStream:()=>fc,BitWriter:()=>Dm,BitWriter2:()=>u1,BufferChain:()=>SZ,CONSENT_FAILURES:()=>mk,CONSENT_INTERVAL:()=>uj,COOKIE:()=>_1,Candidate:()=>gc,CandidatePair:()=>fk,CandidatePairState:()=>hj,CipherContext:()=>Nm,CipherSuite:()=>Qw,CipherSuiteList:()=>i7,Connection:()=>wj,ConnectionStates:()=>vre,CurveType:()=>Yk,DEFAULT_MAX_MESSAGE_SIZE:()=>Ih,DePacketizerBase:()=>pee,Directions:()=>Fw,DtlsClient:()=>ik,DtlsServer:()=>jM,DtlsSocket:()=>oA,DtlsStates:()=>Nte,Event:()=>Ne,EventDisposer:()=>QU,ExtensionProfiles:()=>uc,FINGERPRINT_LENGTH:()=>$M,FINGERPRINT_XOR:()=>FM,GenericNack:()=>Hm,GroupDescription:()=>Bh,H264RtpPayload:()=>F7,HEADER_LENGTH:()=>zo,HashAlgorithm:()=>Om,ICE_COMPLETED:()=>pk,ICE_FAILED:()=>Tm,INTEGRITY_LENGTH:()=>aA,IPV4_PROTOCOL:()=>cA,IPV6_PROTOCOL:()=>dA,IceCandidate:()=>OA,IceGathererStates:()=>Hte,IceTransportStates:()=>Fte,Inactive:()=>Uj,Int:()=>jm,MediaDescription:()=>d1,MediaStream:()=>Mj,MediaStreamTrack:()=>Km,MediaStreamTrackFactory:()=>Rte,Message:()=>wn,NalUnitType:()=>lc,NamedCurveAlgorithm:()=>Xo,NamedCurveAlgorithmList:()=>Xk,OpusRtpPayload:()=>q7,PacketChunk:()=>tM,PacketResult:()=>sM,PacketStatus:()=>rM,PictureLossIndication:()=>$m,Profiles:()=>cee,PromiseQueue:()=>PZ,ProtectionProfileAeadAes128Gcm:()=>_l,ProtectionProfileAes128CmHmacSha1_80:()=>Hh,RETRY_MAX:()=>HM,RETRY_RTO:()=>qM,RTCCertificate:()=>LA,RTCDataChannel:()=>bA,RTCDataChannelParameters:()=>xA,RTCDtlsFingerprint:()=>o1,RTCDtlsParameters:()=>a1,RTCDtlsTransport:()=>vk,RTCIceCandidate:()=>t$,RTCIceGatherer:()=>Zj,RTCIceParameters:()=>NA,RTCIceTransport:()=>Qj,RTCP_HEADER_SIZE:()=>t1,RTCPeerConnection:()=>yre,RTCRtcpFeedback:()=>Ej,RTCRtcpParameters:()=>cte,RTCRtpCodecParameters:()=>yc,RTCRtpCodingParameters:()=>Tj,RTCRtpHeaderExtensionParameters:()=>Wi,RTCRtpReceiver:()=>FA,RTCRtpRtxParameters:()=>Cj,RTCRtpSender:()=>D$,RTCRtpSimulcastParameters:()=>wA,RTCRtpTransceiver:()=>Nj,RTCSctpCapabilities:()=>MA,RTCSctpTransport:()=>k$,RTCSessionDescription:()=>R$,RTCStatsReport:()=>Oj,RTP_EXTENSION_URI:()=>Qt,ReceiverEstimatedMaxBitrate:()=>Fm,RecvDelta:()=>Im,Recvonly:()=>TA,Red:()=>sA,RedEncoder:()=>SM,RedHandler:()=>EM,RedHeader:()=>tk,RtcpHeader:()=>Qo,RtcpPacketConverter:()=>cM,RtcpPayloadSpecificFeedback:()=>Oh,RtcpReceiverInfo:()=>v1,RtcpRrPacket:()=>Nh,RtcpSenderInfo:()=>rA,RtcpSourceDescriptionPacket:()=>Vm,RtcpSrPacket:()=>bl,RtcpTransportLayerFeedback:()=>yl,RtpBuilder:()=>Dee,RtpHeader:()=>Yo,RtpPacket:()=>Jo,RtpRouter:()=>P$,RunLengthChunk:()=>Dh,SDPManager:()=>L$,Sendonly:()=>CA,Sendrecv:()=>kA,SessionDescription:()=>Pm,SignalingStates:()=>wre,SignatureAlgorithm:()=>zi,SignatureScheme:()=>OT,SourceDescriptionChunk:()=>eA,SourceDescriptionItem:()=>tA,SrtcpSession:()=>LM,SrtpAuthenticationError:()=>xl,SrtpContext:()=>Um,SrtpSession:()=>OM,SsrcDescription:()=>l1,StatusVectorChunk:()=>Z7,StunOverTurnProtocol:()=>ej,StunProtocol:()=>r1,TcpTransport:()=>s7,TransceiverManager:()=>N$,TransportWideCC:()=>qm,TurnProtocol:()=>rj,UdpTransport:()=>Jw,Vp8RtpPayload:()=>z7,Vp9RtpPayload:()=>K7,WeriftError:()=>BZ,addSDPHeader:()=>Uk,andDirection:()=>PA,buffer2ArrayBuffer:()=>CZ,bufferArrayXor:()=>vZ,bufferReader:()=>bs,bufferWriter:()=>nr,bufferWriterLE:()=>FU,bufferXor:()=>wZ,candidateFoundation:()=>s1,candidateFromIce:()=>jh,candidateFromSdp:()=>$A,candidatePairPriority:()=>n1,candidatePriority:()=>Rm,candidateToIce:()=>e$,candidateToSdp:()=>jA,certificateTypes:()=>o7,classes:()=>lA,codecParametersFromString:()=>Jm,codecParametersToString:()=>dre,compactNtp:()=>BA,crc32:()=>KU,crc32c:()=>Wk,createBufferWriter:()=>Am,createSelfSignedCertificate:()=>Ite,createStunOverTurnClient:()=>dk,createTurnClient:()=>nj,dePacketizeRtpPackets:()=>mee,debug:()=>ft,deepMerge:()=>Vj,defaultOptions:()=>fj,defaultPeerConfig:()=>bre,depacketizerCodecs:()=>gee,deserializeAbsSendTime:()=>bM,deserializeAudioLevelIndication:()=>xM,deserializeString:()=>gM,deserializeUint16BE:()=>yM,deserializeVideoOrientation:()=>wM,dumpBuffer:()=>EZ,enumerate:()=>yee,findCodecByMimeType:()=>Hk,findPort:()=>YU,fingerprint:()=>IA,generateStatsId:()=>zt,getBit:()=>Te,getDataChannelMessageSize:()=>_j,getGlobalIp:()=>ste,getHostAddresses:()=>xj,getStatsTimestamp:()=>bc,growBufferSize:()=>VT,int:()=>Rh,interfaceAddress:()=>f1,isDtls:()=>jj,isLinkLocalAddress:()=>bj,isMedia:()=>X7,isRtcp:()=>dM,keyLength:()=>B7,leb128decode:()=>j7,makeIntegrityKey:()=>ij,methods:()=>uA,microTime:()=>Fj,milliTime:()=>DA,nodeIpAddress:()=>bk,normalizeFamilyNodeV18:()=>Lm,normalizeFingerprintAlgorithm:()=>RA,normalizeFingerprintValue:()=>i1,ntpTime:()=>Hj,ntpTime2Sec:()=>aM,paddingBits:()=>_Z,paddingByte:()=>Bm,paddingLength:()=>ak,parseGroup:()=>Xw,parseIceServers:()=>qj,parseMessage:()=>S1,random16:()=>zk,random32:()=>Yw,randomPort:()=>Gk,randomPorts:()=>DZ,reverseDirection:()=>$j,reverseSimulcastDirection:()=>kte,rtpHeaderExtensionsParser:()=>lM,saltLength:()=>L7,serializeAbsSendTime:()=>mM,serializeAudioLevelIndication:()=>See,serializeRepairedRtpStreamId:()=>fM,serializeSdesMid:()=>uM,serializeSdesRTPStreamID:()=>hM,serializeTransportWideCC:()=>pM,serverReflexiveCandidate:()=>mj,signatures:()=>Jk,sortCandidatePairs:()=>pj,supportedAudioCodecs:()=>lte,supportedCodecs:()=>EA,supportedVideoCodecs:()=>dte,timer:()=>bee,timestampSeconds:()=>Gm,uint16Add:()=>Jr,uint16Gt:()=>h1,uint16Gte:()=>RZ,uint24:()=>XU,uint32Add:()=>ul,uint32Gt:()=>Hi,uint32Gte:()=>Ah,uint8Add:()=>GU,unwrapRtx:()=>TM,url2Address:()=>nte,useAV1X:()=>Ij,useAbsSendTime:()=>mte,useAudioLevelIndication:()=>yte,useDependencyDescriptor:()=>gte,useFIR:()=>ate,useH264:()=>kj,useNACK:()=>ig,useOPUS:()=>_A,usePCMU:()=>SA,usePLI:()=>Vh,useREMB:()=>og,useRepairedRtpStreamId:()=>fte,useSdesMid:()=>ute,useSdesRTPStreamId:()=>hte,useTWCC:()=>Sj,useTransportWideCC:()=>pte,useVP8:()=>vA,useVP9:()=>Aj,useVideoOrientation:()=>bte,validateAddress:()=>yk,validateRemoteCandidate:()=>gk,wrapRtx:()=>kM});function zk(){return Vk.jspack.Unpack("!H",(0,qk.randomBytes)(2))[0]}function Yw(){return Vk.jspack.Unpack("!L",(0,qk.randomBytes)(4))[0]}function wZ(t,e){if(t.length!==e.length)throw new TypeError("[webrtc-stun] You can not XOR buffers which length are different");let r=t.length,s=Buffer.allocUnsafe(r);for(let n=0;n<r;n++)s[n]=t[n]^e[n];return s}function vZ(t){let e=[...t].sort((s,n)=>s.length-n.length).reverse()[0].length,r=Buffer.allocUnsafe(e);for(let s=0;s<e;s++)r[s]=0,t.forEach(n=>{r[s]^=n[s]??0});return r}function Te(t,e,r=1){let s=t.toString(2).split("");s=[...Array(8-s.length).fill("0"),...s];let n=s.slice(e,e+r).join("");return Number.parseInt(n,2)}function Bm(t){let e=t.toString(2).split("");return[...[...Array(8-e.length)].map(()=>"0"),...e].join("")}function _Z(t,e){let r=t.toString(2);return[...[...Array(e-r.length)].map(()=>"0"),...r].join("")}function nr(t,e){return Am(t)(e)}function Am(t,e){let r=t.reduce((n,i)=>n+i,0),s=e?Buffer.alloc(r):void 0;return n=>{let i=s||Buffer.alloc(r),o=0;return n.forEach((a,c)=>{let d=t[c];d===8?i.writeBigUInt64BE(a,o):i.writeUIntBE(a,o,d),o+=d}),i}}function FU(t,e){let r=t.reduce((i,o)=>i+o,0),s=Buffer.alloc(r),n=0;return e.forEach((i,o)=>{let a=t[o];a===8?s.writeBigUInt64LE(i,n):s.writeUIntLE(i,n,a),n+=a}),s}function bs(t,e){let r=0;return e.map(s=>{let n;return s===8?n=t.readBigUInt64BE(r):n=t.readUIntBE(r,s),r+=s,n})}function CZ(t){return t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}function HU(t){return typeof t!="string"}function qU(t){let e=new Array(256),r=0;for(let s=0;s<256;++s)r=s,r=r&1?t^r>>>1:r>>>1,r=r&1?t^r>>>1:r>>>1,r=r&1?t^r>>>1:r>>>1,r=r&1?t^r>>>1:r>>>1,r=r&1?t^r>>>1:r>>>1,r=r&1?t^r>>>1:r>>>1,r=r&1?t^r>>>1:r>>>1,r=r&1?t^r>>>1:r>>>1,e[s]=r;return new Int32Array(e)}function VU(t){let e=new Int32Array(4096),r=0,s=0,n=0;for(n=0;n<256;++n)e[n]=t[n];for(n=0;n<256;++n)for(s=t[n],r=256+n;r<4096;r+=256)s=e[r]=s>>>8^t[s&255];let i=[];for(n=1;n<16;++n)i[n-1]=e.subarray(n*256,n*256+256);return i}function zU(t,e,r){let s=e^-1,n=0,i=t.length,o=0,a=0;for(;n<i;)o=t.charCodeAt(n++),o<128?s=s>>>8^r[(s^o)&255]:o<2048?(s=s>>>8^r[(s^(192|o>>6&31))&255],s=s>>>8^r[(s^(128|o&63))&255]):o>=55296&&o<57344?(o=(o&1023)+64,a=t.charCodeAt(n++)&1023,s=s>>>8^r[(s^(240|o>>8&7))&255],s=s>>>8^r[(s^(128|o>>2&63))&255],s=s>>>8^r[(s^(128|a>>6&15|(o&3)<<4))&255],s=s>>>8^r[(s^(128|a&63))&255]):(s=s>>>8^r[(s^(224|o>>12&15))&255],s=s>>>8^r[(s^(128|o>>6&63))&255],s=s>>>8^r[(s^(128|o&63))&255]);return~s>>>0}function WU(t,e,r,s){let[n,i,o,a,c,d,u,l,h,p,m,_,f,b,w]=s,S=e^-1,O=0,j=t.length-15;for(;O<j;)S=w[t[O++]^S&255]^b[t[O++]^S>>>8&255]^f[t[O++]^S>>>16&255]^_[t[O++]^S>>>24]^m[t[O++]]^p[t[O++]]^h[t[O++]]^l[t[O++]]^u[t[O++]]^d[t[O++]]^c[t[O++]]^a[t[O++]]^o[t[O++]]^i[t[O++]]^n[t[O++]]^r[t[O++]];for(j+=15;O<j;)S=S>>>8^r[(S^t[O++])&255];return~S>>>0}function KU(t,e=0){return HU(t)?WU(t,e,BT,AZ):zU(t,e,BT)}function Wk(t,e=0){return HU(t)?WU(t,e,LT,IZ):zU(t,e,LT)}function GU(t,e){return t+e&255}function Jr(t,e){return t+e&65535}function ul(t,e){return Number(BigInt(t)+BigInt(e)&0xffffffffn)}function XU(t){return t&16777215}function h1(t,e){return t<e&&e-t>32768||t>e&&t-e<32768}function RZ(t,e){return t===e||h1(t,e)}function Hi(t,e){return t<e&&e-t>2147483648||t>e&&t-e<2147483648}function Ah(t,e){return t===e||Hi(t,e)}async function Gk(t="udp4",e){let r=(0,Kk.createSocket)(t);setImmediate(()=>r.bind({port:0,address:f1(t,e)})),await new Promise(n=>{r.once("error",n),r.once("listening",n)});let s=r.address()?.port;return await new Promise(n=>r.close(()=>n())),s}async function DZ(t,e="udp4",r){return Promise.all([...Array(t)].map(()=>Gk(e,r)))}async function YU(t,e,r="udp4",s){let n;for(let i=t;i<=e;i++){let o=(0,Kk.createSocket)(r);if(setImmediate(()=>o.bind({port:i,address:f1(r,s)})),await new Promise(c=>{o.once("error",d=>c(d)),o.once("listening",()=>c())})){await new Promise(c=>o.close(()=>c()));continue}if(n=o.address()?.port,await new Promise(c=>o.close(()=>c())),t<=n&&n<=e)break}if(!n)throw new Error("port not found");return n}function Lm(t){return t==="IPv4"?4:t==="IPv6"?6:t}function d7(t,e,r){switch(r){case Xo.secp256r1_23:return OZ({publicKey:t,privateKey:e});case Xo.x25519_29:return Buffer.from(c7.default.scalarMult(e,t));default:throw new Error}}function $N(t,e,r){let s=(0,m1.createHmac)(t,e);return s.update(r),s.digest()}function Qm(t,e,r,s="sha256"){let n=r,i=[],o=e;do{o=$N(s,t,o);let a=$N(s,t,Buffer.concat([o,e]));i.push(a),r-=a.length}while(r>0);return Buffer.concat(i,n)}function l7(t,e,r){let s=Buffer.concat([Buffer.from("master secret"),e,r]);return Qm(t,s,48)}function u7(t,e){let r=h7("sha256",e);return Qm(t,Buffer.concat([Buffer.from("extended master secret"),r]),48)}function NZ(t,e,r,s,n,i){let o=i?s:n,a=i?n:s,c=Buffer.concat([Buffer.from(t),o,a]);return Qm(r,c,e)}function h7(t,e){return(0,m1.createHash)(t).update(e).digest()}function f7(t,e,r,s=12){let n=h7("sha256",e);return Qm(t,Buffer.concat([Buffer.from(r),n]),s)}function UZ(t,e){return f7(t,e,"client finished")}function MZ(t,e){return f7(t,e,"server finished")}function jZ(t,e,r,s,n,i,o="sha256"){let a=s*2+n*2,c=t,d=Buffer.concat([r,e]),u=Qm(c,Buffer.concat([Buffer.from("key expansion"),d]),a,o),l=(0,a7.createDecode)(u),h=l.readBuffer(s),p=l.readBuffer(s),m=l.readBuffer(n),_=l.readBuffer(n),f=Buffer.alloc(i,0),b=Buffer.alloc(i,0);return m.copy(f,0),_.copy(b,0),{clientWriteKey:h,serverWriteKey:p,clientNonce:f,serverNonce:b}}function eee(){let t=new sg;return t.id=rg.RSA,t.name="RSA",t.keyType=tg.RSA,t}function tee(){let t=new sg;return t.id=rg.ECDHE_RSA,t.name="ECDHE_RSA",t.signType=g1.ECDHE,t.keyType=tg.RSA,t}function ree(){let t=new sg;return t.id=rg.ECDHE_ECDSA,t.name="ECDHE_ECDSA",t.signType=g1.ECDHE,t.keyType=tg.ECDSA,t}function see(){let t=new sg;return t.id=rg.PSK,t.name="PSK",t.signType=g1.NULL,t.keyType=tg.PSK,t}function nee(){let t=new sg;return t.id=rg.ECDHE_PSK,t.name="ECDHE_PSK",t.signType=g1.ECDHE,t.keyType=tg.PSK,t}function _7(t){switch(t){case Er.TLS_RSA_WITH_AES_128_GCM_SHA256:return $i(Er.TLS_RSA_WITH_AES_128_GCM_SHA256,"TLS_RSA_WITH_AES_128_GCM_SHA256","aes-128-gcm",FN,am);case Er.TLS_RSA_WITH_AES_256_GCM_SHA384:return $i(Er.TLS_RSA_WITH_AES_256_GCM_SHA384,"TLS_RSA_WITH_AES_256_GCM_SHA384","aes-256-gcm",FN,cm,"sha384");case Er.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:return $i(Er.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,"TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256","aes-128-gcm",HN,am);case Er.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:return $i(Er.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,"TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384","aes-256-gcm",HN,cm,"sha384");case Er.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:return $i(Er.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,"TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256","aes-128-gcm",qN,am);case Er.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:return $i(Er.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,"TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384","aes-256-gcm",qN,cm,"sha384");case Er.TLS_PSK_WITH_AES_128_GCM_SHA256:return $i(Er.TLS_PSK_WITH_AES_128_GCM_SHA256,"TLS_PSK_WITH_AES_128_GCM_SHA256","aes-128-gcm",VN,am,"sha256");case Er.TLS_PSK_WITH_AES_256_GCM_SHA384:return $i(Er.TLS_PSK_WITH_AES_256_GCM_SHA384,"TLS_PSK_WITH_AES_256_GCM_SHA384","aes-256-gcm",VN,cm,"sha384");case Er.TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256:return $i(Er.TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256,"TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256","aes-128-gcm",zN,am,"sha256");case Er.TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384:return $i(Er.TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384,"TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384","aes-256-gcm",zN,cm,"sha384");default:break}return null}function $i(t,e,r,s,n,i="sha256"){let o=new oee;return o.id=t,o.name=e,o.blockAlgorithm=r,o.kx=s,o.hashAlgorithm=i,o.keyLength=n.K_LEN,o.nonceLength=n.N_MAX,o.nonceImplicitLength=4,o.nonceExplicitLength=8,o.ivLength=o.nonceImplicitLength,o.authTagLength=16,o}function E7(t){switch(t){case Xo.secp256r1_23:{let{privateKey:e,publicKey:r}=LZ();return{curve:t,privateKey:e,publicKey:r}}case Xo.x25519_29:{let e=S7.default.box.keyPair();return{curve:t,privateKey:Buffer.from(e.secretKey.buffer),publicKey:Buffer.from(e.publicKey.buffer)}}default:throw new Error}}function aee(t,e){return Buffer.from((0,P7.encode)(t,e).slice())}function j7(t){let e=0,r=0;for(let s=0;s<8;s++){let n=t.readUInt8(s);if(e|=(n&127)<<s*7,r++,!(n&128))break}return[e,r]}function mee(t,e,r){let s=n=>{let i=[];for(let c of e){let d=n.deSerialize(c.payload,r);d.fragment?(r??=Buffer.alloc(0),r=d.fragment):d.payload&&(r=void 0),i.push(d)}let o=!!i.find(c=>c.isKeyframe),a=Buffer.concat(i.map(c=>c.payload).filter(c=>c));return{isKeyframe:o,data:a,sequence:e.at(-1)?.header.sequenceNumber??0,timestamp:e.at(-1)?.header.timestamp??0,frameFragmentBuffer:r}};switch(t.toUpperCase()){case"AV1":{let n=e.map(a=>qT.deSerialize(a.payload)),i=!!n.find(a=>a.isKeyframe),o=qT.getFrame(n);return{isKeyframe:i,data:o,sequence:e.at(-1)?.header.sequenceNumber??0,timestamp:e.at(-1)?.header.timestamp??0}}case"MPEG4/ISO/AVC":return s(F7);case"VP8":return s(z7);case"VP9":return s(K7);case"OPUS":return s(q7);default:throw new Error}}function yee(t){return t.map((e,r)=>[r,e])}function VT(t,e){let r=Buffer.alloc(e);return t.copy(r),r}function jm(t){return Number.parseInt(t.toString(),10)}function X7(t){let e=t[0];return e>127&&e<192}function KN(t){return t%4==0?0:4-t%4}function dM(t){return t.length>=2&&t[1]>=192&&t[1]<=208}function lM(t,e){return t.map(r=>{let s=e[r.id];if(!s)return{uri:"unknown",value:r.payload};switch(s){case Qt.sdesMid:case Qt.sdesRTPStreamID:case Qt.repairedRtpStreamId:return{uri:s,value:gM(r.payload)};case Qt.transportWideCC:return{uri:s,value:yM(r.payload)};case Qt.absSendTime:return{uri:s,value:bM(r.payload)};case Qt.audioLevelIndication:return{uri:s,value:xM(r.payload)};case Qt.videoOrientation:return{uri:s,value:wM(r.payload)};default:return{uri:s,value:r.payload}}}).reduce((r,s)=>(s&&(r[s.uri]=s.value),r),{})}function uM(t){return Buffer.from(t)}function hM(t){return Buffer.from(t)}function fM(t){return Buffer.from(t)}function pM(t){return nr([2],[t])}function mM(t){let e=Buffer.alloc(3),r=t>>14n&0x00ffffffn;return e.writeUIntBE(Number(r),0,3),e}function See(t){let e=new fc(Buffer.alloc(1));return e.writeBits(1,1),e.writeBits(7,t),e.uint8Array}function gM(t){return t.toString()}function yM(t){return t.readUInt16BE()}function bM(t){return bs(t,[3])[0]}function xM(t){let e=new fc(t);return{v:e.readBits(1)===1,level:e.readBits(7)}}function wM(t){let e=new fc(t);return e.readBits(4),{c:e.readBits(1),f:e.readBits(1),r1:e.readBits(1),r0:e.readBits(1)}}function TM(t,e,r){return new Jo(new Yo({payloadType:e,marker:t.header.marker,sequenceNumber:nA.jspack.Unpack("!H",t.payload.subarray(0,2))[0],timestamp:t.header.timestamp,ssrc:r}),t.payload.subarray(2))}function kM(t,e,r,s){return new Jo(new Yo({payloadType:e,marker:t.header.marker,sequenceNumber:r,timestamp:t.header.timestamp,ssrc:s,csrc:t.header.csrc,extensions:t.header.extensions}),Buffer.concat([Buffer.from(nA.jspack.Pack("!H",[t.header.sequenceNumber])),t.payload]))}function iA(t,e,r="Failed to authenticate SRTP packet"){let s=t.length-e;zm(t.length>=ZN+e,r);let n=RM(()=>Yo.deSerialize(t.subarray(0,s)),r);return n.paddingSize=0,zm(n.payloadOffset>=ZN&&n.payloadOffset<=s,r),n}function IM(t,e,r,s="Failed to authenticate SRTCP packet"){return zm(t.length>=Tee+e+r,s),RM(()=>Qo.deSerialize(t.subarray(0,t1)),s)}function zm(t,e){if(!t)throw new xl(e)}function RM(t,e){try{return t()}catch{throw new xl(e)}}function PM(t,e,r="Failed to authenticate SRTP packet"){if(!t.padding)return t.paddingSize=0,t;zm(e.length>t.payloadOffset,r);let s=e[e.length-1];return zm(s>0&&s<=e.length-t.payloadOffset,r),t.paddingSize=s,t}function tU(t,e,r){if(t.length!==e.length||!(0,Yn.timingSafeEqual)(t,e))throw new xl(r)}function sU(t,e){try{t.final()}catch{throw new xl(`Failed to authenticate ${e} packet`)}}function lm(t){return(0,fA.randomBytes)(t).toString("hex").substring(0,t)}function VM(){return(0,fA.randomBytes)(12)}function Ch(t){let[e]=t,r=Wm.default.isV4Format(e)?cA:dA,s=Buffer.alloc(4);return s.writeUInt8(0,0),s.writeUInt8(r,1),s.writeUInt16BE(t[1],2),Buffer.concat([s,Wm.default.toBuffer(e)])}function Hee(t){if(t.length<4)throw new Error("STUN error code is less than 4 bytes");let e=t.readUInt8(2),r=t.readUInt8(3),s=t.slice(4).toString("utf8");return[e*100+r,s]}function Th(t){if(t.length<4)throw new Error("STUN address length is less than 4 bytes");let e=t.readUInt8(1),r=t.readUInt16BE(2),s=t.slice(4);switch(e){case cA:if(s.length!=4)throw new Error("STUN address has invalid length for IPv4");return[Wm.default.toString(s),r];case dA:if(s.length!=16)throw new Error("STUN address has invalid length for IPv6");return[Wm.default.toString(s),r];default:throw new Error("STUN address has unknown protocol")}}function zM(t,e){let r=[...pA,...e],s=t.slice(0,2);for(let n=2;n<t.length;n++){let i=t[n]^r[n-2],o=Buffer.alloc(1);o.writeUIntBE(i,0,1),s=Buffer.concat([s,o])}return s}function Nw(t,e){return Th(zM(t,e))}function qee(t){let e=Buffer.alloc(4);e.writeUInt16BE(0,0),e.writeUInt8(Math.floor(t[0]/100),2),e.writeUInt8(t[0]%100,3);let r=Buffer.from(t[1],"utf8");return Buffer.concat([e,r])}function Uw(t,e){return zM(Ch(t),e)}function S1(t,e){if(t.length<zo)return;let r=t.readUint16BE(2);if(t.length!==zo+r)return;let s=t.readUint16BE(0),n=Buffer.from(t.slice(zo-12,zo)),i=new KM;for(let a=zo;a<=t.length-4;){let c=t.readUInt16BE(a),d=t.readUInt16BE(a+2),u=t.slice(a+4,a+4+d),l=4*Math.floor((d+3)/4)-d;if(Object.keys(pU).includes(c.toString())){let[,p,,m]=pU[c];if(m.name===Nw.name?i.setAttribute(p,m(u,n)):i.setAttribute(p,m(u)),p==="FINGERPRINT"){let _=GM(t.slice(0,a));if(i.getAttributeValue("FINGERPRINT")!==_)return}else if(p==="MESSAGE-INTEGRITY"&&e){let _=Xee(t.slice(0,a),e),f=i.getAttributeValue("MESSAGE-INTEGRITY");if(!_.equals(f))return}}a+=4+d+l}let o=i.getAttributes();return i.clear(),new wn(s&16111,s&272,n,o)}function GM(t){let e=mA(t,t.length-zo+$M);return(KU(e)^FM)>>>0}function Xee(t,e){let r=mA(t,t.length-zo+aA);return Buffer.from((0,hA.createHmac)("sha1",e).update(r).digest("hex"),"hex")}function ak(t){let e=t%4;return e===0?0:4-e}async function nj({address:t,username:e,password:r},{lifetime:s,portRange:n,interfaceAddresses:i,transport:o}={}){s??=Qee,o??="udp";let a=o==="udp"?await Jw.init("udp4",{portRange:n,interfaceAddresses:i}):await s7.init(t),c=new rj(t,e,r,s,a);return await c.connectionMade(),c}async function dk({address:t,username:e,password:r},{lifetime:s,portRange:n,interfaceAddresses:i,transport:o}={}){let a=await nj({address:t,username:e,password:r},{lifetime:s,portRange:n,interfaceAddresses:i,transport:o});return new ej(a)}function ij(t,e,r){return(0,QM.createHash)("md5").update(Buffer.from([t,e,r].join(":"))).digest()}function gU(t){return(t[0]&192)==64}function s1(t,e,r){let s=`${t}|${e}|${r}`;return(0,oj.createHash)("md5").update(s,"ascii").digest("hex").slice(7)}function Rm(t,e=65535){let s=0;return t==="host"?s=126:t==="prflx"?s=110:t==="srflx"?s=100:s=0,(1<<24)*s+256*e+255}function gk(t){if(!["host","relay","srflx"].includes(t.type))throw new Error(`Unexpected candidate type "${t.type}"`);return t}function pj(t,e){return t.sort((r,s)=>n1(r.localCandidate,r.remoteCandidate,e)-n1(s.localCandidate,s.remoteCandidate,e)).reverse()}function n1(t,e,r){let s=r&&t.priority||e.priority,n=r&&e.priority||t.priority;return 1*Math.min(s,n)+2*Math.max(s,n)+(s>n?1:0)}async function mj(t,e){let r=new wn(1,0);try{let[s]=await t.request(r,e),n=t.localCandidate;if(!n)throw new Error("not exist");return new gc(s1("srflx","udp",n.host),n.component,n.transport,Rm("srflx"),s.getAttributeValue("XOR-MAPPED-ADDRESS")[0],s.getAttributeValue("XOR-MAPPED-ADDRESS")[1],"srflx",n.host,n.port)}catch(s){tte("error serverReflexiveCandidate",s)}}function yk(t){return t&&Number.isNaN(t[1])?[t[0],443]:t}async function ste(t,e){let r=new r1;await r.connectionMade(!0,void 0,e);let s=new wn(1,0),[n]=await r.request(s,t??["stun.l.google.com",19302]);return await r.close(),n.getAttributeValue("XOR-MAPPED-ADDRESS")[0]}function bj(t){return Lm(t.family)===4&&t.address?.startsWith("169.254.")||Lm(t.family)===6&&t.address?.startsWith("fe80::")}function bk(t,{useLinkLocalAddress:e}={}){let r=["ipsec","tun","utun","tap"],s=["vmnet","veth"],n=gj.networkInterfaces();rte(n);let i=Object.keys(n).map(o=>{for(let c of[...r,...s])if(o.startsWith(c))return{nic:o,addresses:[]};let a=n[o].filter(c=>Lm(c.family)===t&&!yj.default.isLoopback(c.address)&&(e?!0:!bj(c)));return{nic:o,addresses:a.map(c=>c.address)}}).filter(o=>!!o);return i.sort((o,a)=>o.nic.localeCompare(a.nic)),Object.values(i).flatMap(o=>o.addresses)}function xj(t,e,r={}){let s=[];return t&&s.push(...bk(4,r)),e&&s.push(...bk(6,r)),s}function bU(t){return t.map((e,r)=>[r,e])}function Vo(t,e){let r=t.split(e);return[r[0],r.slice(1).join(e)]}function _j(t){return Buffer.isBuffer(t)?t.length:Buffer.byteLength(t)}function ute(){return new Wi({uri:Qt.sdesMid})}function hte(){return new Wi({uri:Qt.sdesRTPStreamID})}function fte(){return new Wi({uri:Qt.repairedRtpStreamId})}function pte(){return new Wi({uri:Qt.transportWideCC})}function mte(){return new Wi({uri:Qt.absSendTime})}function gte(){return new Wi({uri:Qt.dependencyDescriptor})}function yte(){return new Wi({uri:Qt.audioLevelIndication})}function bte(){return new Wi({uri:Qt.videoOrientation})}function zt(t,...e){let r=e.filter(s=>s!==void 0);return`${t}_${r.join("_")}`}function bc(){return performance.now()}function IA(t,e){let r=i=>i.toUpperCase(),s=i=>i.match(/(.{2})/g).join(":"),n=(0,Pj.createHash)(e).update(t).digest("hex");return s(r(n))}function RA(t){return Tte[t.trim().toLowerCase()]}function i1(t){return t.replace(/[^0-9a-f]/gi,"").toLowerCase()}function jj(t){let e=t[0];return e>19&&e<64}function kte(t){return t==="recv"?"send":"recv"}function $j(t){return t==="sendonly"?"recvonly":t==="recvonly"?"sendonly":t}function qj(t){let e=a=>{if(!a)return;let[c,d]=a.split(":");return[c,Number.parseInt(d)]},r=e(t.find(({urls:a})=>a.includes("stun:"))?.urls.slice(5)),s=e(t.find(({urls:a})=>a.includes("turn:"))?.urls.slice(5)),{credential:n,username:i}=t.find(({urls:a})=>a.includes("turn:"))||{},o={stunServer:r,turnServer:s,turnUsername:i,turnPassword:n};return Cte("iceOptions",o),o}function jh(t){let e=new OA(t.component,t.foundation,t.host,t.port,t.priority,t.transport,t.type,t.generation,t.ufrag);return e.relatedAddress=t.relatedAddress,e.relatedPort=t.relatedPort,e.tcpType=t.tcptype,e}function e$(t){return new gc(t.foundation,t.component,t.protocol,t.priority,t.ip,t.port,t.type,t.relatedAddress,t.relatedPort,t.tcpType,t.generation,t.ufrag)}function cg(t){let e=t%4;return e?4-e:0}function S$(t){let e=Buffer.from(""),r=Buffer.from("");return t.forEach(([s,n])=>{let i=n.length+4,o=Buffer.alloc(4);o.writeUInt16BE(s,0),o.writeUInt16BE(i,2),e=Buffer.concat([e,r,o,n]),r=Buffer.concat([...Array(cg(i))].map(()=>Buffer.from("\0")))}),e}function E$(t){let e=[],r=0;for(;r<=t.length-4;){let s=t.readUInt16BE(r),n=t.readUInt16BE(r+2);e.push([s,t.slice(r+4,r+n)]),r+=n+cg(n)}return e}function Wte(t){if(t.length<12)throw new Error("SCTP packet length is less than 12 bytes");let e=t.readUInt16BE(0),r=t.readUInt16BE(2),s=t.readUInt32BE(4),n=t.readUInt32LE(8),i=Wk(Buffer.concat([t.slice(0,8),Buffer.from("\0\0\0\0"),t.slice(12)]));if(n!==i)throw new Error("SCTP packet has invalid checksum");let o=[],a=12;for(;a+4<=t.length;){let c=t.readUInt8(a),d=t.readUInt8(a+1),u=t.readUInt16BE(a+2),l=t.slice(a+4,a+u),h=zte[c.toString()];if(h)o.push(new h(d,l));else throw new Error("unknown");a+=u+cg(u)}return[e,r,s,o]}function Kte(t,e,r,s){let n=Buffer.alloc(8);n.writeUInt16BE(t,0),n.writeUInt16BE(e,2),n.writeUInt32BE(r,4);let i=s.bytes,o=Wk(Buffer.concat([n,Buffer.from("\0\0\0\0"),i])),a=Buffer.alloc(4);return a.writeUInt32LE(o,0),Buffer.concat([n,a,i])}function Gte(t){return t.map((e,r)=>[r,e])}function Xte(t){return t.reduce((e,r)=>(e[r]=new Ne,e),{})}function dl(t){return(t-1)%c1}function kh(t){return(t+1)%c1}function RT(t){let e=t.match(/^IN (IP4|IP6) ([^ ]+)$/);if(!e)throw new Error("exception");return e[2]}function Nk(t){return`IN IP${(0,Kj.isIPv4)(t)?4:6} ${t}`}function jA(t){let e=`${t.foundation} ${t.component} ${t.protocol} ${t.priority} ${t.ip} ${t.port} typ ${t.type}`;return t.relatedAddress!=null&&(e+=` raddr ${t.relatedAddress}`),t.relatedPort!=null&&(e+=` rport ${t.relatedPort}`),t.tcpType!=null&&(e+=` tcptype ${t.tcpType}`),t.generation!=null&&(e+=` generation ${t.generation}`),t.ufrag!=null&&(e+=` ufrag ${t.ufrag}`),e}function cre(t){let e=[],r=[],s=t.split(`\r
|
|
134
|
+
`),Km.prototype[t]=e.toFunction({assertSize:NC})});GL.exports=Km;function NC(t,e){if(t>e)throw new iQ(t,e)}});var sr=Me((h5e,sO)=>{"use strict";g();y();var UC=qm(),oQ=kL(),aQ=PL(),cQ=BL(),dQ=OL(),lQ=ML(),YL=$L(),uQ=HL(),hQ=zL(),{encode:ZL}=zm(),{decode:eO}=ch(),{encodingLength:fQ}=Wm(),pQ=XL(),tO=ah(),rO={array:oQ,bool:cQ,buffer:aQ,reserved:dQ,string:lQ,when:uQ,select:hQ};for(let t of Object.keys(YL))rO[t]=YL[t];var rw=Symbol("schema");function JL(t){let e=new UC({readableObjectMode:!1,writableObjectMode:!0,transform:mQ});return e[rw]=t,e}function QL(t){let e=null,r=Buffer.isBuffer(t);r||(e=t);let s=new UC({transform:gQ,readableObjectMode:!0,writableObjectMode:!1});return s[rw]=e,r&&s.append(t),s}function mQ(t,e,r){try{ZL(t,this[rw],this);let s=this.slice();this.consume(s.length),r(null,s)}catch(s){r(s)}}function gQ(t,e,r){this.append(t);try{for(;this.length>0;){let s=new pQ(this),n=eO(s,this[rw]);s.commit(),this.push(n)}r()}catch(s){s instanceof tO?r():r(s)}}sO.exports={createEncodeStream:JL,createDecodeStream:QL,encode:ZL,decode:eO,encodingLength:fQ,createEncode:JL,createDecode:QL,types:rO,BinaryStream:UC,NotEnoughDataError:tO}});var To,Zd,nO=V(()=>{"use strict";g();y();To=Le(require("crypto"),1),Zd=To&&typeof To=="object"&&"webcrypto"in To?To.webcrypto:To&&typeof To=="object"&&"randomBytes"in To?To:void 0});function el(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Gm(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function Nn(t,...e){if(!el(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function sw(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");Gm(t.outputLen),Gm(t.blockLen)}function lh(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function oO(t,e){Nn(t);let r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function Ao(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function nw(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function Un(t,e){return t<<32-e|t>>>e}function Io(t){if(Nn(t),aO)return t.toHex();let e="";for(let r=0;r<t.length;r++)e+=yQ[t[r]];return e}function iO(t){if(t>=ko._0&&t<=ko._9)return t-ko._0;if(t>=ko.A&&t<=ko.F)return t-(ko.A-10);if(t>=ko.a&&t<=ko.f)return t-(ko.a-10)}function tl(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(aO)return Uint8Array.fromHex(t);let e=t.length,r=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);let s=new Uint8Array(r);for(let n=0,i=0;n<r;n++,i+=2){let o=iO(t.charCodeAt(i)),a=iO(t.charCodeAt(i+1));if(o===void 0||a===void 0){let c=t[i]+t[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}s[n]=o*16+a}return s}function cO(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function Xm(t){return typeof t=="string"&&(t=cO(t)),Nn(t),t}function Mn(...t){let e=0;for(let s=0;s<t.length;s++){let n=t[s];Nn(n),e+=n.length}let r=new Uint8Array(e);for(let s=0,n=0;s<t.length;s++){let i=t[s];r.set(i,n),n+=i.length}return r}function iw(t){let e=s=>t().update(Xm(s)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function ow(t=32){if(Zd&&typeof Zd.getRandomValues=="function")return Zd.getRandomValues(new Uint8Array(t));if(Zd&&typeof Zd.randomBytes=="function")return Uint8Array.from(Zd.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}var aO,yQ,ko,dh,rl=V(()=>{"use strict";g();y();nO();aO=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",yQ=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));ko={_0:48,_9:57,A:65,F:70,a:97,f:102};dh=class{}});function Ym(t,e=""){if(typeof t!="boolean"){let r=e&&`"${e}"`;throw new Error(r+"expected boolean, got type="+typeof t)}return t}function ec(t,e,r=""){let s=el(t),n=t?.length,i=e!==void 0;if(!s||i&&n!==e){let o=r&&`"${r}" `,a=i?` of length ${e}`:"",c=s?`length=${n}`:`type=${typeof t}`;throw new Error(o+"expected Uint8Array"+a+", got "+c)}return t}function Jm(t){let e=t.toString(16);return e.length&1?"0"+e:e}function dO(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?$C:BigInt("0x"+t)}function uh(t){return dO(Io(t))}function FC(t){return Nn(t),dO(Io(Uint8Array.from(t).reverse()))}function aw(t,e){return tl(t.toString(16).padStart(e*2,"0"))}function HC(t,e){return aw(t,e).reverse()}function cs(t,e,r){let s;if(typeof e=="string")try{s=tl(e)}catch(i){throw new Error(t+" must be hex string or Uint8Array, cause: "+i)}else if(el(e))s=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");let n=s.length;if(typeof r=="number"&&n!==r)throw new Error(t+" of length "+r+" expected, got "+n);return s}function lO(t,e,r){return MC(t)&&MC(e)&&MC(r)&&e<=t&&t<r}function uO(t,e,r,s){if(!lO(e,r,s))throw new Error("expected valid "+t+": "+r+" <= n < "+s+", got "+e)}function cw(t){let e;for(e=0;t>$C;t>>=jC,e+=1);return e}function hO(t,e,r){if(typeof t!="number"||t<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof r!="function")throw new Error("hmacFn must be a function");let s=p=>new Uint8Array(p),n=p=>Uint8Array.of(p),i=s(t),o=s(t),a=0,c=()=>{i.fill(1),o.fill(0),a=0},d=(...p)=>r(o,i,...p),u=(p=s(0))=>{o=d(n(0),p),i=d(),p.length!==0&&(o=d(n(1),p),i=d())},l=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let p=0,m=[];for(;p<e;){i=d();let _=i.slice();m.push(_),p+=i.length}return Mn(...m)};return(p,m)=>{c(),u(p);let _;for(;!(_=m(l()));)u();return c(),_}}function Qm(t,e,r={}){if(!t||typeof t!="object")throw new Error("expected valid options object");function s(n,i,o){let a=t[n];if(o&&a===void 0)return;let c=typeof a;if(c!==i||a===null)throw new Error(`param "${n}" is invalid: expected ${i}, got ${c}`)}Object.entries(e).forEach(([n,i])=>s(n,i,!1)),Object.entries(r).forEach(([n,i])=>s(n,i,!0))}function qC(t){let e=new WeakMap;return(r,...s)=>{let n=e.get(r);if(n!==void 0)return n;let i=t(r,...s);return e.set(r,i),i}}var $C,jC,MC,tc,dw=V(()=>{"use strict";g();y();rl();rl();$C=BigInt(0),jC=BigInt(1);MC=t=>typeof t=="bigint"&&$C<=t;tc=t=>(jC<<BigInt(t))-jC});function jn(t,e){let r=t%e;return r>=Ds?r:e+r}function fO(t,e){if(t===Ds)throw new Error("invert: expected non-zero number");if(e<=Ds)throw new Error("invert: expected positive modulus, got "+e);let r=jn(t,e),s=e,n=Ds,i=ds,o=ds,a=Ds;for(;r!==Ds;){let d=s/r,u=s%r,l=n-o*d,h=i-a*d;s=r,r=u,n=o,i=a,o=l,a=h}if(s!==ds)throw new Error("invert: does not exist");return jn(n,e)}function VC(t,e,r){if(!t.eql(t.sqr(e),r))throw new Error("Cannot find square root")}function wO(t,e){let r=(t.ORDER+ds)/gO,s=t.pow(e,r);return VC(t,s,e),s}function wQ(t,e){let r=(t.ORDER-yO)/bO,s=t.mul(e,sl),n=t.pow(s,r),i=t.mul(e,n),o=t.mul(t.mul(i,sl),n),a=t.mul(i,t.sub(o,t.ONE));return VC(t,a,e),a}function vQ(t){let e=Pi(t),r=vO(t),s=r(e,e.neg(e.ONE)),n=r(e,s),i=r(e,e.neg(s)),o=(t+bQ)/xO;return(a,c)=>{let d=a.pow(c,o),u=a.mul(d,s),l=a.mul(d,n),h=a.mul(d,i),p=a.eql(a.sqr(u),c),m=a.eql(a.sqr(l),c);d=a.cmov(d,u,p),u=a.cmov(h,l,m);let _=a.eql(a.sqr(u),c),f=a.cmov(d,u,_);return VC(a,f,c),f}}function vO(t){if(t<mO)throw new Error("sqrt is not defined for small field");let e=t-ds,r=0;for(;e%sl===Ds;)e/=sl,r++;let s=sl,n=Pi(t);for(;pO(n,s)===1;)if(s++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return wO;let i=n.pow(s,e),o=(e+ds)/sl;return function(c,d){if(c.is0(d))return d;if(pO(c,d)!==1)throw new Error("Cannot find square root");let u=r,l=c.mul(c.ONE,i),h=c.pow(d,e),p=c.pow(d,o);for(;!c.eql(h,c.ONE);){if(c.is0(h))return c.ZERO;let m=1,_=c.sqr(h);for(;!c.eql(_,c.ONE);)if(m++,_=c.sqr(_),m===u)throw new Error("Cannot find square root");let f=ds<<BigInt(u-m-1),b=c.pow(l,f);u=m,l=c.sqr(b),h=c.mul(h,l),p=c.mul(p,b)}return p}}function _Q(t){return t%gO===mO?wO:t%bO===yO?wQ:t%xO===xQ?vQ(t):vO(t)}function zC(t){let e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},r=SQ.reduce((s,n)=>(s[n]="function",s),e);return Qm(t,r),t}function EQ(t,e,r){if(r<Ds)throw new Error("invalid exponent, negatives unsupported");if(r===Ds)return t.ONE;if(r===ds)return e;let s=t.ONE,n=e;for(;r>Ds;)r&ds&&(s=t.mul(s,n)),n=t.sqr(n),r>>=ds;return s}function lw(t,e,r=!1){let s=new Array(e.length).fill(r?t.ZERO:void 0),n=e.reduce((o,a,c)=>t.is0(a)?o:(s[c]=o,t.mul(o,a)),t.ONE),i=t.inv(n);return e.reduceRight((o,a,c)=>t.is0(a)?o:(s[c]=t.mul(o,s[c]),t.mul(o,a)),i),s}function pO(t,e){let r=(t.ORDER-ds)/sl,s=t.pow(e,r),n=t.eql(s,t.ONE),i=t.eql(s,t.ZERO),o=t.eql(s,t.neg(t.ONE));if(!n&&!i&&!o)throw new Error("invalid Legendre symbol result");return n?1:i?0:-1}function uw(t,e){e!==void 0&&Gm(e);let r=e!==void 0?e:t.toString(2).length,s=Math.ceil(r/8);return{nBitLength:r,nByteLength:s}}function Pi(t,e,r=!1,s={}){if(t<=Ds)throw new Error("invalid field: expected ORDER > 0, got "+t);let n,i,o=!1,a;if(typeof e=="object"&&e!=null){if(s.sqrt||r)throw new Error("cannot specify opts in two arguments");let h=e;h.BITS&&(n=h.BITS),h.sqrt&&(i=h.sqrt),typeof h.isLE=="boolean"&&(r=h.isLE),typeof h.modFromBytes=="boolean"&&(o=h.modFromBytes),a=h.allowedLengths}else typeof e=="number"&&(n=e),s.sqrt&&(i=s.sqrt);let{nBitLength:c,nByteLength:d}=uw(t,n);if(d>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let u,l=Object.freeze({ORDER:t,isLE:r,BITS:c,BYTES:d,MASK:tc(c),ZERO:Ds,ONE:ds,allowedLengths:a,create:h=>jn(h,t),isValid:h=>{if(typeof h!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof h);return Ds<=h&&h<t},is0:h=>h===Ds,isValidNot0:h=>!l.is0(h)&&l.isValid(h),isOdd:h=>(h&ds)===ds,neg:h=>jn(-h,t),eql:(h,p)=>h===p,sqr:h=>jn(h*h,t),add:(h,p)=>jn(h+p,t),sub:(h,p)=>jn(h-p,t),mul:(h,p)=>jn(h*p,t),pow:(h,p)=>EQ(l,h,p),div:(h,p)=>jn(h*fO(p,t),t),sqrN:h=>h*h,addN:(h,p)=>h+p,subN:(h,p)=>h-p,mulN:(h,p)=>h*p,inv:h=>fO(h,t),sqrt:i||(h=>(u||(u=_Q(t)),u(l,h))),toBytes:h=>r?HC(h,d):aw(h,d),fromBytes:(h,p=!0)=>{if(a){if(!a.includes(h.length)||h.length>d)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+h.length);let _=new Uint8Array(d);_.set(h,r?0:_.length-h.length),h=_}if(h.length!==d)throw new Error("Field.fromBytes: expected "+d+" bytes, got "+h.length);let m=r?FC(h):uh(h);if(o&&(m=jn(m,t)),!p&&!l.isValid(m))throw new Error("invalid field element: outside of range 0..ORDER");return m},invertBatch:h=>lw(l,h),cmov:(h,p,m)=>m?p:h});return Object.freeze(l)}function _O(t){if(typeof t!="bigint")throw new Error("field order must be bigint");let e=t.toString(2).length;return Math.ceil(e/8)}function WC(t){let e=_O(t);return e+Math.ceil(e/2)}function SO(t,e,r=!1){let s=t.length,n=_O(e),i=WC(e);if(s<16||s<i||s>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+s);let o=r?FC(t):uh(t),a=jn(o,e-ds)+ds;return r?HC(a,n):aw(a,n)}var Ds,ds,sl,mO,gO,yO,bQ,bO,xQ,xO,SQ,hw=V(()=>{"use strict";g();y();dw();Ds=BigInt(0),ds=BigInt(1),sl=BigInt(2),mO=BigInt(3),gO=BigInt(4),yO=BigInt(5),bQ=BigInt(7),bO=BigInt(8),xQ=BigInt(9),xO=BigInt(16);SQ=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"]});function CQ(t,e,r,s){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,s);let n=BigInt(32),i=BigInt(4294967295),o=Number(r>>n&i),a=Number(r&i),c=s?4:0,d=s?0:4;t.setUint32(e+c,o,s),t.setUint32(e+d,a,s)}function EO(t,e,r){return t&e^~t&r}function CO(t,e,r){return t&e^t&r^e&r}var Zm,Ro,Kr,Gr,TO=V(()=>{"use strict";g();y();rl();Zm=class extends dh{constructor(e,r,s,n){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=r,this.padOffset=s,this.isLE=n,this.buffer=new Uint8Array(e),this.view=nw(this.buffer)}update(e){lh(this),e=Xm(e),Nn(e);let{view:r,buffer:s,blockLen:n}=this,i=e.length;for(let o=0;o<i;){let a=Math.min(n-this.pos,i-o);if(a===n){let c=nw(e);for(;n<=i-o;o+=n)this.process(c,o);continue}s.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===n&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){lh(this),oO(e,this),this.finished=!0;let{buffer:r,view:s,blockLen:n,isLE:i}=this,{pos:o}=this;r[o++]=128,Ao(this.buffer.subarray(o)),this.padOffset>n-o&&(this.process(s,0),o=0);for(let l=o;l<n;l++)r[l]=0;CQ(s,n-8,BigInt(this.length*8),i),this.process(s,0);let a=nw(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let d=c/4,u=this.get();if(d>u.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;l<d;l++)a.setUint32(4*l,u[l],i)}digest(){let{buffer:e,outputLen:r}=this;this.digestInto(e);let s=e.slice(0,r);return this.destroy(),s}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:r,buffer:s,length:n,finished:i,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=i,e.length=n,e.pos=a,n%r&&e.buffer.set(s),e}clone(){return this._cloneInto()}},Ro=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Kr=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]),Gr=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209])});function TQ(t,e=!1){return e?{h:Number(t&fw),l:Number(t>>kO&fw)}:{h:Number(t>>kO&fw)|0,l:Number(t&fw)|0}}function AO(t,e=!1){let r=t.length,s=new Uint32Array(r),n=new Uint32Array(r);for(let i=0;i<r;i++){let{h:o,l:a}=TQ(t[i],e);[s[i],n[i]]=[o,a]}return[s,n]}function Di(t,e,r,s){let n=(e>>>0)+(s>>>0);return{h:t+r+(n/2**32|0)|0,l:n|0}}var fw,kO,KC,GC,nl,il,e0,t0,IO,RO,PO,DO,BO,LO,OO=V(()=>{"use strict";g();y();fw=BigInt(4294967295),kO=BigInt(32);KC=(t,e,r)=>t>>>r,GC=(t,e,r)=>t<<32-r|e>>>r,nl=(t,e,r)=>t>>>r|e<<32-r,il=(t,e,r)=>t<<32-r|e>>>r,e0=(t,e,r)=>t<<64-r|e>>>r-32,t0=(t,e,r)=>t>>>r-32|e<<64-r;IO=(t,e,r)=>(t>>>0)+(e>>>0)+(r>>>0),RO=(t,e,r,s)=>e+r+s+(t/2**32|0)|0,PO=(t,e,r,s)=>(t>>>0)+(e>>>0)+(r>>>0)+(s>>>0),DO=(t,e,r,s,n)=>e+r+s+n+(t/2**32|0)|0,BO=(t,e,r,s,n)=>(t>>>0)+(e>>>0)+(r>>>0)+(s>>>0)+(n>>>0),LO=(t,e,r,s,n,i)=>e+r+s+n+i+(t/2**32|0)|0});var AQ,rc,XC,NO,IQ,RQ,sc,nc,pw,YC,UO,MO,jO,$O=V(()=>{"use strict";g();y();TO();OO();rl();AQ=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),rc=new Uint32Array(64),XC=class extends Zm{constructor(e=32){super(64,e,8,!1),this.A=Ro[0]|0,this.B=Ro[1]|0,this.C=Ro[2]|0,this.D=Ro[3]|0,this.E=Ro[4]|0,this.F=Ro[5]|0,this.G=Ro[6]|0,this.H=Ro[7]|0}get(){let{A:e,B:r,C:s,D:n,E:i,F:o,G:a,H:c}=this;return[e,r,s,n,i,o,a,c]}set(e,r,s,n,i,o,a,c){this.A=e|0,this.B=r|0,this.C=s|0,this.D=n|0,this.E=i|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,r){for(let l=0;l<16;l++,r+=4)rc[l]=e.getUint32(r,!1);for(let l=16;l<64;l++){let h=rc[l-15],p=rc[l-2],m=Un(h,7)^Un(h,18)^h>>>3,_=Un(p,17)^Un(p,19)^p>>>10;rc[l]=_+rc[l-7]+m+rc[l-16]|0}let{A:s,B:n,C:i,D:o,E:a,F:c,G:d,H:u}=this;for(let l=0;l<64;l++){let h=Un(a,6)^Un(a,11)^Un(a,25),p=u+h+EO(a,c,d)+AQ[l]+rc[l]|0,_=(Un(s,2)^Un(s,13)^Un(s,22))+CO(s,n,i)|0;u=d,d=c,c=a,a=o+p|0,o=i,i=n,n=s,s=p+_|0}s=s+this.A|0,n=n+this.B|0,i=i+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,d=d+this.G|0,u=u+this.H|0,this.set(s,n,i,o,a,c,d,u)}roundClean(){Ao(rc)}destroy(){this.set(0,0,0,0,0,0,0,0),Ao(this.buffer)}},NO=AO(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(t=>BigInt(t))),IQ=NO[0],RQ=NO[1],sc=new Uint32Array(80),nc=new Uint32Array(80),pw=class extends Zm{constructor(e=64){super(128,e,16,!1),this.Ah=Gr[0]|0,this.Al=Gr[1]|0,this.Bh=Gr[2]|0,this.Bl=Gr[3]|0,this.Ch=Gr[4]|0,this.Cl=Gr[5]|0,this.Dh=Gr[6]|0,this.Dl=Gr[7]|0,this.Eh=Gr[8]|0,this.El=Gr[9]|0,this.Fh=Gr[10]|0,this.Fl=Gr[11]|0,this.Gh=Gr[12]|0,this.Gl=Gr[13]|0,this.Hh=Gr[14]|0,this.Hl=Gr[15]|0}get(){let{Ah:e,Al:r,Bh:s,Bl:n,Ch:i,Cl:o,Dh:a,Dl:c,Eh:d,El:u,Fh:l,Fl:h,Gh:p,Gl:m,Hh:_,Hl:f}=this;return[e,r,s,n,i,o,a,c,d,u,l,h,p,m,_,f]}set(e,r,s,n,i,o,a,c,d,u,l,h,p,m,_,f){this.Ah=e|0,this.Al=r|0,this.Bh=s|0,this.Bl=n|0,this.Ch=i|0,this.Cl=o|0,this.Dh=a|0,this.Dl=c|0,this.Eh=d|0,this.El=u|0,this.Fh=l|0,this.Fl=h|0,this.Gh=p|0,this.Gl=m|0,this.Hh=_|0,this.Hl=f|0}process(e,r){for(let S=0;S<16;S++,r+=4)sc[S]=e.getUint32(r),nc[S]=e.getUint32(r+=4);for(let S=16;S<80;S++){let O=sc[S-15]|0,j=nc[S-15]|0,P=nl(O,j,1)^nl(O,j,8)^KC(O,j,7),k=il(O,j,1)^il(O,j,8)^GC(O,j,7),C=sc[S-2]|0,D=nc[S-2]|0,H=nl(C,D,19)^e0(C,D,61)^KC(C,D,6),W=il(C,D,19)^t0(C,D,61)^GC(C,D,6),J=PO(k,W,nc[S-7],nc[S-16]),F=DO(J,P,H,sc[S-7],sc[S-16]);sc[S]=F|0,nc[S]=J|0}let{Ah:s,Al:n,Bh:i,Bl:o,Ch:a,Cl:c,Dh:d,Dl:u,Eh:l,El:h,Fh:p,Fl:m,Gh:_,Gl:f,Hh:b,Hl:w}=this;for(let S=0;S<80;S++){let O=nl(l,h,14)^nl(l,h,18)^e0(l,h,41),j=il(l,h,14)^il(l,h,18)^t0(l,h,41),P=l&p^~l&_,k=h&m^~h&f,C=BO(w,j,k,RQ[S],nc[S]),D=LO(C,b,O,P,IQ[S],sc[S]),H=C|0,W=nl(s,n,28)^e0(s,n,34)^e0(s,n,39),J=il(s,n,28)^t0(s,n,34)^t0(s,n,39),F=s&i^s&a^i&a,q=n&o^n&c^o&c;b=_|0,w=f|0,_=p|0,f=m|0,p=l|0,m=h|0,{h:l,l:h}=Di(d|0,u|0,D|0,H|0),d=a|0,u=c|0,a=i|0,c=o|0,i=s|0,o=n|0;let Q=IO(H,J,q);s=RO(Q,D,W,F),n=Q|0}({h:s,l:n}=Di(this.Ah|0,this.Al|0,s|0,n|0)),{h:i,l:o}=Di(this.Bh|0,this.Bl|0,i|0,o|0),{h:a,l:c}=Di(this.Ch|0,this.Cl|0,a|0,c|0),{h:d,l:u}=Di(this.Dh|0,this.Dl|0,d|0,u|0),{h:l,l:h}=Di(this.Eh|0,this.El|0,l|0,h|0),{h:p,l:m}=Di(this.Fh|0,this.Fl|0,p|0,m|0),{h:_,l:f}=Di(this.Gh|0,this.Gl|0,_|0,f|0),{h:b,l:w}=Di(this.Hh|0,this.Hl|0,b|0,w|0),this.set(s,n,i,o,a,c,d,u,l,h,p,m,_,f,b,w)}roundClean(){Ao(sc,nc)}destroy(){Ao(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},YC=class extends pw{constructor(){super(48),this.Ah=Kr[0]|0,this.Al=Kr[1]|0,this.Bh=Kr[2]|0,this.Bl=Kr[3]|0,this.Ch=Kr[4]|0,this.Cl=Kr[5]|0,this.Dh=Kr[6]|0,this.Dl=Kr[7]|0,this.Eh=Kr[8]|0,this.El=Kr[9]|0,this.Fh=Kr[10]|0,this.Fl=Kr[11]|0,this.Gh=Kr[12]|0,this.Gl=Kr[13]|0,this.Hh=Kr[14]|0,this.Hl=Kr[15]|0}},UO=iw(()=>new XC),MO=iw(()=>new pw),jO=iw(()=>new YC)});var mw,JC,FO=V(()=>{"use strict";g();y();rl();mw=class extends dh{constructor(e,r){super(),this.finished=!1,this.destroyed=!1,sw(e);let s=Xm(r);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,i=new Uint8Array(n);i.set(s.length>n?e.create().update(s).digest():s);for(let o=0;o<i.length;o++)i[o]^=54;this.iHash.update(i),this.oHash=e.create();for(let o=0;o<i.length;o++)i[o]^=106;this.oHash.update(i),Ao(i)}update(e){return lh(this),this.iHash.update(e),this}digestInto(e){lh(this),Nn(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));let{oHash:r,iHash:s,finished:n,destroyed:i,blockLen:o,outputLen:a}=this;return e=e,e.finished=n,e.destroyed=i,e.blockLen=o,e.outputLen=a,e.oHash=r._cloneInto(e.oHash),e.iHash=s._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},JC=(t,e,r)=>new mw(t,e).update(r).digest();JC.create=(t,e)=>new mw(t,e)});function r0(t,e){let r=e.negate();return t?r:e}function yw(t,e){let r=lw(t.Fp,e.map(s=>s.Z));return e.map((s,n)=>t.fromAffine(s.toAffine(r[n])))}function zO(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function QC(t,e){zO(t,e);let r=Math.ceil(e/t)+1,s=2**(t-1),n=2**t,i=tc(t),o=BigInt(t);return{windows:r,windowSize:s,mask:i,maxNumber:n,shiftBy:o}}function HO(t,e,r){let{windowSize:s,mask:n,maxNumber:i,shiftBy:o}=r,a=Number(t&n),c=t>>o;a>s&&(a-=i,c+=ol);let d=e*s,u=d+Math.abs(a)-1,l=a===0,h=a<0,p=e%2!==0;return{nextN:c,offset:u,isZero:l,isNeg:h,isNegF:p,offsetF:d}}function PQ(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((r,s)=>{if(!(r instanceof e))throw new Error("invalid point at index "+s)})}function DQ(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((r,s)=>{if(!e.isValid(r))throw new Error("invalid scalar at index "+s)})}function eT(t){return WO.get(t)||1}function qO(t){if(t!==hh)throw new Error("invalid wNAF")}function KO(t,e,r,s){let n=e,i=t.ZERO,o=t.ZERO;for(;r>hh||s>hh;)r&ol&&(i=i.add(n)),s&ol&&(o=o.add(n)),n=n.double(),r>>=ol,s>>=ol;return{p1:i,p2:o}}function GO(t,e,r,s){PQ(r,t),DQ(s,e);let n=r.length,i=s.length;if(n!==i)throw new Error("arrays of points and scalars must have equal length");let o=t.ZERO,a=cw(BigInt(n)),c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);let d=tc(c),u=new Array(Number(d)+1).fill(o),l=Math.floor((e.BITS-1)/c)*c,h=o;for(let p=l;p>=0;p-=c){u.fill(o);for(let _=0;_<i;_++){let f=s[_],b=Number(f>>BigInt(p)&d);u[b]=u[b].add(r[_])}let m=o;for(let _=u.length-1,f=o;_>0;_--)f=f.add(u[_]),m=m.add(f);if(h=h.add(m),p!==0)for(let _=0;_<c;_++)h=h.double()}return h}function VO(t,e,r){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return zC(e),e}else return Pi(t,{isLE:r})}function XO(t,e,r={},s){if(s===void 0&&(s=t==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);for(let c of["p","n","h"]){let d=e[c];if(!(typeof d=="bigint"&&d>hh))throw new Error(`CURVE.${c} must be positive bigint`)}let n=VO(e.p,r.Fp,s),i=VO(e.n,r.Fn,s),a=["Gx","Gy","a",t==="weierstrass"?"b":"d"];for(let c of a)if(!n.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:n,Fn:i}}var hh,ol,ZC,WO,gw,YO=V(()=>{"use strict";g();y();dw();hw();hh=BigInt(0),ol=BigInt(1);ZC=new WeakMap,WO=new WeakMap;gw=class{constructor(e,r){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=r}_unsafeLadder(e,r,s=this.ZERO){let n=e;for(;r>hh;)r&ol&&(s=s.add(n)),n=n.double(),r>>=ol;return s}precomputeWindow(e,r){let{windows:s,windowSize:n}=QC(r,this.bits),i=[],o=e,a=o;for(let c=0;c<s;c++){a=o,i.push(a);for(let d=1;d<n;d++)a=a.add(o),i.push(a);o=a.double()}return i}wNAF(e,r,s){if(!this.Fn.isValid(s))throw new Error("invalid scalar");let n=this.ZERO,i=this.BASE,o=QC(e,this.bits);for(let a=0;a<o.windows;a++){let{nextN:c,offset:d,isZero:u,isNeg:l,isNegF:h,offsetF:p}=HO(s,a,o);s=c,u?i=i.add(r0(h,r[p])):n=n.add(r0(l,r[d]))}return qO(s),{p:n,f:i}}wNAFUnsafe(e,r,s,n=this.ZERO){let i=QC(e,this.bits);for(let o=0;o<i.windows&&s!==hh;o++){let{nextN:a,offset:c,isZero:d,isNeg:u}=HO(s,o,i);if(s=a,!d){let l=r[c];n=n.add(u?l.negate():l)}}return qO(s),n}getPrecomputes(e,r,s){let n=ZC.get(r);return n||(n=this.precomputeWindow(r,e),e!==1&&(typeof s=="function"&&(n=s(n)),ZC.set(r,n))),n}cached(e,r,s){let n=eT(e);return this.wNAF(n,this.getPrecomputes(n,e,s),r)}unsafe(e,r,s,n){let i=eT(e);return i===1?this._unsafeLadder(e,r,n):this.wNAFUnsafe(i,this.getPrecomputes(i,e,s),r,n)}createCache(e,r){zO(r,this.bits),WO.set(e,r),ZC.delete(e)}hasCache(e){return eT(e)!==1}}});function BQ(t,e,r){let[[s,n],[i,o]]=e,a=JO(o*t,r),c=JO(-n*t,r),d=t-a*s-c*i,u=-a*n-c*o,l=d<Do,h=u<Do;l&&(d=-d),h&&(u=-u);let p=tc(Math.ceil(cw(r)/2))+ph;if(d<Do||d>=p||u<Do||u>=p)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:l,k1:d,k2neg:h,k2:u}}function rT(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function tT(t,e){let r={};for(let s of Object.keys(e))r[s]=t[s]===void 0?e[s]:t[s];return Ym(r.lowS,"lowS"),Ym(r.prehash,"prehash"),r.format!==void 0&&rT(r.format),r}function fh(t,e){let{BYTES:r}=t,s;if(typeof e=="bigint")s=e;else{let n=cs("private key",e);try{s=t.fromBytes(n)}catch{throw new Error(`invalid private key: expected ui8a of size ${r}, got ${typeof e}`)}}if(!t.isValidNot0(s))throw new Error("invalid private key: out of range [1..N-1]");return s}function OQ(t,e={}){let r=XO("weierstrass",t,e),{Fp:s,Fn:n}=r,i=r.CURVE,{h:o,n:a}=i;Qm(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});let{endo:c}=e;if(c&&(!s.is0(i.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let d=eN(s,n);function u(){if(!s.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function l(J,F,q){let{x:Q,y:R}=F.toAffine(),Y=s.toBytes(Q);if(Ym(q,"isCompressed"),q){u();let Z=!s.isOdd(R);return Mn(ZO(Z),Y)}else return Mn(Uint8Array.of(4),Y,s.toBytes(R))}function h(J){ec(J,void 0,"Point");let{publicKey:F,publicKeyUncompressed:q}=d,Q=J.length,R=J[0],Y=J.subarray(1);if(Q===F&&(R===2||R===3)){let Z=s.fromBytes(Y);if(!s.isValid(Z))throw new Error("bad point: is not on curve, wrong x");let I=_(Z),U;try{U=s.sqrt(I)}catch(G){let de=G instanceof Error?": "+G.message:"";throw new Error("bad point: is not on curve, sqrt error"+de)}u();let K=s.isOdd(U);return(R&1)===1!==K&&(U=s.neg(U)),{x:Z,y:U}}else if(Q===q&&R===4){let Z=s.BYTES,I=s.fromBytes(Y.subarray(0,Z)),U=s.fromBytes(Y.subarray(Z,Z*2));if(!f(I,U))throw new Error("bad point: is not on curve");return{x:I,y:U}}else throw new Error(`bad point: got length ${Q}, expected compressed=${F} or uncompressed=${q}`)}let p=e.toBytes||l,m=e.fromBytes||h;function _(J){let F=s.sqr(J),q=s.mul(F,J);return s.add(s.add(q,s.mul(J,i.a)),i.b)}function f(J,F){let q=s.sqr(F),Q=_(J);return s.eql(q,Q)}if(!f(i.Gx,i.Gy))throw new Error("bad curve params: generator point");let b=s.mul(s.pow(i.a,bw),LQ),w=s.mul(s.sqr(i.b),BigInt(27));if(s.is0(s.add(b,w)))throw new Error("bad curve params: a or b");function S(J,F,q=!1){if(!s.isValid(F)||q&&s.is0(F))throw new Error(`bad point coordinate ${J}`);return F}function O(J){if(!(J instanceof D))throw new Error("ProjectivePoint expected")}function j(J){if(!c||!c.basises)throw new Error("no endo");return BQ(J,c.basises,n.ORDER)}let P=qC((J,F)=>{let{X:q,Y:Q,Z:R}=J;if(s.eql(R,s.ONE))return{x:q,y:Q};let Y=J.is0();F==null&&(F=Y?s.ONE:s.inv(R));let Z=s.mul(q,F),I=s.mul(Q,F),U=s.mul(R,F);if(Y)return{x:s.ZERO,y:s.ZERO};if(!s.eql(U,s.ONE))throw new Error("invZ was invalid");return{x:Z,y:I}}),k=qC(J=>{if(J.is0()){if(e.allowInfinityPoint&&!s.is0(J.Y))return;throw new Error("bad point: ZERO")}let{x:F,y:q}=J.toAffine();if(!s.isValid(F)||!s.isValid(q))throw new Error("bad point: x or y not field elements");if(!f(F,q))throw new Error("bad point: equation left != right");if(!J.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function C(J,F,q,Q,R){return q=new D(s.mul(q.X,J),q.Y,q.Z),F=r0(Q,F),q=r0(R,q),F.add(q)}class D{constructor(F,q,Q){this.X=S("x",F),this.Y=S("y",q,!0),this.Z=S("z",Q),Object.freeze(this)}static CURVE(){return i}static fromAffine(F){let{x:q,y:Q}=F||{};if(!F||!s.isValid(q)||!s.isValid(Q))throw new Error("invalid affine point");if(F instanceof D)throw new Error("projective point not allowed");return s.is0(q)&&s.is0(Q)?D.ZERO:new D(q,Q,s.ONE)}static fromBytes(F){let q=D.fromAffine(m(ec(F,void 0,"point")));return q.assertValidity(),q}static fromHex(F){return D.fromBytes(cs("pointHex",F))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(F=8,q=!0){return W.createCache(this,F),q||this.multiply(bw),this}assertValidity(){k(this)}hasEvenY(){let{y:F}=this.toAffine();if(!s.isOdd)throw new Error("Field doesn't support isOdd");return!s.isOdd(F)}equals(F){O(F);let{X:q,Y:Q,Z:R}=this,{X:Y,Y:Z,Z:I}=F,U=s.eql(s.mul(q,I),s.mul(Y,R)),K=s.eql(s.mul(Q,I),s.mul(Z,R));return U&&K}negate(){return new D(this.X,s.neg(this.Y),this.Z)}double(){let{a:F,b:q}=i,Q=s.mul(q,bw),{X:R,Y,Z}=this,I=s.ZERO,U=s.ZERO,K=s.ZERO,z=s.mul(R,R),G=s.mul(Y,Y),de=s.mul(Z,Z),ce=s.mul(R,Y);return ce=s.add(ce,ce),K=s.mul(R,Z),K=s.add(K,K),I=s.mul(F,K),U=s.mul(Q,de),U=s.add(I,U),I=s.sub(G,U),U=s.add(G,U),U=s.mul(I,U),I=s.mul(ce,I),K=s.mul(Q,K),de=s.mul(F,de),ce=s.sub(z,de),ce=s.mul(F,ce),ce=s.add(ce,K),K=s.add(z,z),z=s.add(K,z),z=s.add(z,de),z=s.mul(z,ce),U=s.add(U,z),de=s.mul(Y,Z),de=s.add(de,de),z=s.mul(de,ce),I=s.sub(I,z),K=s.mul(de,G),K=s.add(K,K),K=s.add(K,K),new D(I,U,K)}add(F){O(F);let{X:q,Y:Q,Z:R}=this,{X:Y,Y:Z,Z:I}=F,U=s.ZERO,K=s.ZERO,z=s.ZERO,G=i.a,de=s.mul(i.b,bw),ce=s.mul(q,Y),Je=s.mul(Q,Z),tt=s.mul(R,I),Ot=s.add(q,Q),Et=s.add(Y,Z);Ot=s.mul(Ot,Et),Et=s.add(ce,Je),Ot=s.sub(Ot,Et),Et=s.add(q,R);let Ut=s.add(Y,I);return Et=s.mul(Et,Ut),Ut=s.add(ce,tt),Et=s.sub(Et,Ut),Ut=s.add(Q,R),U=s.add(Z,I),Ut=s.mul(Ut,U),U=s.add(Je,tt),Ut=s.sub(Ut,U),z=s.mul(G,Et),U=s.mul(de,tt),z=s.add(U,z),U=s.sub(Je,z),z=s.add(Je,z),K=s.mul(U,z),Je=s.add(ce,ce),Je=s.add(Je,ce),tt=s.mul(G,tt),Et=s.mul(de,Et),Je=s.add(Je,tt),tt=s.sub(ce,tt),tt=s.mul(G,tt),Et=s.add(Et,tt),ce=s.mul(Je,Et),K=s.add(K,ce),ce=s.mul(Ut,Et),U=s.mul(Ot,U),U=s.sub(U,ce),ce=s.mul(Ot,Je),z=s.mul(Ut,z),z=s.add(z,ce),new D(U,K,z)}subtract(F){return this.add(F.negate())}is0(){return this.equals(D.ZERO)}multiply(F){let{endo:q}=e;if(!n.isValidNot0(F))throw new Error("invalid scalar: out of range");let Q,R,Y=Z=>W.cached(this,Z,I=>yw(D,I));if(q){let{k1neg:Z,k1:I,k2neg:U,k2:K}=j(F),{p:z,f:G}=Y(I),{p:de,f:ce}=Y(K);R=G.add(ce),Q=C(q.beta,z,de,Z,U)}else{let{p:Z,f:I}=Y(F);Q=Z,R=I}return yw(D,[Q,R])[0]}multiplyUnsafe(F){let{endo:q}=e,Q=this;if(!n.isValid(F))throw new Error("invalid scalar: out of range");if(F===Do||Q.is0())return D.ZERO;if(F===ph)return Q;if(W.hasCache(this))return this.multiply(F);if(q){let{k1neg:R,k1:Y,k2neg:Z,k2:I}=j(F),{p1:U,p2:K}=KO(D,Q,Y,I);return C(q.beta,U,K,R,Z)}else return W.unsafe(Q,F)}multiplyAndAddUnsafe(F,q,Q){let R=this.multiplyUnsafe(q).add(F.multiplyUnsafe(Q));return R.is0()?void 0:R}toAffine(F){return P(this,F)}isTorsionFree(){let{isTorsionFree:F}=e;return o===ph?!0:F?F(D,this):W.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:F}=e;return o===ph?this:F?F(D,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(F=!0){return Ym(F,"isCompressed"),this.assertValidity(),p(D,this,F)}toHex(F=!0){return Io(this.toBytes(F))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(F=!0){return this.toBytes(F)}_setWindowSize(F){this.precompute(F)}static normalizeZ(F){return yw(D,F)}static msm(F,q){return GO(D,n,F,q)}static fromPrivateKey(F){return D.BASE.multiply(fh(n,F))}}D.BASE=new D(i.Gx,i.Gy,s.ONE),D.ZERO=new D(s.ZERO,s.ONE,s.ZERO),D.Fp=s,D.Fn=n;let H=n.BITS,W=new gw(D,e.endo?Math.ceil(H/2):H);return D.BASE.precompute(8),D}function ZO(t){return Uint8Array.of(t?2:3)}function eN(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function NQ(t,e={}){let{Fn:r}=t,s=e.randomBytes||ow,n=Object.assign(eN(t.Fp,r),{seed:WC(r.ORDER)});function i(p){try{return!!fh(r,p)}catch{return!1}}function o(p,m){let{publicKey:_,publicKeyUncompressed:f}=n;try{let b=p.length;return m===!0&&b!==_||m===!1&&b!==f?!1:!!t.fromBytes(p)}catch{return!1}}function a(p=s(n.seed)){return SO(ec(p,n.seed,"seed"),r.ORDER)}function c(p,m=!0){return t.BASE.multiply(fh(r,p)).toBytes(m)}function d(p){let m=a(p);return{secretKey:m,publicKey:c(m)}}function u(p){if(typeof p=="bigint")return!1;if(p instanceof t)return!0;let{secretKey:m,publicKey:_,publicKeyUncompressed:f}=n;if(r.allowedLengths||m===_)return;let b=cs("key",p).length;return b===_||b===f}function l(p,m,_=!0){if(u(p)===!0)throw new Error("first arg must be private key");if(u(m)===!1)throw new Error("second arg must be public key");let f=fh(r,p);return t.fromHex(m).multiply(f).toBytes(_)}return Object.freeze({getPublicKey:c,getSharedSecret:l,keygen:d,Point:t,utils:{isValidSecretKey:i,isValidPublicKey:o,randomSecretKey:a,isValidPrivateKey:i,randomPrivateKey:a,normPrivateKeyToScalar:p=>fh(r,p),precompute(p=8,m=t.BASE){return m.precompute(p,!1)}},lengths:n})}function UQ(t,e,r={}){sw(e),Qm(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let s=r.randomBytes||ow,n=r.hmac||((q,...Q)=>JC(e,q,Mn(...Q))),{Fp:i,Fn:o}=t,{ORDER:a,BITS:c}=o,{keygen:d,getPublicKey:u,getSharedSecret:l,utils:h,lengths:p}=NQ(t,r),m={prehash:!1,lowS:typeof r.lowS=="boolean"?r.lowS:!1,format:void 0,extraEntropy:!1},_="compact";function f(q){let Q=a>>ph;return q>Q}function b(q,Q){if(!o.isValidNot0(Q))throw new Error(`invalid signature ${q}: out of range 1..Point.Fn.ORDER`);return Q}function w(q,Q){rT(Q);let R=p.signature,Y=Q==="compact"?R:Q==="recovered"?R+1:void 0;return ec(q,Y,`${Q} signature`)}class S{constructor(Q,R,Y){this.r=b("r",Q),this.s=b("s",R),Y!=null&&(this.recovery=Y),Object.freeze(this)}static fromBytes(Q,R=_){w(Q,R);let Y;if(R==="der"){let{r:K,s:z}=Po.toSig(ec(Q));return new S(K,z)}R==="recovered"&&(Y=Q[0],R="compact",Q=Q.subarray(1));let Z=o.BYTES,I=Q.subarray(0,Z),U=Q.subarray(Z,Z*2);return new S(o.fromBytes(I),o.fromBytes(U),Y)}static fromHex(Q,R){return this.fromBytes(tl(Q),R)}addRecoveryBit(Q){return new S(this.r,this.s,Q)}recoverPublicKey(Q){let R=i.ORDER,{r:Y,s:Z,recovery:I}=this;if(I==null||![0,1,2,3].includes(I))throw new Error("recovery id invalid");if(a*QO<R&&I>1)throw new Error("recovery id is ambiguous for h>1 curve");let K=I===2||I===3?Y+a:Y;if(!i.isValid(K))throw new Error("recovery id 2 or 3 invalid");let z=i.toBytes(K),G=t.fromBytes(Mn(ZO((I&1)===0),z)),de=o.inv(K),ce=j(cs("msgHash",Q)),Je=o.create(-ce*de),tt=o.create(Z*de),Ot=t.BASE.multiplyUnsafe(Je).add(G.multiplyUnsafe(tt));if(Ot.is0())throw new Error("point at infinify");return Ot.assertValidity(),Ot}hasHighS(){return f(this.s)}toBytes(Q=_){if(rT(Q),Q==="der")return tl(Po.hexFromSig(this));let R=o.toBytes(this.r),Y=o.toBytes(this.s);if(Q==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return Mn(Uint8Array.of(this.recovery),R,Y)}return Mn(R,Y)}toHex(Q){return Io(this.toBytes(Q))}assertValidity(){}static fromCompact(Q){return S.fromBytes(cs("sig",Q),"compact")}static fromDER(Q){return S.fromBytes(cs("sig",Q),"der")}normalizeS(){return this.hasHighS()?new S(this.r,o.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return Io(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return Io(this.toBytes("compact"))}}let O=r.bits2int||function(Q){if(Q.length>8192)throw new Error("input is too large");let R=uh(Q),Y=Q.length*8-c;return Y>0?R>>BigInt(Y):R},j=r.bits2int_modN||function(Q){return o.create(O(Q))},P=tc(c);function k(q){return uO("num < 2^"+c,q,Do,P),o.toBytes(q)}function C(q,Q){return ec(q,void 0,"message"),Q?ec(e(q),void 0,"prehashed message"):q}function D(q,Q,R){if(["recovered","canonical"].some(Je=>Je in R))throw new Error("sign() legacy options not supported");let{lowS:Y,prehash:Z,extraEntropy:I}=tT(R,m);q=C(q,Z);let U=j(q),K=fh(o,Q),z=[k(K),k(U)];if(I!=null&&I!==!1){let Je=I===!0?s(p.secretKey):I;z.push(cs("extraEntropy",Je))}let G=Mn(...z),de=U;function ce(Je){let tt=O(Je);if(!o.isValidNot0(tt))return;let Ot=o.inv(tt),Et=t.BASE.multiply(tt).toAffine(),Ut=o.create(Et.x);if(Ut===Do)return;let Js=o.create(Ot*o.create(de+Ut*K));if(Js===Do)return;let Qs=(Et.x===Ut?0:2)|Number(Et.y&ph),_c=Js;return Y&&f(Js)&&(_c=o.neg(Js),Qs^=1),new S(Ut,_c,Qs)}return{seed:G,k2sig:ce}}function H(q,Q,R={}){q=cs("message",q);let{seed:Y,k2sig:Z}=D(q,Q,R);return hO(e.outputLen,o.BYTES,n)(Y,Z)}function W(q){let Q,R=typeof q=="string"||el(q),Y=!R&&q!==null&&typeof q=="object"&&typeof q.r=="bigint"&&typeof q.s=="bigint";if(!R&&!Y)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(Y)Q=new S(q.r,q.s);else if(R){try{Q=S.fromBytes(cs("sig",q),"der")}catch(Z){if(!(Z instanceof Po.Err))throw Z}if(!Q)try{Q=S.fromBytes(cs("sig",q),"compact")}catch{return!1}}return Q||!1}function J(q,Q,R,Y={}){let{lowS:Z,prehash:I,format:U}=tT(Y,m);if(R=cs("publicKey",R),Q=C(cs("message",Q),I),"strict"in Y)throw new Error("options.strict was renamed to lowS");let K=U===void 0?W(q):S.fromBytes(cs("sig",q),U);if(K===!1)return!1;try{let z=t.fromBytes(R);if(Z&&K.hasHighS())return!1;let{r:G,s:de}=K,ce=j(Q),Je=o.inv(de),tt=o.create(ce*Je),Ot=o.create(G*Je),Et=t.BASE.multiplyUnsafe(tt).add(z.multiplyUnsafe(Ot));return Et.is0()?!1:o.create(Et.x)===G}catch{return!1}}function F(q,Q,R={}){let{prehash:Y}=tT(R,m);return Q=C(Q,Y),S.fromBytes(q,"recovered").recoverPublicKey(Q).toBytes()}return Object.freeze({keygen:d,getPublicKey:u,getSharedSecret:l,utils:h,lengths:p,Point:t,sign:H,verify:J,recoverPublicKey:F,Signature:S,hash:e})}function MQ(t){let e={a:t.a,b:t.b,p:t.Fp.ORDER,n:t.n,h:t.h,Gx:t.Gx,Gy:t.Gy},r=t.Fp,s=t.allowedPrivateKeyLengths?Array.from(new Set(t.allowedPrivateKeyLengths.map(o=>Math.ceil(o/2)))):void 0,n=Pi(e.n,{BITS:t.nBitLength,allowedLengths:s,modFromBytes:t.wrapPrivateKey}),i={Fp:r,Fn:n,allowInfinityPoint:t.allowInfinityPoint,endo:t.endo,isTorsionFree:t.isTorsionFree,clearCofactor:t.clearCofactor,fromBytes:t.fromBytes,toBytes:t.toBytes};return{CURVE:e,curveOpts:i}}function jQ(t){let{CURVE:e,curveOpts:r}=MQ(t),s={hmac:t.hmac,randomBytes:t.randomBytes,lowS:t.lowS,bits2int:t.bits2int,bits2int_modN:t.bits2int_modN};return{CURVE:e,curveOpts:r,hash:t.hash,ecdsaOpts:s}}function $Q(t,e){let r=e.Point;return Object.assign({},e,{ProjectivePoint:r,CURVE:Object.assign({},t,uw(r.Fn.ORDER,r.Fn.BITS))})}function tN(t){let{CURVE:e,curveOpts:r,hash:s,ecdsaOpts:n}=jQ(t),i=OQ(e,r),o=UQ(i,s,n);return $Q(t,o)}var JO,sT,Po,Do,ph,QO,bw,LQ,rN=V(()=>{"use strict";g();y();FO();rl();dw();YO();hw();JO=(t,e)=>(t+(t>=0?e:-e)/QO)/e;sT=class extends Error{constructor(e=""){super(e)}},Po={Err:sT,_tlv:{encode:(t,e)=>{let{Err:r}=Po;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length&1)throw new r("tlv.encode: unpadded data");let s=e.length/2,n=Jm(s);if(n.length/2&128)throw new r("tlv.encode: long form length too big");let i=s>127?Jm(n.length/2|128):"";return Jm(t)+i+n+e},decode(t,e){let{Err:r}=Po,s=0;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length<2||e[s++]!==t)throw new r("tlv.decode: wrong tlv");let n=e[s++],i=!!(n&128),o=0;if(!i)o=n;else{let c=n&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");let d=e.subarray(s,s+c);if(d.length!==c)throw new r("tlv.decode: length bytes not complete");if(d[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(let u of d)o=o<<8|u;if(s+=c,o<128)throw new r("tlv.decode(long): not minimal encoding")}let a=e.subarray(s,s+o);if(a.length!==o)throw new r("tlv.decode: wrong value length");return{v:a,l:e.subarray(s+o)}}},_int:{encode(t){let{Err:e}=Po;if(t<Do)throw new e("integer: negative integers are not allowed");let r=Jm(t);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return r},decode(t){let{Err:e}=Po;if(t[0]&128)throw new e("invalid signature integer: negative");if(t[0]===0&&!(t[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return uh(t)}},toSig(t){let{Err:e,_int:r,_tlv:s}=Po,n=cs("signature",t),{v:i,l:o}=s.decode(48,n);if(o.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=s.decode(2,i),{v:d,l:u}=s.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(d)}},hexFromSig(t){let{_tlv:e,_int:r}=Po,s=e.encode(2,r.encode(t.r)),n=e.encode(2,r.encode(t.s)),i=s+n;return e.encode(48,i)}},Do=BigInt(0),ph=BigInt(1),QO=BigInt(2),bw=BigInt(3),LQ=BigInt(4)});function xw(t,e){let r=s=>tN({...t,hash:s});return{...r(e),create:r}}var sN=V(()=>{"use strict";g();y();rN();});var nN,iN,oN,FQ,HQ,qQ,aN,mPe,gPe,cN=V(()=>{"use strict";g();y();$O();sN();hw();nN={p:BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),h:BigInt(1),a:BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")},iN={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff"),n:BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),h:BigInt(1),a:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc"),b:BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"),Gx:BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"),Gy:BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f")},oN={p:BigInt("0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),n:BigInt("0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409"),h:BigInt(1),a:BigInt("0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc"),b:BigInt("0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00"),Gx:BigInt("0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66"),Gy:BigInt("0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650")},FQ=Pi(nN.p),HQ=Pi(iN.p),qQ=Pi(oN.p),aN=xw({...nN,Fp:FQ,lowS:!1},UO),mPe=xw({...iN,Fp:HQ,lowS:!1},jO),gPe=xw({...oN,Fp:qQ,lowS:!1,allowedPrivateKeyLengths:[130,131,132]},MO)});var ww,dN=V(()=>{"use strict";g();y();cN();ww=aN});var uN=Me(ic=>{"use strict";g();y();Object.defineProperty(ic,"__esModule",{value:!0});ic.LEB128=ic.SignedLEB128=ic.UnsignedLEB128=void 0;var mh;(function(t){t[t.LOWER_7=127]="LOWER_7",t[t.UPPER_1=128]="UPPER_1"})(mh||(mh={}));var lN=t=>Number.isSafeInteger(t),al=class{static decode(e,r=0){let s=this.$scanForNullBytes(e,r),n=0,i=0;for(let o=0;o<=s-r;o++){let a=e[r+o]&mh.LOWER_7;n|=a<<i,i+=7}return n}static encode(e){if(this.check(e),e<0)throw new Error(`An unsigned number must NOT be negative, ${e} is!`);let r=[],s=e;do{let n=s&mh.LOWER_7;s>>=7,s&&(n=n|mh.UPPER_1),r.push(n)}while(s);return Uint8Array.from(r)}static check(e){if(!lN(e))throw new Error(`${e} is not a safe integer!`)}static $scanForNullBytes(e,r=0){let s=r,n=0;do{if(s>=e.byteLength)throw new Error("This is not a LEB128-encoded Uint8Array, no ending found!");n=e.slice(s,s+1)[0],s++}while(n&mh.UPPER_1);return s-1}static getLength(e,r=0){return this.$scanForNullBytes(e,r)-r}};ic.UnsignedLEB128=al;var s0=class{static $ceil7mul(e){let r=e;for(;r%7;)r++;return r}static check(e){if(!lN(e))throw new Error(`${e} is not a safe integer!`)}static encode(e){if(this.check(e),e>=0)throw new Error(`A signed number must be negative, ${e} isn't!`);let r=Math.ceil(Math.log2(-e));return al.encode((1<<this.$ceil7mul(r))+e)}static decode(e,r=0){let s=al.decode(e,r);return-((1<<Math.ceil(Math.log2(s)))-s)}};ic.SignedLEB128=s0;var n0=class{};ic.LEB128=n0;n0.encode=t=>(t>=0?al:s0).encode(t);n0.decode=(t,e=0,r=!1)=>(r?s0:al).decode(t,e)});var fN=Me((nT,hN)=>{"use strict";g();y();(function(t){"use strict";function e(I){return parseInt(I)===I}function r(I){if(!e(I.length))return!1;for(var U=0;U<I.length;U++)if(!e(I[U])||I[U]<0||I[U]>255)return!1;return!0}function s(I,U){if(I.buffer&&I.name==="Uint8Array")return U&&(I.slice?I=I.slice():I=Array.prototype.slice.call(I)),I;if(Array.isArray(I)){if(!r(I))throw new Error("Array contains invalid value: "+I);return new Uint8Array(I)}if(e(I.length)&&r(I))return new Uint8Array(I);throw new Error("unsupported array-like object")}function n(I){return new Uint8Array(I)}function i(I,U,K,z,G){(z!=null||G!=null)&&(I.slice?I=I.slice(z,G):I=Array.prototype.slice.call(I,z,G)),U.set(I,K)}var o=(function(){function I(K){var z=[],G=0;for(K=encodeURI(K);G<K.length;){var de=K.charCodeAt(G++);de===37?(z.push(parseInt(K.substr(G,2),16)),G+=2):z.push(de)}return s(z)}function U(K){for(var z=[],G=0;G<K.length;){var de=K[G];de<128?(z.push(String.fromCharCode(de)),G++):de>191&&de<224?(z.push(String.fromCharCode((de&31)<<6|K[G+1]&63)),G+=2):(z.push(String.fromCharCode((de&15)<<12|(K[G+1]&63)<<6|K[G+2]&63)),G+=3)}return z.join("")}return{toBytes:I,fromBytes:U}})(),a=(function(){function I(z){for(var G=[],de=0;de<z.length;de+=2)G.push(parseInt(z.substr(de,2),16));return G}var U="0123456789abcdef";function K(z){for(var G=[],de=0;de<z.length;de++){var ce=z[de];G.push(U[(ce&240)>>4]+U[ce&15])}return G.join("")}return{toBytes:I,fromBytes:K}})(),c={16:10,24:12,32:14},d=[1,2,4,8,16,32,64,128,27,54,108,216,171,77,154,47,94,188,99,198,151,53,106,212,179,125,250,239,197,145],u=[99,124,119,123,242,107,111,197,48,1,103,43,254,215,171,118,202,130,201,125,250,89,71,240,173,212,162,175,156,164,114,192,183,253,147,38,54,63,247,204,52,165,229,241,113,216,49,21,4,199,35,195,24,150,5,154,7,18,128,226,235,39,178,117,9,131,44,26,27,110,90,160,82,59,214,179,41,227,47,132,83,209,0,237,32,252,177,91,106,203,190,57,74,76,88,207,208,239,170,251,67,77,51,133,69,249,2,127,80,60,159,168,81,163,64,143,146,157,56,245,188,182,218,33,16,255,243,210,205,12,19,236,95,151,68,23,196,167,126,61,100,93,25,115,96,129,79,220,34,42,144,136,70,238,184,20,222,94,11,219,224,50,58,10,73,6,36,92,194,211,172,98,145,149,228,121,231,200,55,109,141,213,78,169,108,86,244,234,101,122,174,8,186,120,37,46,28,166,180,198,232,221,116,31,75,189,139,138,112,62,181,102,72,3,246,14,97,53,87,185,134,193,29,158,225,248,152,17,105,217,142,148,155,30,135,233,206,85,40,223,140,161,137,13,191,230,66,104,65,153,45,15,176,84,187,22],l=[82,9,106,213,48,54,165,56,191,64,163,158,129,243,215,251,124,227,57,130,155,47,255,135,52,142,67,68,196,222,233,203,84,123,148,50,166,194,35,61,238,76,149,11,66,250,195,78,8,46,161,102,40,217,36,178,118,91,162,73,109,139,209,37,114,248,246,100,134,104,152,22,212,164,92,204,93,101,182,146,108,112,72,80,253,237,185,218,94,21,70,87,167,141,157,132,144,216,171,0,140,188,211,10,247,228,88,5,184,179,69,6,208,44,30,143,202,63,15,2,193,175,189,3,1,19,138,107,58,145,17,65,79,103,220,234,151,242,207,206,240,180,230,115,150,172,116,34,231,173,53,133,226,249,55,232,28,117,223,110,71,241,26,113,29,41,197,137,111,183,98,14,170,24,190,27,252,86,62,75,198,210,121,32,154,219,192,254,120,205,90,244,31,221,168,51,136,7,199,49,177,18,16,89,39,128,236,95,96,81,127,169,25,181,74,13,45,229,122,159,147,201,156,239,160,224,59,77,174,42,245,176,200,235,187,60,131,83,153,97,23,43,4,126,186,119,214,38,225,105,20,99,85,33,12,125],h=[3328402341,4168907908,4000806809,4135287693,4294111757,3597364157,3731845041,2445657428,1613770832,33620227,3462883241,1445669757,3892248089,3050821474,1303096294,3967186586,2412431941,528646813,2311702848,4202528135,4026202645,2992200171,2387036105,4226871307,1101901292,3017069671,1604494077,1169141738,597466303,1403299063,3832705686,2613100635,1974974402,3791519004,1033081774,1277568618,1815492186,2118074177,4126668546,2211236943,1748251740,1369810420,3521504564,4193382664,3799085459,2883115123,1647391059,706024767,134480908,2512897874,1176707941,2646852446,806885416,932615841,168101135,798661301,235341577,605164086,461406363,3756188221,3454790438,1311188841,2142417613,3933566367,302582043,495158174,1479289972,874125870,907746093,3698224818,3025820398,1537253627,2756858614,1983593293,3084310113,2108928974,1378429307,3722699582,1580150641,327451799,2790478837,3117535592,0,3253595436,1075847264,3825007647,2041688520,3059440621,3563743934,2378943302,1740553945,1916352843,2487896798,2555137236,2958579944,2244988746,3151024235,3320835882,1336584933,3992714006,2252555205,2588757463,1714631509,293963156,2319795663,3925473552,67240454,4269768577,2689618160,2017213508,631218106,1269344483,2723238387,1571005438,2151694528,93294474,1066570413,563977660,1882732616,4059428100,1673313503,2008463041,2950355573,1109467491,537923632,3858759450,4260623118,3218264685,2177748300,403442708,638784309,3287084079,3193921505,899127202,2286175436,773265209,2479146071,1437050866,4236148354,2050833735,3362022572,3126681063,840505643,3866325909,3227541664,427917720,2655997905,2749160575,1143087718,1412049534,999329963,193497219,2353415882,3354324521,1807268051,672404540,2816401017,3160301282,369822493,2916866934,3688947771,1681011286,1949973070,336202270,2454276571,201721354,1210328172,3093060836,2680341085,3184776046,1135389935,3294782118,965841320,831886756,3554993207,4068047243,3588745010,2345191491,1849112409,3664604599,26054028,2983581028,2622377682,1235855840,3630984372,2891339514,4092916743,3488279077,3395642799,4101667470,1202630377,268961816,1874508501,4034427016,1243948399,1546530418,941366308,1470539505,1941222599,2546386513,3421038627,2715671932,3899946140,1042226977,2521517021,1639824860,227249030,260737669,3765465232,2084453954,1907733956,3429263018,2420656344,100860677,4160157185,470683154,3261161891,1781871967,2924959737,1773779408,394692241,2579611992,974986535,664706745,3655459128,3958962195,731420851,571543859,3530123707,2849626480,126783113,865375399,765172662,1008606754,361203602,3387549984,2278477385,2857719295,1344809080,2782912378,59542671,1503764984,160008576,437062935,1707065306,3622233649,2218934982,3496503480,2185314755,697932208,1512910199,504303377,2075177163,2824099068,1841019862,739644986],p=[2781242211,2230877308,2582542199,2381740923,234877682,3184946027,2984144751,1418839493,1348481072,50462977,2848876391,2102799147,434634494,1656084439,3863849899,2599188086,1167051466,2636087938,1082771913,2281340285,368048890,3954334041,3381544775,201060592,3963727277,1739838676,4250903202,3930435503,3206782108,4149453988,2531553906,1536934080,3262494647,484572669,2923271059,1783375398,1517041206,1098792767,49674231,1334037708,1550332980,4098991525,886171109,150598129,2481090929,1940642008,1398944049,1059722517,201851908,1385547719,1699095331,1587397571,674240536,2704774806,252314885,3039795866,151914247,908333586,2602270848,1038082786,651029483,1766729511,3447698098,2682942837,454166793,2652734339,1951935532,775166490,758520603,3000790638,4004797018,4217086112,4137964114,1299594043,1639438038,3464344499,2068982057,1054729187,1901997871,2534638724,4121318227,1757008337,0,750906861,1614815264,535035132,3363418545,3988151131,3201591914,1183697867,3647454910,1265776953,3734260298,3566750796,3903871064,1250283471,1807470800,717615087,3847203498,384695291,3313910595,3617213773,1432761139,2484176261,3481945413,283769337,100925954,2180939647,4037038160,1148730428,3123027871,3813386408,4087501137,4267549603,3229630528,2315620239,2906624658,3156319645,1215313976,82966005,3747855548,3245848246,1974459098,1665278241,807407632,451280895,251524083,1841287890,1283575245,337120268,891687699,801369324,3787349855,2721421207,3431482436,959321879,1469301956,4065699751,2197585534,1199193405,2898814052,3887750493,724703513,2514908019,2696962144,2551808385,3516813135,2141445340,1715741218,2119445034,2872807568,2198571144,3398190662,700968686,3547052216,1009259540,2041044702,3803995742,487983883,1991105499,1004265696,1449407026,1316239930,504629770,3683797321,168560134,1816667172,3837287516,1570751170,1857934291,4014189740,2797888098,2822345105,2754712981,936633572,2347923833,852879335,1133234376,1500395319,3084545389,2348912013,1689376213,3533459022,3762923945,3034082412,4205598294,133428468,634383082,2949277029,2398386810,3913789102,403703816,3580869306,2297460856,1867130149,1918643758,607656988,4049053350,3346248884,1368901318,600565992,2090982877,2632479860,557719327,3717614411,3697393085,2249034635,2232388234,2430627952,1115438654,3295786421,2865522278,3633334344,84280067,33027830,303828494,2747425121,1600795957,4188952407,3496589753,2434238086,1486471617,658119965,3106381470,953803233,334231800,3005978776,857870609,3151128937,1890179545,2298973838,2805175444,3056442267,574365214,2450884487,550103529,1233637070,4289353045,2018519080,2057691103,2399374476,4166623649,2148108681,387583245,3664101311,836232934,3330556482,3100665960,3280093505,2955516313,2002398509,287182607,3413881008,4238890068,3597515707,975967766],m=[1671808611,2089089148,2006576759,2072901243,4061003762,1807603307,1873927791,3310653893,810573872,16974337,1739181671,729634347,4263110654,3613570519,2883997099,1989864566,3393556426,2191335298,3376449993,2106063485,4195741690,1508618841,1204391495,4027317232,2917941677,3563566036,2734514082,2951366063,2629772188,2767672228,1922491506,3227229120,3082974647,4246528509,2477669779,644500518,911895606,1061256767,4144166391,3427763148,878471220,2784252325,3845444069,4043897329,1905517169,3631459288,827548209,356461077,67897348,3344078279,593839651,3277757891,405286936,2527147926,84871685,2595565466,118033927,305538066,2157648768,3795705826,3945188843,661212711,2999812018,1973414517,152769033,2208177539,745822252,439235610,455947803,1857215598,1525593178,2700827552,1391895634,994932283,3596728278,3016654259,695947817,3812548067,795958831,2224493444,1408607827,3513301457,0,3979133421,543178784,4229948412,2982705585,1542305371,1790891114,3410398667,3201918910,961245753,1256100938,1289001036,1491644504,3477767631,3496721360,4012557807,2867154858,4212583931,1137018435,1305975373,861234739,2241073541,1171229253,4178635257,33948674,2139225727,1357946960,1011120188,2679776671,2833468328,1374921297,2751356323,1086357568,2408187279,2460827538,2646352285,944271416,4110742005,3168756668,3066132406,3665145818,560153121,271589392,4279952895,4077846003,3530407890,3444343245,202643468,322250259,3962553324,1608629855,2543990167,1154254916,389623319,3294073796,2817676711,2122513534,1028094525,1689045092,1575467613,422261273,1939203699,1621147744,2174228865,1339137615,3699352540,577127458,712922154,2427141008,2290289544,1187679302,3995715566,3100863416,339486740,3732514782,1591917662,186455563,3681988059,3762019296,844522546,978220090,169743370,1239126601,101321734,611076132,1558493276,3260915650,3547250131,2901361580,1655096418,2443721105,2510565781,3828863972,2039214713,3878868455,3359869896,928607799,1840765549,2374762893,3580146133,1322425422,2850048425,1823791212,1459268694,4094161908,3928346602,1706019429,2056189050,2934523822,135794696,3134549946,2022240376,628050469,779246638,472135708,2800834470,3032970164,3327236038,3894660072,3715932637,1956440180,522272287,1272813131,3185336765,2340818315,2323976074,1888542832,1044544574,3049550261,1722469478,1222152264,50660867,4127324150,236067854,1638122081,895445557,1475980887,3117443513,2257655686,3243809217,489110045,2662934430,3778599393,4162055160,2561878936,288563729,1773916777,3648039385,2391345038,2493985684,2612407707,505560094,2274497927,3911240169,3460925390,1442818645,678973480,3749357023,2358182796,2717407649,2306869641,219617805,3218761151,3862026214,1120306242,1756942440,1103331905,2578459033,762796589,252780047,2966125488,1425844308,3151392187,372911126],_=[1667474886,2088535288,2004326894,2071694838,4075949567,1802223062,1869591006,3318043793,808472672,16843522,1734846926,724270422,4278065639,3621216949,2880169549,1987484396,3402253711,2189597983,3385409673,2105378810,4210693615,1499065266,1195886990,4042263547,2913856577,3570689971,2728590687,2947541573,2627518243,2762274643,1920112356,3233831835,3082273397,4261223649,2475929149,640051788,909531756,1061110142,4160160501,3435941763,875846760,2779116625,3857003729,4059105529,1903268834,3638064043,825316194,353713962,67374088,3351728789,589522246,3284360861,404236336,2526454071,84217610,2593830191,117901582,303183396,2155911963,3806477791,3958056653,656894286,2998062463,1970642922,151591698,2206440989,741110872,437923380,454765878,1852748508,1515908788,2694904667,1381168804,993742198,3604373943,3014905469,690584402,3823320797,791638366,2223281939,1398011302,3520161977,0,3991743681,538992704,4244381667,2981218425,1532751286,1785380564,3419096717,3200178535,960056178,1246420628,1280103576,1482221744,3486468741,3503319995,4025428677,2863326543,4227536621,1128514950,1296947098,859002214,2240123921,1162203018,4193849577,33687044,2139062782,1347481760,1010582648,2678045221,2829640523,1364325282,2745433693,1077985408,2408548869,2459086143,2644360225,943212656,4126475505,3166494563,3065430391,3671750063,555836226,269496352,4294908645,4092792573,3537006015,3452783745,202118168,320025894,3974901699,1600119230,2543297077,1145359496,387397934,3301201811,2812801621,2122220284,1027426170,1684319432,1566435258,421079858,1936954854,1616945344,2172753945,1330631070,3705438115,572679748,707427924,2425400123,2290647819,1179044492,4008585671,3099120491,336870440,3739122087,1583276732,185277718,3688593069,3772791771,842159716,976899700,168435220,1229577106,101059084,606366792,1549591736,3267517855,3553849021,2897014595,1650632388,2442242105,2509612081,3840161747,2038008818,3890688725,3368567691,926374254,1835907034,2374863873,3587531953,1313788572,2846482505,1819063512,1448540844,4109633523,3941213647,1701162954,2054852340,2930698567,134748176,3132806511,2021165296,623210314,774795868,471606328,2795958615,3031746419,3334885783,3907527627,3722280097,1953799400,522133822,1263263126,3183336545,2341176845,2324333839,1886425312,1044267644,3048588401,1718004428,1212733584,50529542,4143317495,235803164,1633788866,892690282,1465383342,3115962473,2256965911,3250673817,488449850,2661202215,3789633753,4177007595,2560144171,286339874,1768537042,3654906025,2391705863,2492770099,2610673197,505291324,2273808917,3924369609,3469625735,1431699370,673740880,3755965093,2358021891,2711746649,2307489801,218961690,3217021541,3873845719,1111672452,1751693520,1094828930,2576986153,757954394,252645662,2964376443,1414855848,3149649517,370555436],f=[1374988112,2118214995,437757123,975658646,1001089995,530400753,2902087851,1273168787,540080725,2910219766,2295101073,4110568485,1340463100,3307916247,641025152,3043140495,3736164937,632953703,1172967064,1576976609,3274667266,2169303058,2370213795,1809054150,59727847,361929877,3211623147,2505202138,3569255213,1484005843,1239443753,2395588676,1975683434,4102977912,2572697195,666464733,3202437046,4035489047,3374361702,2110667444,1675577880,3843699074,2538681184,1649639237,2976151520,3144396420,4269907996,4178062228,1883793496,2403728665,2497604743,1383856311,2876494627,1917518562,3810496343,1716890410,3001755655,800440835,2261089178,3543599269,807962610,599762354,33778362,3977675356,2328828971,2809771154,4077384432,1315562145,1708848333,101039829,3509871135,3299278474,875451293,2733856160,92987698,2767645557,193195065,1080094634,1584504582,3178106961,1042385657,2531067453,3711829422,1306967366,2438237621,1908694277,67556463,1615861247,429456164,3602770327,2302690252,1742315127,2968011453,126454664,3877198648,2043211483,2709260871,2084704233,4169408201,0,159417987,841739592,504459436,1817866830,4245618683,260388950,1034867998,908933415,168810852,1750902305,2606453969,607530554,202008497,2472011535,3035535058,463180190,2160117071,1641816226,1517767529,470948374,3801332234,3231722213,1008918595,303765277,235474187,4069246893,766945465,337553864,1475418501,2943682380,4003061179,2743034109,4144047775,1551037884,1147550661,1543208500,2336434550,3408119516,3069049960,3102011747,3610369226,1113818384,328671808,2227573024,2236228733,3535486456,2935566865,3341394285,496906059,3702665459,226906860,2009195472,733156972,2842737049,294930682,1206477858,2835123396,2700099354,1451044056,573804783,2269728455,3644379585,2362090238,2564033334,2801107407,2776292904,3669462566,1068351396,742039012,1350078989,1784663195,1417561698,4136440770,2430122216,775550814,2193862645,2673705150,1775276924,1876241833,3475313331,3366754619,270040487,3902563182,3678124923,3441850377,1851332852,3969562369,2203032232,3868552805,2868897406,566021896,4011190502,3135740889,1248802510,3936291284,699432150,832877231,708780849,3332740144,899835584,1951317047,4236429990,3767586992,866637845,4043610186,1106041591,2144161806,395441711,1984812685,1139781709,3433712980,3835036895,2664543715,1282050075,3240894392,1181045119,2640243204,25965917,4203181171,4211818798,3009879386,2463879762,3910161971,1842759443,2597806476,933301370,1509430414,3943906441,3467192302,3076639029,3776767469,2051518780,2631065433,1441952575,404016761,1942435775,1408749034,1610459739,3745345300,2017778566,3400528769,3110650942,941896748,3265478751,371049330,3168937228,675039627,4279080257,967311729,135050206,3635733660,1683407248,2076935265,3576870512,1215061108,3501741890],b=[1347548327,1400783205,3273267108,2520393566,3409685355,4045380933,2880240216,2471224067,1428173050,4138563181,2441661558,636813900,4233094615,3620022987,2149987652,2411029155,1239331162,1730525723,2554718734,3781033664,46346101,310463728,2743944855,3328955385,3875770207,2501218972,3955191162,3667219033,768917123,3545789473,692707433,1150208456,1786102409,2029293177,1805211710,3710368113,3065962831,401639597,1724457132,3028143674,409198410,2196052529,1620529459,1164071807,3769721975,2226875310,486441376,2499348523,1483753576,428819965,2274680428,3075636216,598438867,3799141122,1474502543,711349675,129166120,53458370,2592523643,2782082824,4063242375,2988687269,3120694122,1559041666,730517276,2460449204,4042459122,2706270690,3446004468,3573941694,533804130,2328143614,2637442643,2695033685,839224033,1973745387,957055980,2856345839,106852767,1371368976,4181598602,1033297158,2933734917,1179510461,3046200461,91341917,1862534868,4284502037,605657339,2547432937,3431546947,2003294622,3182487618,2282195339,954669403,3682191598,1201765386,3917234703,3388507166,0,2198438022,1211247597,2887651696,1315723890,4227665663,1443857720,507358933,657861945,1678381017,560487590,3516619604,975451694,2970356327,261314535,3535072918,2652609425,1333838021,2724322336,1767536459,370938394,182621114,3854606378,1128014560,487725847,185469197,2918353863,3106780840,3356761769,2237133081,1286567175,3152976349,4255350624,2683765030,3160175349,3309594171,878443390,1988838185,3704300486,1756818940,1673061617,3403100636,272786309,1075025698,545572369,2105887268,4174560061,296679730,1841768865,1260232239,4091327024,3960309330,3497509347,1814803222,2578018489,4195456072,575138148,3299409036,446754879,3629546796,4011996048,3347532110,3252238545,4270639778,915985419,3483825537,681933534,651868046,2755636671,3828103837,223377554,2607439820,1649704518,3270937875,3901806776,1580087799,4118987695,3198115200,2087309459,2842678573,3016697106,1003007129,2802849917,1860738147,2077965243,164439672,4100872472,32283319,2827177882,1709610350,2125135846,136428751,3874428392,3652904859,3460984630,3572145929,3593056380,2939266226,824852259,818324884,3224740454,930369212,2801566410,2967507152,355706840,1257309336,4148292826,243256656,790073846,2373340630,1296297904,1422699085,3756299780,3818836405,457992840,3099667487,2135319889,77422314,1560382517,1945798516,788204353,1521706781,1385356242,870912086,325965383,2358957921,2050466060,2388260884,2313884476,4006521127,901210569,3990953189,1014646705,1503449823,1062597235,2031621326,3212035895,3931371469,1533017514,350174575,2256028891,2177544179,1052338372,741876788,1606591296,1914052035,213705253,2334669897,1107234197,1899603969,3725069491,2631447780,2422494913,1635502980,1893020342,1950903388,1120974935],w=[2807058932,1699970625,2764249623,1586903591,1808481195,1173430173,1487645946,59984867,4199882800,1844882806,1989249228,1277555970,3623636965,3419915562,1149249077,2744104290,1514790577,459744698,244860394,3235995134,1963115311,4027744588,2544078150,4190530515,1608975247,2627016082,2062270317,1507497298,2200818878,567498868,1764313568,3359936201,2305455554,2037970062,1047239e3,1910319033,1337376481,2904027272,2892417312,984907214,1243112415,830661914,861968209,2135253587,2011214180,2927934315,2686254721,731183368,1750626376,4246310725,1820824798,4172763771,3542330227,48394827,2404901663,2871682645,671593195,3254988725,2073724613,145085239,2280796200,2779915199,1790575107,2187128086,472615631,3029510009,4075877127,3802222185,4107101658,3201631749,1646252340,4270507174,1402811438,1436590835,3778151818,3950355702,3963161475,4020912224,2667994737,273792366,2331590177,104699613,95345982,3175501286,2377486676,1560637892,3564045318,369057872,4213447064,3919042237,1137477952,2658625497,1119727848,2340947849,1530455833,4007360968,172466556,266959938,516552836,0,2256734592,3980931627,1890328081,1917742170,4294704398,945164165,3575528878,958871085,3647212047,2787207260,1423022939,775562294,1739656202,3876557655,2530391278,2443058075,3310321856,547512796,1265195639,437656594,3121275539,719700128,3762502690,387781147,218828297,3350065803,2830708150,2848461854,428169201,122466165,3720081049,1627235199,648017665,4122762354,1002783846,2117360635,695634755,3336358691,4234721005,4049844452,3704280881,2232435299,574624663,287343814,612205898,1039717051,840019705,2708326185,793451934,821288114,1391201670,3822090177,376187827,3113855344,1224348052,1679968233,2361698556,1058709744,752375421,2431590963,1321699145,3519142200,2734591178,188127444,2177869557,3727205754,2384911031,3215212461,2648976442,2450346104,3432737375,1180849278,331544205,3102249176,4150144569,2952102595,2159976285,2474404304,766078933,313773861,2570832044,2108100632,1668212892,3145456443,2013908262,418672217,3070356634,2594734927,1852171925,3867060991,3473416636,3907448597,2614737639,919489135,164948639,2094410160,2997825956,590424639,2486224549,1723872674,3157750862,3399941250,3501252752,3625268135,2555048196,3673637356,1343127501,4130281361,3599595085,2957853679,1297403050,81781910,3051593425,2283490410,532201772,1367295589,3926170974,895287692,1953757831,1093597963,492483431,3528626907,1446242576,1192455638,1636604631,209336225,344873464,1015671571,669961897,3375740769,3857572124,2973530695,3747192018,1933530610,3464042516,935293895,3454686199,2858115069,1863638845,3683022916,4085369519,3292445032,875313188,1080017571,3279033885,621591778,1233856572,2504130317,24197544,3017672716,3835484340,3247465558,2220981195,3060847922,1551124588,1463996600],S=[4104605777,1097159550,396673818,660510266,2875968315,2638606623,4200115116,3808662347,821712160,1986918061,3430322568,38544885,3856137295,718002117,893681702,1654886325,2975484382,3122358053,3926825029,4274053469,796197571,1290801793,1184342925,3556361835,2405426947,2459735317,1836772287,1381620373,3196267988,1948373848,3764988233,3385345166,3263785589,2390325492,1480485785,3111247143,3780097726,2293045232,548169417,3459953789,3746175075,439452389,1362321559,1400849762,1685577905,1806599355,2174754046,137073913,1214797936,1174215055,3731654548,2079897426,1943217067,1258480242,529487843,1437280870,3945269170,3049390895,3313212038,923313619,679998e3,3215307299,57326082,377642221,3474729866,2041877159,133361907,1776460110,3673476453,96392454,878845905,2801699524,777231668,4082475170,2330014213,4142626212,2213296395,1626319424,1906247262,1846563261,562755902,3708173718,1040559837,3871163981,1418573201,3294430577,114585348,1343618912,2566595609,3186202582,1078185097,3651041127,3896688048,2307622919,425408743,3371096953,2081048481,1108339068,2216610296,0,2156299017,736970802,292596766,1517440620,251657213,2235061775,2933202493,758720310,265905162,1554391400,1532285339,908999204,174567692,1474760595,4002861748,2610011675,3234156416,3693126241,2001430874,303699484,2478443234,2687165888,585122620,454499602,151849742,2345119218,3064510765,514443284,4044981591,1963412655,2581445614,2137062819,19308535,1928707164,1715193156,4219352155,1126790795,600235211,3992742070,3841024952,836553431,1669664834,2535604243,3323011204,1243905413,3141400786,4180808110,698445255,2653899549,2989552604,2253581325,3252932727,3004591147,1891211689,2487810577,3915653703,4237083816,4030667424,2100090966,865136418,1229899655,953270745,3399679628,3557504664,4118925222,2061379749,3079546586,2915017791,983426092,2022837584,1607244650,2118541908,2366882550,3635996816,972512814,3283088770,1568718495,3499326569,3576539503,621982671,2895723464,410887952,2623762152,1002142683,645401037,1494807662,2595684844,1335535747,2507040230,4293295786,3167684641,367585007,3885750714,1865862730,2668221674,2960971305,2763173681,1059270954,2777952454,2724642869,1320957812,2194319100,2429595872,2815956275,77089521,3973773121,3444575871,2448830231,1305906550,4021308739,2857194700,2516901860,3518358430,1787304780,740276417,1699839814,1592394909,2352307457,2272556026,188821243,1729977011,3687994002,274084841,3594982253,3613494426,2701949495,4162096729,322734571,2837966542,1640576439,484830689,1202797690,3537852828,4067639125,349075736,3342319475,4157467219,4255800159,1030690015,1155237496,2951971274,1757691577,607398968,2738905026,499347990,3794078908,1011452712,227885567,2818666809,213114376,3034881240,1455525988,3414450555,850817237,1817998408,3092726480],O=[0,235474187,470948374,303765277,941896748,908933415,607530554,708780849,1883793496,2118214995,1817866830,1649639237,1215061108,1181045119,1417561698,1517767529,3767586992,4003061179,4236429990,4069246893,3635733660,3602770327,3299278474,3400528769,2430122216,2664543715,2362090238,2193862645,2835123396,2801107407,3035535058,3135740889,3678124923,3576870512,3341394285,3374361702,3810496343,3977675356,4279080257,4043610186,2876494627,2776292904,3076639029,3110650942,2472011535,2640243204,2403728665,2169303058,1001089995,899835584,666464733,699432150,59727847,226906860,530400753,294930682,1273168787,1172967064,1475418501,1509430414,1942435775,2110667444,1876241833,1641816226,2910219766,2743034109,2976151520,3211623147,2505202138,2606453969,2302690252,2269728455,3711829422,3543599269,3240894392,3475313331,3843699074,3943906441,4178062228,4144047775,1306967366,1139781709,1374988112,1610459739,1975683434,2076935265,1775276924,1742315127,1034867998,866637845,566021896,800440835,92987698,193195065,429456164,395441711,1984812685,2017778566,1784663195,1683407248,1315562145,1080094634,1383856311,1551037884,101039829,135050206,437757123,337553864,1042385657,807962610,573804783,742039012,2531067453,2564033334,2328828971,2227573024,2935566865,2700099354,3001755655,3168937228,3868552805,3902563182,4203181171,4102977912,3736164937,3501741890,3265478751,3433712980,1106041591,1340463100,1576976609,1408749034,2043211483,2009195472,1708848333,1809054150,832877231,1068351396,766945465,599762354,159417987,126454664,361929877,463180190,2709260871,2943682380,3178106961,3009879386,2572697195,2538681184,2236228733,2336434550,3509871135,3745345300,3441850377,3274667266,3910161971,3877198648,4110568485,4211818798,2597806476,2497604743,2261089178,2295101073,2733856160,2902087851,3202437046,2968011453,3936291284,3835036895,4136440770,4169408201,3535486456,3702665459,3467192302,3231722213,2051518780,1951317047,1716890410,1750902305,1113818384,1282050075,1584504582,1350078989,168810852,67556463,371049330,404016761,841739592,1008918595,775550814,540080725,3969562369,3801332234,4035489047,4269907996,3569255213,3669462566,3366754619,3332740144,2631065433,2463879762,2160117071,2395588676,2767645557,2868897406,3102011747,3069049960,202008497,33778362,270040487,504459436,875451293,975658646,675039627,641025152,2084704233,1917518562,1615861247,1851332852,1147550661,1248802510,1484005843,1451044056,933301370,967311729,733156972,632953703,260388950,25965917,328671808,496906059,1206477858,1239443753,1543208500,1441952575,2144161806,1908694277,1675577880,1842759443,3610369226,3644379585,3408119516,3307916247,4011190502,3776767469,4077384432,4245618683,2809771154,2842737049,3144396420,3043140495,2673705150,2438237621,2203032232,2370213795],j=[0,185469197,370938394,487725847,741876788,657861945,975451694,824852259,1483753576,1400783205,1315723890,1164071807,1950903388,2135319889,1649704518,1767536459,2967507152,3152976349,2801566410,2918353863,2631447780,2547432937,2328143614,2177544179,3901806776,3818836405,4270639778,4118987695,3299409036,3483825537,3535072918,3652904859,2077965243,1893020342,1841768865,1724457132,1474502543,1559041666,1107234197,1257309336,598438867,681933534,901210569,1052338372,261314535,77422314,428819965,310463728,3409685355,3224740454,3710368113,3593056380,3875770207,3960309330,4045380933,4195456072,2471224067,2554718734,2237133081,2388260884,3212035895,3028143674,2842678573,2724322336,4138563181,4255350624,3769721975,3955191162,3667219033,3516619604,3431546947,3347532110,2933734917,2782082824,3099667487,3016697106,2196052529,2313884476,2499348523,2683765030,1179510461,1296297904,1347548327,1533017514,1786102409,1635502980,2087309459,2003294622,507358933,355706840,136428751,53458370,839224033,957055980,605657339,790073846,2373340630,2256028891,2607439820,2422494913,2706270690,2856345839,3075636216,3160175349,3573941694,3725069491,3273267108,3356761769,4181598602,4063242375,4011996048,3828103837,1033297158,915985419,730517276,545572369,296679730,446754879,129166120,213705253,1709610350,1860738147,1945798516,2029293177,1239331162,1120974935,1606591296,1422699085,4148292826,4233094615,3781033664,3931371469,3682191598,3497509347,3446004468,3328955385,2939266226,2755636671,3106780840,2988687269,2198438022,2282195339,2501218972,2652609425,1201765386,1286567175,1371368976,1521706781,1805211710,1620529459,2105887268,1988838185,533804130,350174575,164439672,46346101,870912086,954669403,636813900,788204353,2358957921,2274680428,2592523643,2441661558,2695033685,2880240216,3065962831,3182487618,3572145929,3756299780,3270937875,3388507166,4174560061,4091327024,4006521127,3854606378,1014646705,930369212,711349675,560487590,272786309,457992840,106852767,223377554,1678381017,1862534868,1914052035,2031621326,1211247597,1128014560,1580087799,1428173050,32283319,182621114,401639597,486441376,768917123,651868046,1003007129,818324884,1503449823,1385356242,1333838021,1150208456,1973745387,2125135846,1673061617,1756818940,2970356327,3120694122,2802849917,2887651696,2637442643,2520393566,2334669897,2149987652,3917234703,3799141122,4284502037,4100872472,3309594171,3460984630,3545789473,3629546796,2050466060,1899603969,1814803222,1730525723,1443857720,1560382517,1075025698,1260232239,575138148,692707433,878443390,1062597235,243256656,91341917,409198410,325965383,3403100636,3252238545,3704300486,3620022987,3874428392,3990953189,4042459122,4227665663,2460449204,2578018489,2226875310,2411029155,3198115200,3046200461,2827177882,2743944855],P=[0,218828297,437656594,387781147,875313188,958871085,775562294,590424639,1750626376,1699970625,1917742170,2135253587,1551124588,1367295589,1180849278,1265195639,3501252752,3720081049,3399941250,3350065803,3835484340,3919042237,4270507174,4085369519,3102249176,3051593425,2734591178,2952102595,2361698556,2177869557,2530391278,2614737639,3145456443,3060847922,2708326185,2892417312,2404901663,2187128086,2504130317,2555048196,3542330227,3727205754,3375740769,3292445032,3876557655,3926170974,4246310725,4027744588,1808481195,1723872674,1910319033,2094410160,1608975247,1391201670,1173430173,1224348052,59984867,244860394,428169201,344873464,935293895,984907214,766078933,547512796,1844882806,1627235199,2011214180,2062270317,1507497298,1423022939,1137477952,1321699145,95345982,145085239,532201772,313773861,830661914,1015671571,731183368,648017665,3175501286,2957853679,2807058932,2858115069,2305455554,2220981195,2474404304,2658625497,3575528878,3625268135,3473416636,3254988725,3778151818,3963161475,4213447064,4130281361,3599595085,3683022916,3432737375,3247465558,3802222185,4020912224,4172763771,4122762354,3201631749,3017672716,2764249623,2848461854,2331590177,2280796200,2431590963,2648976442,104699613,188127444,472615631,287343814,840019705,1058709744,671593195,621591778,1852171925,1668212892,1953757831,2037970062,1514790577,1463996600,1080017571,1297403050,3673637356,3623636965,3235995134,3454686199,4007360968,3822090177,4107101658,4190530515,2997825956,3215212461,2830708150,2779915199,2256734592,2340947849,2627016082,2443058075,172466556,122466165,273792366,492483431,1047239e3,861968209,612205898,695634755,1646252340,1863638845,2013908262,1963115311,1446242576,1530455833,1277555970,1093597963,1636604631,1820824798,2073724613,1989249228,1436590835,1487645946,1337376481,1119727848,164948639,81781910,331544205,516552836,1039717051,821288114,669961897,719700128,2973530695,3157750862,2871682645,2787207260,2232435299,2283490410,2667994737,2450346104,3647212047,3564045318,3279033885,3464042516,3980931627,3762502690,4150144569,4199882800,3070356634,3121275539,2904027272,2686254721,2200818878,2384911031,2570832044,2486224549,3747192018,3528626907,3310321856,3359936201,3950355702,3867060991,4049844452,4234721005,1739656202,1790575107,2108100632,1890328081,1402811438,1586903591,1233856572,1149249077,266959938,48394827,369057872,418672217,1002783846,919489135,567498868,752375421,209336225,24197544,376187827,459744698,945164165,895287692,574624663,793451934,1679968233,1764313568,2117360635,1933530610,1343127501,1560637892,1243112415,1192455638,3704280881,3519142200,3336358691,3419915562,3907448597,3857572124,4075877127,4294704398,3029510009,3113855344,2927934315,2744104290,2159976285,2377486676,2594734927,2544078150],k=[0,151849742,303699484,454499602,607398968,758720310,908999204,1059270954,1214797936,1097159550,1517440620,1400849762,1817998408,1699839814,2118541908,2001430874,2429595872,2581445614,2194319100,2345119218,3034881240,3186202582,2801699524,2951971274,3635996816,3518358430,3399679628,3283088770,4237083816,4118925222,4002861748,3885750714,1002142683,850817237,698445255,548169417,529487843,377642221,227885567,77089521,1943217067,2061379749,1640576439,1757691577,1474760595,1592394909,1174215055,1290801793,2875968315,2724642869,3111247143,2960971305,2405426947,2253581325,2638606623,2487810577,3808662347,3926825029,4044981591,4162096729,3342319475,3459953789,3576539503,3693126241,1986918061,2137062819,1685577905,1836772287,1381620373,1532285339,1078185097,1229899655,1040559837,923313619,740276417,621982671,439452389,322734571,137073913,19308535,3871163981,4021308739,4104605777,4255800159,3263785589,3414450555,3499326569,3651041127,2933202493,2815956275,3167684641,3049390895,2330014213,2213296395,2566595609,2448830231,1305906550,1155237496,1607244650,1455525988,1776460110,1626319424,2079897426,1928707164,96392454,213114376,396673818,514443284,562755902,679998e3,865136418,983426092,3708173718,3557504664,3474729866,3323011204,4180808110,4030667424,3945269170,3794078908,2507040230,2623762152,2272556026,2390325492,2975484382,3092726480,2738905026,2857194700,3973773121,3856137295,4274053469,4157467219,3371096953,3252932727,3673476453,3556361835,2763173681,2915017791,3064510765,3215307299,2156299017,2307622919,2459735317,2610011675,2081048481,1963412655,1846563261,1729977011,1480485785,1362321559,1243905413,1126790795,878845905,1030690015,645401037,796197571,274084841,425408743,38544885,188821243,3613494426,3731654548,3313212038,3430322568,4082475170,4200115116,3780097726,3896688048,2668221674,2516901860,2366882550,2216610296,3141400786,2989552604,2837966542,2687165888,1202797690,1320957812,1437280870,1554391400,1669664834,1787304780,1906247262,2022837584,265905162,114585348,499347990,349075736,736970802,585122620,972512814,821712160,2595684844,2478443234,2293045232,2174754046,3196267988,3079546586,2895723464,2777952454,3537852828,3687994002,3234156416,3385345166,4142626212,4293295786,3841024952,3992742070,174567692,57326082,410887952,292596766,777231668,660510266,1011452712,893681702,1108339068,1258480242,1343618912,1494807662,1715193156,1865862730,1948373848,2100090966,2701949495,2818666809,3004591147,3122358053,2235061775,2352307457,2535604243,2653899549,3915653703,3764988233,4219352155,4067639125,3444575871,3294430577,3746175075,3594982253,836553431,953270745,600235211,718002117,367585007,484830689,133361907,251657213,2041877159,1891211689,1806599355,1654886325,1568718495,1418573201,1335535747,1184342925];function C(I){for(var U=[],K=0;K<I.length;K+=4)U.push(I[K]<<24|I[K+1]<<16|I[K+2]<<8|I[K+3]);return U}var D=function(I){if(!(this instanceof D))throw Error("AES must be instanitated with `new`");Object.defineProperty(this,"key",{value:s(I,!0)}),this._prepare()};D.prototype._prepare=function(){var I=c[this.key.length];if(I==null)throw new Error("invalid key size (must be 16, 24 or 32 bytes)");this._Ke=[],this._Kd=[];for(var U=0;U<=I;U++)this._Ke.push([0,0,0,0]),this._Kd.push([0,0,0,0]);for(var K=(I+1)*4,z=this.key.length/4,G=C(this.key),de,U=0;U<z;U++)de=U>>2,this._Ke[de][U%4]=G[U],this._Kd[I-de][U%4]=G[U];for(var ce=0,Je=z,tt;Je<K;){if(tt=G[z-1],G[0]^=u[tt>>16&255]<<24^u[tt>>8&255]<<16^u[tt&255]<<8^u[tt>>24&255]^d[ce]<<24,ce+=1,z!=8)for(var U=1;U<z;U++)G[U]^=G[U-1];else{for(var U=1;U<z/2;U++)G[U]^=G[U-1];tt=G[z/2-1],G[z/2]^=u[tt&255]^u[tt>>8&255]<<8^u[tt>>16&255]<<16^u[tt>>24&255]<<24;for(var U=z/2+1;U<z;U++)G[U]^=G[U-1]}for(var U=0,Ot,Et;U<z&&Je<K;)Ot=Je>>2,Et=Je%4,this._Ke[Ot][Et]=G[U],this._Kd[I-Ot][Et]=G[U++],Je++}for(var Ot=1;Ot<I;Ot++)for(var Et=0;Et<4;Et++)tt=this._Kd[Ot][Et],this._Kd[Ot][Et]=O[tt>>24&255]^j[tt>>16&255]^P[tt>>8&255]^k[tt&255]},D.prototype.encrypt=function(I){if(I.length!=16)throw new Error("invalid plaintext size (must be 16 bytes)");for(var U=this._Ke.length-1,K=[0,0,0,0],z=C(I),G=0;G<4;G++)z[G]^=this._Ke[0][G];for(var de=1;de<U;de++){for(var G=0;G<4;G++)K[G]=h[z[G]>>24&255]^p[z[(G+1)%4]>>16&255]^m[z[(G+2)%4]>>8&255]^_[z[(G+3)%4]&255]^this._Ke[de][G];z=K.slice()}for(var ce=n(16),Je,G=0;G<4;G++)Je=this._Ke[U][G],ce[4*G]=(u[z[G]>>24&255]^Je>>24)&255,ce[4*G+1]=(u[z[(G+1)%4]>>16&255]^Je>>16)&255,ce[4*G+2]=(u[z[(G+2)%4]>>8&255]^Je>>8)&255,ce[4*G+3]=(u[z[(G+3)%4]&255]^Je)&255;return ce},D.prototype.decrypt=function(I){if(I.length!=16)throw new Error("invalid ciphertext size (must be 16 bytes)");for(var U=this._Kd.length-1,K=[0,0,0,0],z=C(I),G=0;G<4;G++)z[G]^=this._Kd[0][G];for(var de=1;de<U;de++){for(var G=0;G<4;G++)K[G]=f[z[G]>>24&255]^b[z[(G+3)%4]>>16&255]^w[z[(G+2)%4]>>8&255]^S[z[(G+1)%4]&255]^this._Kd[de][G];z=K.slice()}for(var ce=n(16),Je,G=0;G<4;G++)Je=this._Kd[U][G],ce[4*G]=(l[z[G]>>24&255]^Je>>24)&255,ce[4*G+1]=(l[z[(G+3)%4]>>16&255]^Je>>16)&255,ce[4*G+2]=(l[z[(G+2)%4]>>8&255]^Je>>8)&255,ce[4*G+3]=(l[z[(G+1)%4]&255]^Je)&255;return ce};var H=function(I){if(!(this instanceof H))throw Error("AES must be instanitated with `new`");this.description="Electronic Code Block",this.name="ecb",this._aes=new D(I)};H.prototype.encrypt=function(I){if(I=s(I),I.length%16!==0)throw new Error("invalid plaintext size (must be multiple of 16 bytes)");for(var U=n(I.length),K=n(16),z=0;z<I.length;z+=16)i(I,K,0,z,z+16),K=this._aes.encrypt(K),i(K,U,z);return U},H.prototype.decrypt=function(I){if(I=s(I),I.length%16!==0)throw new Error("invalid ciphertext size (must be multiple of 16 bytes)");for(var U=n(I.length),K=n(16),z=0;z<I.length;z+=16)i(I,K,0,z,z+16),K=this._aes.decrypt(K),i(K,U,z);return U};var W=function(I,U){if(!(this instanceof W))throw Error("AES must be instanitated with `new`");if(this.description="Cipher Block Chaining",this.name="cbc",!U)U=n(16);else if(U.length!=16)throw new Error("invalid initialation vector size (must be 16 bytes)");this._lastCipherblock=s(U,!0),this._aes=new D(I)};W.prototype.encrypt=function(I){if(I=s(I),I.length%16!==0)throw new Error("invalid plaintext size (must be multiple of 16 bytes)");for(var U=n(I.length),K=n(16),z=0;z<I.length;z+=16){i(I,K,0,z,z+16);for(var G=0;G<16;G++)K[G]^=this._lastCipherblock[G];this._lastCipherblock=this._aes.encrypt(K),i(this._lastCipherblock,U,z)}return U},W.prototype.decrypt=function(I){if(I=s(I),I.length%16!==0)throw new Error("invalid ciphertext size (must be multiple of 16 bytes)");for(var U=n(I.length),K=n(16),z=0;z<I.length;z+=16){i(I,K,0,z,z+16),K=this._aes.decrypt(K);for(var G=0;G<16;G++)U[z+G]=K[G]^this._lastCipherblock[G];i(I,this._lastCipherblock,0,z,z+16)}return U};var J=function(I,U,K){if(!(this instanceof J))throw Error("AES must be instanitated with `new`");if(this.description="Cipher Feedback",this.name="cfb",!U)U=n(16);else if(U.length!=16)throw new Error("invalid initialation vector size (must be 16 size)");K||(K=1),this.segmentSize=K,this._shiftRegister=s(U,!0),this._aes=new D(I)};J.prototype.encrypt=function(I){if(I.length%this.segmentSize!=0)throw new Error("invalid plaintext size (must be segmentSize bytes)");for(var U=s(I,!0),K,z=0;z<U.length;z+=this.segmentSize){K=this._aes.encrypt(this._shiftRegister);for(var G=0;G<this.segmentSize;G++)U[z+G]^=K[G];i(this._shiftRegister,this._shiftRegister,0,this.segmentSize),i(U,this._shiftRegister,16-this.segmentSize,z,z+this.segmentSize)}return U},J.prototype.decrypt=function(I){if(I.length%this.segmentSize!=0)throw new Error("invalid ciphertext size (must be segmentSize bytes)");for(var U=s(I,!0),K,z=0;z<U.length;z+=this.segmentSize){K=this._aes.encrypt(this._shiftRegister);for(var G=0;G<this.segmentSize;G++)U[z+G]^=K[G];i(this._shiftRegister,this._shiftRegister,0,this.segmentSize),i(I,this._shiftRegister,16-this.segmentSize,z,z+this.segmentSize)}return U};var F=function(I,U){if(!(this instanceof F))throw Error("AES must be instanitated with `new`");if(this.description="Output Feedback",this.name="ofb",!U)U=n(16);else if(U.length!=16)throw new Error("invalid initialation vector size (must be 16 bytes)");this._lastPrecipher=s(U,!0),this._lastPrecipherIndex=16,this._aes=new D(I)};F.prototype.encrypt=function(I){for(var U=s(I,!0),K=0;K<U.length;K++)this._lastPrecipherIndex===16&&(this._lastPrecipher=this._aes.encrypt(this._lastPrecipher),this._lastPrecipherIndex=0),U[K]^=this._lastPrecipher[this._lastPrecipherIndex++];return U},F.prototype.decrypt=F.prototype.encrypt;var q=function(I){if(!(this instanceof q))throw Error("Counter must be instanitated with `new`");I!==0&&!I&&(I=1),typeof I=="number"?(this._counter=n(16),this.setValue(I)):this.setBytes(I)};q.prototype.setValue=function(I){if(typeof I!="number"||parseInt(I)!=I)throw new Error("invalid counter value (must be an integer)");if(I>Number.MAX_SAFE_INTEGER)throw new Error("integer value out of safe range");for(var U=15;U>=0;--U)this._counter[U]=I%256,I=parseInt(I/256)},q.prototype.setBytes=function(I){if(I=s(I,!0),I.length!=16)throw new Error("invalid counter bytes size (must be 16 bytes)");this._counter=I},q.prototype.increment=function(){for(var I=15;I>=0;I--)if(this._counter[I]===255)this._counter[I]=0;else{this._counter[I]++;break}};var Q=function(I,U){if(!(this instanceof Q))throw Error("AES must be instanitated with `new`");this.description="Counter",this.name="ctr",U instanceof q||(U=new q(U)),this._counter=U,this._remainingCounter=null,this._remainingCounterIndex=16,this._aes=new D(I)};Q.prototype.encrypt=function(I){for(var U=s(I,!0),K=0;K<U.length;K++)this._remainingCounterIndex===16&&(this._remainingCounter=this._aes.encrypt(this._counter._counter),this._remainingCounterIndex=0,this._counter.increment()),U[K]^=this._remainingCounter[this._remainingCounterIndex++];return U},Q.prototype.decrypt=Q.prototype.encrypt;function R(I){I=s(I,!0);var U=16-I.length%16,K=n(I.length+U);i(I,K);for(var z=I.length;z<K.length;z++)K[z]=U;return K}function Y(I){if(I=s(I,!0),I.length<16)throw new Error("PKCS#7 invalid length");var U=I[I.length-1];if(U>16)throw new Error("PKCS#7 padding byte out of range");for(var K=I.length-U,z=0;z<U;z++)if(I[K+z]!==U)throw new Error("PKCS#7 invalid padding byte");var G=n(K);return i(I,G,0,0,K),G}var Z={AES:D,Counter:q,ModeOfOperation:{ecb:H,cbc:W,cfb:J,ofb:F,ctr:Q},utils:{hex:a,utf8:o},padding:{pkcs7:{pad:R,strip:Y}},_arrayTest:{coerceArray:s,createArray:n,copyArray:i}};typeof nT<"u"?hN.exports=Z:typeof define=="function"&&define.amd?define([],function(){return Z}):(t.aesjs&&(Z._aesjs=t.aesjs),t.aesjs=Z)})(nT)});function gN(t,e,r){var s=e?0:4,n=e?4:0,i=e?0:3,o=e?1:2,a=e?2:1,c=e?3:0,d=e?GQ:YQ,u=e?XQ:JQ,l=m.prototype,h="is"+t,p="_"+h;return l.buffer=void 0,l.offset=0,l[p]=!0,l.toNumber=w,l.toString=S,l.toJSON=w,l.toArray=WQ,bh&&(l.toBuffer=KQ),yh&&(l.toArrayBuffer=yN),m[h]=_,m;function m(P,k,C,D){return this instanceof m?f(this,P,k,C,D):new m(P,k,C,D)}function _(P){return!!(P&&P[p])}function f(P,k,C,D,H){if(yh&&vw&&(k instanceof vw&&(k=new yh(k)),D instanceof vw&&(D=new yh(D))),!k&&!C&&!D&&!xh){P.buffer=bN(pN,0);return}if(!mN(k,C)){var W=xh||Array;H=C,D=k,C=0,k=xh===bh?bh.alloc(8):new W(8)}P.buffer=k,P.offset=C|=0,_w!==typeof D&&(typeof D=="string"?b(k,C,D,H||10):mN(D,H)?iT(k,C,D,H):typeof H=="number"?(O(k,C+s,D),O(k,C+n,H)):D>0?d(k,C,D):D<0?u(k,C,D):iT(k,C,pN,0))}function b(P,k,C,D){var H=0,W=C.length,J=0,F=0;C[0]==="-"&&H++;for(var q=H;H<W;){var Q=parseInt(C[H++],D);if(!(Q>=0))break;F=F*D+Q,J=J*D+Math.floor(F/gh),F%=gh}q&&(J=~J,F?F=gh-F:J++),O(P,k+s,J),O(P,k+n,F)}function w(){var P=this.buffer,k=this.offset,C=j(P,k+s),D=j(P,k+n);return r||(C|=0),C?C*gh+D:D}function S(P){var k=this.buffer,C=this.offset,D=j(k,C+s),H=j(k,C+n),W="",J=!r&&D&2147483648;for(J&&(D=~D,H=gh-H),P=P||10;;){var F=D%P*gh+H;if(D=Math.floor(D/P),H=Math.floor(F/P),W=(F%P).toString(P)+W,!D&&!H)break}return J&&(W="-"+W),W}function O(P,k,C){P[k+c]=C&255,C=C>>8,P[k+a]=C&255,C=C>>8,P[k+o]=C&255,C=C>>8,P[k+i]=C&255}function j(P,k){return P[k+i]*zQ+(P[k+o]<<16)+(P[k+a]<<8)+P[k+c]}}function WQ(t){var e=this.buffer,r=this.offset;return xh=null,t!==!1&&VQ(e)?e.length===8?e:e.slice(r,r+8):bN(e,r)}function KQ(t){var e=this.buffer,r=this.offset;return xh=bh,t!==!1&&bh.isBuffer(e)?e.length===8?e:e.slice(r,r+8):bh.from(yN.call(this,t))}function yN(t){var e=this.buffer,r=this.offset,s=e.buffer;if(xh=yh,t!==!1&&!e.offset&&s instanceof vw)return s.byteLength===8?s:s.slice(r,r+8);var n=new yh(8);return iT(n,0,e,r),n.buffer}function mN(t,e){var r=t&&t.length;return e|=0,r&&e+8<=r&&typeof t[e]!="string"}function iT(t,e,r,s){e|=0,s|=0;for(var n=0;n<8;n++)t[e++]=r[s++]&255}function bN(t,e){return Array.prototype.slice.call(t,e,e+8)}function GQ(t,e,r){for(var s=e+8;s>e;)t[--s]=r&255,r/=256}function XQ(t,e,r){var s=e+8;for(r++;s>e;)t[--s]=-r&255^255,r/=256}function YQ(t,e,r){for(var s=e+8;e<s;)t[e++]=r&255,r/=256}function JQ(t,e,r){var s=e+8;for(r++;e<s;)t[e++]=-r&255^255,r/=256}function QQ(t){return!!t&&Object.prototype.toString.call(t)=="[object Array]"}var _w,bh,yh,vw,pN,VQ,gh,zQ,xh,Sw,oT,Ew=V(()=>{"use strict";g();y();_w="undefined",bh=_w!==typeof Buffer&&Buffer,yh=_w!==typeof Uint8Array&&Uint8Array,vw=_w!==typeof ArrayBuffer&&ArrayBuffer,pN=[0,0,0,0,0,0,0,0],VQ=Array.isArray||QQ,gh=4294967296,zQ=16777216,Sw=gN("Uint64BE",!0,!0),oT=gN("Int64BE",!0,!1)});var cT=Me(xN=>{"use strict";g();y();var Ye=xN,{Buffer:Cw}=require("buffer"),ZQ=require("os");Ye.toBuffer=function(t,e,r){r=~~r;let s;if(this.isV4Format(t))s=e||Cw.alloc(r+4),t.split(/\./g).map(n=>{s[r++]=parseInt(n,10)&255});else if(this.isV6Format(t)){let n=t.split(":",8),i;for(i=0;i<n.length;i++){let o=this.isV4Format(n[i]),a;o&&(a=this.toBuffer(n[i]),n[i]=a.slice(0,2).toString("hex")),a&&++i<8&&n.splice(i,0,a.slice(2,4).toString("hex"))}if(n[0]==="")for(;n.length<8;)n.unshift("0");else if(n[n.length-1]==="")for(;n.length<8;)n.push("0");else if(n.length<8){for(i=0;i<n.length&&n[i]!=="";i++);let o=[i,1];for(i=9-n.length;i>0;i--)o.push("0");n.splice(...o)}for(s=e||Cw.alloc(r+16),i=0;i<n.length;i++){let o=parseInt(n[i],16);s[r++]=o>>8&255,s[r++]=o&255}}if(!s)throw Error(`Invalid ip address: ${t}`);return s};Ye.toString=function(t,e,r){e=~~e,r=r||t.length-e;let s=[];if(r===4){for(let n=0;n<r;n++)s.push(t[e+n]);s=s.join(".")}else if(r===16){for(let n=0;n<r;n+=2)s.push(t.readUInt16BE(e+n).toString(16));s=s.join(":"),s=s.replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3"),s=s.replace(/:{3,4}/,"::")}return s};var eZ=/^(\d{1,3}\.){3,3}\d{1,3}$/,tZ=/^(::)?(((\d{1,3}\.){3}(\d{1,3}){1})?([0-9a-f]){0,4}:{0,2}){1,8}(::)?$/i;Ye.isV4Format=function(t){return eZ.test(t)};Ye.isV6Format=function(t){return tZ.test(t)};function i0(t){return t===4?"ipv4":t===6?"ipv6":t?t.toLowerCase():"ipv4"}Ye.fromPrefixLen=function(t,e){t>32?e="ipv6":e=i0(e);let r=4;e==="ipv6"&&(r=16);let s=Cw.alloc(r);for(let n=0,i=s.length;n<i;++n){let o=8;t<8&&(o=t),t-=o,s[n]=~(255>>o)&255}return Ye.toString(s)};Ye.mask=function(t,e){t=Ye.toBuffer(t),e=Ye.toBuffer(e);let r=Cw.alloc(Math.max(t.length,e.length)),s;if(t.length===e.length)for(s=0;s<t.length;s++)r[s]=t[s]&e[s];else if(e.length===4)for(s=0;s<e.length;s++)r[s]=t[t.length-4+s]&e[s];else{for(s=0;s<r.length-6;s++)r[s]=0;for(r[10]=255,r[11]=255,s=0;s<t.length;s++)r[s+12]=t[s]&e[s+12];s+=12}for(;s<r.length;s++)r[s]=0;return Ye.toString(r)};Ye.cidr=function(t){let e=t.split("/"),r=e[0];if(e.length!==2)throw new Error(`invalid CIDR subnet: ${r}`);let s=Ye.fromPrefixLen(parseInt(e[1],10));return Ye.mask(r,s)};Ye.subnet=function(t,e){let r=Ye.toLong(Ye.mask(t,e)),s=Ye.toBuffer(e),n=0;for(let o=0;o<s.length;o++)if(s[o]===255)n+=8;else{let a=s[o]&255;for(;a;)a=a<<1&255,n++}let i=2**(32-n);return{networkAddress:Ye.fromLong(r),firstAddress:i<=2?Ye.fromLong(r):Ye.fromLong(r+1),lastAddress:i<=2?Ye.fromLong(r+i-1):Ye.fromLong(r+i-2),broadcastAddress:Ye.fromLong(r+i-1),subnetMask:e,subnetMaskLength:n,numHosts:i<=2?i:i-2,length:i,contains(o){return r===Ye.toLong(Ye.mask(o,e))}}};Ye.cidrSubnet=function(t){let e=t.split("/"),r=e[0];if(e.length!==2)throw new Error(`invalid CIDR subnet: ${r}`);let s=Ye.fromPrefixLen(parseInt(e[1],10));return Ye.subnet(r,s)};Ye.not=function(t){let e=Ye.toBuffer(t);for(let r=0;r<e.length;r++)e[r]=255^e[r];return Ye.toString(e)};Ye.or=function(t,e){if(t=Ye.toBuffer(t),e=Ye.toBuffer(e),t.length===e.length){for(let i=0;i<t.length;++i)t[i]|=e[i];return Ye.toString(t)}let r=t,s=e;e.length>t.length&&(r=e,s=t);let n=r.length-s.length;for(let i=n;i<r.length;++i)r[i]|=s[i-n];return Ye.toString(r)};Ye.isEqual=function(t,e){if(t=Ye.toBuffer(t),e=Ye.toBuffer(e),t.length===e.length){for(let s=0;s<t.length;s++)if(t[s]!==e[s])return!1;return!0}if(e.length===4){let s=e;e=t,t=s}for(let s=0;s<10;s++)if(e[s]!==0)return!1;let r=e.readUInt16BE(10);if(r!==0&&r!==65535)return!1;for(let s=0;s<4;s++)if(t[s]!==e[s+12])return!1;return!0};Ye.isPrivate=function(t){if(Ye.isLoopback(t))return!0;if(!Ye.isV6Format(t)){let e=Ye.normalizeToLong(t);if(e<0)throw new Error("invalid ipv4 address");t=Ye.fromLong(e)}return/^(::f{4}:)?10\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(t)||/^(::f{4}:)?192\.168\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(t)||/^(::f{4}:)?172\.(1[6-9]|2\d|30|31)\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(t)||/^(::f{4}:)?169\.254\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(t)||/^f[cd][0-9a-f]{2}:/i.test(t)||/^fe80:/i.test(t)||/^::1$/.test(t)||/^::$/.test(t)};Ye.isPublic=function(t){return!Ye.isPrivate(t)};Ye.isLoopback=function(t){return!/\./.test(t)&&!/:/.test(t)&&(t=Ye.fromLong(Number(t))),/^(::f{4}:)?127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})/.test(t)||/^0177\./.test(t)||/^0x7f\./i.test(t)||/^fe80::1$/i.test(t)||/^::1$/.test(t)||/^::$/.test(t)};Ye.loopback=function(t){if(t=i0(t),t!=="ipv4"&&t!=="ipv6")throw new Error("family must be ipv4 or ipv6");return t==="ipv4"?"127.0.0.1":"fe80::1"};Ye.address=function(t,e){let r=ZQ.networkInterfaces();if(e=i0(e),t&&t!=="private"&&t!=="public"){let n=r[t].filter(i=>i0(i.family)===e);return n.length===0?void 0:n[0].address}let s=Object.keys(r).map(n=>{let i=r[n].filter(o=>(o.family=i0(o.family),o.family!==e||Ye.isLoopback(o.address)?!1:t?t==="public"?Ye.isPrivate(o.address):Ye.isPublic(o.address):!0));return i.length?i[0].address:void 0}).filter(Boolean);return s.length?s[0]:Ye.loopback(e)};Ye.toLong=function(t){let e=0;return t.split(".").forEach(r=>{e<<=8,e+=parseInt(r)}),e>>>0};Ye.fromLong=function(t){return`${t>>>24}.${t>>16&255}.${t>>8&255}.${t&255}`};Ye.normalizeToLong=function(t){let e=t.split(".").map(n=>n.startsWith("0x")||n.startsWith("0X")?parseInt(n,16):n.startsWith("0")&&n!=="0"&&/^[0-7]+$/.test(n)?parseInt(n,8):/^[1-9]\d*$/.test(n)||n==="0"?parseInt(n,10):NaN);if(e.some(isNaN))return-1;let r=0;switch(e.length){case 1:r=e[0];break;case 2:if(e[0]>255||e[1]>16777215)return-1;r=e[0]<<24|e[1]&16777215;break;case 3:if(e[0]>255||e[1]>255||e[2]>65535)return-1;r=e[0]<<24|e[1]<<16|e[2]&65535;break;case 4:if(e.some(n=>n>255))return-1;r=e[0]<<24|e[1]<<16|e[2]<<8|e[3];break;default:return-1}return r>>>0}});var vN=Me((OPe,wN)=>{"use strict";g();y();wN.exports=function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var s,n,i;if(Array.isArray(e)){if(s=e.length,s!=r.length)return!1;for(n=s;n--!==0;)if(!t(e[n],r[n]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(i=Object.keys(e),s=i.length,s!==Object.keys(r).length)return!1;for(n=s;n--!==0;)if(!Object.prototype.hasOwnProperty.call(r,i[n]))return!1;for(n=s;n--!==0;){var o=i[n];if(!t(e[o],r[o]))return!1}return!0}return e!==e&&r!==r}});var _N=Me(dT=>{"use strict";g();y();dT.toString=function(t){switch(t){case 1:return"A";case 10:return"NULL";case 28:return"AAAA";case 18:return"AFSDB";case 42:return"APL";case 257:return"CAA";case 60:return"CDNSKEY";case 59:return"CDS";case 37:return"CERT";case 5:return"CNAME";case 49:return"DHCID";case 32769:return"DLV";case 39:return"DNAME";case 48:return"DNSKEY";case 43:return"DS";case 55:return"HIP";case 13:return"HINFO";case 45:return"IPSECKEY";case 25:return"KEY";case 36:return"KX";case 29:return"LOC";case 15:return"MX";case 35:return"NAPTR";case 2:return"NS";case 47:return"NSEC";case 50:return"NSEC3";case 51:return"NSEC3PARAM";case 12:return"PTR";case 46:return"RRSIG";case 17:return"RP";case 24:return"SIG";case 6:return"SOA";case 99:return"SPF";case 33:return"SRV";case 44:return"SSHFP";case 32768:return"TA";case 249:return"TKEY";case 52:return"TLSA";case 250:return"TSIG";case 16:return"TXT";case 252:return"AXFR";case 251:return"IXFR";case 41:return"OPT";case 255:return"ANY"}return"UNKNOWN_"+t};dT.toType=function(t){switch(t.toUpperCase()){case"A":return 1;case"NULL":return 10;case"AAAA":return 28;case"AFSDB":return 18;case"APL":return 42;case"CAA":return 257;case"CDNSKEY":return 60;case"CDS":return 59;case"CERT":return 37;case"CNAME":return 5;case"DHCID":return 49;case"DLV":return 32769;case"DNAME":return 39;case"DNSKEY":return 48;case"DS":return 43;case"HIP":return 55;case"HINFO":return 13;case"IPSECKEY":return 45;case"KEY":return 25;case"KX":return 36;case"LOC":return 29;case"MX":return 15;case"NAPTR":return 35;case"NS":return 2;case"NSEC":return 47;case"NSEC3":return 50;case"NSEC3PARAM":return 51;case"PTR":return 12;case"RRSIG":return 46;case"RP":return 17;case"SIG":return 24;case"SOA":return 6;case"SPF":return 99;case"SRV":return 33;case"SSHFP":return 44;case"TA":return 32768;case"TKEY":return 249;case"TLSA":return 52;case"TSIG":return 250;case"TXT":return 16;case"AXFR":return 252;case"IXFR":return 251;case"OPT":return 41;case"ANY":return 255;case"*":return 255}return t.toUpperCase().startsWith("UNKNOWN_")?parseInt(t.slice(8)):0}});var SN=Me(lT=>{"use strict";g();y();lT.toString=function(t){switch(t){case 0:return"NOERROR";case 1:return"FORMERR";case 2:return"SERVFAIL";case 3:return"NXDOMAIN";case 4:return"NOTIMP";case 5:return"REFUSED";case 6:return"YXDOMAIN";case 7:return"YXRRSET";case 8:return"NXRRSET";case 9:return"NOTAUTH";case 10:return"NOTZONE";case 11:return"RCODE_11";case 12:return"RCODE_12";case 13:return"RCODE_13";case 14:return"RCODE_14";case 15:return"RCODE_15"}return"RCODE_"+t};lT.toRcode=function(t){switch(t.toUpperCase()){case"NOERROR":return 0;case"FORMERR":return 1;case"SERVFAIL":return 2;case"NXDOMAIN":return 3;case"NOTIMP":return 4;case"REFUSED":return 5;case"YXDOMAIN":return 6;case"YXRRSET":return 7;case"NXRRSET":return 8;case"NOTAUTH":return 9;case"NOTZONE":return 10;case"RCODE_11":return 11;case"RCODE_12":return 12;case"RCODE_13":return 13;case"RCODE_14":return 14;case"RCODE_15":return 15}return 0}});var EN=Me(uT=>{"use strict";g();y();uT.toString=function(t){switch(t){case 0:return"QUERY";case 1:return"IQUERY";case 2:return"STATUS";case 3:return"OPCODE_3";case 4:return"NOTIFY";case 5:return"UPDATE";case 6:return"OPCODE_6";case 7:return"OPCODE_7";case 8:return"OPCODE_8";case 9:return"OPCODE_9";case 10:return"OPCODE_10";case 11:return"OPCODE_11";case 12:return"OPCODE_12";case 13:return"OPCODE_13";case 14:return"OPCODE_14";case 15:return"OPCODE_15"}return"OPCODE_"+t};uT.toOpcode=function(t){switch(t.toUpperCase()){case"QUERY":return 0;case"IQUERY":return 1;case"STATUS":return 2;case"OPCODE_3":return 3;case"NOTIFY":return 4;case"UPDATE":return 5;case"OPCODE_6":return 6;case"OPCODE_7":return 7;case"OPCODE_8":return 8;case"OPCODE_9":return 9;case"OPCODE_10":return 10;case"OPCODE_11":return 11;case"OPCODE_12":return 12;case"OPCODE_13":return 13;case"OPCODE_14":return 14;case"OPCODE_15":return 15}return 0}});var CN=Me(hT=>{"use strict";g();y();hT.toString=function(t){switch(t){case 1:return"IN";case 2:return"CS";case 3:return"CH";case 4:return"HS";case 255:return"ANY"}return"UNKNOWN_"+t};hT.toClass=function(t){switch(t.toUpperCase()){case"IN":return 1;case"CS":return 2;case"CH":return 3;case"HS":return 4;case"ANY":return 255}return 0}});var TN=Me(fT=>{"use strict";g();y();fT.toString=function(t){switch(t){case 1:return"LLQ";case 2:return"UL";case 3:return"NSID";case 5:return"DAU";case 6:return"DHU";case 7:return"N3U";case 8:return"CLIENT_SUBNET";case 9:return"EXPIRE";case 10:return"COOKIE";case 11:return"TCP_KEEPALIVE";case 12:return"PADDING";case 13:return"CHAIN";case 14:return"KEY_TAG";case 26946:return"DEVICEID"}return t<0?null:`OPTION_${t}`};fT.toCode=function(t){if(typeof t=="number")return t;if(!t)return-1;switch(t.toUpperCase()){case"OPTION_0":return 0;case"LLQ":return 1;case"UL":return 2;case"NSID":return 3;case"OPTION_4":return 4;case"DAU":return 5;case"DHU":return 6;case"N3U":return 7;case"CLIENT_SUBNET":return 8;case"EXPIRE":return 9;case"COOKIE":return 10;case"TCP_KEEPALIVE":return 11;case"PADDING":return 12;case"CHAIN":return 13;case"KEY_TAG":return 14;case"DEVICEID":return 26946;case"OPTION_65535":return 65535}let e=t.match(/_(\d+)$/);return e?parseInt(e[1],10):-1}});var IN=Me((AN,pT)=>{"use strict";g();y();var kN=(function(t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.decode=l,t.encode=u,t.familyOf=d,t.name=void 0,t.sizeOf=c,t.v6=t.v4=void 0;let e=/^(\d{1,3}\.){3,3}\d{1,3}$/,r=4,s=/^(::)?(((\d{1,3}\.){3}(\d{1,3}){1})?([0-9a-f]){0,4}:{0,2}){1,8}(::)?$/i,n=16,i={name:"v4",size:r,isFormat:h=>e.test(h),encode(h,p,m){m=~~m,p=p||new Uint8Array(m+r);let _=h.length,f=0;for(let b=0;b<_;){let w=h.charCodeAt(b++);w===46?(p[m++]=f,f=0):f=f*10+(w-48)}return p[m]=f,p},decode(h,p){return p=~~p,`${h[p++]}.${h[p++]}.${h[p++]}.${h[p]}`}};t.v4=i;let o={name:"v6",size:n,isFormat:h=>h.length>0&&s.test(h),encode(h,p,m){m=~~m;let _=m+n,f=-1,b=0,w=0,S=!0,O=!1;p=p||new Uint8Array(m+n);for(let j=0;j<h.length;j++){let P=h.charCodeAt(j);P===58?(S?f!==-1?(m<_&&(p[m]=0),m<_-1&&(p[m+1]=0),m+=2):m<_&&(f=m):(O===!0?(m<_&&(p[m]=w),m++):(m<_&&(p[m]=b>>8),m<_-1&&(p[m+1]=b&255),m+=2),b=0,w=0),S=!0,O=!1):P===46?(m<_&&(p[m]=w),m++,w=0,b=0,S=!1,O=!0):(S=!1,P>=97?P-=87:P>=65?P-=55:(P-=48,w=w*10+P),b=(b<<4)+P)}if(S===!1)O===!0?(m<_&&(p[m]=w),m++):(m<_&&(p[m]=b>>8),m<_-1&&(p[m+1]=b&255),m+=2);else if(f===0)m<_&&(p[m]=0),m<_-1&&(p[m+1]=0),m+=2;else if(f!==-1){m+=2;for(let j=Math.min(m-1,_-1);j>=f+2;j--)p[j]=p[j-2];p[f]=0,p[f+1]=0,f=m}if(f!==m&&f!==-1)for(m>_-2&&(m=_-2);_>f;)p[--_]=m<_&&m>f?p[--m]:0;else for(;m<_;)p[m++]=0;return p},decode(h,p){p=~~p;let m="";for(let _=0;_<n;_+=2)_!==0&&(m+=":"),m+=(h[p+_]<<8|h[p+_+1]).toString(16);return m.replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}};t.v6=o;let a="ip";t.name=a;function c(h){if(i.isFormat(h))return i.size;if(o.isFormat(h))return o.size;throw Error(`Invalid ip address: ${h}`)}function d(h){return c(h)===i.size?1:2}function u(h,p,m){m=~~m;let _=c(h);return typeof p=="function"&&(p=p(m+_)),_===i.size?i.encode(h,p,m):o.encode(h,p,m)}function l(h,p,m){if(p=~~p,m=m||h.length-p,m===i.size)return i.decode(h,p,m);if(m===o.size)return o.decode(h,p,m);throw Error(`Invalid buffer size needs to be ${i.size} for v4 or ${o.size} for v6.`)}return"default"in t?t.default:t})({});typeof define=="function"&&define.amd?define([],function(){return kN}):typeof pT=="object"&&typeof AN=="object"&&(pT.exports=kN)});var DN=Me(Qe=>{"use strict";g();y();var Ze=require("buffer").Buffer,Ho=_N(),rZ=SN(),sZ=EN(),kw=CN(),mT=TN(),cl=IN(),nZ=0,RN=32768,gT=32768,iZ=~gT,PN=32768,oZ=~PN,Ie=Qe.name={};Ie.encode=function(t,e,r,{mail:s=!1}={}){e||(e=Ze.alloc(Ie.encodingLength(t))),r||(r=0);let n=r,i=t.replace(/^\.|\.$/gm,"");if(i.length){let o=[];if(s){let a="";i.split(".").forEach(c=>{c.endsWith("\\")?a+=(a.length?".":"")+c.slice(0,-1):o.length===0&&a.length?o.push(a+"."+c):o.push(c)})}else o=i.split(".");for(let a=0;a<o.length;a++){let c=e.write(o[a],r+1);e[r]=c,r+=c+1}}return e[r++]=0,Ie.encode.bytes=r-n,e};Ie.encode.bytes=0;Ie.decode=function(t,e,{mail:r=!1}={}){e||(e=0);let s=[],n=e,i=0,o=0,a=!1;for(;;){if(e>=t.length)throw new Error("Cannot decode name (buffer overflow)");let c=t[e++];if(o+=a?0:1,c===0)break;if((c&192)===0){if(e+c>t.length)throw new Error("Cannot decode name (buffer overflow)");if(i+=c+1,i>254)throw new Error("Cannot decode name (name too long)");let d=t.toString("utf-8",e,e+c);r&&(d=d.replace(/\./g,"\\.")),s.push(d),e+=c,o+=a?0:c}else if((c&192)===192){if(e+1>t.length)throw new Error("Cannot decode name (buffer overflow)");let d=t.readUInt16BE(e-1)-49152;if(d>=n)throw new Error("Cannot decode name (bad pointer)");e=d,n=d,o+=a?0:1,a=!0}else throw new Error("Cannot decode name (bad label)")}return Ie.decode.bytes=o,s.length===0?".":s.join(".")};Ie.decode.bytes=0;Ie.encodingLength=function(t){return t==="."||t===".."?1:Ze.byteLength(t.replace(/^\.|\.$/gm,""))+2};var St={};St.encode=function(t,e,r){e||(e=Ze.alloc(St.encodingLength(t))),r||(r=0);let s=e.write(t,r+1);return e[r]=s,St.encode.bytes=s+1,e};St.encode.bytes=0;St.decode=function(t,e){e||(e=0);let r=t[e],s=t.toString("utf-8",e+1,e+1+r);return St.decode.bytes=r+1,s};St.decode.bytes=0;St.encodingLength=function(t){return Ze.byteLength(t)+1};var Hn={};Hn.encode=function(t,e,r){e||(e=Hn.encodingLength(t)),r||(r=0);let s=(t.flags||0)&32767,n=t.type==="response"?RN:nZ;return e.writeUInt16BE(t.id||0,r),e.writeUInt16BE(s|n,r+2),e.writeUInt16BE(t.questions.length,r+4),e.writeUInt16BE(t.answers.length,r+6),e.writeUInt16BE(t.authorities.length,r+8),e.writeUInt16BE(t.additionals.length,r+10),e};Hn.encode.bytes=12;Hn.decode=function(t,e){if(e||(e=0),t.length<12)throw new Error("Header must be 12 bytes");let r=t.readUInt16BE(e+2);return{id:t.readUInt16BE(e),type:r&RN?"response":"query",flags:r&32767,flag_qr:(r>>15&1)===1,opcode:sZ.toString(r>>11&15),flag_aa:(r>>10&1)===1,flag_tc:(r>>9&1)===1,flag_rd:(r>>8&1)===1,flag_ra:(r>>7&1)===1,flag_z:(r>>6&1)===1,flag_ad:(r>>5&1)===1,flag_cd:(r>>4&1)===1,rcode:rZ.toString(r&15),questions:new Array(t.readUInt16BE(e+4)),answers:new Array(t.readUInt16BE(e+6)),authorities:new Array(t.readUInt16BE(e+8)),additionals:new Array(t.readUInt16BE(e+10))}};Hn.decode.bytes=12;Hn.encodingLength=function(){return 12};var Bo=Qe.unknown={};Bo.encode=function(t,e,r){return e||(e=Ze.alloc(Bo.encodingLength(t))),r||(r=0),e.writeUInt16BE(t.length,r),t.copy(e,r+2),Bo.encode.bytes=t.length+2,e};Bo.encode.bytes=0;Bo.decode=function(t,e){e||(e=0);let r=t.readUInt16BE(e),s=t.slice(e+2,e+2+r);return Bo.decode.bytes=r+2,s};Bo.decode.bytes=0;Bo.encodingLength=function(t){return t.length+2};var Lo=Qe.ns={};Lo.encode=function(t,e,r){return e||(e=Ze.alloc(Lo.encodingLength(t))),r||(r=0),Ie.encode(t,e,r+2),e.writeUInt16BE(Ie.encode.bytes,r),Lo.encode.bytes=Ie.encode.bytes+2,e};Lo.encode.bytes=0;Lo.decode=function(t,e){e||(e=0);let r=t.readUInt16BE(e),s=Ie.decode(t,e+2);return Lo.decode.bytes=r+2,s};Lo.decode.bytes=0;Lo.encodingLength=function(t){return Ie.encodingLength(t)+2};var Oo=Qe.soa={};Oo.encode=function(t,e,r){e||(e=Ze.alloc(Oo.encodingLength(t))),r||(r=0);let s=r;return r+=2,Ie.encode(t.mname,e,r),r+=Ie.encode.bytes,Ie.encode(t.rname,e,r,{mail:!0}),r+=Ie.encode.bytes,e.writeUInt32BE(t.serial||0,r),r+=4,e.writeUInt32BE(t.refresh||0,r),r+=4,e.writeUInt32BE(t.retry||0,r),r+=4,e.writeUInt32BE(t.expire||0,r),r+=4,e.writeUInt32BE(t.minimum||0,r),r+=4,e.writeUInt16BE(r-s-2,s),Oo.encode.bytes=r-s,e};Oo.encode.bytes=0;Oo.decode=function(t,e){e||(e=0);let r=e,s={};return e+=2,s.mname=Ie.decode(t,e),e+=Ie.decode.bytes,s.rname=Ie.decode(t,e,{mail:!0}),e+=Ie.decode.bytes,s.serial=t.readUInt32BE(e),e+=4,s.refresh=t.readUInt32BE(e),e+=4,s.retry=t.readUInt32BE(e),e+=4,s.expire=t.readUInt32BE(e),e+=4,s.minimum=t.readUInt32BE(e),e+=4,Oo.decode.bytes=e-r,s};Oo.decode.bytes=0;Oo.encodingLength=function(t){return 22+Ie.encodingLength(t.mname)+Ie.encodingLength(t.rname)};var No=Qe.txt={};No.encode=function(t,e,r){Array.isArray(t)||(t=[t]);for(let n=0;n<t.length;n++)if(typeof t[n]=="string"&&(t[n]=Ze.from(t[n])),!Ze.isBuffer(t[n]))throw new Error("Must be a Buffer");e||(e=Ze.alloc(No.encodingLength(t))),r||(r=0);let s=r;return r+=2,t.forEach(function(n){e[r++]=n.length,n.copy(e,r,0,n.length),r+=n.length}),e.writeUInt16BE(r-s-2,s),No.encode.bytes=r-s,e};No.encode.bytes=0;No.decode=function(t,e){e||(e=0);let r=e,s=t.readUInt16BE(e);e+=2;let n=[];for(;s>0;){let i=t[e++];if(--s,s<i)throw new Error("Buffer overflow");n.push(t.slice(e,e+i)),e+=i,s-=i}return No.decode.bytes=e-r,n};No.decode.bytes=0;No.encodingLength=function(t){Array.isArray(t)||(t=[t]);let e=2;return t.forEach(function(r){typeof r=="string"?e+=Ze.byteLength(r)+1:e+=r.length+1}),e};var Uo=Qe.null={};Uo.encode=function(t,e,r){e||(e=Ze.alloc(Uo.encodingLength(t))),r||(r=0),typeof t=="string"&&(t=Ze.from(t)),t||(t=Ze.alloc(0));let s=r;r+=2;let n=t.length;return t.copy(e,r,0,n),r+=n,e.writeUInt16BE(r-s-2,s),Uo.encode.bytes=r-s,e};Uo.encode.bytes=0;Uo.decode=function(t,e){e||(e=0);let r=e,s=t.readUInt16BE(e);e+=2;let n=t.slice(e,e+s);return e+=s,Uo.decode.bytes=e-r,n};Uo.decode.bytes=0;Uo.encodingLength=function(t){return t?(Ze.isBuffer(t)?t.length:Ze.byteLength(t))+2:2};var Mo=Qe.hinfo={};Mo.encode=function(t,e,r){e||(e=Ze.alloc(Mo.encodingLength(t))),r||(r=0);let s=r;return r+=2,St.encode(t.cpu,e,r),r+=St.encode.bytes,St.encode(t.os,e,r),r+=St.encode.bytes,e.writeUInt16BE(r-s-2,s),Mo.encode.bytes=r-s,e};Mo.encode.bytes=0;Mo.decode=function(t,e){e||(e=0);let r=e,s={};return e+=2,s.cpu=St.decode(t,e),e+=St.decode.bytes,s.os=St.decode(t,e),e+=St.decode.bytes,Mo.decode.bytes=e-r,s};Mo.decode.bytes=0;Mo.encodingLength=function(t){return St.encodingLength(t.cpu)+St.encodingLength(t.os)+2};var $n=Qe.ptr={},aZ=Qe.cname=$n,cZ=Qe.dname=$n;$n.encode=function(t,e,r){return e||(e=Ze.alloc($n.encodingLength(t))),r||(r=0),Ie.encode(t,e,r+2),e.writeUInt16BE(Ie.encode.bytes,r),$n.encode.bytes=Ie.encode.bytes+2,e};$n.encode.bytes=0;$n.decode=function(t,e){e||(e=0);let r=Ie.decode(t,e+2);return $n.decode.bytes=Ie.decode.bytes+2,r};$n.decode.bytes=0;$n.encodingLength=function(t){return Ie.encodingLength(t)+2};var jo=Qe.srv={};jo.encode=function(t,e,r){e||(e=Ze.alloc(jo.encodingLength(t))),r||(r=0),e.writeUInt16BE(t.priority||0,r+2),e.writeUInt16BE(t.weight||0,r+4),e.writeUInt16BE(t.port||0,r+6),Ie.encode(t.target,e,r+8);let s=Ie.encode.bytes+6;return e.writeUInt16BE(s,r),jo.encode.bytes=s+2,e};jo.encode.bytes=0;jo.decode=function(t,e){e||(e=0);let r=t.readUInt16BE(e),s={};return s.priority=t.readUInt16BE(e+2),s.weight=t.readUInt16BE(e+4),s.port=t.readUInt16BE(e+6),s.target=Ie.decode(t,e+8),jo.decode.bytes=r+2,s};jo.decode.bytes=0;jo.encodingLength=function(t){return 8+Ie.encodingLength(t.target)};var Ws=Qe.caa={};Ws.ISSUER_CRITICAL=128;Ws.encode=function(t,e,r){let s=Ws.encodingLength(t);return e||(e=Ze.alloc(Ws.encodingLength(t))),r||(r=0),t.issuerCritical&&(t.flags=Ws.ISSUER_CRITICAL),e.writeUInt16BE(s-2,r),r+=2,e.writeUInt8(t.flags||0,r),r+=1,St.encode(t.tag,e,r),r+=St.encode.bytes,e.write(t.value,r),r+=Ze.byteLength(t.value),Ws.encode.bytes=s,e};Ws.encode.bytes=0;Ws.decode=function(t,e){e||(e=0);let r=t.readUInt16BE(e);e+=2;let s=e,n={};return n.flags=t.readUInt8(e),e+=1,n.tag=St.decode(t,e),e+=St.decode.bytes,n.value=t.toString("utf-8",e,s+r),n.issuerCritical=!!(n.flags&Ws.ISSUER_CRITICAL),Ws.decode.bytes=r+2,n};Ws.decode.bytes=0;Ws.encodingLength=function(t){return St.encodingLength(t.tag)+St.encodingLength(t.value)+2};var oc=Qe.mx={};oc.encode=function(t,e,r){e||(e=Ze.alloc(oc.encodingLength(t))),r||(r=0);let s=r;return r+=2,e.writeUInt16BE(t.preference||0,r),r+=2,Ie.encode(t.exchange,e,r),r+=Ie.encode.bytes,e.writeUInt16BE(r-s-2,s),oc.encode.bytes=r-s,e};oc.encode.bytes=0;oc.decode=function(t,e){e||(e=0);let r=e,s={};return e+=2,s.preference=t.readUInt16BE(e),e+=2,s.exchange=Ie.decode(t,e),e+=Ie.decode.bytes,oc.decode.bytes=e-r,s};oc.encodingLength=function(t){return 4+Ie.encodingLength(t.exchange)};var $o=Qe.a={};$o.encode=function(t,e,r){return e||(e=Ze.alloc($o.encodingLength(t))),r||(r=0),e.writeUInt16BE(4,r),r+=2,cl.v4.encode(t,e,r),$o.encode.bytes=6,e};$o.encode.bytes=0;$o.decode=function(t,e){e||(e=0),e+=2;let r=cl.v4.decode(t,e);return $o.decode.bytes=6,r};$o.decode.bytes=0;$o.encodingLength=function(){return 6};var Fo=Qe.aaaa={};Fo.encode=function(t,e,r){return e||(e=Ze.alloc(Fo.encodingLength(t))),r||(r=0),e.writeUInt16BE(16,r),r+=2,cl.v6.encode(t,e,r),Fo.encode.bytes=18,e};Fo.encode.bytes=0;Fo.decode=function(t,e){e||(e=0),e+=2;let r=cl.v6.decode(t,e);return Fo.decode.bytes=18,r};Fo.decode.bytes=0;Fo.encodingLength=function(){return 18};var Bs=Qe.option={};Bs.encode=function(t,e,r){e||(e=Ze.alloc(Bs.encodingLength(t))),r||(r=0);let s=r,n=mT.toCode(t.code);if(e.writeUInt16BE(n,r),r+=2,t.data)e.writeUInt16BE(t.data.length,r),r+=2,t.data.copy(e,r),r+=t.data.length;else switch(n){case 8:let i=t.sourcePrefixLength||0,o=t.family||cl.familyOf(t.ip),a=cl.encode(t.ip,Ze.alloc),c=Math.ceil(i/8);e.writeUInt16BE(c+4,r),r+=2,e.writeUInt16BE(o,r),r+=2,e.writeUInt8(i,r++),e.writeUInt8(t.scopePrefixLength||0,r++),a.copy(e,r,0,c),r+=c;break;case 11:t.timeout?(e.writeUInt16BE(2,r),r+=2,e.writeUInt16BE(t.timeout,r),r+=2):(e.writeUInt16BE(0,r),r+=2);break;case 12:let d=t.length||0;e.writeUInt16BE(d,r),r+=2,e.fill(0,r,r+d),r+=d;break;case 14:let u=t.tags.length*2;e.writeUInt16BE(u,r),r+=2;for(let l of t.tags)e.writeUInt16BE(l,r),r+=2;break;default:throw new Error(`Unknown roption code: ${t.code}`)}return Bs.encode.bytes=r-s,e};Bs.encode.bytes=0;Bs.decode=function(t,e){e||(e=0);let r={};r.code=t.readUInt16BE(e),r.type=mT.toString(r.code),e+=2;let s=t.readUInt16BE(e);switch(e+=2,r.data=t.slice(e,e+s),r.code){case 8:r.family=t.readUInt16BE(e),e+=2,r.sourcePrefixLength=t.readUInt8(e++),r.scopePrefixLength=t.readUInt8(e++);let n=Ze.alloc(r.family===1?4:16);t.copy(n,0,e,e+s-4),r.ip=cl.decode(n);break;case 11:s>0&&(r.timeout=t.readUInt16BE(e),e+=2);break;case 14:r.tags=[];for(let i=0;i<s;i+=2)r.tags.push(t.readUInt16BE(e)),e+=2}return Bs.decode.bytes=s+4,r};Bs.decode.bytes=0;Bs.encodingLength=function(t){if(t.data)return t.data.length+4;switch(mT.toCode(t.code)){case 8:let r=t.sourcePrefixLength||0;return Math.ceil(r/8)+8;case 11:return typeof t.timeout=="number"?6:4;case 12:return t.length+4;case 14:return 4+t.tags.length*2}throw new Error(`Unknown roption code: ${t.code}`)};var Gs=Qe.opt={};Gs.encode=function(t,e,r){e||(e=Ze.alloc(Gs.encodingLength(t))),r||(r=0);let s=r,n=wh(t,Bs);return e.writeUInt16BE(n,r),r=o0(t,Bs,e,r+2),Gs.encode.bytes=r-s,e};Gs.encode.bytes=0;Gs.decode=function(t,e){e||(e=0);let r=e,s=[],n=t.readUInt16BE(e);e+=2;let i=0;for(;n>0;)s[i++]=Bs.decode(t,e),e+=Bs.decode.bytes,n-=Bs.decode.bytes;return Gs.decode.bytes=e-r,s};Gs.decode.bytes=0;Gs.encodingLength=function(t){return 2+wh(t||[],Bs)};var gs=Qe.dnskey={};gs.PROTOCOL_DNSSEC=3;gs.ZONE_KEY=128;gs.SECURE_ENTRYPOINT=32768;gs.encode=function(t,e,r){e||(e=Ze.alloc(gs.encodingLength(t))),r||(r=0);let s=r,n=t.key;if(!Ze.isBuffer(n))throw new Error("Key must be a Buffer");return r+=2,e.writeUInt16BE(t.flags,r),r+=2,e.writeUInt8(gs.PROTOCOL_DNSSEC,r),r+=1,e.writeUInt8(t.algorithm,r),r+=1,n.copy(e,r,0,n.length),r+=n.length,gs.encode.bytes=r-s,e.writeUInt16BE(gs.encode.bytes-2,s),e};gs.encode.bytes=0;gs.decode=function(t,e){e||(e=0);let r=e;var s={},n=t.readUInt16BE(e);if(e+=2,s.flags=t.readUInt16BE(e),e+=2,t.readUInt8(e)!==gs.PROTOCOL_DNSSEC)throw new Error("Protocol must be 3");return e+=1,s.algorithm=t.readUInt8(e),e+=1,s.key=t.slice(e,r+n+2),e+=s.key.length,gs.decode.bytes=e-r,s};gs.decode.bytes=0;gs.encodingLength=function(t){return 6+Ze.byteLength(t.key)};var Bi=Qe.rrsig={};Bi.encode=function(t,e,r){e||(e=Ze.alloc(Bi.encodingLength(t))),r||(r=0);let s=r,n=t.signature;if(!Ze.isBuffer(n))throw new Error("Signature must be a Buffer");return r+=2,e.writeUInt16BE(Ho.toType(t.typeCovered),r),r+=2,e.writeUInt8(t.algorithm,r),r+=1,e.writeUInt8(t.labels,r),r+=1,e.writeUInt32BE(t.originalTTL,r),r+=4,e.writeUInt32BE(t.expiration,r),r+=4,e.writeUInt32BE(t.inception,r),r+=4,e.writeUInt16BE(t.keyTag,r),r+=2,Ie.encode(t.signersName,e,r),r+=Ie.encode.bytes,n.copy(e,r,0,n.length),r+=n.length,Bi.encode.bytes=r-s,e.writeUInt16BE(Bi.encode.bytes-2,s),e};Bi.encode.bytes=0;Bi.decode=function(t,e){e||(e=0);let r=e;var s={},n=t.readUInt16BE(e);return e+=2,s.typeCovered=Ho.toString(t.readUInt16BE(e)),e+=2,s.algorithm=t.readUInt8(e),e+=1,s.labels=t.readUInt8(e),e+=1,s.originalTTL=t.readUInt32BE(e),e+=4,s.expiration=t.readUInt32BE(e),e+=4,s.inception=t.readUInt32BE(e),e+=4,s.keyTag=t.readUInt16BE(e),e+=2,s.signersName=Ie.decode(t,e),e+=Ie.decode.bytes,s.signature=t.slice(e,r+n+2),e+=s.signature.length,Bi.decode.bytes=e-r,s};Bi.decode.bytes=0;Bi.encodingLength=function(t){return 20+Ie.encodingLength(t.signersName)+Ze.byteLength(t.signature)};var Li=Qe.rp={};Li.encode=function(t,e,r){e||(e=Ze.alloc(Li.encodingLength(t))),r||(r=0);let s=r;return r+=2,Ie.encode(t.mbox||".",e,r,{mail:!0}),r+=Ie.encode.bytes,Ie.encode(t.txt||".",e,r),r+=Ie.encode.bytes,Li.encode.bytes=r-s,e.writeUInt16BE(Li.encode.bytes-2,s),e};Li.encode.bytes=0;Li.decode=function(t,e){e||(e=0);let r=e,s={};return e+=2,s.mbox=Ie.decode(t,e,{mail:!0})||".",e+=Ie.decode.bytes,s.txt=Ie.decode(t,e)||".",e+=Ie.decode.bytes,Li.decode.bytes=e-r,s};Li.decode.bytes=0;Li.encodingLength=function(t){return 2+Ie.encodingLength(t.mbox||".")+Ie.encodingLength(t.txt||".")};var Mr={};Mr.encode=function(t,e,r){e||(e=Ze.alloc(Mr.encodingLength(t))),r||(r=0);let s=r;for(var n=[],i=0;i<t.length;i++){var o=Ho.toType(t[i]);n[o>>8]===void 0&&(n[o>>8]=[]),n[o>>8][o>>3&31]|=1<<7-(o&7)}for(i=0;i<n.length;i++)if(n[i]!==void 0){var a=Ze.from(n[i]);e.writeUInt8(i,r),r+=1,e.writeUInt8(a.length,r),r+=1,a.copy(e,r),r+=a.length}return Mr.encode.bytes=r-s,e};Mr.encode.bytes=0;Mr.decode=function(t,e,r){e||(e=0);let s=e;for(var n=[];e-s<r;){var i=t.readUInt8(e);e+=1;var o=t.readUInt8(e);e+=1;for(var a=0;a<o;a++)for(var c=t.readUInt8(e+a),d=0;d<8;d++)if(c&1<<7-d){var u=Ho.toString(i<<8|a<<3|d);n.push(u)}e+=o}return Mr.decode.bytes=e-s,n};Mr.decode.bytes=0;Mr.encodingLength=function(t){for(var e=[],r=0;r<t.length;r++){var s=Ho.toType(t[r]);e[s>>8]=Math.max(e[s>>8]||0,s&255)}var n=0;for(r=0;r<e.length;r++)e[r]!==void 0&&(n+=2+Math.ceil((e[r]+1)/8));return n};var Oi=Qe.nsec={};Oi.encode=function(t,e,r){e||(e=Ze.alloc(Oi.encodingLength(t))),r||(r=0);let s=r;return r+=2,Ie.encode(t.nextDomain,e,r),r+=Ie.encode.bytes,Mr.encode(t.rrtypes,e,r),r+=Mr.encode.bytes,Oi.encode.bytes=r-s,e.writeUInt16BE(Oi.encode.bytes-2,s),e};Oi.encode.bytes=0;Oi.decode=function(t,e){e||(e=0);let r=e;var s={},n=t.readUInt16BE(e);return e+=2,s.nextDomain=Ie.decode(t,e),e+=Ie.decode.bytes,s.rrtypes=Mr.decode(t,e,n-(e-r)),e+=Mr.decode.bytes,Oi.decode.bytes=e-r,s};Oi.decode.bytes=0;Oi.encodingLength=function(t){return 2+Ie.encodingLength(t.nextDomain)+Mr.encodingLength(t.rrtypes)};var Ni=Qe.nsec3={};Ni.encode=function(t,e,r){e||(e=Ze.alloc(Ni.encodingLength(t))),r||(r=0);let s=r,n=t.salt;if(!Ze.isBuffer(n))throw new Error("salt must be a Buffer");let i=t.nextDomain;if(!Ze.isBuffer(i))throw new Error("nextDomain must be a Buffer");return r+=2,e.writeUInt8(t.algorithm,r),r+=1,e.writeUInt8(t.flags,r),r+=1,e.writeUInt16BE(t.iterations,r),r+=2,e.writeUInt8(n.length,r),r+=1,n.copy(e,r,0,n.length),r+=n.length,e.writeUInt8(i.length,r),r+=1,i.copy(e,r,0,i.length),r+=i.length,Mr.encode(t.rrtypes,e,r),r+=Mr.encode.bytes,Ni.encode.bytes=r-s,e.writeUInt16BE(Ni.encode.bytes-2,s),e};Ni.encode.bytes=0;Ni.decode=function(t,e){e||(e=0);let r=e;var s={},n=t.readUInt16BE(e);e+=2,s.algorithm=t.readUInt8(e),e+=1,s.flags=t.readUInt8(e),e+=1,s.iterations=t.readUInt16BE(e),e+=2;let i=t.readUInt8(e);e+=1,s.salt=t.slice(e,e+i),e+=i;let o=t.readUInt8(e);return e+=1,s.nextDomain=t.slice(e,e+o),e+=o,s.rrtypes=Mr.decode(t,e,n-(e-r)),e+=Mr.decode.bytes,Ni.decode.bytes=e-r,s};Ni.decode.bytes=0;Ni.encodingLength=function(t){return 8+t.salt.length+t.nextDomain.length+Mr.encodingLength(t.rrtypes)};var Ui=Qe.ds={};Ui.encode=function(t,e,r){e||(e=Ze.alloc(Ui.encodingLength(t))),r||(r=0);let s=r,n=t.digest;if(!Ze.isBuffer(n))throw new Error("Digest must be a Buffer");return r+=2,e.writeUInt16BE(t.keyTag,r),r+=2,e.writeUInt8(t.algorithm,r),r+=1,e.writeUInt8(t.digestType,r),r+=1,n.copy(e,r,0,n.length),r+=n.length,Ui.encode.bytes=r-s,e.writeUInt16BE(Ui.encode.bytes-2,s),e};Ui.encode.bytes=0;Ui.decode=function(t,e){e||(e=0);let r=e;var s={},n=t.readUInt16BE(e);return e+=2,s.keyTag=t.readUInt16BE(e),e+=2,s.algorithm=t.readUInt8(e),e+=1,s.digestType=t.readUInt8(e),e+=1,s.digest=t.slice(e,r+n+2),e+=s.digest.length,Ui.decode.bytes=e-r,s};Ui.decode.bytes=0;Ui.encodingLength=function(t){return 6+Ze.byteLength(t.digest)};var Ks=Qe.sshfp={};Ks.getFingerprintLengthForHashType=function(e){switch(e){case 1:return 20;case 2:return 32}};Ks.encode=function(e,r,s){r||(r=Ze.alloc(Ks.encodingLength(e))),s||(s=0);let n=s;s+=2,r[s]=e.algorithm,s+=1,r[s]=e.hash,s+=1;let i=Ze.from(e.fingerprint.toUpperCase(),"hex");if(i.length!==Ks.getFingerprintLengthForHashType(e.hash))throw new Error("Invalid fingerprint length");return i.copy(r,s),s+=i.byteLength,Ks.encode.bytes=s-n,r.writeUInt16BE(Ks.encode.bytes-2,n),r};Ks.encode.bytes=0;Ks.decode=function(e,r){r||(r=0);let s=r,n={};r+=2,n.algorithm=e[r],r+=1,n.hash=e[r],r+=1;let i=Ks.getFingerprintLengthForHashType(n.hash);return n.fingerprint=e.slice(r,r+i).toString("hex").toUpperCase(),r+=i,Ks.decode.bytes=r-s,n};Ks.decode.bytes=0;Ks.encodingLength=function(t){return 4+Ze.from(t.fingerprint,"hex").byteLength};var Mi=Qe.naptr={};Mi.encode=function(t,e,r){e||(e=Ze.alloc(Mi.encodingLength(t))),r||(r=0);let s=r;return r+=2,e.writeUInt16BE(t.order||0,r),r+=2,e.writeUInt16BE(t.preference||0,r),r+=2,St.encode(t.flags,e,r),r+=St.encode.bytes,St.encode(t.services,e,r),r+=St.encode.bytes,St.encode(t.regexp,e,r),r+=St.encode.bytes,Ie.encode(t.replacement,e,r),r+=Ie.encode.bytes,Mi.encode.bytes=r-s,e.writeUInt16BE(Mi.encode.bytes-2,s),e};Mi.encode.bytes=0;Mi.decode=function(t,e){e||(e=0);let r=e,s={};return e+=2,s.order=t.readUInt16BE(e),e+=2,s.preference=t.readUInt16BE(e),e+=2,s.flags=St.decode(t,e),e+=St.decode.bytes,s.services=St.decode(t,e),e+=St.decode.bytes,s.regexp=St.decode(t,e),e+=St.decode.bytes,s.replacement=Ie.decode(t,e),e+=Ie.decode.bytes,Mi.decode.bytes=e-r,s};Mi.decode.bytes=0;Mi.encodingLength=function(t){return St.encodingLength(t.flags)+St.encodingLength(t.services)+St.encodingLength(t.regexp)+Ie.encodingLength(t.replacement)+6};var ji=Qe.tlsa={};ji.encode=function(t,e,r){e||(e=Ze.alloc(ji.encodingLength(t))),r||(r=0);let s=r,n=t.certificate;if(!Ze.isBuffer(n))throw new Error("Certificate must be a Buffer");return r+=2,e.writeUInt8(t.usage,r),r+=1,e.writeUInt8(t.selector,r),r+=1,e.writeUInt8(t.matchingType,r),r+=1,n.copy(e,r,0,n.length),r+=n.length,ji.encode.bytes=r-s,e.writeUInt16BE(ji.encode.bytes-2,s),e};ji.encode.bytes=0;ji.decode=function(t,e){e||(e=0);let r=e,s={},n=t.readUInt16BE(e);return e+=2,s.usage=t.readUInt8(e),e+=1,s.selector=t.readUInt8(e),e+=1,s.matchingType=t.readUInt8(e),e+=1,s.certificate=t.slice(e,r+n+2),e+=s.certificate.length,ji.decode.bytes=e-r,s};ji.decode.bytes=0;ji.encodingLength=function(t){return 5+Ze.byteLength(t.certificate)};var yT=Qe.record=function(t){switch(t.toUpperCase()){case"A":return $o;case"PTR":return $n;case"CNAME":return aZ;case"DNAME":return cZ;case"TXT":return No;case"NULL":return Uo;case"AAAA":return Fo;case"SRV":return jo;case"HINFO":return Mo;case"CAA":return Ws;case"NS":return Lo;case"SOA":return Oo;case"MX":return oc;case"OPT":return Gs;case"DNSKEY":return gs;case"RRSIG":return Bi;case"RP":return Li;case"NSEC":return Oi;case"NSEC3":return Ni;case"SSHFP":return Ks;case"DS":return Ui;case"NAPTR":return Mi;case"TLSA":return ji}return Bo},Xr=Qe.answer={};Xr.encode=function(t,e,r){e||(e=Ze.alloc(Xr.encodingLength(t))),r||(r=0);let s=r;if(Ie.encode(t.name,e,r),r+=Ie.encode.bytes,e.writeUInt16BE(Ho.toType(t.type),r),t.type.toUpperCase()==="OPT"){if(t.name!==".")throw new Error("OPT name must be root.");e.writeUInt16BE(t.udpPayloadSize||4096,r+2),e.writeUInt8(t.extendedRcode||0,r+4),e.writeUInt8(t.ednsVersion||0,r+5),e.writeUInt16BE(t.flags||0,r+6),r+=8,Gs.encode(t.options||[],e,r),r+=Gs.encode.bytes}else{let n=kw.toClass(t.class===void 0?"IN":t.class);t.flush&&(n|=gT),e.writeUInt16BE(n,r+2),e.writeUInt32BE(t.ttl||0,r+4),r+=8;let i=yT(t.type);i.encode(t.data,e,r),r+=i.encode.bytes}return Xr.encode.bytes=r-s,e};Xr.encode.bytes=0;Xr.decode=function(t,e){e||(e=0);let r={},s=e;if(r.name=Ie.decode(t,e),e+=Ie.decode.bytes,r.type=Ho.toString(t.readUInt16BE(e)),r.type==="OPT")r.udpPayloadSize=t.readUInt16BE(e+2),r.extendedRcode=t.readUInt8(e+4),r.ednsVersion=t.readUInt8(e+5),r.flags=t.readUInt16BE(e+6),r.flag_do=(r.flags>>15&1)===1,r.options=Gs.decode(t,e+8),e+=8+Gs.decode.bytes;else{let n=t.readUInt16BE(e+2);r.ttl=t.readUInt32BE(e+4),r.class=kw.toString(n&iZ),r.flush=!!(n&gT);let i=yT(r.type);r.data=i.decode(t,e+8),e+=8+i.decode.bytes}return Xr.decode.bytes=e-s,r};Xr.decode.bytes=0;Xr.encodingLength=function(t){let e=t.data!==null&&t.data!==void 0?t.data:t.options;return Ie.encodingLength(t.name)+8+yT(t.type).encodingLength(e)};var Fn=Qe.question={};Fn.encode=function(t,e,r){e||(e=Ze.alloc(Fn.encodingLength(t))),r||(r=0);let s=r;return Ie.encode(t.name,e,r),r+=Ie.encode.bytes,e.writeUInt16BE(Ho.toType(t.type),r),r+=2,e.writeUInt16BE(kw.toClass(t.class===void 0?"IN":t.class),r),r+=2,Fn.encode.bytes=r-s,t};Fn.encode.bytes=0;Fn.decode=function(t,e){e||(e=0);let r=e,s={};return s.name=Ie.decode(t,e),e+=Ie.decode.bytes,s.type=Ho.toString(t.readUInt16BE(e)),e+=2,s.class=kw.toString(t.readUInt16BE(e)),e+=2,s.class&PN&&(s.class&=oZ),Fn.decode.bytes=e-r,s};Fn.decode.bytes=0;Fn.encodingLength=function(t){return Ie.encodingLength(t.name)+4};Qe.AUTHORITATIVE_ANSWER=1024;Qe.TRUNCATED_RESPONSE=512;Qe.RECURSION_DESIRED=256;Qe.RECURSION_AVAILABLE=128;Qe.AUTHENTIC_DATA=32;Qe.CHECKING_DISABLED=16;Qe.DNSSEC_OK=32768;Qe.encode=function(t,e,r){let s=!e;s&&(e=Ze.alloc(Qe.encodingLength(t))),r||(r=0);let n=r;return t.questions||(t.questions=[]),t.answers||(t.answers=[]),t.authorities||(t.authorities=[]),t.additionals||(t.additionals=[]),Hn.encode(t,e,r),r+=Hn.encode.bytes,r=o0(t.questions,Fn,e,r),r=o0(t.answers,Xr,e,r),r=o0(t.authorities,Xr,e,r),r=o0(t.additionals,Xr,e,r),Qe.encode.bytes=r-n,s&&Qe.encode.bytes!==e.length?e.slice(0,Qe.encode.bytes):e};Qe.encode.bytes=0;Qe.decode=function(t,e){e||(e=0);let r=e,s=Hn.decode(t,e);return e+=Hn.decode.bytes,e=Tw(s.questions,Fn,t,e),e=Tw(s.answers,Xr,t,e),e=Tw(s.authorities,Xr,t,e),e=Tw(s.additionals,Xr,t,e),Qe.decode.bytes=e-r,s};Qe.decode.bytes=0;Qe.encodingLength=function(t){return Hn.encodingLength(t)+wh(t.questions||[],Fn)+wh(t.answers||[],Xr)+wh(t.authorities||[],Xr)+wh(t.additionals||[],Xr)};Qe.streamEncode=function(t){let e=Qe.encode(t),r=Ze.alloc(2);r.writeUInt16BE(e.byteLength);let s=Ze.concat([r,e]);return Qe.streamEncode.bytes=s.byteLength,s};Qe.streamEncode.bytes=0;Qe.streamDecode=function(t){let e=t.readUInt16BE(0);if(t.byteLength<e+2)return null;let r=Qe.decode(t.slice(2));return Qe.streamDecode.bytes=Qe.decode.bytes,r};Qe.streamDecode.bytes=0;function wh(t,e){let r=0;for(let s=0;s<t.length;s++)r+=e.encodingLength(t[s]);return r}function o0(t,e,r,s){for(let n=0;n<t.length;n++)e.encode(t[n],r,s),s+=e.encode.bytes;return s}function Tw(t,e,r,s){for(let n=0;n<t.length;n++)t[n]=e.decode(r,s),s+=e.decode.bytes;return s}});var ON=Me((nDe,LN)=>{"use strict";g();y();var BN=pZ;process.nextTick(fZ,42);LN.exports=dZ;function dZ(t){var e=s;return r;function r(n){e(n||uZ)}function s(n){var i=[n];e=o,t(a);function o(c){i.push(c)}function a(c){var d=arguments;for(e=lZ(c)?s:u;i.length;)u(i.shift());function u(l){BN(hZ,l,d)}}}}function lZ(t){return Object.prototype.toString.call(t)==="[object Error]"}function uZ(){}function hZ(t,e){t.apply(null,e)}function fZ(t){t===42&&(BN=process.nextTick)}function pZ(t,e,r){process.nextTick(function(){t(e,r)})}});var MN=Me((aDe,UN)=>{"use strict";g();y();var bT=DN(),mZ=require("dgram"),gZ=ON(),yZ=require("events"),wT=require("os"),xT=function(){};UN.exports=function(t){t||(t={});var e=new yZ.EventEmitter,r=typeof t.port=="number"?t.port:5353,s=t.type||"udp4",n=t.ip||t.host||(s==="udp4"?"224.0.0.251":null),i={address:n,port:r},o={},a=!1,c=null;if(s==="udp6"&&(!n||!t.interface))throw new Error("For IPv6 multicast you must specify `ip` and `interface`");var d=t.socket||mZ.createSocket({type:s,reuseAddr:t.reuseAddr!==!1,toString:function(){return s}});d.on("error",function(l){l.code==="EACCES"||l.code==="EADDRINUSE"?e.emit("error",l):e.emit("warning",l)}),d.on("message",function(l,h){try{l=bT.decode(l)}catch(p){e.emit("warning",p);return}e.emit("packet",l,h),l.type==="query"&&e.emit("query",l,h),l.type==="response"&&e.emit("response",l,h)}),d.on("listening",function(){r||(r=i.port=d.address().port),t.multicast!==!1&&(e.update(),c=setInterval(e.update,5e3),d.setMulticastTTL(t.ttl||255),d.setMulticastLoopback(t.loopback!==!1))});var u=gZ(function(l){if(!r||t.bind===!1)return l(null);d.once("error",l),d.bind(r,t.bind||t.interface,function(){d.removeListener("error",l),l(null)})});return u(function(l){if(l)return e.emit("error",l);e.emit("ready")}),e.send=function(l,h,p){if(typeof h=="function")return e.send(l,null,h);p||(p=xT),h?!h.host&&!h.address&&(h.address=i.address):h=i,u(m);function m(_){if(a)return p();if(_)return p(_);var f=bT.encode(l);d.send(f,0,f.length,h.port,h.address||h.host,p)}},e.response=e.respond=function(l,h,p){Array.isArray(l)&&(l={answers:l}),l.type="response",l.flags=(l.flags||0)|bT.AUTHORITATIVE_ANSWER,e.send(l,h,p)},e.query=function(l,h,p,m){if(typeof h=="function")return e.query(l,null,null,h);if(typeof h=="object"&&h&&h.port)return e.query(l,null,h,p);if(typeof p=="function")return e.query(l,h,null,p);m||(m=xT),typeof l=="string"&&(l=[{name:l,type:h||"ANY"}]),Array.isArray(l)&&(l={type:"query",questions:l}),l.type="query",e.send(l,p,m)},e.destroy=function(l){if(l||(l=xT),a)return process.nextTick(l);a=!0,clearInterval(c);for(var h in o)try{d.dropMembership(n,h)}catch{}o={},d.close(l)},e.update=function(){for(var l=t.interface?[].concat(t.interface):xZ(),h=!1,p=0;p<l.length;p++){var m=l[p];if(!o[m])try{d.addMembership(n,m),o[m]=!0,h=!0}catch(_){e.emit("warning",_)}}if(h){if(d.setMulticastInterface)try{d.setMulticastInterface(t.interface||bZ())}catch(_){e.emit("warning",_)}e.emit("networkInterface")}},e};function bZ(){for(var t=wT.networkInterfaces(),e=Object.keys(t),r=0;r<e.length;r++)for(var s=t[e[r]],n=0;n<s.length;n++){var i=s[n];if(NN(i.family)&&!i.internal)return wT.platform()==="darwin"&&e[r]==="en0"?i.address:"0.0.0.0"}return"127.0.0.1"}function xZ(){for(var t=wT.networkInterfaces(),e=Object.keys(t),r=[],s=0;s<e.length;s++)for(var n=t[e[s]],i=0;i<n.length;i++){var o=n[i];if(NN(o.family)){r.push(o.address);break}}return r}function NN(t){return t===4||t==="IPv4"}});var U$={};sa(U$,{AV1Obu:()=>U7,AV1RtpPayload:()=>qT,AttributeKeys:()=>Fee,BitStream:()=>fc,BitWriter:()=>D0,BitWriter2:()=>u1,BufferChain:()=>SZ,CONSENT_FAILURES:()=>mk,CONSENT_INTERVAL:()=>uj,COOKIE:()=>_1,Candidate:()=>gc,CandidatePair:()=>fk,CandidatePairState:()=>hj,CipherContext:()=>N0,CipherSuite:()=>Qw,CipherSuiteList:()=>i7,Connection:()=>wj,ConnectionStates:()=>vre,CurveType:()=>Yk,DEFAULT_MAX_MESSAGE_SIZE:()=>Ih,DePacketizerBase:()=>pee,Directions:()=>Fw,DtlsClient:()=>ik,DtlsServer:()=>jM,DtlsSocket:()=>oA,DtlsStates:()=>Nte,Event:()=>Ne,EventDisposer:()=>QU,ExtensionProfiles:()=>uc,FINGERPRINT_LENGTH:()=>$M,FINGERPRINT_XOR:()=>FM,GenericNack:()=>H0,GroupDescription:()=>Bh,H264RtpPayload:()=>F7,HEADER_LENGTH:()=>zo,HashAlgorithm:()=>O0,ICE_COMPLETED:()=>pk,ICE_FAILED:()=>T0,INTEGRITY_LENGTH:()=>aA,IPV4_PROTOCOL:()=>cA,IPV6_PROTOCOL:()=>dA,IceCandidate:()=>OA,IceGathererStates:()=>Hte,IceTransportStates:()=>Fte,Inactive:()=>Uj,Int:()=>j0,MediaDescription:()=>d1,MediaStream:()=>Mj,MediaStreamTrack:()=>K0,MediaStreamTrackFactory:()=>Rte,Message:()=>wn,NalUnitType:()=>lc,NamedCurveAlgorithm:()=>Xo,NamedCurveAlgorithmList:()=>Xk,OpusRtpPayload:()=>q7,PacketChunk:()=>tM,PacketResult:()=>sM,PacketStatus:()=>rM,PictureLossIndication:()=>$0,Profiles:()=>cee,PromiseQueue:()=>PZ,ProtectionProfileAeadAes128Gcm:()=>_l,ProtectionProfileAes128CmHmacSha1_80:()=>Hh,RETRY_MAX:()=>HM,RETRY_RTO:()=>qM,RTCCertificate:()=>LA,RTCDataChannel:()=>bA,RTCDataChannelParameters:()=>xA,RTCDtlsFingerprint:()=>o1,RTCDtlsParameters:()=>a1,RTCDtlsTransport:()=>vk,RTCIceCandidate:()=>t$,RTCIceGatherer:()=>Zj,RTCIceParameters:()=>NA,RTCIceTransport:()=>Qj,RTCP_HEADER_SIZE:()=>t1,RTCPeerConnection:()=>yre,RTCRtcpFeedback:()=>Ej,RTCRtcpParameters:()=>cte,RTCRtpCodecParameters:()=>yc,RTCRtpCodingParameters:()=>Tj,RTCRtpHeaderExtensionParameters:()=>Wi,RTCRtpReceiver:()=>FA,RTCRtpRtxParameters:()=>Cj,RTCRtpSender:()=>D$,RTCRtpSimulcastParameters:()=>wA,RTCRtpTransceiver:()=>Nj,RTCSctpCapabilities:()=>MA,RTCSctpTransport:()=>k$,RTCSessionDescription:()=>R$,RTCStatsReport:()=>Oj,RTP_EXTENSION_URI:()=>Qt,ReceiverEstimatedMaxBitrate:()=>F0,RecvDelta:()=>I0,Recvonly:()=>TA,Red:()=>sA,RedEncoder:()=>SM,RedHandler:()=>EM,RedHeader:()=>tk,RtcpHeader:()=>Qo,RtcpPacketConverter:()=>cM,RtcpPayloadSpecificFeedback:()=>Oh,RtcpReceiverInfo:()=>v1,RtcpRrPacket:()=>Nh,RtcpSenderInfo:()=>rA,RtcpSourceDescriptionPacket:()=>V0,RtcpSrPacket:()=>bl,RtcpTransportLayerFeedback:()=>yl,RtpBuilder:()=>Dee,RtpHeader:()=>Yo,RtpPacket:()=>Jo,RtpRouter:()=>P$,RunLengthChunk:()=>Dh,SDPManager:()=>L$,Sendonly:()=>CA,Sendrecv:()=>kA,SessionDescription:()=>P0,SignalingStates:()=>wre,SignatureAlgorithm:()=>zi,SignatureScheme:()=>OT,SourceDescriptionChunk:()=>eA,SourceDescriptionItem:()=>tA,SrtcpSession:()=>LM,SrtpAuthenticationError:()=>xl,SrtpContext:()=>U0,SrtpSession:()=>OM,SsrcDescription:()=>l1,StatusVectorChunk:()=>Z7,StunOverTurnProtocol:()=>ej,StunProtocol:()=>r1,TcpTransport:()=>s7,TransceiverManager:()=>N$,TransportWideCC:()=>q0,TurnProtocol:()=>rj,UdpTransport:()=>Jw,Vp8RtpPayload:()=>z7,Vp9RtpPayload:()=>K7,WeriftError:()=>BZ,addSDPHeader:()=>Uk,andDirection:()=>PA,buffer2ArrayBuffer:()=>CZ,bufferArrayXor:()=>vZ,bufferReader:()=>bs,bufferWriter:()=>nr,bufferWriterLE:()=>FU,bufferXor:()=>wZ,candidateFoundation:()=>s1,candidateFromIce:()=>jh,candidateFromSdp:()=>$A,candidatePairPriority:()=>n1,candidatePriority:()=>R0,candidateToIce:()=>e$,candidateToSdp:()=>jA,certificateTypes:()=>o7,classes:()=>lA,codecParametersFromString:()=>J0,codecParametersToString:()=>dre,compactNtp:()=>BA,crc32:()=>KU,crc32c:()=>Wk,createBufferWriter:()=>A0,createSelfSignedCertificate:()=>Ite,createStunOverTurnClient:()=>dk,createTurnClient:()=>nj,dePacketizeRtpPackets:()=>mee,debug:()=>ft,deepMerge:()=>Vj,defaultOptions:()=>fj,defaultPeerConfig:()=>bre,depacketizerCodecs:()=>gee,deserializeAbsSendTime:()=>bM,deserializeAudioLevelIndication:()=>xM,deserializeString:()=>gM,deserializeUint16BE:()=>yM,deserializeVideoOrientation:()=>wM,dumpBuffer:()=>EZ,enumerate:()=>yee,findCodecByMimeType:()=>Hk,findPort:()=>YU,fingerprint:()=>IA,generateStatsId:()=>zt,getBit:()=>Te,getDataChannelMessageSize:()=>_j,getGlobalIp:()=>ste,getHostAddresses:()=>xj,getStatsTimestamp:()=>bc,growBufferSize:()=>VT,int:()=>Rh,interfaceAddress:()=>f1,isDtls:()=>jj,isLinkLocalAddress:()=>bj,isMedia:()=>X7,isRtcp:()=>dM,keyLength:()=>B7,leb128decode:()=>j7,makeIntegrityKey:()=>ij,methods:()=>uA,microTime:()=>Fj,milliTime:()=>DA,nodeIpAddress:()=>bk,normalizeFamilyNodeV18:()=>L0,normalizeFingerprintAlgorithm:()=>RA,normalizeFingerprintValue:()=>i1,ntpTime:()=>Hj,ntpTime2Sec:()=>aM,paddingBits:()=>_Z,paddingByte:()=>B0,paddingLength:()=>ak,parseGroup:()=>Xw,parseIceServers:()=>qj,parseMessage:()=>S1,random16:()=>zk,random32:()=>Yw,randomPort:()=>Gk,randomPorts:()=>DZ,reverseDirection:()=>$j,reverseSimulcastDirection:()=>kte,rtpHeaderExtensionsParser:()=>lM,saltLength:()=>L7,serializeAbsSendTime:()=>mM,serializeAudioLevelIndication:()=>See,serializeRepairedRtpStreamId:()=>fM,serializeSdesMid:()=>uM,serializeSdesRTPStreamID:()=>hM,serializeTransportWideCC:()=>pM,serverReflexiveCandidate:()=>mj,signatures:()=>Jk,sortCandidatePairs:()=>pj,supportedAudioCodecs:()=>lte,supportedCodecs:()=>EA,supportedVideoCodecs:()=>dte,timer:()=>bee,timestampSeconds:()=>G0,uint16Add:()=>Jr,uint16Gt:()=>h1,uint16Gte:()=>RZ,uint24:()=>XU,uint32Add:()=>ul,uint32Gt:()=>Hi,uint32Gte:()=>Ah,uint8Add:()=>GU,unwrapRtx:()=>TM,url2Address:()=>nte,useAV1X:()=>Ij,useAbsSendTime:()=>mte,useAudioLevelIndication:()=>yte,useDependencyDescriptor:()=>gte,useFIR:()=>ate,useH264:()=>kj,useNACK:()=>ig,useOPUS:()=>_A,usePCMU:()=>SA,usePLI:()=>Vh,useREMB:()=>og,useRepairedRtpStreamId:()=>fte,useSdesMid:()=>ute,useSdesRTPStreamId:()=>hte,useTWCC:()=>Sj,useTransportWideCC:()=>pte,useVP8:()=>vA,useVP9:()=>Aj,useVideoOrientation:()=>bte,validateAddress:()=>yk,validateRemoteCandidate:()=>gk,wrapRtx:()=>kM});function zk(){return Vk.jspack.Unpack("!H",(0,qk.randomBytes)(2))[0]}function Yw(){return Vk.jspack.Unpack("!L",(0,qk.randomBytes)(4))[0]}function wZ(t,e){if(t.length!==e.length)throw new TypeError("[webrtc-stun] You can not XOR buffers which length are different");let r=t.length,s=Buffer.allocUnsafe(r);for(let n=0;n<r;n++)s[n]=t[n]^e[n];return s}function vZ(t){let e=[...t].sort((s,n)=>s.length-n.length).reverse()[0].length,r=Buffer.allocUnsafe(e);for(let s=0;s<e;s++)r[s]=0,t.forEach(n=>{r[s]^=n[s]??0});return r}function Te(t,e,r=1){let s=t.toString(2).split("");s=[...Array(8-s.length).fill("0"),...s];let n=s.slice(e,e+r).join("");return Number.parseInt(n,2)}function B0(t){let e=t.toString(2).split("");return[...[...Array(8-e.length)].map(()=>"0"),...e].join("")}function _Z(t,e){let r=t.toString(2);return[...[...Array(e-r.length)].map(()=>"0"),...r].join("")}function nr(t,e){return A0(t)(e)}function A0(t,e){let r=t.reduce((n,i)=>n+i,0),s=e?Buffer.alloc(r):void 0;return n=>{let i=s||Buffer.alloc(r),o=0;return n.forEach((a,c)=>{let d=t[c];d===8?i.writeBigUInt64BE(a,o):i.writeUIntBE(a,o,d),o+=d}),i}}function FU(t,e){let r=t.reduce((i,o)=>i+o,0),s=Buffer.alloc(r),n=0;return e.forEach((i,o)=>{let a=t[o];a===8?s.writeBigUInt64LE(i,n):s.writeUIntLE(i,n,a),n+=a}),s}function bs(t,e){let r=0;return e.map(s=>{let n;return s===8?n=t.readBigUInt64BE(r):n=t.readUIntBE(r,s),r+=s,n})}function CZ(t){return t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}function HU(t){return typeof t!="string"}function qU(t){let e=new Array(256),r=0;for(let s=0;s<256;++s)r=s,r=r&1?t^r>>>1:r>>>1,r=r&1?t^r>>>1:r>>>1,r=r&1?t^r>>>1:r>>>1,r=r&1?t^r>>>1:r>>>1,r=r&1?t^r>>>1:r>>>1,r=r&1?t^r>>>1:r>>>1,r=r&1?t^r>>>1:r>>>1,r=r&1?t^r>>>1:r>>>1,e[s]=r;return new Int32Array(e)}function VU(t){let e=new Int32Array(4096),r=0,s=0,n=0;for(n=0;n<256;++n)e[n]=t[n];for(n=0;n<256;++n)for(s=t[n],r=256+n;r<4096;r+=256)s=e[r]=s>>>8^t[s&255];let i=[];for(n=1;n<16;++n)i[n-1]=e.subarray(n*256,n*256+256);return i}function zU(t,e,r){let s=e^-1,n=0,i=t.length,o=0,a=0;for(;n<i;)o=t.charCodeAt(n++),o<128?s=s>>>8^r[(s^o)&255]:o<2048?(s=s>>>8^r[(s^(192|o>>6&31))&255],s=s>>>8^r[(s^(128|o&63))&255]):o>=55296&&o<57344?(o=(o&1023)+64,a=t.charCodeAt(n++)&1023,s=s>>>8^r[(s^(240|o>>8&7))&255],s=s>>>8^r[(s^(128|o>>2&63))&255],s=s>>>8^r[(s^(128|a>>6&15|(o&3)<<4))&255],s=s>>>8^r[(s^(128|a&63))&255]):(s=s>>>8^r[(s^(224|o>>12&15))&255],s=s>>>8^r[(s^(128|o>>6&63))&255],s=s>>>8^r[(s^(128|o&63))&255]);return~s>>>0}function WU(t,e,r,s){let[n,i,o,a,c,d,u,l,h,p,m,_,f,b,w]=s,S=e^-1,O=0,j=t.length-15;for(;O<j;)S=w[t[O++]^S&255]^b[t[O++]^S>>>8&255]^f[t[O++]^S>>>16&255]^_[t[O++]^S>>>24]^m[t[O++]]^p[t[O++]]^h[t[O++]]^l[t[O++]]^u[t[O++]]^d[t[O++]]^c[t[O++]]^a[t[O++]]^o[t[O++]]^i[t[O++]]^n[t[O++]]^r[t[O++]];for(j+=15;O<j;)S=S>>>8^r[(S^t[O++])&255];return~S>>>0}function KU(t,e=0){return HU(t)?WU(t,e,BT,AZ):zU(t,e,BT)}function Wk(t,e=0){return HU(t)?WU(t,e,LT,IZ):zU(t,e,LT)}function GU(t,e){return t+e&255}function Jr(t,e){return t+e&65535}function ul(t,e){return Number(BigInt(t)+BigInt(e)&0xffffffffn)}function XU(t){return t&16777215}function h1(t,e){return t<e&&e-t>32768||t>e&&t-e<32768}function RZ(t,e){return t===e||h1(t,e)}function Hi(t,e){return t<e&&e-t>2147483648||t>e&&t-e<2147483648}function Ah(t,e){return t===e||Hi(t,e)}async function Gk(t="udp4",e){let r=(0,Kk.createSocket)(t);setImmediate(()=>r.bind({port:0,address:f1(t,e)})),await new Promise(n=>{r.once("error",n),r.once("listening",n)});let s=r.address()?.port;return await new Promise(n=>r.close(()=>n())),s}async function DZ(t,e="udp4",r){return Promise.all([...Array(t)].map(()=>Gk(e,r)))}async function YU(t,e,r="udp4",s){let n;for(let i=t;i<=e;i++){let o=(0,Kk.createSocket)(r);if(setImmediate(()=>o.bind({port:i,address:f1(r,s)})),await new Promise(c=>{o.once("error",d=>c(d)),o.once("listening",()=>c())})){await new Promise(c=>o.close(()=>c()));continue}if(n=o.address()?.port,await new Promise(c=>o.close(()=>c())),t<=n&&n<=e)break}if(!n)throw new Error("port not found");return n}function L0(t){return t==="IPv4"?4:t==="IPv6"?6:t}function d7(t,e,r){switch(r){case Xo.secp256r1_23:return OZ({publicKey:t,privateKey:e});case Xo.x25519_29:return Buffer.from(c7.default.scalarMult(e,t));default:throw new Error}}function $N(t,e,r){let s=(0,m1.createHmac)(t,e);return s.update(r),s.digest()}function Q0(t,e,r,s="sha256"){let n=r,i=[],o=e;do{o=$N(s,t,o);let a=$N(s,t,Buffer.concat([o,e]));i.push(a),r-=a.length}while(r>0);return Buffer.concat(i,n)}function l7(t,e,r){let s=Buffer.concat([Buffer.from("master secret"),e,r]);return Q0(t,s,48)}function u7(t,e){let r=h7("sha256",e);return Q0(t,Buffer.concat([Buffer.from("extended master secret"),r]),48)}function NZ(t,e,r,s,n,i){let o=i?s:n,a=i?n:s,c=Buffer.concat([Buffer.from(t),o,a]);return Q0(r,c,e)}function h7(t,e){return(0,m1.createHash)(t).update(e).digest()}function f7(t,e,r,s=12){let n=h7("sha256",e);return Q0(t,Buffer.concat([Buffer.from(r),n]),s)}function UZ(t,e){return f7(t,e,"client finished")}function MZ(t,e){return f7(t,e,"server finished")}function jZ(t,e,r,s,n,i,o="sha256"){let a=s*2+n*2,c=t,d=Buffer.concat([r,e]),u=Q0(c,Buffer.concat([Buffer.from("key expansion"),d]),a,o),l=(0,a7.createDecode)(u),h=l.readBuffer(s),p=l.readBuffer(s),m=l.readBuffer(n),_=l.readBuffer(n),f=Buffer.alloc(i,0),b=Buffer.alloc(i,0);return m.copy(f,0),_.copy(b,0),{clientWriteKey:h,serverWriteKey:p,clientNonce:f,serverNonce:b}}function eee(){let t=new sg;return t.id=rg.RSA,t.name="RSA",t.keyType=tg.RSA,t}function tee(){let t=new sg;return t.id=rg.ECDHE_RSA,t.name="ECDHE_RSA",t.signType=g1.ECDHE,t.keyType=tg.RSA,t}function ree(){let t=new sg;return t.id=rg.ECDHE_ECDSA,t.name="ECDHE_ECDSA",t.signType=g1.ECDHE,t.keyType=tg.ECDSA,t}function see(){let t=new sg;return t.id=rg.PSK,t.name="PSK",t.signType=g1.NULL,t.keyType=tg.PSK,t}function nee(){let t=new sg;return t.id=rg.ECDHE_PSK,t.name="ECDHE_PSK",t.signType=g1.ECDHE,t.keyType=tg.PSK,t}function _7(t){switch(t){case Er.TLS_RSA_WITH_AES_128_GCM_SHA256:return $i(Er.TLS_RSA_WITH_AES_128_GCM_SHA256,"TLS_RSA_WITH_AES_128_GCM_SHA256","aes-128-gcm",FN,a0);case Er.TLS_RSA_WITH_AES_256_GCM_SHA384:return $i(Er.TLS_RSA_WITH_AES_256_GCM_SHA384,"TLS_RSA_WITH_AES_256_GCM_SHA384","aes-256-gcm",FN,c0,"sha384");case Er.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:return $i(Er.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,"TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256","aes-128-gcm",HN,a0);case Er.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:return $i(Er.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,"TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384","aes-256-gcm",HN,c0,"sha384");case Er.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:return $i(Er.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,"TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256","aes-128-gcm",qN,a0);case Er.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:return $i(Er.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,"TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384","aes-256-gcm",qN,c0,"sha384");case Er.TLS_PSK_WITH_AES_128_GCM_SHA256:return $i(Er.TLS_PSK_WITH_AES_128_GCM_SHA256,"TLS_PSK_WITH_AES_128_GCM_SHA256","aes-128-gcm",VN,a0,"sha256");case Er.TLS_PSK_WITH_AES_256_GCM_SHA384:return $i(Er.TLS_PSK_WITH_AES_256_GCM_SHA384,"TLS_PSK_WITH_AES_256_GCM_SHA384","aes-256-gcm",VN,c0,"sha384");case Er.TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256:return $i(Er.TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256,"TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256","aes-128-gcm",zN,a0,"sha256");case Er.TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384:return $i(Er.TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384,"TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384","aes-256-gcm",zN,c0,"sha384");default:break}return null}function $i(t,e,r,s,n,i="sha256"){let o=new oee;return o.id=t,o.name=e,o.blockAlgorithm=r,o.kx=s,o.hashAlgorithm=i,o.keyLength=n.K_LEN,o.nonceLength=n.N_MAX,o.nonceImplicitLength=4,o.nonceExplicitLength=8,o.ivLength=o.nonceImplicitLength,o.authTagLength=16,o}function E7(t){switch(t){case Xo.secp256r1_23:{let{privateKey:e,publicKey:r}=LZ();return{curve:t,privateKey:e,publicKey:r}}case Xo.x25519_29:{let e=S7.default.box.keyPair();return{curve:t,privateKey:Buffer.from(e.secretKey.buffer),publicKey:Buffer.from(e.publicKey.buffer)}}default:throw new Error}}function aee(t,e){return Buffer.from((0,P7.encode)(t,e).slice())}function j7(t){let e=0,r=0;for(let s=0;s<8;s++){let n=t.readUInt8(s);if(e|=(n&127)<<s*7,r++,!(n&128))break}return[e,r]}function mee(t,e,r){let s=n=>{let i=[];for(let c of e){let d=n.deSerialize(c.payload,r);d.fragment?(r??=Buffer.alloc(0),r=d.fragment):d.payload&&(r=void 0),i.push(d)}let o=!!i.find(c=>c.isKeyframe),a=Buffer.concat(i.map(c=>c.payload).filter(c=>c));return{isKeyframe:o,data:a,sequence:e.at(-1)?.header.sequenceNumber??0,timestamp:e.at(-1)?.header.timestamp??0,frameFragmentBuffer:r}};switch(t.toUpperCase()){case"AV1":{let n=e.map(a=>qT.deSerialize(a.payload)),i=!!n.find(a=>a.isKeyframe),o=qT.getFrame(n);return{isKeyframe:i,data:o,sequence:e.at(-1)?.header.sequenceNumber??0,timestamp:e.at(-1)?.header.timestamp??0}}case"MPEG4/ISO/AVC":return s(F7);case"VP8":return s(z7);case"VP9":return s(K7);case"OPUS":return s(q7);default:throw new Error}}function yee(t){return t.map((e,r)=>[r,e])}function VT(t,e){let r=Buffer.alloc(e);return t.copy(r),r}function j0(t){return Number.parseInt(t.toString(),10)}function X7(t){let e=t[0];return e>127&&e<192}function KN(t){return t%4==0?0:4-t%4}function dM(t){return t.length>=2&&t[1]>=192&&t[1]<=208}function lM(t,e){return t.map(r=>{let s=e[r.id];if(!s)return{uri:"unknown",value:r.payload};switch(s){case Qt.sdesMid:case Qt.sdesRTPStreamID:case Qt.repairedRtpStreamId:return{uri:s,value:gM(r.payload)};case Qt.transportWideCC:return{uri:s,value:yM(r.payload)};case Qt.absSendTime:return{uri:s,value:bM(r.payload)};case Qt.audioLevelIndication:return{uri:s,value:xM(r.payload)};case Qt.videoOrientation:return{uri:s,value:wM(r.payload)};default:return{uri:s,value:r.payload}}}).reduce((r,s)=>(s&&(r[s.uri]=s.value),r),{})}function uM(t){return Buffer.from(t)}function hM(t){return Buffer.from(t)}function fM(t){return Buffer.from(t)}function pM(t){return nr([2],[t])}function mM(t){let e=Buffer.alloc(3),r=t>>14n&0x00ffffffn;return e.writeUIntBE(Number(r),0,3),e}function See(t){let e=new fc(Buffer.alloc(1));return e.writeBits(1,1),e.writeBits(7,t),e.uint8Array}function gM(t){return t.toString()}function yM(t){return t.readUInt16BE()}function bM(t){return bs(t,[3])[0]}function xM(t){let e=new fc(t);return{v:e.readBits(1)===1,level:e.readBits(7)}}function wM(t){let e=new fc(t);return e.readBits(4),{c:e.readBits(1),f:e.readBits(1),r1:e.readBits(1),r0:e.readBits(1)}}function TM(t,e,r){return new Jo(new Yo({payloadType:e,marker:t.header.marker,sequenceNumber:nA.jspack.Unpack("!H",t.payload.subarray(0,2))[0],timestamp:t.header.timestamp,ssrc:r}),t.payload.subarray(2))}function kM(t,e,r,s){return new Jo(new Yo({payloadType:e,marker:t.header.marker,sequenceNumber:r,timestamp:t.header.timestamp,ssrc:s,csrc:t.header.csrc,extensions:t.header.extensions}),Buffer.concat([Buffer.from(nA.jspack.Pack("!H",[t.header.sequenceNumber])),t.payload]))}function iA(t,e,r="Failed to authenticate SRTP packet"){let s=t.length-e;z0(t.length>=ZN+e,r);let n=RM(()=>Yo.deSerialize(t.subarray(0,s)),r);return n.paddingSize=0,z0(n.payloadOffset>=ZN&&n.payloadOffset<=s,r),n}function IM(t,e,r,s="Failed to authenticate SRTCP packet"){return z0(t.length>=Tee+e+r,s),RM(()=>Qo.deSerialize(t.subarray(0,t1)),s)}function z0(t,e){if(!t)throw new xl(e)}function RM(t,e){try{return t()}catch{throw new xl(e)}}function PM(t,e,r="Failed to authenticate SRTP packet"){if(!t.padding)return t.paddingSize=0,t;z0(e.length>t.payloadOffset,r);let s=e[e.length-1];return z0(s>0&&s<=e.length-t.payloadOffset,r),t.paddingSize=s,t}function tU(t,e,r){if(t.length!==e.length||!(0,Yn.timingSafeEqual)(t,e))throw new xl(r)}function sU(t,e){try{t.final()}catch{throw new xl(`Failed to authenticate ${e} packet`)}}function l0(t){return(0,fA.randomBytes)(t).toString("hex").substring(0,t)}function VM(){return(0,fA.randomBytes)(12)}function Ch(t){let[e]=t,r=W0.default.isV4Format(e)?cA:dA,s=Buffer.alloc(4);return s.writeUInt8(0,0),s.writeUInt8(r,1),s.writeUInt16BE(t[1],2),Buffer.concat([s,W0.default.toBuffer(e)])}function Hee(t){if(t.length<4)throw new Error("STUN error code is less than 4 bytes");let e=t.readUInt8(2),r=t.readUInt8(3),s=t.slice(4).toString("utf8");return[e*100+r,s]}function Th(t){if(t.length<4)throw new Error("STUN address length is less than 4 bytes");let e=t.readUInt8(1),r=t.readUInt16BE(2),s=t.slice(4);switch(e){case cA:if(s.length!=4)throw new Error("STUN address has invalid length for IPv4");return[W0.default.toString(s),r];case dA:if(s.length!=16)throw new Error("STUN address has invalid length for IPv6");return[W0.default.toString(s),r];default:throw new Error("STUN address has unknown protocol")}}function zM(t,e){let r=[...pA,...e],s=t.slice(0,2);for(let n=2;n<t.length;n++){let i=t[n]^r[n-2],o=Buffer.alloc(1);o.writeUIntBE(i,0,1),s=Buffer.concat([s,o])}return s}function Nw(t,e){return Th(zM(t,e))}function qee(t){let e=Buffer.alloc(4);e.writeUInt16BE(0,0),e.writeUInt8(Math.floor(t[0]/100),2),e.writeUInt8(t[0]%100,3);let r=Buffer.from(t[1],"utf8");return Buffer.concat([e,r])}function Uw(t,e){return zM(Ch(t),e)}function S1(t,e){if(t.length<zo)return;let r=t.readUint16BE(2);if(t.length!==zo+r)return;let s=t.readUint16BE(0),n=Buffer.from(t.slice(zo-12,zo)),i=new KM;for(let a=zo;a<=t.length-4;){let c=t.readUInt16BE(a),d=t.readUInt16BE(a+2),u=t.slice(a+4,a+4+d),l=4*Math.floor((d+3)/4)-d;if(Object.keys(pU).includes(c.toString())){let[,p,,m]=pU[c];if(m.name===Nw.name?i.setAttribute(p,m(u,n)):i.setAttribute(p,m(u)),p==="FINGERPRINT"){let _=GM(t.slice(0,a));if(i.getAttributeValue("FINGERPRINT")!==_)return}else if(p==="MESSAGE-INTEGRITY"&&e){let _=Xee(t.slice(0,a),e),f=i.getAttributeValue("MESSAGE-INTEGRITY");if(!_.equals(f))return}}a+=4+d+l}let o=i.getAttributes();return i.clear(),new wn(s&16111,s&272,n,o)}function GM(t){let e=mA(t,t.length-zo+$M);return(KU(e)^FM)>>>0}function Xee(t,e){let r=mA(t,t.length-zo+aA);return Buffer.from((0,hA.createHmac)("sha1",e).update(r).digest("hex"),"hex")}function ak(t){let e=t%4;return e===0?0:4-e}async function nj({address:t,username:e,password:r},{lifetime:s,portRange:n,interfaceAddresses:i,transport:o}={}){s??=Qee,o??="udp";let a=o==="udp"?await Jw.init("udp4",{portRange:n,interfaceAddresses:i}):await s7.init(t),c=new rj(t,e,r,s,a);return await c.connectionMade(),c}async function dk({address:t,username:e,password:r},{lifetime:s,portRange:n,interfaceAddresses:i,transport:o}={}){let a=await nj({address:t,username:e,password:r},{lifetime:s,portRange:n,interfaceAddresses:i,transport:o});return new ej(a)}function ij(t,e,r){return(0,QM.createHash)("md5").update(Buffer.from([t,e,r].join(":"))).digest()}function gU(t){return(t[0]&192)==64}function s1(t,e,r){let s=`${t}|${e}|${r}`;return(0,oj.createHash)("md5").update(s,"ascii").digest("hex").slice(7)}function R0(t,e=65535){let s=0;return t==="host"?s=126:t==="prflx"?s=110:t==="srflx"?s=100:s=0,(1<<24)*s+256*e+255}function gk(t){if(!["host","relay","srflx"].includes(t.type))throw new Error(`Unexpected candidate type "${t.type}"`);return t}function pj(t,e){return t.sort((r,s)=>n1(r.localCandidate,r.remoteCandidate,e)-n1(s.localCandidate,s.remoteCandidate,e)).reverse()}function n1(t,e,r){let s=r&&t.priority||e.priority,n=r&&e.priority||t.priority;return 1*Math.min(s,n)+2*Math.max(s,n)+(s>n?1:0)}async function mj(t,e){let r=new wn(1,0);try{let[s]=await t.request(r,e),n=t.localCandidate;if(!n)throw new Error("not exist");return new gc(s1("srflx","udp",n.host),n.component,n.transport,R0("srflx"),s.getAttributeValue("XOR-MAPPED-ADDRESS")[0],s.getAttributeValue("XOR-MAPPED-ADDRESS")[1],"srflx",n.host,n.port)}catch(s){tte("error serverReflexiveCandidate",s)}}function yk(t){return t&&Number.isNaN(t[1])?[t[0],443]:t}async function ste(t,e){let r=new r1;await r.connectionMade(!0,void 0,e);let s=new wn(1,0),[n]=await r.request(s,t??["stun.l.google.com",19302]);return await r.close(),n.getAttributeValue("XOR-MAPPED-ADDRESS")[0]}function bj(t){return L0(t.family)===4&&t.address?.startsWith("169.254.")||L0(t.family)===6&&t.address?.startsWith("fe80::")}function bk(t,{useLinkLocalAddress:e}={}){let r=["ipsec","tun","utun","tap"],s=["vmnet","veth"],n=gj.networkInterfaces();rte(n);let i=Object.keys(n).map(o=>{for(let c of[...r,...s])if(o.startsWith(c))return{nic:o,addresses:[]};let a=n[o].filter(c=>L0(c.family)===t&&!yj.default.isLoopback(c.address)&&(e?!0:!bj(c)));return{nic:o,addresses:a.map(c=>c.address)}}).filter(o=>!!o);return i.sort((o,a)=>o.nic.localeCompare(a.nic)),Object.values(i).flatMap(o=>o.addresses)}function xj(t,e,r={}){let s=[];return t&&s.push(...bk(4,r)),e&&s.push(...bk(6,r)),s}function bU(t){return t.map((e,r)=>[r,e])}function Vo(t,e){let r=t.split(e);return[r[0],r.slice(1).join(e)]}function _j(t){return Buffer.isBuffer(t)?t.length:Buffer.byteLength(t)}function ute(){return new Wi({uri:Qt.sdesMid})}function hte(){return new Wi({uri:Qt.sdesRTPStreamID})}function fte(){return new Wi({uri:Qt.repairedRtpStreamId})}function pte(){return new Wi({uri:Qt.transportWideCC})}function mte(){return new Wi({uri:Qt.absSendTime})}function gte(){return new Wi({uri:Qt.dependencyDescriptor})}function yte(){return new Wi({uri:Qt.audioLevelIndication})}function bte(){return new Wi({uri:Qt.videoOrientation})}function zt(t,...e){let r=e.filter(s=>s!==void 0);return`${t}_${r.join("_")}`}function bc(){return performance.now()}function IA(t,e){let r=i=>i.toUpperCase(),s=i=>i.match(/(.{2})/g).join(":"),n=(0,Pj.createHash)(e).update(t).digest("hex");return s(r(n))}function RA(t){return Tte[t.trim().toLowerCase()]}function i1(t){return t.replace(/[^0-9a-f]/gi,"").toLowerCase()}function jj(t){let e=t[0];return e>19&&e<64}function kte(t){return t==="recv"?"send":"recv"}function $j(t){return t==="sendonly"?"recvonly":t==="recvonly"?"sendonly":t}function qj(t){let e=a=>{if(!a)return;let[c,d]=a.split(":");return[c,Number.parseInt(d)]},r=e(t.find(({urls:a})=>a.includes("stun:"))?.urls.slice(5)),s=e(t.find(({urls:a})=>a.includes("turn:"))?.urls.slice(5)),{credential:n,username:i}=t.find(({urls:a})=>a.includes("turn:"))||{},o={stunServer:r,turnServer:s,turnUsername:i,turnPassword:n};return Cte("iceOptions",o),o}function jh(t){let e=new OA(t.component,t.foundation,t.host,t.port,t.priority,t.transport,t.type,t.generation,t.ufrag);return e.relatedAddress=t.relatedAddress,e.relatedPort=t.relatedPort,e.tcpType=t.tcptype,e}function e$(t){return new gc(t.foundation,t.component,t.protocol,t.priority,t.ip,t.port,t.type,t.relatedAddress,t.relatedPort,t.tcpType,t.generation,t.ufrag)}function cg(t){let e=t%4;return e?4-e:0}function S$(t){let e=Buffer.from(""),r=Buffer.from("");return t.forEach(([s,n])=>{let i=n.length+4,o=Buffer.alloc(4);o.writeUInt16BE(s,0),o.writeUInt16BE(i,2),e=Buffer.concat([e,r,o,n]),r=Buffer.concat([...Array(cg(i))].map(()=>Buffer.from("\0")))}),e}function E$(t){let e=[],r=0;for(;r<=t.length-4;){let s=t.readUInt16BE(r),n=t.readUInt16BE(r+2);e.push([s,t.slice(r+4,r+n)]),r+=n+cg(n)}return e}function Wte(t){if(t.length<12)throw new Error("SCTP packet length is less than 12 bytes");let e=t.readUInt16BE(0),r=t.readUInt16BE(2),s=t.readUInt32BE(4),n=t.readUInt32LE(8),i=Wk(Buffer.concat([t.slice(0,8),Buffer.from("\0\0\0\0"),t.slice(12)]));if(n!==i)throw new Error("SCTP packet has invalid checksum");let o=[],a=12;for(;a+4<=t.length;){let c=t.readUInt8(a),d=t.readUInt8(a+1),u=t.readUInt16BE(a+2),l=t.slice(a+4,a+u),h=zte[c.toString()];if(h)o.push(new h(d,l));else throw new Error("unknown");a+=u+cg(u)}return[e,r,s,o]}function Kte(t,e,r,s){let n=Buffer.alloc(8);n.writeUInt16BE(t,0),n.writeUInt16BE(e,2),n.writeUInt32BE(r,4);let i=s.bytes,o=Wk(Buffer.concat([n,Buffer.from("\0\0\0\0"),i])),a=Buffer.alloc(4);return a.writeUInt32LE(o,0),Buffer.concat([n,a,i])}function Gte(t){return t.map((e,r)=>[r,e])}function Xte(t){return t.reduce((e,r)=>(e[r]=new Ne,e),{})}function dl(t){return(t-1)%c1}function kh(t){return(t+1)%c1}function RT(t){let e=t.match(/^IN (IP4|IP6) ([^ ]+)$/);if(!e)throw new Error("exception");return e[2]}function Nk(t){return`IN IP${(0,Kj.isIPv4)(t)?4:6} ${t}`}function jA(t){let e=`${t.foundation} ${t.component} ${t.protocol} ${t.priority} ${t.ip} ${t.port} typ ${t.type}`;return t.relatedAddress!=null&&(e+=` raddr ${t.relatedAddress}`),t.relatedPort!=null&&(e+=` rport ${t.relatedPort}`),t.tcpType!=null&&(e+=` tcptype ${t.tcpType}`),t.generation!=null&&(e+=` generation ${t.generation}`),t.ufrag!=null&&(e+=` ufrag ${t.ufrag}`),e}function cre(t){let e=[],r=[],s=t.split(`\r
|
|
135
135
|
`);return s.length===1&&(s=t.split(`
|
|
136
|
-
`)),s.forEach(n=>{n.startsWith("m=")?r.push([n]):r.length>0?r[r.length-1].push(n):e.push(n)}),[e,r]}function PT(t){if(t.includes(":")){let e=Vo(t.slice(2),":");return[e[0],e[1]]}else return[t.slice(2),void 0]}function Xw(t,e,r=s=>s.toString()){let s=e.split(" ");s.length>0&&t.push(new Bh(s[0],s.slice(1).map(r)))}function $A(t){let e=gc.fromSdp(t);return jh(e)}function Uk(t,e){let s=new Sw((0,Wj.randomBytes)(64)).toString().slice(0,8),n=0;e.origin=`- ${s} ${n} IN IP4 0.0.0.0`,e.msidSemantic.push(new Bh("WMS",["*"])),e.type=t}function Jm(t){let e={};return t.split(";").forEach(r=>{if(r.includes("=")){let[s,n]=Vo(r,"=");Ste.includes(s)?e[s]=Number(n):e[s]=n}else if(r.includes(":")){let[s,n]=r.split(":");e[s]=Number.isNaN(Number(n))?n:Number(n)}else e[r]=void 0}),e}function dre(t,e="="){let r=Object.entries(t).map(([s,n])=>n?`${s}${e}${n}`:s);if(r.length>0)return r.join(";")}function O$(){return{codecs:{audio:[_A(),SA()],video:[vA()]},headerExtensions:{audio:[],video:[]},iceTransportPolicy:"all",iceServers:[{urls:"stun:stun.l.google.com:19302"}],icePortRange:void 0,iceInterfaceAddresses:void 0,iceAdditionalHostAddresses:void 0,iceUseIpv4:!0,iceUseIpv6:!0,iceFilterStunResponse:void 0,iceFilterCandidatePair:void 0,icePasswordPrefix:void 0,iceUseLinkLocalAddress:void 0,dtls:{},bundlePolicy:"max-compat",debug:{},midSuffix:!1,forceTurnTCP:!1,maxMessageSize:Ih}}var qk,Vk,Kk,JU,ZU,e7,t7,$h,p1,Ph,m1,a7,c7,Yr,Kn,m7,y7,hl,x7,Wo,y1,S7,pl,pc,ml,Fh,mc,gl,Gn,Xn,w1,Wn,P7,O7,nA,Bw,Lw,Yn,Uh,wl,ll,UM,Vi,qi,vl,MM,hA,fA,Wm,QM,ck,ZM,oj,lk,cj,uk,hk,Mw,dj,lj,gj,yj,vj,Rj,jw,Pj,Dj,xk,Bj,AA,zj,Wj,Kj,Xm,Gj,Xj,Jj,r$,Hw,Ym,qw,Ko,Mk,jk,$k,Fk,B$,Dm,u1,SZ,EZ,fc,TZ,kZ,BT,AZ,LT,IZ,Rh,PZ,f1,BZ,ft,Ne,QU,jN,Jw,s7,zi,Om,Qw,i7,Xo,Xk,Yk,OT,o7,Jk,LZ,OZ,Go,$Z,NT,Nm,Um,Qk,p7,vn,Zw,FZ,g7,HZ,Mm,qZ,VZ,UT,zZ,WZ,KZ,GZ,Zk,fl,b7,XZ,w7,v7,Zm,jT,YZ,vT,eg,JZ,QZ,ZZ,g1,tg,rg,sg,iee,oee,Er,am,cm,FN,HN,qN,VN,zN,b1,x1,Lh,e1,C7,T7,k7,FT,A7,I7,R7,D7,Hh,_l,cee,B7,L7,dee,qT,U7,$7,lee,F7,lc,uee,hee,fee,q7,z7,K7,pee,gee,bee,t1,Qo,WN,$m,Fm,xee,Oh,Nh,v1,J7,Hm,wee,qm,Dh,Z7,Im,tM,rM,sM,vee,yl,Vm,eA,tA,bl,rA,aM,_ee,cM,Qt,Eee,sA,tk,SM,Cee,EM,uc,GN,XN,YN,JN,QN,Yo,Jo,AM,xl,ZN,Tee,kee,eU,Aee,_T,rU,DM,dm,nU,Iee,Ree,BM,LM,Pee,OM,Dee,ys,Bee,qh,NM,Lee,iU,Oee,sk,nk,oU,aU,ST,Nee,Uee,cU,dU,oA,ET,ik,Fi,Mee,lU,jee,Mh,$ee,ng,vh,jM,_1,$M,FM,zo,aA,cA,dA,HM,qM,Fee,lA,uA,uU,ok,pA,um,hm,Vee,zee,hU,fU,CT,TT,kT,AT,Wee,Kee,WM,KM,pU,Gee,wn,mA,XM,YM,Yee,IT,gA,mU,r1,Ls,Jee,Qee,Zee,ej,rj,gc,ete,tte,fk,pk,Tm,uj,mk,hj,fj,rte,nte,jt,wj,ite,yU,yA,ote,bA,xA,ate,ig,Vh,og,Sj,yc,Wi,cte,Ej,Cj,Tj,wA,kj,vA,Aj,Ij,_A,SA,EA,dte,lte,xU,wU,xte,Aw,vU,_U,wte,vte,_te,SU,wk,EU,Ste,Lj,CU,$w,Ete,Oj,Nj,Uj,CA,TA,kA,Fw,Km,Mj,Cte,Tte,PA,DA,Ate,Fj,Gm,Hj,BA,Ite,Rte,Vj,Pte,TU,Dte,Bte,Lte,Ote,qn,vk,Nte,LA,o1,a1,Ute,Mte,jte,$te,kU,AU,Qj,Fte,Hte,Zj,t$,OA,NA,Ki,UA,Vw,_k,qte,zw,Ww,Sk,Ek,ag,Ck,Kw,kk,f$,Ak,Ik,y$,x$,v$,Vte,zte,Rk,C$,Iw,Gw,IU,Nt,Yte,Jte,RU,Vn,km,T$,Lk,PU,Qte,DU,BU,LU,Zte,ere,c1,tre,rre,OU,NU,UU,MU,sre,nre,ire,ore,_h,Ih,k$,MA,are,Pm,d1,Bh,R$,l1,Rw,FA,fm,P$,lre,Sh,ure,hre,DT,jU,$U,D$,fre,pre,L$,pm,mre,gre,zn,yre,Hk,bre,xre,N$,wre,vre,M$=V(()=>{"use strict";g();y();qk=require("crypto"),Vk=Le(ma(),1),Kk=require("dgram"),JU=Le(g8(),1),ZU=require("dgram"),e7=Le(require("net"),1),t7=require("net"),$h=require("crypto"),p1=Le(AS(),1);T9();Ph=Le(sr(),1),m1=require("crypto"),a7=Le(sr(),1),c7=Le(eb(),1);dN();Yr=Le(sr(),1),Kn=Le(sr(),1),m7=Le(sr(),1),y7=require("crypto"),hl=Le(sr(),1),x7=require("timers/promises"),Wo=Le(sr(),1),y1=require("crypto"),S7=Le(eb(),1),pl=Le(sr(),1),pc=Le(sr(),1),ml=Le(sr(),1),Fh=Le(sr(),1),mc=Le(sr(),1),gl=Le(sr(),1),Gn=Le(sr(),1),Xn=Le(sr(),1),w1=Le(sr(),1),Wn=Le(sr(),1),P7=Le(sr(),1),O7=Le(uN(),1),nA=Le(ma(),1),Bw=require("crypto"),Lw=Le(fN(),1),Yn=require("crypto"),Uh=require("crypto"),wl=Le(sr(),1),ll=Le(sr(),1),UM=require("timers/promises"),Vi=Le(sr(),1),qi=Le(sr(),1),vl=Le(sr(),1),MM=require("crypto"),hA=require("crypto"),fA=require("crypto");Ew();Wm=Le(cT(),1),QM=require("crypto"),ck=Le(ma(),1),ZM=require("timers/promises"),oj=require("crypto"),lk=require("net"),cj=require("crypto"),uk=require("net");Ew();hk=Le(require("timers/promises"),1),Mw=Le(vN(),1),dj=Le(MN(),1),lj=require("crypto"),gj=Le(require("os"),1),yj=Le(cT(),1),vj=require("events"),Rj=require("crypto"),jw=require("timers/promises"),Pj=require("crypto"),Dj=require("dgram"),xk=require("perf_hooks"),Bj=require("crypto"),AA=require("crypto"),zj=require("timers/promises"),Wj=require("crypto"),Kj=require("net");Ew();Xm=Le(AS(),1),Gj=require("crypto"),Xj=require("timers/promises"),Jj=require("crypto"),r$=require("crypto"),Hw=Le(ma(),1),Ym=require("crypto"),qw=Le(ma(),1),Ko=Le(ma(),1),Mk=require("crypto"),jk=Le(ma(),1),$k=require("crypto"),Fk=require("timers/promises"),B$=require("crypto");Dm=class{constructor(t){this.bitLength=t}value=0;set(t,e,r){return r&=(1<<t)-1,this.value|=r<<this.bitLength-t-e,this}get buffer(){let t=Math.ceil(this.bitLength/8),e=Buffer.alloc(t);return e.writeUIntBE(this.value,0,t),e}},u1=class{constructor(t){if(this.bitLength=t,t>32)throw new Error}_value=0n;offset=0n;set(t,e=1){let r=BigInt(t),s=BigInt(e);return r&=(1n<<s)-1n,this._value|=r<<BigInt(this.bitLength)-s-this.offset,this.offset+=s,this}get value(){return Number(this._value)}get buffer(){let t=Math.ceil(this.bitLength/8),e=Buffer.alloc(t);return e.writeUIntBE(this.value,0,t),e}};SZ=class{buffer;constructor(t){this.buffer=Buffer.alloc(t)}writeInt16BE(t,e){return this.buffer.writeInt16BE(t,e),this}writeUInt8(t,e){return this.buffer.writeUInt8(t,e),this}},EZ=t=>"0x"+t.toString("hex").replace(/(.)(.)/g,"$1$2 ").split(" ").filter(e=>e!=null&&e.length>0).join(",0x");fc=class{constructor(t){this.uint8Array=t}position=0;bitsPending=0;writeBits(t,e){if(t==0)return this;e&=4294967295>>>32-t;let r;return this.bitsPending>0?this.bitsPending>t?(this.uint8Array[this.position-1]|=e<<this.bitsPending-t,r=t,this.bitsPending-=t):this.bitsPending==t?(this.uint8Array[this.position-1]|=e,r=t,this.bitsPending=0):(this.uint8Array[this.position-1]|=e>>t-this.bitsPending,r=this.bitsPending,this.bitsPending=0):(r=Math.min(8,t),this.bitsPending=8-r,this.uint8Array[this.position++]=e>>t-r<<this.bitsPending),t-=r,t>0&&this.writeBits(t,e),this}readBits(t){return this._readBits(t)}_readBits(t,e){if(typeof e>"u"&&(e=0),t==0)return e;let r,s;if(this.bitsPending>0){let n=this.uint8Array[this.position-1]&255>>8-this.bitsPending;s=Math.min(this.bitsPending,t),this.bitsPending-=s,r=n>>this.bitsPending}else s=Math.min(8,t),this.bitsPending=8-s,r=this.uint8Array[this.position++]>>this.bitsPending;return t-=s,e=e<<s|r,t>0?this._readBits(t,e):e}seekTo(t){this.position=t/8|0,this.bitsPending=t%8,this.bitsPending>0&&(this.bitsPending=8-this.bitsPending,this.position++)}},TZ=3988292384,kZ=2197175160;BT=qU(TZ),AZ=VU(BT),LT=qU(kZ),IZ=VU(LT);Rh=t=>Number.parseInt(t,10),PZ=class{queue=[];running=!1;push=t=>new Promise((e,r)=>{this.queue.push({promise:t,done:e,failed:r}),this.running||this.run()});async run(){let t=this.queue.shift();if(t){this.running=!0;try{let e=await t.promise();t.done(e)}catch(e){t.failed(e)}this.run()}else this.running=!1}cancel(){this.queue=[]}},f1=(t,e)=>e?e[t]:void 0;BZ=class extends Error{message;payload;path;constructor(t){super(t.message)}toJSON(){return{message:this.message,payload:JSON.parse(JSON.stringify(this.payload)),path:this.path}}},ft=JU.default.debug,Ne=class{event={stack:[],promiseStack:[],eventId:0};ended=!1;onended;onerror=t=>{};execute=(...t)=>{if(!this.ended){for(let e of this.event.stack)e.execute(...t);(async()=>{for(let e of this.event.promiseStack)await e.execute(...t)})().catch(e=>{this.onerror(e)})}};complete=()=>{if(!this.ended){for(let t of this.event.stack)t.complete&&t.complete();this.allUnsubscribe(),this.ended=!0,this.onended&&(this.onended(),this.onended=void 0)}};error=t=>{if(!this.ended){for(let e of this.event.stack)e.error&&e.error(t);this.allUnsubscribe()}};allUnsubscribe=()=>{if(this.ended)throw new Error("event completed");this.event={stack:[],promiseStack:[],eventId:0}};subscribe=(t,e,r)=>{let s=this.event.eventId;this.event.stack.push({execute:t,id:s,complete:e,error:r}),this.event.eventId++;let n=()=>{this.event.stack=this.event.stack.filter(o=>o.id!==s&&o)};return{unSubscribe:n,disposer:o=>{o.push(n)}}};pipe(t){this.subscribe((...e)=>{t.execute(...e)})}queuingSubscribe=(t,e,r)=>{if(this.ended)throw new Error("event completed");let s=this.event.eventId;this.event.promiseStack.push({execute:t,id:s,complete:e,error:r}),this.event.eventId++;let n=()=>{this.event.stack=this.event.stack.filter(o=>o.id!==s&&o)};return{unSubscribe:n,disposer:o=>{o.push(n)}}};once=(t,e,r)=>{let s=this.subscribe((...n)=>{s.unSubscribe(),t(...n)},e,r)};watch=(t,e)=>new Promise((r,s)=>{let n=e&&setTimeout(()=>{s("Event watch timeout")},e),{unSubscribe:i}=this.subscribe((...o)=>{t(...o)&&(n&&clearTimeout(n),i(),r(o))})});asPromise=t=>new Promise((e,r)=>{let s=t&&setTimeout(()=>{r("Event asPromise timeout")},t);this.once((...n)=>{s&&clearTimeout(s),e(n)},()=>{s&&clearTimeout(s),e([])},n=>{s&&clearTimeout(s),r(n)})});get returnTrigger(){let{execute:t,error:e,complete:r}=this;return{execute:t,error:e,complete:r}}get returnListener(){let{subscribe:t,once:e,asPromise:r}=this;return{subscribe:t,once:e,asPromise:r}}get length(){return this.event.stack.length}},QU=class{_disposer=[];push(t){this._disposer.push(t)}dispose(){this._disposer.forEach(t=>t()),this._disposer=[]}},jN=ft("werift-ice:packages/ice/src/transport.ts"),Jw=class r7{constructor(e,r={}){this.socketType=e,this.options=r,this.socket=(0,ZU.createSocket)(e),this.socket.on("message",(s,n)=>{Lm(n.family)===6&&([n.address]=n.address.split("%")),this.rinfo=n;try{this.onData(s,[n.address,n.port])}catch(i){jN("onData error",i)}})}type="udp";socket;rinfo;onData=()=>{};closed=!1;static async init(e,r={}){let s=new r7(e,r);return await s.init(),s}async init(){let e=f1(this.socketType,this.options.interfaceAddresses);if(this.options.port)this.socket.bind({port:this.options.port,address:e});else if(this.options.portRange){let r=await YU(this.options.portRange[0],this.options.portRange[1],this.socketType,this.options.interfaceAddresses);this.socket.bind({port:r,address:e})}else this.socket.bind({address:e});await new Promise(r=>this.socket.once("listening",r))}send=async(e,r)=>{if(r&&!e7.isIP(r[0]))return new Promise((s,n)=>{this.socket.send(e,r[1],r[0],i=>{i?(jN("send error",r,e),n(i)):s()})});r=r??[this.rinfo?.address,this.rinfo?.port],this.socket.send(e,r[1],r[0])};get address(){return this.socket.address()}get host(){return this.socket.address().address}get port(){return this.socket.address().port}close=()=>new Promise(e=>{this.closed=!0,this.socket.once("close",e);try{this.socket.close()}catch{e()}})},s7=class n7{constructor(e){this.addr=e,this.connect()}type="tcp";connecting;client;onData=()=>{};closed=!1;connect(){this.closed||(this.client&&this.client.destroy(),this.connecting=new Promise((e,r)=>{try{this.client=(0,t7.connect)({port:this.addr[1],host:this.addr[0]},e)}catch(s){r(s)}}),this.client.on("data",e=>{let r=[this.client.remoteAddress,this.client.remotePort];this.onData(e,r)}),this.client.on("end",()=>{this.connect()}),this.client.on("error",e=>{E.log("error",e)}))}async init(){await this.connecting}static async init(e){let r=new n7(e);return await r.init(),r}get address(){return{}}send=async(e,r)=>{await this.connecting,this.client.write(e,s=>{s&&E.log("err",s)})};close=async()=>{this.closed=!0,this.client.destroy()}},zi={rsa_1:1,ecdsa_3:3},Om={sha256_4:4},Qw={TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256_49195:49195,TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256_49199:49199},i7=Object.values(Qw),Xo={x25519_29:29,secp256r1_23:23},Xk=Object.values(Xo),Yk={named_curve_3:3},OT={rsa_pkcs1_sha256:1025,ecdsa_secp256r1_sha256:1027},o7=[1,64],Jk=[{hash:Om.sha256_4,signature:zi.rsa_1},{hash:Om.sha256_4,signature:zi.ecdsa_3}],LZ=()=>{let t=ww.utils.randomPrivateKey(),e=ww.getPublicKey(t,!1),r=Buffer.from(t),s=Buffer.from(e);return{privateKey:r,publicKey:s}},OZ=({publicKey:t,privateKey:e})=>{let r=ww.getSharedSecret(e,t);return Buffer.from(r).subarray(1)};Go={CLIENT:1,SERVER:2},$Z=class{id=0;name;hashAlgorithm;verifyDataLength=12;blockAlgorithm;kx;init(...t){throw new Error("not implemented")}encrypt(...t){throw new Error("not implemented")}decrypt(...t){throw new Error("not implemented")}toString(){return this.name}},NT=$h.webcrypto;Sr.set(NT);Nm=class{constructor(t,e,r,s){this.sessionType=t,this.certPem=e,this.keyPem=r,e&&r&&s&&this.parseX509(e,r,s)}localRandom;remoteRandom;cipherSuite;remoteCertificate;remoteKeyPair;localKeyPair;masterSecret;cipher;namedCurve;signatureHashAlgorithm;localCert;localPrivateKey;static createSelfSignedCertificateWithKey=async(t,e)=>{let r=(()=>{switch(t.signature){case zi.rsa_1:return"RSASSA-PKCS1-v1_5";case zi.ecdsa_3:return"ECDSA"}})(),s=(()=>{if(t.hash===Om.sha256_4)return"SHA-256"})(),n=(()=>{switch(e){case Xo.secp256r1_23:return"P-256";case Xo.x25519_29:return r==="ECDSA"?"P-256":"X25519";default:{if(r==="ECDSA")return"P-256";if(r==="RSASSA-PKCS1-v1_5")return"X25519"}}})(),i=(()=>{switch(r){case"ECDSA":return{name:r,hash:s,namedCurve:n};case"RSASSA-PKCS1-v1_5":return{name:r,hash:s,publicExponent:new Uint8Array([1,0,1]),modulusLength:2048}}})(),o=await NT.subtle.generateKey(i,!0,["sign","verify"]),c=(await Wx.createSelfSigned({serialNumber:(0,$h.randomBytes)(8).toString("hex"),name:"C=AU, ST=Some-State, O=Internet Widgits Pty Ltd",notBefore:new Date,notAfter:new Date(Date.now()+10*365*24*60*60*1e3),signingAlgorithm:i,keys:o})).toString("pem"),d=Wr.encode(await NT.subtle.exportKey("pkcs8",o.privateKey),"private key");return{certPem:c,keyPem:d,signatureHash:t}};encryptPacket(t){let e=t.recordLayerHeader,r=e.protocolVersion.major<<8|e.protocolVersion.minor,s=this.cipher.encrypt(this.sessionType,t.fragment,{type:e.contentType,version:r,epoch:e.epoch,sequenceNumber:e.sequenceNumber});return t.fragment=s,t.recordLayerHeader.contentLen=s.length,t}decryptPacket(t){let e=t.recordLayerHeader,r=e.protocolVersion.major<<8|e.protocolVersion.minor;return this.cipher.decrypt(this.sessionType,t.fragment,{type:e.contentType,version:r,epoch:e.epoch,sequenceNumber:e.sequenceNumber})}verifyData(t){return this.sessionType===Go.CLIENT?UZ(this.masterSecret,t):MZ(this.masterSecret,t)}signatureData(t,e){let r=(0,$h.createSign)(e).update(t),s=this.localPrivateKey.toPEM().toString();return r.sign(s)}generateKeySignature(t){let e=this.sessionType===Go.CLIENT?this.localRandom:this.remoteRandom,r=this.sessionType===Go.SERVER?this.localRandom:this.remoteRandom,s=this.valueKeySignature(e.serialize(),r.serialize(),this.localKeyPair.publicKey,this.namedCurve);return this.localPrivateKey.sign(s,t)}parseX509(t,e,r){let s=p1.Certificate.fromPEM(Buffer.from(t)),n=p1.PrivateKey.fromPEM(Buffer.from(e));this.localCert=s.raw,this.localPrivateKey=n,this.signatureHashAlgorithm=r}valueKeySignature(t,e,r,s){let n=Buffer.from((0,Ph.encode)({type:Yk.named_curve_3,curve:s,len:r.length},{type:Ph.types.uint8,curve:Ph.types.uint16be,len:Ph.types.uint8}).slice());return Buffer.concat([t,e,n,r])}},Um=class{srtpProfile;static findMatchingSRTPProfile(t,e){for(let r of e)if(t.includes(r))return r}},Qk=t=>"0x"+t.toString("hex").replace(/(.)(.)/g,"$1$2 ").split(" ").filter(e=>e!=null&&e.length>0).join(",0x"),p7=t=>Object.entries({...t}).reduce((e,[r,s])=>((typeof s=="number"||typeof s=="string")&&(e[r]=s),Buffer.isBuffer(s)&&(e[r]=Qk(s)),e),{}),vn=class ac{constructor(e,r,s,n,i,o){this.msg_type=e,this.length=r,this.message_seq=s,this.fragment_offset=n,this.fragment_length=i,this.fragment=o}static spec={msg_type:Kn.types.uint8,length:Kn.types.uint24be,message_seq:Kn.types.uint16be,fragment_offset:Kn.types.uint24be,fragment_length:Kn.types.uint24be,fragment:Kn.types.buffer(e=>e.current.fragment_length)};get summary(){return p7(this)}static createEmpty(){return new ac(void 0,void 0,void 0,void 0,void 0,void 0)}static deSerialize(e){return new ac(...Object.values((0,Kn.decode)(e,ac.spec)))}serialize(){let e=(0,Kn.encode)(this,ac.spec).slice();return Buffer.from(e)}chunk(e){let r=0,s=this.fragment.length;if(s===0)return[new ac(this.msg_type,s,this.message_seq,r,0,this.fragment)];let n=[];for(e||(e=1240);r<s;){let i=Math.min(e,s-r),o=Buffer.from(this.fragment.slice(r,r+i));if(o.length<=0)throw new Error("Zero or less bytes processed while fragmenting handshake message.");n.push(new ac(this.msg_type,s,this.message_seq,r,o.length,o)),r+=o.length}return n}static assemble(e){if(!e?.length)throw new Error("cannot reassemble handshake from empty array");e=e.sort((s,n)=>s.fragment_offset-n.fragment_offset);let r=Buffer.alloc(e[0].length);for(let s of e)s.fragment.copy(r,s.fragment_offset);return new ac(e[0].msg_type,e[0].length,e[0].message_seq,0,r.length,r)}static findAllFragments(e,r){let s=e.find(n=>n.msg_type===r);return s?e?.length?e.filter(n=>n.msg_type===s.msg_type&&n.message_seq===s.message_seq&&n.length===s.length):[]:[]}},{uint16be:Zw,uint24be:FZ,buffer:g7,array:HZ,uint8:Mm,string:qZ}=m7.types,VZ={type:Zw,data:g7(Zw)},UT=HZ(VZ,Zw,"bytes"),zZ=g7(FZ),WZ=Mm,KZ=qZ(Zw),GZ={hash:Mm,signature:Mm},Zk={major:Mm,minor:Mm},fl=class mm{constructor(e=Math.floor(Date.now()/1e3),r=(0,y7.randomBytes)(28)){this.gmt_unix_time=e,this.random_bytes=r}static spec={gmt_unix_time:hl.types.uint32be,random_bytes:hl.types.buffer(28)};static deSerialize(e){return new mm(...Object.values((0,hl.decode)(e,mm.spec)))}static from(e){return new mm(...Object.values(e))}serialize(){let e=(0,hl.encode)(this,mm.spec).slice();return Buffer.from(e)}},b7=class gm{constructor(e,r,s,n,i,o,a){this.clientVersion=e,this.random=r,this.sessionId=s,this.cookie=n,this.cipherSuites=i,this.compressionMethods=o,this.extensions=a}msgType=1;messageSeq=0;static spec={clientVersion:{major:Yr.types.uint8,minor:Yr.types.uint8},random:fl.spec,sessionId:Yr.types.buffer(Yr.types.uint8),cookie:Yr.types.buffer(Yr.types.uint8),cipherSuites:Yr.types.array(Yr.types.uint16be,Yr.types.uint16be,"bytes"),compressionMethods:Yr.types.array(Yr.types.uint8,Yr.types.uint8,"bytes"),extensions:UT};static createEmpty(){return new gm(void 0,void 0,void 0,void 0,void 0,void 0,void 0)}static deSerialize(e){return new gm(...Object.values((0,Yr.decode)(e,gm.spec)))}serialize(){let e=(0,Yr.encode)(this,gm.spec).slice();return Buffer.from(e)}toFragment(){let e=this.serialize();return new vn(this.msgType,e.length,this.messageSeq,0,e.length,e)}},XZ=class ym{constructor(e,r,s,n,i){this.epoch=e,this.sequenceNumber=r,this.contentType=s,this.protocolVersion=n,this.contentLen=i}static spec={epoch:Wo.types.uint16be,sequenceNumber:Wo.types.uint48be,contentType:Wo.types.uint8,protocolVersion:Zk,contentLen:Wo.types.uint16be};static createEmpty(){return new ym(void 0,void 0,void 0,void 0,void 0)}static deSerialize(e){return new ym(...Object.values((0,Wo.decode)(e,ym.spec)))}serialize(){let e=(0,Wo.encode)(this,ym.spec).slice();return Buffer.from(e)}},w7=class MT{constructor(e,r){this.recordLayerHeader=e,this.fragment=r}get summary(){return{header:this.recordLayerHeader,fragment:Qk(this.fragment)}}static createEmpty(){return new MT(void 0,void 0)}static deSerialize(e){if(e.length<13)throw new Error("Invalid DTLS record: buffer is too short");let r=e.readUInt8(0),s=e.readUInt8(1),n=e.readUInt8(2),i=e.readUInt16BE(3),o=e.slice(5,11).readUIntBE(0,6),a=e.readUInt16BE(11);if(e.length<13+a)throw new Error("Invalid DTLS record: fragment length exceeds buffer");let c=e.slice(13,13+a);return new MT({contentType:r,protocolVersion:{major:s,minor:n},epoch:i,sequenceNumber:o,contentLen:a},c)}serialize(){let e=this.fragment.length,r=13+e,s=Buffer.alloc(r);return s.writeUInt8(this.recordLayerHeader.contentType,0),s.writeUInt8(this.recordLayerHeader.protocolVersion.major,1),s.writeUInt8(this.recordLayerHeader.protocolVersion.minor,2),s.writeUInt16BE(this.recordLayerHeader.epoch,3),s.writeUIntBE(this.recordLayerHeader.sequenceNumber,5,6),s.writeUInt16BE(e,11),this.fragment.copy(s,13),s}computeMACHeader(){return new XZ(this.recordLayerHeader.epoch,this.recordLayerHeader.sequenceNumber,this.recordLayerHeader.contentType,this.recordLayerHeader.protocolVersion,this.recordLayerHeader.contentLen).serialize()}},v7=t=>e=>(t.lastFlight=e,e.flatMap(r=>(r.messageSeq=t.sequenceNumber++,r.toFragment().chunk()))),Zm=t=>(e,r)=>e.map(s=>new w7({contentType:s.type,protocolVersion:t.version,epoch:t.epoch,sequenceNumber:r,contentLen:s.fragment.length},s.fragment)),jT=(t=>(t[t.CloseNotify=0]="CloseNotify",t[t.UnexpectedMessage=10]="UnexpectedMessage",t[t.BadRecordMac=20]="BadRecordMac",t[t.DecryptionFailed=21]="DecryptionFailed",t[t.RecordOverflow=22]="RecordOverflow",t[t.DecompressionFailure=30]="DecompressionFailure",t[t.HandshakeFailure=40]="HandshakeFailure",t[t.NoCertificate=41]="NoCertificate",t[t.BadCertificate=42]="BadCertificate",t[t.UnsupportedCertificate=43]="UnsupportedCertificate",t[t.CertificateRevoked=44]="CertificateRevoked",t[t.CertificateExpired=45]="CertificateExpired",t[t.CertificateUnknown=46]="CertificateUnknown",t[t.IllegalParameter=47]="IllegalParameter",t[t.UnknownCa=48]="UnknownCa",t[t.AccessDenied=49]="AccessDenied",t[t.DecodeError=50]="DecodeError",t[t.DecryptError=51]="DecryptError",t[t.ExportRestriction=60]="ExportRestriction",t[t.ProtocolVersion=70]="ProtocolVersion",t[t.InsufficientSecurity=71]="InsufficientSecurity",t[t.InternalError=80]="InternalError",t[t.UserCanceled=90]="UserCanceled",t[t.NoRenegotiation=100]="NoRenegotiation",t[t.UnsupportedExtension=110]="UnsupportedExtension",t))(jT||{}),YZ=ft("werift-dtls : packages/dtls/src/flight/flight.ts : warn"),vT=ft("werift-dtls : packages/dtls/src/flight/flight.ts : err"),eg=class $T{constructor(e,r,s,n){this.transport=e,this.dtls=r,this.flight=s,this.nextFlight=n}state="PREPARING";static RetransmitCount=10;createPacket(e){let r=v7(this.dtls)(e);return this.dtls.bufferHandshakeCache(r,!0,this.flight),Zm(this.dtls)(r.map(n=>({type:22,fragment:n.serialize()})),++this.dtls.recordSequenceNumber)}async transmit(e){let r=0;for(;r<=$T.RetransmitCount;r++){if(this.setState("SENDING"),this.send(e).catch(s=>{vT("fail to send",vT)}),this.setState("WAITING"),this.nextFlight===void 0){this.setState("FINISHED");break}if(await(0,x7.setTimeout)(1e3*((r+1)/2)),this.dtls.flight>=this.nextFlight){this.setState("FINISHED");break}else YZ(this.dtls.sessionId,"retransmit",r,this.dtls.flight)}if(r>$T.RetransmitCount)throw vT(this.dtls.sessionId,"retransmit failed",r),new Error(`over retransmitCount : ${this.flight} ${this.nextFlight}`)}send=e=>Promise.all(e.map(r=>this.transport.send(r)));setState(e){this.state=e}},JZ=class extends eg{constructor(t,e,r){super(t,e,1,3),this.cipher=r}async exec(t){if(this.dtls.flight===1)throw new Error;this.dtls.flight=1;let e=new b7({major:254,minor:253},new fl,Buffer.from([]),Buffer.from([]),i7,[0],t);this.dtls.version=e.clientVersion,this.cipher.localRandom=fl.from(e.random);let r=this.createPacket([e]),s=Buffer.concat(r.map(n=>n.serialize()));await this.transmit([s])}},QZ=ft("werift-dtls : packages/dtls/src/flight/client/flight3.ts : log"),ZZ=class extends eg{constructor(t,e){super(t,e,3,5)}async exec(t){if(this.dtls.flight===3)throw new Error;this.dtls.flight=3,this.dtls.handshakeCache=[];let[e]=this.dtls.lastFlight;QZ("dtls version",e.clientVersion),e.cookie=t.cookie,this.dtls.cookie=t.cookie;let r=this.createPacket([e]),s=Buffer.concat(r.map(n=>n.serialize()));await this.transmit([s])}},g1={NULL:0,ECDHE:1},tg={NULL:0,RSA:1,ECDSA:2,PSK:3},rg={NULL:0,RSA:1,ECDHE_RSA:2,ECDHE_ECDSA:3,PSK:4,ECDHE_PSK:5},sg=class{id=0;name;signType;keyType;toString(){return this.name}};iee=ft("werift-dtls : packages/dtls/src/cipher/suites/aead.ts : err"),oee=class extends $Z{keyLength=0;nonceLength=0;ivLength=0;authTagLength=0;nonceImplicitLength=0;nonceExplicitLength=0;clientWriteKey;serverWriteKey;clientNonce;serverNonce;constructor(){super()}get summary(){return p7(this)}init(t,e,r){let s=jZ(t,r,e,this.keyLength,this.ivLength,this.nonceLength,this.hashAlgorithm);this.clientWriteKey=s.clientWriteKey,this.serverWriteKey=s.serverWriteKey,this.clientNonce=s.clientNonce,this.serverNonce=s.serverNonce}encrypt(t,e,r){let s=t===Go.CLIENT,n=s?this.clientNonce:this.serverNonce,i=s?this.clientWriteKey:this.serverWriteKey;if(!n||!i)throw new Error;n.writeUInt16BE(r.epoch,this.nonceImplicitLength),n.writeUIntBE(r.sequenceNumber,this.nonceImplicitLength+2,6);let o=n.slice(this.nonceImplicitLength),a=this.encodeAdditionalBuffer(r,e.length),c=(0,y1.createCipheriv)(this.blockAlgorithm,i,n,{authTagLength:this.authTagLength});c.setAAD(a,{plaintextLength:e.length});let d=c.update(e),u=c.final(),l=c.getAuthTag();return Buffer.concat([o,d,u,l])}encodeAdditionalBuffer(t,e){let r=Buffer.alloc(13);return r.writeUInt16BE(t.epoch,0),r.writeUintBE(t.sequenceNumber,2,6),r.writeUInt8(t.type,8),r.writeUInt16BE(t.version,9),r.writeUInt16BE(e,11),r}decrypt(t,e,r){let s=t===Go.CLIENT,n=s?this.serverNonce:this.clientNonce,i=s?this.serverWriteKey:this.clientWriteKey;if(!n||!i)throw new Error;e.subarray(0,this.nonceExplicitLength).copy(n,this.nonceImplicitLength);let a=e.subarray(this.nonceExplicitLength,e.length-this.authTagLength),c=e.subarray(e.length-this.authTagLength),d=this.encodeAdditionalBuffer(r,a.length),u=(0,y1.createDecipheriv)(this.blockAlgorithm,i,n,{authTagLength:this.authTagLength});u.setAuthTag(c),u.setAAD(d,{plaintextLength:a.length});let l=u.update(a);try{let h=u.final();return h.length>0?Buffer.concat([l,h]):l}catch(h){throw iee("decrypt failed",h,t,Qk(e),r,this.summary),h}}},Er={TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:49195,TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:49196,TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:49199,TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:49200,TLS_RSA_WITH_AES_128_GCM_SHA256:156,TLS_RSA_WITH_AES_256_GCM_SHA384:157,TLS_PSK_WITH_AES_128_GCM_SHA256:168,TLS_PSK_WITH_AES_256_GCM_SHA384:169,TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256:53249,TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384:53250,TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256:52396,TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256:52393,TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256:52392,TLS_PSK_WITH_CHACHA20_POLY1305_SHA256:52395},am={K_LEN:16,N_MIN:12,N_MAX:12,P_MAX:2**36-31,A_MAX:2**53-1,C_MAX:2**36-15},cm={K_LEN:32,N_MIN:12,N_MAX:12,P_MAX:2**36-31,A_MAX:2**53-1,C_MAX:2**36-15},FN=eee(),HN=tee(),qN=ree(),VN=see(),zN=nee();b1=class{static type=23},x1=class Eh{static type=65281;static spec={type:pl.types.uint16be,data:pl.types.uint8};type=Eh.type;data=0;constructor(e={}){Object.assign(this,e)}static createEmpty(){return new Eh}static deSerialize(e){return new Eh((0,pl.decode)(e,Eh.spec))}serialize(){let e=(0,pl.encode)(this,Eh.spec).slice();return Buffer.from(e)}get extension(){return{type:this.type,data:this.serialize().slice(2)}}},Lh=class cc{static type=14;static spec={type:pc.types.uint16be,data:pc.types.buffer(pc.types.uint16be)};type=cc.type;data=Buffer.from([]);profiles=[];mki=Buffer.from([0]);constructor(e={}){Object.assign(this,e)}static create(e,r){return new cc({profiles:e,mki:r})}static deSerialize(e){let r=new cc((0,pc.decode)(e,cc.spec)),s=r.data.readUInt16BE(),n=new Array(s/2);for(let i=0;i<n.length;i++)n[i]=r.data.readUInt16BE(i*2+2);return r.profiles=n,r.mki=r.data.slice(s+2),r}serialize(){let e=Buffer.alloc(2);e.writeUInt16BE(this.profiles.length*2);let r=Buffer.concat([e,...this.profiles.map(n=>{let i=Buffer.alloc(2);return i.writeUInt16BE(n),i}),this.mki]);this.data=r;let s=(0,pc.encode)(this,cc.spec).slice();return Buffer.from(s)}static fromData(e){let r=Buffer.alloc(4);return r.writeUInt16BE(cc.type),r.writeUInt16BE(e.length,2),cc.deSerialize(Buffer.concat([r,e]))}get extension(){return{type:this.type,data:this.serialize().slice(4)}}},e1=class bm{constructor(e){this.certificateList=e}msgType=11;messageSeq;static spec={certificateList:ml.types.array(zZ,ml.types.uint24be,"bytes")};static createEmpty(){return new bm(void 0)}static deSerialize(e){return new bm(...Object.values((0,ml.decode)(e,bm.spec)))}serialize(){let e=(0,ml.encode)(this,bm.spec).slice();return Buffer.from(e)}toFragment(){let e=this.serialize();return new vn(this.msgType,e.length,this.messageSeq,0,e.length,e)}},C7=class xm{constructor(e=1){this.type=e}static spec={type:Fh.types.uint8};static createEmpty(){return new xm}static deSerialize(e){return new xm(...Object.values((0,Fh.decode)(e,xm.spec)))}serialize(){let e=(0,Fh.encode)(this,xm.spec).slice();return Buffer.from(e)}},T7=class wm{constructor(e,r){this.algorithm=e,this.signature=r}msgType=15;messageSeq;static spec={algorithm:mc.types.uint16be,signature:mc.types.buffer(mc.types.uint16be)};static createEmpty(){return new wm(void 0,void 0)}static deSerialize(e){let r=(0,mc.decode)(e,wm.spec);return new wm(...Object.values(r))}serialize(){let e=(0,mc.encode)(this,wm.spec).slice();return Buffer.from(e)}toFragment(){let e=this.serialize();return new vn(this.msgType,e.length,this.messageSeq,0,e.length,e)}},k7=class vm{constructor(e){this.publicKey=e}msgType=16;messageSeq;static spec={publicKey:gl.types.buffer(gl.types.uint8)};static createEmpty(){return new vm(void 0)}static deSerialize(e){let r=(0,gl.decode)(e,vm.spec);return new vm(...Object.values(r))}serialize(){let e=(0,gl.encode)(this,vm.spec).slice();return Buffer.from(e)}toFragment(){let e=this.serialize();return new vn(this.msgType,e.length,this.messageSeq,0,e.length,e)}},FT=class HT{constructor(e){this.verifyData=e}msgType=20;messageSeq;static createEmpty(){return new HT(void 0)}static deSerialize(e){return new HT(e)}serialize(){return this.verifyData}toFragment(){let e=this.serialize();return new vn(this.msgType,e.length,this.messageSeq,0,e.length,e)}},A7=class _m{constructor(e,r,s){this.certificateTypes=e,this.signatures=r,this.authorities=s}msgType=13;messageSeq;static spec={certificateTypes:Gn.types.array(WZ,Gn.types.uint8,"bytes"),signatures:Gn.types.array(GZ,Gn.types.uint16be,"bytes"),authorities:Gn.types.array(KZ,Gn.types.uint16be,"bytes")};static createEmpty(){return new _m(void 0,void 0,void 0)}static deSerialize(e){return new _m(...Object.values((0,Gn.decode)(e,_m.spec)))}serialize(){let e=(0,Gn.encode)(this,_m.spec).slice();return Buffer.from(e)}toFragment(){let e=this.serialize();return new vn(this.msgType,e.length,this.messageSeq,0,e.length,e)}},I7=class dc{constructor(e,r,s,n,i,o){this.serverVersion=e,this.random=r,this.sessionId=s,this.cipherSuite=n,this.compressionMethod=i,this.extensions=o}msgType=2;messageSeq;static spec={serverVersion:Zk,random:fl.spec,sessionId:Xn.types.buffer(Xn.types.uint8),cipherSuite:Xn.types.uint16be,compressionMethod:Xn.types.uint8};static createEmpty(){return new dc(void 0,void 0,void 0,void 0,void 0,void 0)}static deSerialize(e){let r=(0,Xn.decode)(e,dc.spec),s=new dc(...Object.values(r));return s.serialize().length<e.length?new dc(...Object.values((0,Xn.decode)(e,{...dc.spec,extensions:UT}))):s}serialize(){let e=this.extensions===void 0?(0,Xn.encode)(this,dc.spec).slice():(0,Xn.encode)(this,{...dc.spec,extensions:UT}).slice();return Buffer.from(e)}toFragment(){let e=this.serialize();return new vn(this.msgType,e.length,this.messageSeq,0,e.length,e)}},R7=class Sm{msgType=14;messageSeq;static spec={};static createEmpty(){return new Sm}static deSerialize(e){return new Sm(...Object.values((0,w1.decode)(e,Sm.spec)))}serialize(){let e=(0,w1.encode)(this,Sm.spec).slice();return Buffer.from(e)}toFragment(){let e=this.serialize();return new vn(this.msgType,e.length,this.messageSeq,0,e.length,e)}};D7=class Em{constructor(e,r,s,n,i,o,a,c){this.ellipticCurveType=e,this.namedCurve=r,this.publicKeyLength=s,this.publicKey=n,this.hashAlgorithm=i,this.signatureAlgorithm=o,this.signatureLength=a,this.signature=c}msgType=12;messageSeq;static spec={ellipticCurveType:Wn.types.uint8,namedCurve:Wn.types.uint16be,publicKeyLength:Wn.types.uint8,publicKey:Wn.types.buffer(e=>e.current.publicKeyLength),hashAlgorithm:Wn.types.uint8,signatureAlgorithm:Wn.types.uint8,signatureLength:Wn.types.uint16be,signature:Wn.types.buffer(e=>e.current.signatureLength)};static createEmpty(){return new Em(void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0)}static deSerialize(e){let r=(0,Wn.decode)(e,Em.spec);return new Em(...Object.values(r))}serialize(){return aee(this,Em.spec)}toFragment(){let e=this.serialize();return new vn(this.msgType,e.length,this.messageSeq,0,e.length,e)}},Hh=1,_l=7,cee=[Hh,_l],B7=t=>{switch(t){case Hh:case _l:return 16}},L7=t=>{switch(t){case Hh:return 14;case _l:return 12}},dee=ft("werift-rtp : packages/rtp/src/codec/av1.ts"),qT=class N7{zBit_RtpStartsWithFragment;yBit_RtpEndsWithFragment;w_RtpNumObus;nBit_RtpStartsNewCodedVideoSequence;obu_or_fragment=[];static deSerialize=e=>{let r=new N7,s=0;if(r.zBit_RtpStartsWithFragment=Te(e[s],0),r.yBit_RtpEndsWithFragment=Te(e[s],1),r.w_RtpNumObus=Te(e[s],2,2),r.nBit_RtpStartsNewCodedVideoSequence=Te(e[s],4),s++,r.nBit_RtpStartsNewCodedVideoSequence&&r.zBit_RtpStartsWithFragment)throw new Error;[...Array(r.w_RtpNumObus-1).keys()].forEach(i=>{let[o,a]=j7(e.subarray(s)),c=s+a,d=c+o,u=!1;r.zBit_RtpStartsWithFragment&&i===0&&(u=!0),r.obu_or_fragment.push({data:e.subarray(c,d),isFragment:u}),s+=a+o});let n=!1;return(r.yBit_RtpEndsWithFragment||r.w_RtpNumObus===1&&r.zBit_RtpStartsWithFragment)&&(n=!0),r.obu_or_fragment.push({data:e.subarray(s),isFragment:n}),r};static isDetectedFinalPacketInSequence(e){return e.marker}get isKeyframe(){return this.nBit_RtpStartsNewCodedVideoSequence===1}static getFrame(e){let r=[],s=e.flatMap(a=>a.obu_or_fragment).reduce((a,c,d)=>(a[d]=c,a),{}),n=Object.keys(s).length;for(let a of Object.keys(s).map(Number)){let c=s[a];if(!c)continue;let{data:d,isFragment:u}=c;if(u){let l=[];for(let h=a;h<n;h++){let p=s[h];if(p.isFragment)l.push(p.data),delete s[h];else break}l.length<=1&&(dee("fragment lost, maybe packet lost"),l=[]),r.push(Buffer.concat(l))}else r.push(d)}let i=r.map(a=>U7.deSerialize(a)),o=i.pop();return Buffer.concat([...i.map(a=>(a.obu_has_size_field=1,a.serialize())),o.serialize()])}},U7=class M7{obu_forbidden_bit;obu_type;obu_extension_flag;obu_has_size_field;obu_reserved_1bit;payload;static deSerialize(e){let r=new M7,s=0;return r.obu_forbidden_bit=Te(e[s],0),r.obu_type=$7[Te(e[s],1,4)],r.obu_extension_flag=Te(e[s],5),r.obu_has_size_field=Te(e[s],6),r.obu_reserved_1bit=Te(e[s],7),s++,r.payload=e.subarray(s),r}serialize(){let e=new u1(8).set(this.obu_forbidden_bit).set(lee[this.obu_type],4).set(this.obu_extension_flag).set(this.obu_has_size_field).set(this.obu_reserved_1bit).buffer,r=Buffer.alloc(0);return this.obu_has_size_field&&(r=O7.LEB128.encode(this.payload.length)),Buffer.concat([e,r,this.payload])}};$7={0:"Reserved",1:"OBU_SEQUENCE_HEADER",2:"OBU_TEMPORAL_DELIMITER",3:"OBU_FRAME_HEADER",4:"OBU_TILE_GROUP",5:"OBU_METADATA",6:"OBU_FRAME",7:"OBU_REDUNDANT_FRAME_HEADER",8:"OBU_TILE_LIST",15:"OBU_PADDING"},lee=Object.entries($7).reduce((t,[e,r])=>(t[r]=Number(e),t),{}),F7=class H7{f;nri;nalUnitType;s;e;r;nalUnitPayloadType;payload;fragment;static deSerialize(e,r){let s=new H7,n=0,i=e[n];if(s.f=Te(i,0),s.nri=Te(i,1,2),s.nalUnitType=Te(i,3,5),n++,s.s=Te(e[n],0),s.e=Te(e[n],1),s.r=Te(e[n],2),s.nalUnitPayloadType=Te(e[n],3,5),n++,0<s.nalUnitType&&s.nalUnitType<lc.stap_a)s.payload=this.packaging(e);else if(s.nalUnitType===lc.stap_a){let o=hee,a=Buffer.alloc(0);for(;o<e.length;){let c=e.readUInt16BE(o);o+=fee,a=Buffer.concat([a,this.packaging(e.subarray(o,o+c))]),o+=c}s.payload=a}else if(s.nalUnitType===lc.fu_a){r||(r=Buffer.alloc(0));let o=e.subarray(n);if(s.fragment=Buffer.concat([r,o]),s.e){let a=new fc(Buffer.alloc(1)).writeBits(1,0).writeBits(2,s.nri).writeBits(5,s.nalUnitPayloadType),c=Buffer.concat([a.uint8Array,s.fragment]);s.fragment=void 0,s.payload=this.packaging(c)}}return s}static packaging(e){return Buffer.concat([uee,e])}static isDetectedFinalPacketInSequence(e){return e.marker}get isKeyframe(){return this.nalUnitType===lc.idrSlice||this.nalUnitPayloadType===lc.idrSlice}get isPartitionHead(){return this.nalUnitType===lc.fu_a||this.nalUnitType===lc.fu_b?this.s!==0:!0}},lc={idrSlice:5,stap_a:24,stap_b:25,mtap16:26,mtap24:27,fu_a:28,fu_b:29},uee=Buffer.from([0,0,0,1]),hee=1,fee=2,q7=class V7{payload;static deSerialize(e){let r=new V7;return r.payload=e,r}static isDetectedFinalPacketInSequence(e){return!0}get isKeyframe(){return!0}static createCodecPrivate(e=48e3){return Buffer.concat([Buffer.from("OpusHead"),nr([1,1],[1,2]),FU([2,4,2,1],[312,e,0,0])])}},z7=class W7{xBit;nBit;sBit;pid;iBit;lBit;tBit;kBit;mBit;pictureId;payload;size0=0;hBit;ver;pBit;size1=0;size2=0;static deSerialize(e){let r=new W7,s=0;if(r.xBit=Te(e[s],0),r.nBit=Te(e[s],2),r.sBit=Te(e[s],3),r.pid=Te(e[s],5,3),s++,r.xBit&&(r.iBit=Te(e[s],0),r.lBit=Te(e[s],1),r.tBit=Te(e[s],2),r.kBit=Te(e[s],3),s++),r.iBit)if(r.mBit=Te(e[s],0),r.mBit){let n=Bm(Te(e[s],1,7)),i=Bm(e[s+1]);r.pictureId=Number.parseInt(n+i,2),s+=2}else r.pictureId=Te(e[s],1,7),s++;return r.lBit&&s++,(r.lBit||r.kBit)&&(r.tBit,r.kBit,s++),r.payload=e.subarray(s),r.payloadHeaderExist&&(r.size0=Te(e[s],0,3),r.hBit=Te(e[s],3),r.ver=Te(e[s],4,3),r.pBit=Te(e[s],7),s++,r.size1=e[s],s++,r.size2=e[s]),r}static isDetectedFinalPacketInSequence(e){return e.marker}get isKeyframe(){return this.pBit===0}get isPartitionHead(){return this.sBit===1}get payloadHeaderExist(){return this.sBit===1&&this.pid===0}get size(){return this.payloadHeaderExist?this.size0+8*this.size1+2048*this.size2:0}},K7=class G7{iBit;pBit;lBit;fBit;bBit;eBit;vBit;zBit;m;pictureId;tid;u;sid;d;tl0PicIdx;pDiff=[];n_s;y;g;width=[];height=[];n_g=0;pgT=[];pgU=[];pgP_Diff=[];payload;static deSerialize(e){let{p:r,offset:s}=this.parseRtpPayload(e);return r.payload=e.subarray(s),r}static parseRtpPayload(e){let r=new G7,s=0;if(r.iBit=Te(e[s],0),r.pBit=Te(e[s],1),r.lBit=Te(e[s],2),r.fBit=Te(e[s],3),r.bBit=Te(e[s],4),r.eBit=Te(e[s],5),r.vBit=Te(e[s],6),r.zBit=Te(e[s],7),s++,r.iBit)if(r.m=Te(e[s],0),r.m){let n=Bm(Te(e[s],1,7)),i=Bm(e[s+1]);r.pictureId=Number.parseInt(n+i,2),s+=2}else r.pictureId=Te(e[s],1,7),s++;if(r.lBit&&(r.tid=Te(e[s],0,3),r.u=Te(e[s],3),r.sid=Te(e[s],4,3),r.d=Te(e[s],7),s++,r.fBit===0&&(r.tl0PicIdx=e[s],s++)),r.fBit&&r.pBit)for(;;){r.pDiff=[...r.pDiff,Te(e[s],0,7)];let n=Te(e[s],7);if(s++,n===0)break}return r.vBit&&(r.n_s=Te(e[s],0,3),r.y=Te(e[s],3),r.g=Te(e[s],4),s++,r.y&&[...Array(r.n_s+1)].forEach(()=>{r.width.push(e.readUInt16BE(s)),s+=2,r.height.push(e.readUInt16BE(s)),s+=2}),r.g&&(r.n_g=e[s],s++),r.n_g>0&&[...Array(r.n_g).keys()].forEach(n=>{r.pgT.push(Te(e[s],0,3)),r.pgU.push(Te(e[s],3));let i=Te(e[s],4,2);s++,r.pgP_Diff[n]=[],i>0&&[...Array(i)].forEach(()=>{r.pgP_Diff[n].push(e[s]),s++})})),{offset:s,p:r}}static isDetectedFinalPacketInSequence(e){return e.marker}get isKeyframe(){return!!(!this.pBit&&this.bBit&&(!this.sid||!this.lBit))}get isPartitionHead(){return this.bBit&&(!this.lBit||!this.d)}},pee=class{payload;fragment;static deSerialize(t,e){return{}}static isDetectedFinalPacketInSequence(t){return!0}get isKeyframe(){return!0}};gee=["MPEG4/ISO/AVC","VP8","VP9","OPUS","AV1"];bee={setTimeout:(...t)=>{let e=setTimeout(...t);return()=>clearTimeout(e)},setInterval:(...t)=>{let e=setInterval(()=>{t[0]()},...t.slice(1));return()=>clearInterval(e)}};t1=4,Qo=class zT{version=2;padding=!1;count=0;type=0;length=0;constructor(e={}){Object.assign(this,e)}static serialize(e,r,s,n){let o=new zT({type:e,count:r,version:2,length:n}).serialize();return Buffer.concat([o,s])}serialize(){let e=new Dm(8);return e.set(2,0,this.version),this.padding&&e.set(1,2,1),e.set(5,3,this.count),nr([1,1,2],[e.value,this.type,this.length])}static deSerialize(e){let[r,s,n]=bs(e,[1,1,2]),i=Te(r,0,2),o=Te(r,2,1)>0,a=Te(r,3,5);return new zT({version:i,padding:o,count:a,type:s,length:n})}},WN=class WT{static count=4;count=WT.count;senderSsrc;mediaSsrc;fir=[];constructor(e={}){Object.assign(this,e)}get length(){return Math.floor(this.serialize().length/4-1)}static deSerialize(e){let[r,s]=bs(e,[4,4]),n=[];for(let i=8;i<e.length;i+=8)n.push({ssrc:e.readUInt32BE(i),sequenceNumber:e[i+4]});return new WT({senderSsrc:r,mediaSsrc:s,fir:n})}serialize(){let e=nr([4,4],[this.senderSsrc,this.mediaSsrc]),r=Buffer.alloc(this.fir.length*8);return this.fir.forEach(({ssrc:s,sequenceNumber:n},i)=>{r.writeUInt32BE(s,i*8),r[i*8+4]=n}),Buffer.concat([e,r])}},$m=class KT{static count=1;count=KT.count;length=2;senderSsrc;mediaSsrc;constructor(e={}){Object.assign(this,e)}static deSerialize(e){let[r,s]=bs(e,[4,4]);return new KT({senderSsrc:r,mediaSsrc:s})}serialize(){return nr([4,4],[this.senderSsrc,this.mediaSsrc])}},Fm=class GT{static count=15;length;count=GT.count;senderSsrc;mediaSsrc;uniqueID="REMB";ssrcNum=0;brExp;brMantissa;bitrate;ssrcFeedbacks=[];constructor(e={}){Object.assign(this,e)}static deSerialize(e){let[r,s,n,i,o]=bs(e,[4,4,4,1,1]),a=Te(o,0,6),c=(Te(o,6,2)<<16)+(e[14]<<8)+e[15],d=a>46?18446744073709551615n:BigInt(c)<<BigInt(a),u=[];for(let l=16;l<e.length;l+=4){let h=e.slice(l).readUIntBE(0,4);u.push(h)}return new GT({senderSsrc:r,mediaSsrc:s,uniqueID:nr([4],[n]).toString(),ssrcNum:i,brExp:a,brMantissa:c,ssrcFeedbacks:u,bitrate:d})}serialize(){let e=Buffer.concat([nr([4,4],[this.senderSsrc,this.mediaSsrc]),Buffer.from(this.uniqueID),nr([1],[this.ssrcNum])]),r=new Dm(24);r.set(6,0,this.brExp).set(18,6,this.brMantissa);let s=Buffer.concat(this.ssrcFeedbacks.map(i=>nr([4],[i]))),n=Buffer.concat([e,nr([3],[r.value]),s]);return this.length=n.length/4,n}},xee=ft("werift-rtp: /rtcp/psfb/index"),Oh=class XT{static type=206;type=XT.type;feedback;constructor(e={}){Object.assign(this,e)}serialize(){let e=this.feedback.serialize();return Qo.serialize(this.type,this.feedback.count,e,this.feedback.length)}static deSerialize(e,r){let s;switch(r.count){case WN.count:s=WN.deSerialize(e);break;case $m.count:s=$m.deSerialize(e);break;case Fm.count:s=Fm.deSerialize(e);break;default:xee("unknown psfb packet",r.count);break}return new XT({feedback:s})}},Nh=class Pw{ssrc=0;reports=[];static type=201;type=Pw.type;constructor(e={}){Object.assign(this,e)}serialize(){let e=nr([4],[this.ssrc]);return e=Buffer.concat([e,...this.reports.map(r=>r.serialize())]),Qo.serialize(Pw.type,this.reports.length,e,Math.floor(e.length/4))}static deSerialize(e,r){let[s]=bs(e,[4]),n=4,i=[];for(let o=0;o<r;o++)i.push(v1.deSerialize(e.slice(n,n+24))),n+=24;return new Pw({ssrc:s,reports:i})}},v1=class Y7{ssrc;fractionLost;packetsLost;highestSequence;jitter;lsr;dlsr;constructor(e={}){Object.assign(this,e)}toJSON(){return{ssrc:this.ssrc,fractionLost:this.fractionLost,packetsLost:this.packetsLost,highestSequence:this.highestSequence,jitter:this.jitter,lsr:this.lsr,dlsr:this.dlsr}}serialize(){return nr([4,1,3,4,4,4,4],[this.ssrc,this.fractionLost,this.packetsLost,this.highestSequence,this.jitter,this.lsr,this.dlsr])}static deSerialize(e){let[r,s,n,i,o,a,c]=bs(e,[4,1,3,4,4,4,4]);return new Y7({ssrc:r,fractionLost:s,packetsLost:n,highestSequence:i,jitter:o,lsr:a,dlsr:c})}},J7=205,Hm=class YT{static count=1;count=YT.count;header;senderSsrc;mediaSourceSsrc;lost=[];toJSON(){return{lost:this.lost,senderSsrc:this.senderSsrc,mediaSourceSsrc:this.mediaSourceSsrc}}constructor(e={}){Object.assign(this,e),this.header||(this.header=new Qo({type:J7,count:this.count,version:2}))}static deSerialize(e,r){let[s,n]=bs(e,[4,4]),i=[];for(let o=8;o<e.length;o+=4){let[a,c]=bs(e.subarray(o),[2,2]);i.push(a);for(let d=0;d<16;d++)c>>d&1&&i.push(a+d+1)}return new YT({header:r,senderSsrc:s,mediaSourceSsrc:n,lost:i})}serialize(){let e=nr([4,4],[this.senderSsrc,this.mediaSourceSsrc]),r=[];if(this.lost.length>0){let n=this.lost[0],i=0;this.lost.slice(1).forEach(o=>{let a=o-n-1;a>=0&&a<16?i|=1<<a:(r.push(nr([2,2],[n,i])),n=o,i=0)}),r.push(nr([2,2],[n,i]))}let s=Buffer.concat([e,Buffer.concat(r)]);return this.header.length=s.length/4,Buffer.concat([this.header.serialize(),s])}},wee=ft("werift/rtp/rtcp/rtpfb/twcc"),qm=class JT{static count=15;count=JT.count;length=2;senderSsrc;mediaSourceSsrc;baseSequenceNumber;packetStatusCount;referenceTime;fbPktCount;packetChunks=[];recvDeltas=[];header;constructor(e={}){Object.assign(this,e),this.header||(this.header=new Qo({type:205,count:this.count,version:2}))}static deSerialize(e,r){let[s,n,i,o,a,c]=bs(e,[4,4,2,2,3,1]),d=[],u=[],l=16;for(let p=0;p<o;){let m=Te(e.slice(l,l+1)[0],0,1),_;switch(m){case 0:{let f=Dh.deSerialize(e.slice(l,l+2));_=f;let b=Math.min(o-p,f.runLength);if(f.packetStatus===1||f.packetStatus===2)for(let w=0;w<b;w++)u.push(new Im({type:f.packetStatus}));p+=b}break;case 1:{let f=Z7.deSerialize(e.slice(l,l+2));_=f,f.symbolSize===0&&f.symbolList.forEach(b=>{b===1&&u.push(new Im({type:1}))}),f.symbolSize===1&&f.symbolList.forEach(b=>{(b===1||b===2)&&u.push(new Im({type:b}))}),p+=f.symbolList.length}break}if(!_)throw new Error;l+=2,d.push(_)}let h=l;return u.forEach(p=>{p.type===1&&(p.deSerialize(e.slice(h,h+1)),h++),p.type===2&&(p.deSerialize(e.slice(h,h+2)),h+=2)}),new JT({senderSsrc:s,mediaSourceSsrc:n,baseSequenceNumber:i,packetStatusCount:o,referenceTime:a,fbPktCount:c,recvDeltas:u,packetChunks:d,header:r})}serialize(){let e=nr([4,4,2,2,3,1],[this.senderSsrc,this.mediaSourceSsrc,this.baseSequenceNumber,this.packetStatusCount,this.referenceTime,this.fbPktCount]),r=Buffer.concat(this.packetChunks.map(i=>i.serialize())),s=Buffer.concat(this.recvDeltas.map(i=>{try{return i.serialize()}catch(o){wee(o?.message);return}}).filter(i=>i)),n=Buffer.concat([e,r,s]);if(this.header.padding&&n.length%4!==0){let i=4-n.length%4,o=Buffer.alloc(i);return o[o.length-1]=o.length,this.header.length=Math.floor((n.length+o.length)/4),Buffer.concat([this.header.serialize(),n,o])}return this.header.length=Math.floor(n.length/4),Buffer.concat([this.header.serialize(),n])}get packetResults(){let e=this.baseSequenceNumber-1,r=this.packetChunks.filter(o=>o instanceof Dh).flatMap(o=>o.results(e)),s=0,i=BigInt(this.referenceTime)*64n;for(let o of r){let a=this.recvDeltas[s];!o.received||!a||(i+=BigInt(a.delta)/1000n,o.delta=a.delta,o.receivedAtMs=Number(i),s++)}return r}},Dh=class Q7{type;packetStatus;runLength;constructor(e={}){Object.assign(this,e),this.type=0}static deSerialize(e){let r=Te(e[0],1,2),s=(Te(e[0],3,5)<<8)+e[1];return new Q7({type:0,packetStatus:r,runLength:s})}serialize(){return new u1(16).set(0).set(this.packetStatus,2).set(this.runLength,13).buffer}results(e){let r=this.packetStatus===1||this.packetStatus===2,s=[];for(let n=0;n<=this.runLength;++n)s.push(new sM({sequenceNumber:++e,received:r}));return s}},Z7=class eM{type;symbolSize;symbolList=[];constructor(e={}){Object.assign(this,e)}static deSerialize(e){let s=Te(e[0],1,1),n=[];function i(o,a){for(let c=0;c<o;c++)a(c)}switch(s){case 0:i(6,o=>n.push(Te(e[0],2+o,1))),i(8,o=>n.push(Te(e[1],o,1)));break;case 1:i(3,o=>n.push(Te(e[0],2+o*2,2))),i(4,o=>n.push(Te(e[1],o*2,2)));break;default:s=(Te(e[0],2,6)<<8)+e[1]}return new eM({type:1,symbolSize:s,symbolList:n})}serialize(){let e=Buffer.alloc(2),r=new u1(16).set(1).set(this.symbolSize),s=this.symbolSize===0?1:2;return this.symbolList.forEach(n=>{r.set(n,s)}),e.writeUInt16BE(r.value),e}},Im=class QT{type;delta;constructor(e={}){Object.assign(this,e)}static deSerialize(e){let r,s;if(e.length===1?(r=1,s=250*e[0]):e.length===2&&(r=2,s=250*e.readInt16BE()),r===void 0||s===void 0)throw new Error;return new QT({type:r,delta:s})}deSerialize(e){let r=QT.deSerialize(e);this.delta=r.delta}parsed=!1;parseDelta(){this.delta=Math.floor(this.delta/250),this.delta<0||this.delta>255?(this.delta>32767&&(this.delta=32767),this.delta<-32768&&(this.delta=-32768),this.type||(this.type=2)):this.type||(this.type=1),this.parsed=!0}serialize(){if(this.parsed||this.parseDelta(),this.type===1){let e=Buffer.alloc(1);return e.writeUInt8(this.delta),e}else if(this.type===2){let e=Buffer.alloc(2);return e.writeInt16BE(this.delta),e}throw new Error("errDeltaExceedLimit "+this.delta+" "+this.type)}},tM=(t=>(t[t.TypeTCCRunLengthChunk=0]="TypeTCCRunLengthChunk",t[t.TypeTCCStatusVectorChunk=1]="TypeTCCStatusVectorChunk",t[t.packetStatusChunkLength=2]="packetStatusChunkLength",t))(tM||{}),rM=(t=>(t[t.TypeTCCPacketNotReceived=0]="TypeTCCPacketNotReceived",t[t.TypeTCCPacketReceivedSmallDelta=1]="TypeTCCPacketReceivedSmallDelta",t[t.TypeTCCPacketReceivedLargeDelta=2]="TypeTCCPacketReceivedLargeDelta",t[t.TypeTCCPacketReceivedWithoutDelta=3]="TypeTCCPacketReceivedWithoutDelta",t))(rM||{}),sM=class{sequenceNumber=0;delta=0;received=!1;receivedAtMs=0;constructor(t){Object.assign(this,t)}},vee=ft("werift-rtp:packages/rtp/rtcp/rtpfb/index"),yl=class ZT{static type=J7;type=ZT.type;feedback;header;constructor(e={}){Object.assign(this,e)}serialize(){return this.feedback.serialize()}static deSerialize(e,r){let s;switch(r.count){case Hm.count:s=Hm.deSerialize(e,r);break;case qm.count:s=qm.deSerialize(e,r);break;default:vee("unknown rtpfb packet",r.count);break}return new ZT({feedback:s,header:r})}},Vm=class ek{static type=202;type=ek.type;chunks=[];constructor(e){Object.assign(this,e)}get length(){let e=0;return this.chunks.forEach(r=>e+=r.length),e}serialize(){let e=Buffer.concat(this.chunks.map(r=>r.serialize()));for(;e.length%4;)e=Buffer.concat([e,Buffer.from([0])]);return Qo.serialize(this.type,this.chunks.length,e,e.length/4)}static deSerialize(e,r){let s=[];for(let n=0;n<e.length;){let i=eA.deSerialize(e.slice(n));s.push(i),n+=i.length}return new ek({chunks:s})}},eA=class nM{source;items=[];constructor(e={}){Object.assign(this,e)}get length(){let e=4;return this.items.forEach(r=>e+=r.length),e+=1,e+=KN(e),e}serialize(){let e=Buffer.concat([nr([4],[this.source]),Buffer.concat(this.items.map(s=>s.serialize()))]);return Buffer.concat([e,Buffer.alloc(KN(e.length))])}static deSerialize(e){let r=e.readUInt32BE(),s=[];for(let n=4;n<e.length&&e[n]!==0;){let o=tA.deSerialize(e.slice(n));s.push(o),n+=o.length}return new nM({source:r,items:s})}},tA=class iM{type;text;constructor(e){Object.assign(this,e)}get length(){return 2+Buffer.from(this.text).length}serialize(){let e=Buffer.from(this.text);return Buffer.concat([nr([1,1],[this.type,e.length]),e])}static deSerialize(e){let r=e[0],s=e[1],n=e.slice(2,2+s).toString();return new iM({type:r,text:n})}};bl=class Dw{ssrc=0;senderInfo;reports=[];static type=200;type=Dw.type;constructor(e){Object.assign(this,e)}toJSON(){return{ssrc:this.ssrc,senderInfo:this.senderInfo.toJSON(),reports:this.reports.map(e=>e.toJSON())}}serialize(){let e=Buffer.alloc(4);return e.writeUInt32BE(this.ssrc),e=Buffer.concat([e,this.senderInfo.serialize()]),e=Buffer.concat([e,...this.reports.map(r=>r.serialize())]),Qo.serialize(Dw.type,this.reports.length,e,Math.floor(e.length/4))}static deSerialize(e,r){let s=e.readUInt32BE(),n=rA.deSerialize(e.subarray(4,24)),i=24,o=[];for(let c=0;c<r;c++)o.push(v1.deSerialize(e.subarray(i,i+24))),i+=24;return new Dw({ssrc:s,senderInfo:n,reports:o})}},rA=class oM{ntpTimestamp;rtpTimestamp;packetCount;octetCount;constructor(e={}){Object.assign(this,e)}toJSON(){return{ntpTimestamp:aM(this.ntpTimestamp),rtpTimestamp:this.rtpTimestamp}}serialize(){return nr([8,4,4,4],[this.ntpTimestamp,this.rtpTimestamp,this.packetCount,this.octetCount])}static deSerialize(e){let[r,s,n,i]=bs(e,[8,4,4,4]);return new oM({ntpTimestamp:r,rtpTimestamp:s,packetCount:n,octetCount:i})}},aM=t=>{let[e,r]=bs(nr([8],[t]),[4,4]);return+`${e}.${r}`},_ee=ft("werift-rtp:packages/rtp/src/rtcp/rtcp.ts"),cM=class{static deSerialize(t){let e=0,r=[];for(;e<t.length;){let s=Qo.deSerialize(t.subarray(e,e+t1));e+=t1;let n=t.subarray(e);e+=s.length*4,s.padding&&(n=n.subarray(0,n.length-n.subarray(-1)[0]));try{switch(s.type){case bl.type:r.push(bl.deSerialize(n,s.count));break;case Nh.type:r.push(Nh.deSerialize(n,s.count));break;case Vm.type:r.push(Vm.deSerialize(n,s));break;case yl.type:r.push(yl.deSerialize(n,s));break;case Oh.type:r.push(Oh.deSerialize(n,s));break;default:break}}catch(i){_ee("deSerialize RTCP",i)}}return r}};Qt={sdesMid:"urn:ietf:params:rtp-hdrext:sdes:mid",sdesRTPStreamID:"urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id",repairedRtpStreamId:"urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id",transportWideCC:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",absSendTime:"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time",dependencyDescriptor:"https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension",audioLevelIndication:"urn:ietf:params:rtp-hdrext:ssrc-audio-level",videoOrientation:"urn:3gpp:video-orientation"};Eee=ft("packages/rtp/src/rtp/red/packet.ts"),sA=class vM{header;blocks=[];static deSerialize(e){let r=e instanceof ArrayBuffer?Buffer.from(e):e,s=new vM,n=0;return[s.header,n]=tk.deSerialize(r),s.header.fields.forEach(({blockLength:i,timestampOffset:o,blockPT:a})=>{if(i&&o){let c=r.subarray(n,n+i);s.blocks.push({block:c,blockPT:a,timestampOffset:o}),n+=i}else{let c=r.subarray(n);s.blocks.push({block:c,blockPT:a})}}),s}serialize(){this.header=new tk;for(let{timestampOffset:r,blockPT:s,block:n}of this.blocks)r?this.header.fields.push({fBit:1,blockPT:s,blockLength:n.length,timestampOffset:r}):this.header.fields.push({fBit:0,blockPT:s});let e=this.header.serialize();for(let{block:r}of this.blocks)e=Buffer.concat([e,r]);return e}},tk=class _M{fields=[];static deSerialize(e){let r=0,s=new _M;for(;;){let n={};s.fields.push(n);let i=new fc(e.subarray(r));if(n.fBit=i.readBits(1),n.blockPT=i.readBits(7),r++,n.fBit===0)break;n.timestampOffset=i.readBits(14),n.blockLength=i.readBits(10),r+=3}return[s,r]}serialize(){let e=Buffer.alloc(0);for(let r of this.fields)try{if(r.timestampOffset&&r.blockLength){let s=new fc(Buffer.alloc(4)).writeBits(1,r.fBit).writeBits(7,r.blockPT).writeBits(14,r.timestampOffset).writeBits(10,r.blockLength);e=Buffer.concat([e,s.uint8Array])}else{let s=new fc(Buffer.alloc(1)).writeBits(1,0).writeBits(7,r.blockPT);e=Buffer.concat([e,s.uint8Array])}}catch(s){Eee(s?.message)}return e}},SM=class{constructor(t=1){this.distance=t}cache=[];cacheSize=10;push(t){this.cache.push(t),this.cache.length>this.cacheSize&&this.cache.shift()}build(){let t=new sA,e=this.cache.slice(-(this.distance+1)),r=e.pop();return r&&(e.forEach(s=>{let n=ul(r.timestamp,-s.timestamp);n>Cee||t.blocks.push({block:s.block,blockPT:s.blockPT,timestampOffset:n})}),t.blocks.push({block:r.block,blockPT:r.blockPT})),t}},Cee=16383,EM=class{size=150;sequenceNumbers=[];push(t,e){let r=[];return t.blocks.forEach(({blockPT:n,timestampOffset:i,block:o},a)=>{let c=Jr(e.header.sequenceNumber,-(t.blocks.length-(a+1)));i?r.push(new Jo(new Yo({timestamp:ul(e.header.timestamp,-i),payloadType:n,ssrc:e.header.ssrc,sequenceNumber:c,marker:!0}),o)):r.push(new Jo(new Yo({timestamp:e.header.timestamp,payloadType:n,ssrc:e.header.ssrc,sequenceNumber:c,marker:!0}),o))}),r.filter(n=>this.sequenceNumbers.includes(n.header.sequenceNumber)?!1:(this.sequenceNumbers.length>this.size&&this.sequenceNumbers.shift(),this.sequenceNumbers.push(n.header.sequenceNumber),!0))}},uc={OneByte:48862,TwoByte:4096},GN=2,XN=4,YN=8,JN=12,QN=4,Yo=class CM{version=2;padding=!1;paddingSize=0;extension=!1;marker=!1;payloadOffset=0;payloadType=0;sequenceNumber=0;timestamp=0;ssrc=0;csrcLength=0;csrc=[];extensionProfile=uc.OneByte;extensionLength;extensions=[];constructor(e={}){Object.assign(this,e)}static deSerialize(e){let r=new CM,s=0,n=e[s++];r.version=Te(n,0,2),r.padding=Te(n,2)>0,r.extension=Te(n,3)>0,r.csrcLength=Te(n,4,4),r.csrc=[...Array(r.csrcLength)].map(()=>{let o=e.readUInt32BE(s);return s+=4,o}),s+=JN-1;let i=e[1];r.marker=Te(i,0)>0,r.payloadType=Te(i,1,7),r.sequenceNumber=e.readUInt16BE(GN),r.timestamp=e.readUInt32BE(XN),r.ssrc=e.readUInt32BE(YN);for(let o=0;o<r.csrc.length;o++){let a=JN+o*QN;r.csrc[o]=e.subarray(a).readUInt32BE()}if(r.extension){r.extensionProfile=e.subarray(s).readUInt16BE(),s+=2;let o=e.subarray(s).readUInt16BE()*4;switch(r.extensionLength=o,s+=2,r.extensionProfile){case uc.OneByte:{let a=s+o;for(;s<a;){if(e[s]===0){s++;continue}let c=e[s]>>4,d=(e[s]&(e[s]^240))+1;if(s++,c===15)break;let u={id:c,payload:e.subarray(s,s+d)};r.extensions=[...r.extensions,u],s+=d}}break;case uc.TwoByte:{let a=s+o;for(;s<a;){if(e[s]===0){s++;continue}let c=e[s];s++;let d=e[s];s++;let u={id:c,payload:e.subarray(s,s+d)};r.extensions=[...r.extensions,u],s+=d}}break;default:{let a={id:0,payload:e.subarray(s,s+o)};r.extensions=[...r.extensions,a],s+=r.extensions[0].payload.length}break}}return r.payloadOffset=s,r.padding&&(r.paddingSize=e[e.length-1]),r}get serializeSize(){let{csrc:e,extensionProfile:r,extensions:s}=this,n=12+e.length*QN;if(s.length>0||this.extension===!0){let i=4;switch(r){case uc.OneByte:for(let o of s)i+=1+o.payload.length;break;case uc.TwoByte:for(let o of s)i+=2+o.payload.length;break;default:i+=s[0].payload.length}n+=Math.floor((i+3)/4)*4}return n}serialize(e){let r=Buffer.alloc(e),s=0,n=new Dm(8);n.set(2,0,this.version),this.padding&&n.set(1,2,1),this.extensions.length>0&&(this.extension=!0),this.extension&&n.set(1,3,1),n.set(4,4,this.csrc.length),r.writeUInt8(n.value,s++);let i=new Dm(8);this.marker&&i.set(1,0,1),i.set(7,1,this.payloadType),r.writeUInt8(i.value,s++),r.writeUInt16BE(this.sequenceNumber,GN),s+=2,r.writeUInt32BE(this.timestamp,XN),s+=4,r.writeUInt32BE(this.ssrc,YN),s+=4;for(let o of this.csrc)r.writeUInt32BE(o,s),s+=4;if(this.extension){let o=s;r.writeUInt16BE(this.extensionProfile,s),s+=4;let a=s;switch(this.extensionProfile){case uc.OneByte:for(let u of this.extensions)r.writeUInt8(u.id<<4|u.payload.length-1,s++),u.payload.copy(r,s),s+=u.payload.length;break;case uc.TwoByte:for(let u of this.extensions)r.writeUInt8(u.id,s++),r.writeUInt8(u.payload.length,s++),u.payload.copy(r,s),s+=u.payload.length;break;default:{let u=this.extensions[0].payload.length;if(u%4!=0)throw new Error;this.extensions[0].payload.copy(r,s),s+=u}}let c=s-a,d=Math.trunc((c+3)/4)*4;r.writeUInt16BE(Math.trunc(d/4),o+2);for(let u=0;u<d-c;u++)r.writeUInt8(0,s),s++}return this.payloadOffset=s,r}},Jo=class rk{constructor(e,r){this.header=e,this.payload=r}get serializeSize(){return this.header.serializeSize+this.payload.length}clone(){return new rk(new Yo({...this.header}),this.payload)}serialize(){let e=this.header.serialize(this.header.serializeSize+this.payload.length),{payloadOffset:r}=this.header;if(this.payload.copy(e,r),this.header.padding){let s=Buffer.alloc(this.header.paddingSize);s.writeUInt8(this.header.paddingSize,this.header.paddingSize-1),e=Buffer.concat([e,s])}return e}static deSerialize(e){let r=Yo.deSerialize(e);return new rk(r,e.subarray(r.payloadOffset,e.length-r.paddingSize))}clear(){this.payload=null}};AM=class{constructor(t,e,r,s){this.srtpSessionKey=t,this.srtpSessionSalt=e,this.srtcpSessionKey=r,this.srtcpSessionSalt=s}encryptRtp(t,e,r){return Buffer.from([])}decryptRtp(t,e,r){return[]}encryptRTCP(t,e){return Buffer.from([])}decryptRTCP(t){return[]}},xl=class extends Error{constructor(t){super(t),this.name="SrtpAuthenticationError"}},ZN=12,Tee=8;kee=class extends AM{constructor(t,e,r,s,n,i){super(t,e,r,s),this.srtpSessionAuthTag=n,this.srtcpSessionAuthTag=i}authTagLength=10;encryptRtp(t,e,r){let s=t.serialize(t.serializeSize),n=this.generateCounter(t.sequenceNumber,r,t.ssrc,this.srtpSessionSalt),o=(0,Yn.createCipheriv)("aes-128-ctr",this.srtpSessionKey,n).update(e),a=this.generateSrtpAuthTag(r,s,o);return Buffer.concat([s,o,a])}decryptRtp(t,e,r=iA(t,this.authTagLength)){let s=t.length-this.authTagLength,n=t.subarray(0,s),i=t.subarray(s),o=this.generateSrtpAuthTag(e,n.subarray(0,r.payloadOffset),n.subarray(r.payloadOffset));tU(i,o,"Failed to authenticate SRTP packet");let a=this.generateCounter(r.sequenceNumber,e,r.ssrc,this.srtpSessionSalt),c=(0,Yn.createDecipheriv)("aes-128-ctr",this.srtpSessionKey,a),d=n.subarray(r.payloadOffset),u=c.update(d),l=Buffer.concat([n.subarray(0,r.payloadOffset),u]);return[l,PM(r,l,"Failed to authenticate SRTP packet")]}encryptRTCP(t,e){let r=Buffer.from(t),s=r.readUInt32BE(4),n=this.generateCounter(e&65535,e>>16,s,this.srtcpSessionSalt);(0,Yn.createCipheriv)("aes-128-ctr",this.srtcpSessionKey,n).update(r.slice(8)).copy(r,8),r=Buffer.concat([r,Buffer.alloc(4)]),r.writeUInt32BE(e,r.length-4),r[r.length-4]|=128;let a=this.generateSrtcpAuthTag(r);return r=Buffer.concat([r,a]),r}decryptRTCP(t){let e=IM(t,this.authTagLength,eU),r=t.length-(this.authTagLength+eU),s=t.subarray(0,t.length-this.authTagLength),n=t.subarray(t.length-this.authTagLength),i=this.generateSrtcpAuthTag(s);tU(n,i,"Failed to authenticate SRTCP packet");let o=Buffer.from(t).slice(0,r);if(t[r]>>>7===0)return[o,e];let c=t.readUInt32BE(r);c&=~(1<<31);let d=t.readUInt32BE(4),u=this.generateCounter(c&65535,c>>16,d,this.srtcpSessionSalt);return(0,Yn.createDecipheriv)("aes-128-ctr",this.srtcpSessionKey,u).update(o.subarray(8)).copy(o,8),[o,e]}generateSrtcpAuthTag(t){return(0,Yn.createHmac)("sha1",this.srtcpSessionAuthTag).update(t).digest().slice(0,10)}generateCounter(t,e,r,s){let n=Buffer.alloc(16);n.writeUInt32BE(r,4),n.writeUInt32BE(e,8),n.writeUInt32BE(Number(BigInt(t)<<16n),12);for(let i=0;i<s.length;i++)n[i]^=s[i];return n}generateSrtpAuthTag(t,...e){let r=(0,Yn.createHmac)("sha1",this.srtpSessionAuthTag),s=Buffer.alloc(4);s.writeUInt32BE(t);for(let n of e)r.update(n);return r.update(s).digest().subarray(0,10)}},eU=4;Aee=class extends AM{aeadAuthTagLen=16;rtpIvWriter=Am([2,4,4,2],!0);rtcpIvWriter=Am([2,4,2,4],!0);aadWriter=Am([4],!0);constructor(t,e,r,s){super(t,e,r,s)}encryptRtp(t,e,r){let s=t.serialize(t.serializeSize),n=this.rtpInitializationVector(t,r),i=(0,Uh.createCipheriv)("aes-128-gcm",this.srtpSessionKey,n);i.setAAD(s);let o=i.update(e);i.final();let a=i.getAuthTag();return Buffer.concat([s,o,a])}decryptRtp(t,e,r=iA(t,this.aeadAuthTagLen)){let s=t.subarray(0,r.payloadOffset),n=t.length-this.aeadAuthTagLen,i=t.subarray(n),o=Buffer.from([]);o=VT(o,t.length-this.aeadAuthTagLen),s.copy(o);let a=this.rtpInitializationVector(r,e),c=t.slice(r.payloadOffset,n),d=(0,Uh.createDecipheriv)("aes-128-gcm",this.srtpSessionKey,a);d.setAAD(s),d.setAuthTag(i);let u=d.update(c);return sU(d,"SRTP"),u.copy(o,r.payloadOffset),[o,PM(r,o,"Failed to authenticate SRTP packet")]}encryptRTCP(t,e){let r=t.readUInt32BE(4),s=t.length+this.aeadAuthTagLen,n=Buffer.from([]);n=VT(n,s+_T),t.slice(0,8).copy(n);let i=this.rtcpInitializationVector(r,e),o=this.rtcpAdditionalAuthenticatedData(t,e),a=(0,Uh.createCipheriv)("aes-128-gcm",this.srtcpSessionKey,i);a.setAAD(o);let c=a.update(t.slice(8));return a.final(),c.copy(n,8),a.getAuthTag().copy(n,8+c.length),o.slice(8,12).copy(n,s),n}decryptRTCP(t){let e=IM(t,this.aeadAuthTagLen,_T),r=t.length-_T,s=r-this.aeadAuthTagLen,n=t.readUInt32BE(4),i=t.readUInt32BE(r),o=i>>>31===1,a=i&~(rU<<24),c=this.rtcpInitializationVector(n,a),d=o?Buffer.concat([t.subarray(0,8),t.subarray(r)]):Buffer.concat([t.subarray(0,s),t.subarray(r)]),u=o?t.slice(8,s):Buffer.alloc(0),l=o?Buffer.alloc(s):Buffer.from(t.subarray(0,s));o&&t.slice(0,8).copy(l);let h=(0,Uh.createDecipheriv)("aes-128-gcm",this.srtcpSessionKey,c);h.setAAD(d),h.setAuthTag(t.subarray(s,r));let p=h.update(u);return sU(h,"SRTCP"),o&&p.copy(l,8),[l,e]}rtpInitializationVector(t,e){let r=this.rtpIvWriter([0,t.ssrc,e,t.sequenceNumber]);for(let s=0;s<r.length;s++)r[s]^=this.srtpSessionSalt[s];return r}rtcpInitializationVector(t,e){let r=this.rtcpIvWriter([0,t,0,e]);for(let s=0;s<r.length;s++)r[s]^=this.srtcpSessionSalt[s];return r}rtcpAdditionalAuthenticatedData(t,e){let r=Buffer.concat([t.subarray(0,8),this.aadWriter([e])]);return r[8]|=rU,r}},_T=4,rU=128;DM=class{constructor(t,e,r){this.masterKey=t,this.masterSalt=e,this.profile=r;{let s=14-e.length;s>0&&(this.masterSalt=Buffer.concat([e,Buffer.alloc(s)]))}switch(this.srtpSessionKey=this.generateSessionKey(0),this.srtpSessionSalt=this.generateSessionSalt(2),this.srtpSessionAuthTag=this.generateSessionAuthTag(1),this.srtpSessionAuth=(0,Bw.createHmac)("sha1",this.srtpSessionAuthTag),this.srtcpSessionKey=this.generateSessionKey(3),this.srtcpSessionSalt=this.generateSessionSalt(5),this.srtcpSessionAuthTag=this.generateSessionAuthTag(4),this.srtcpSessionAuth=(0,Bw.createHmac)("sha1",this.srtcpSessionAuthTag),r){case Hh:this.cipher=new kee(this.srtpSessionKey,this.srtpSessionSalt,this.srtcpSessionKey,this.srtcpSessionSalt,this.srtpSessionAuthTag,this.srtcpSessionAuthTag);break;case _l:this.cipher=new Aee(this.srtpSessionKey,this.srtpSessionSalt,this.srtcpSessionKey,this.srtcpSessionSalt);break}}srtpSSRCStates={};srtpSessionKey;srtpSessionSalt;srtpSessionAuthTag;srtpSessionAuth;srtcpSSRCStates={};srtcpSessionKey;srtcpSessionSalt;srtcpSessionAuthTag;srtcpSessionAuth;cipher;generateSessionKey(t){let e=Buffer.from(this.masterSalt),r=Buffer.from([t,0,0,0,0,0,0]);for(let n=r.length-1,i=e.length-1;n>=0;n--,i--)e[i]=e[i]^r[n];e=Buffer.concat([e,Buffer.from([0,0])]);let s=new Lw.default.AES(this.masterKey);return Buffer.from(s.encrypt(e))}generateSessionSalt(t){let e=Buffer.from(this.masterSalt),r=Buffer.from([t,0,0,0,0,0,0]);for(let n=r.length-1,i=e.length-1;n>=0;n--,i--)e[i]=e[i]^r[n];e=Buffer.concat([e,Buffer.from([0,0])]);let s=new Lw.default.AES(this.masterKey);return e=Buffer.from(s.encrypt(e)),e.subarray(0,14)}generateSessionAuthTag(t){let e=Buffer.from(this.masterSalt),r=Buffer.from([t,0,0,0,0,0,0]);for(let o=r.length-1,a=e.length-1;o>=0;o--,a--)e[a]=e[a]^r[o];let s=Buffer.concat([e,Buffer.from([0,0])]),n=Buffer.concat([e,Buffer.from([0,1])]),i=new Lw.default.AES(this.masterKey);return s=Buffer.from(i.encrypt(s)),n=Buffer.from(i.encrypt(n)),Buffer.concat([s,n.subarray(0,4)])}getSrtpSsrcState(t){let e=this.srtpSSRCStates[t];return e||(e={ssrc:t,rolloverCounter:0,lastSequenceNumber:0},this.srtpSSRCStates[t]=e,e)}getSrtcpSsrcState(t){let e=this.srtcpSSRCStates[t];return e||(e={srtcpIndex:0,ssrc:t},this.srtcpSSRCStates[t]=e,e)}updateRolloverCount(t,e){e.rolloverHasProcessed?t===0?e.lastSequenceNumber>dm&&e.rolloverCounter++:e.lastSequenceNumber<dm&&t>nU-dm?e.rolloverCounter>0&&e.rolloverCounter--:t<dm&&e.lastSequenceNumber>nU-dm&&e.rolloverCounter++:e.rolloverHasProcessed=!0,e.lastSequenceNumber=t}generateSrtpAuthTag(t,e){this.srtpSessionAuth=(0,Bw.createHmac)("sha1",this.srtpSessionAuthTag);let r=Buffer.alloc(4);return r.writeUInt32BE(e),this.srtpSessionAuth.update(t).update(r).digest().slice(0,10)}index(t){let e=this.srtcpSSRCStates[t];return e?e.srtcpIndex:0}setIndex(t,e){let r=this.getSrtcpSsrcState(t);r.srtcpIndex=e%2147483647}},dm=100,nU=65535,Iee=class extends DM{constructor(t,e,r){super(t,e,r)}encryptRTCP(t){let e=t.readUInt32BE(4),r=this.getSrtcpSsrcState(e);return r.srtcpIndex++,r.srtcpIndex>>Ree&&(r.srtcpIndex=0),this.cipher.encryptRTCP(t,r.srtcpIndex)}decryptRTCP(t){return this.cipher.decryptRTCP(t)}},Ree=2147483647,BM=class{constructor(t){this.ContextCls=t}localContext;remoteContext;onData;start(t,e,r,s,n){this.localContext=new this.ContextCls(t,e,n),this.remoteContext=new this.ContextCls(r,s,n)}},LM=class extends BM{constructor(t){super(Iee),this.config=t,this.start(t.keys.localMasterKey,t.keys.localMasterSalt,t.keys.remoteMasterKey,t.keys.remoteMasterSalt,t.profile)}decrypt=t=>{let[e]=this.remoteContext.decryptRTCP(t);return e};encrypt(t){return this.localContext.encryptRTCP(t)}},Pee=class extends DM{constructor(t,e,r){super(t,e,r)}encryptRtp(t,e){let r=this.getSrtpSsrcState(e.ssrc);return this.updateRolloverCount(e.sequenceNumber,r),this.cipher.encryptRtp(e,t,r.rolloverCounter)}decryptRtp(t){let e=iA(t,this.rtpAuthTagLength),r=this.srtpSSRCStates[e.ssrc],s=r?{...r}:{ssrc:e.ssrc,rolloverCounter:0,lastSequenceNumber:0};this.updateRolloverCount(e.sequenceNumber,s);let n=this.cipher.decryptRtp(t,s.rolloverCounter,e);return r?Object.assign(r,s):this.srtpSSRCStates[e.ssrc]=s,n}get rtpAuthTagLength(){return this.profile===_l?16:10}},OM=class extends BM{constructor(t){super(Pee),this.config=t,this.start(t.keys.localMasterKey,t.keys.localMasterSalt,t.keys.remoteMasterKey,t.keys.remoteMasterSalt,t.profile)}decrypt=t=>{let[e]=this.remoteContext.decryptRtp(t);return e};encrypt(t,e){return this.localContext.encryptRtp(t,e)}},Dee=class{constructor(t){this.props=t}sequenceNumber=zk();timestamp=Yw();create(t){this.sequenceNumber=Jr(this.sequenceNumber,1);let e=this.props.between*this.props.clockRate/1e3;this.timestamp=ul(this.timestamp,e);let r=new Yo({sequenceNumber:this.sequenceNumber,timestamp:Number(this.timestamp),payloadType:96,extension:!0,marker:!1,padding:!1});return new Jo(r,t)}},ys=ft("werift-dtls : packages/dtls/src/flight/client/flight5.ts : log"),Bee=class extends eg{constructor(t,e,r,s){super(t,e,5,7),this.cipher=r,this.srtp=s}handleHandshake(t){this.dtls.bufferHandshakeCache([t],!1,4);let e=(()=>{switch(t.msg_type){case 2:return I7.deSerialize(t.fragment);case 11:return e1.deSerialize(t.fragment);case 12:return D7.deSerialize(t.fragment);case 13:return A7.deSerialize(t.fragment);case 14:return R7.deSerialize(t.fragment)}})();e&&qh[e.msgType]({dtls:this.dtls,cipher:this.cipher,srtp:this.srtp})(e)}async exec(){if(this.dtls.flight===5){ys(this.dtls.sessionId,"flight5 twice"),this.send(this.dtls.lastMessage);return}this.dtls.flight=5;let t=this.dtls.requestedCertificateTypes.length>0;ys(this.dtls.sessionId,"send flight5",t);let e=[t&&this.sendCertificate(),this.sendClientKeyExchange(),t&&this.sendCertificateVerify(),this.sendChangeCipherSpec(),this.sendFinished()].filter(r=>r);this.dtls.lastMessage=e,await this.transmit(e)}sendCertificate(){let t=new e1([Buffer.from(this.cipher.localCert)]),e=this.createPacket([t]);return Buffer.concat(e.map(s=>s.serialize()))}sendClientKeyExchange(){if(!this.cipher.localKeyPair)throw new Error;let t=new k7(this.cipher.localKeyPair.publicKey),e=this.createPacket([t]),r=Buffer.concat(e.map(a=>a.serialize())),s=this.cipher.localKeyPair,n=this.cipher.remoteKeyPair;if(!n.publicKey)throw new Error("not exist");let i=d7(n.publicKey,s.privateKey,s.curve);ys(this.dtls.sessionId,"extendedMasterSecret",this.dtls.options.extendedMasterSecret,this.dtls.remoteExtendedMasterSecret);let o=Buffer.concat(this.dtls.sortedHandshakeCache.map(a=>a.serialize()));return this.cipher.masterSecret=this.dtls.options.extendedMasterSecret&&this.dtls.remoteExtendedMasterSecret?u7(i,o):l7(i,this.cipher.localRandom.serialize(),this.cipher.remoteRandom.serialize()),this.cipher.cipher=_7(this.cipher.cipherSuite),this.cipher.cipher.init(this.cipher.masterSecret,this.cipher.remoteRandom.serialize(),this.cipher.localRandom.serialize()),ys(this.dtls.sessionId,"cipher",this.cipher.cipher.summary),r}sendCertificateVerify(){let t=Buffer.concat(this.dtls.sortedHandshakeCache.map(o=>o.serialize())),e=this.cipher.signatureData(t,"sha256"),r=(()=>{switch(this.cipher.signatureHashAlgorithm?.signature){case zi.ecdsa_3:return OT.ecdsa_secp256r1_sha256;case zi.rsa_1:return OT.rsa_pkcs1_sha256}})();if(!r)throw new Error;ys(this.dtls.sessionId,"signatureScheme",this.cipher.signatureHashAlgorithm?.signature,r);let s=new T7(r,e),n=this.createPacket([s]);return Buffer.concat(n.map(o=>o.serialize()))}sendChangeCipherSpec(){let t=C7.createEmpty().serialize(),e=Zm(this.dtls)([{type:20,fragment:t}],++this.dtls.recordSequenceNumber);return Buffer.concat(e.map(s=>s.serialize()))}sendFinished(){let t=Buffer.concat(this.dtls.sortedHandshakeCache.map(i=>i.serialize())),e=this.cipher.verifyData(t),r=new FT(e);this.dtls.epoch=1;let[s]=this.createPacket([r]);this.dtls.recordSequenceNumber=0;let n=this.cipher.encryptPacket(s).serialize();return ys(this.dtls.sessionId,"finished",this.cipher.cipher.summary),n}},qh={};qh[2]=({cipher:t,srtp:e,dtls:r})=>s=>{ys(r.sessionId,"serverHello",s.cipherSuite),t.remoteRandom=fl.from(s.random),t.cipherSuite=s.cipherSuite,ys(r.sessionId,"selected cipherSuite",t.cipherSuite),s.extensions&&s.extensions.forEach(n=>{switch(n.type){case Lh.type:{let i=Lh.fromData(n.data),o=Um.findMatchingSRTPProfile(i.profiles,r.options.srtpProfiles||[]);if(ys(r.sessionId,"selected srtp profile",o),o==null)return;e.srtpProfile=o}break;case b1.type:r.remoteExtendedMasterSecret=!0;break;case x1.type:ys(r.sessionId,"RenegotiationIndication");break}})};qh[11]=({cipher:t,dtls:e})=>r=>{ys(e.sessionId,"handshake certificate",r),t.remoteCertificate=r.certificateList[0]};qh[12]=({cipher:t,dtls:e})=>r=>{if(!t.localRandom||!t.remoteRandom)throw new Error;ys(e.sessionId,"ServerKeyExchange",r),ys(e.sessionId,"selected curve",r.namedCurve),t.remoteKeyPair={curve:r.namedCurve,publicKey:r.publicKey},t.localKeyPair=E7(r.namedCurve)};qh[13]=({dtls:t})=>e=>{ys(t.sessionId,"certificate_request",e),t.requestedCertificateTypes=e.certificateTypes,t.requestedSignatureAlgorithms=e.signatures};qh[14]=({dtls:t})=>e=>{ys(t.sessionId,"server_hello_done",e)};NM=class Cm{constructor(e,r){this.serverVersion=e,this.cookie=r}msgType=3;messageSeq;static spec={serverVersion:Zk,cookie:wl.types.buffer(wl.types.uint8)};static createEmpty(){return new Cm(void 0,void 0)}static deSerialize(e){return new Cm(...Object.values((0,wl.decode)(e,Cm.spec)))}serialize(){let e=(0,wl.encode)(this,Cm.spec).slice();return Buffer.from(e)}get version(){return{major:255-this.serverVersion.major,minor:255-this.serverVersion.minor}}toFragment(){let e=this.serialize();return new vn(this.msgType,e.length,this.messageSeq,0,e.length,e)}},Lee=ft("werift-dtls : packages/dtls/src/context/dtls.ts : log"),iU=class{constructor(t,e){this.options=t,this.sessionType=e}version={major:254,minor:253};lastFlight=[];lastMessage=[];recordSequenceNumber=0;sequenceNumber=0;epoch=0;flight=0;handshakeCache={};cookie;requestedCertificateTypes=[];requestedSignatureAlgorithms=[];remoteExtendedMasterSecret=!1;get sessionId(){return this.cookie?this.cookie.toString("hex").slice(0,10):""}get sortedHandshakeCache(){return Object.entries(this.handshakeCache).sort(([t],[e])=>Number(t)-Number(e)).flatMap(([,{data:t}])=>t.sort((e,r)=>e.message_seq-r.message_seq))}checkHandshakesExist=t=>!t.find(e=>this.sortedHandshakeCache.find(r=>r.msg_type===e)==null);bufferHandshakeCache(t,e,r){this.handshakeCache[r]||(this.handshakeCache[r]={data:[],isLocal:e,flight:r});let s=t.filter(n=>{let i=this.handshakeCache[r].data.find(o=>o.msg_type===n.msg_type);return i?(Lee(this.sessionId,"exist",i.summary,e,r),!1):!0});this.handshakeCache[r].data=[...this.handshakeCache[r].data,...s]}},Oee=class{constructor(t){this.socket=t}send=t=>this.socket.send(t)},sk=class qo{static type=10;static spec={type:Vi.types.uint16be,data:Vi.types.array(Vi.types.uint16be,Vi.types.uint16be,"bytes")};type=qo.type;data=[];constructor(e={}){Object.assign(this,e)}static createEmpty(){return new qo}static fromData(e){return new qo({type:qo.type,data:(0,Vi.decode)(e,qo.spec.data)})}static deSerialize(e){return new qo((0,Vi.decode)(e,qo.spec))}serialize(){return Buffer.from((0,Vi.encode)(this,qo.spec).slice())}get extension(){return{type:this.type,data:this.serialize().slice(2)}}},nk=class hc{static type=13;static spec={type:qi.types.uint16be,data:qi.types.array({hash:qi.types.uint8,signature:qi.types.uint8},qi.types.uint16be,"bytes")};type=hc.type;data=[];constructor(e={}){Object.assign(this,e)}static createEmpty(){return new hc}static deSerialize(e){return new hc((0,qi.decode)(e,hc.spec))}serialize(){let e=(0,qi.encode)(this,hc.spec).slice();return Buffer.from(e)}static fromData(e){let r=Buffer.alloc(2);return r.writeUInt16BE(hc.type),hc.deSerialize(Buffer.concat([r,e]))}get extension(){return{type:this.type,data:this.serialize().slice(2)}}},oU=class Ow{constructor(e,r){this.level=e,this.description=r}static spec={level:vl.types.uint8,description:vl.types.uint8};static deSerialize(e){return new Ow(...Object.values((0,vl.decode)(e,Ow.spec)))}serialize(){let e=(0,vl.encode)(this,Ow.spec).slice();return Buffer.from(e)}},aU=ft("werift-dtls : packages/dtls/record/receive.ts : log"),ST=ft("werift-dtls : packages/dtls/record/receive.ts : err"),Nee=t=>{let e=0,r=[];for(;t.length>e;){let s=t.readUInt16BE(e+11);if(t.length<e+(12+s))break;let n=w7.deSerialize(t.subarray(e));r.push(n),e+=13+s}return r},Uee=(t,e)=>r=>{switch(r.recordLayerHeader.contentType){case 20:return aU(t.sessionId,"change cipher spec"),[{type:20,data:void 0}];case 22:{let n=r.fragment;try{r.recordLayerHeader.epoch>0&&(aU(t.sessionId,"decrypt handshake"),n=e.decryptPacket(r))}catch(i){throw ST(t.sessionId,"decrypt failed",i),i}try{let i=0,o=[];for(;n.length>i;){let a=vn.deSerialize(n.subarray(i));o.push({type:22,data:a}),i+=a.fragment_length+12}return o}catch(i){throw ST(t.sessionId,"decSerialize failed",i,n),i}}case 23:return[{type:23,data:e.decryptPacket(r)}];case 21:{let n=oU.deSerialize(r.fragment);if(jT[n.description]==null){let i=e.decryptPacket(r);n=oU.deSerialize(i)}if(ST(t.sessionId,"ContentType.alert",n,jT[n.description],"flight",t.flight,"lastFlight",t.lastFlight),n.level>1)throw new Error("alert fatal error");return[{type:21,data:void 0}]}default:return[{type:21,data:void 0}]}},cU=ft("werift-dtls : packages/dtls/src/socket.ts : log"),dU=ft("werift-dtls : packages/dtls/src/socket.ts : err"),oA=class{constructor(t,e){this.options=t,this.sessionType=e,this.dtls=new iU(this.options,this.sessionType),this.cipher=new Nm(this.sessionType,this.options.cert,this.options.key,this.options.signatureHash),this.transport=new Oee(this.options.transport),this.setupExtensions(),this.transport.socket.onData=this.udpOnMessage}onConnect=new Ne;onData=new Ne;onError=new Ne;onClose=new Ne;transport;cipher;dtls;srtp=new Um;connected=!1;extensions=[];onHandleHandshakes;bufferFragmentedHandshakes=[];renegotiation(){cU("renegotiation",this.sessionType),this.connected=!1,this.cipher=new Nm(this.sessionType,this.options.cert,this.options.key,this.options.signatureHash),this.dtls=new iU(this.options,this.sessionType),this.srtp=new Um,this.extensions=[],this.bufferFragmentedHandshakes=[]}udpOnMessage=t=>{let e=Nee(t);for(let r of e)try{let s=Uee(this.dtls,this.cipher)(r);for(let n of s)switch(n.type){case 22:{let i=n.data,o=this.handleFragmentHandshake([i]),a=Object.values(o.reduce((c,d)=>(c[d.msg_type]||(c[d.msg_type]=[]),c[d.msg_type].push(d),c),{})).map(c=>vn.assemble(c)).sort((c,d)=>c.msg_type-d.msg_type);this.onHandleHandshakes(a).catch(c=>{dU(this.dtls.sessionId,"onHandleHandshakes error",c),this.onError.execute(c)})}break;case 23:this.onData.execute(n.data);break;case 21:this.onClose.execute();break}}catch(s){dU(this.dtls.sessionId,"catch udpOnMessage error",s)}};setupExtensions(){if(cU(this.dtls.sessionId,"support srtpProfiles",this.options.srtpProfiles),this.options.srtpProfiles&&this.options.srtpProfiles.length>0){let t=Lh.create(this.options.srtpProfiles,Buffer.from([0]));this.extensions.push(t.extension)}{let t=sk.createEmpty();t.data=Xk,this.extensions.push(t.extension)}{let t=nk.createEmpty();t.data=Jk,this.extensions.push(t.extension)}this.options.extendedMasterSecret&&this.extensions.push({type:b1.type,data:Buffer.alloc(0)});{let t=x1.createEmpty();this.extensions.push(t.extension)}}waitForReady=t=>new Promise(async(e,r)=>{for(let s=0;s<10;s++)if(t()){e();break}else await(0,UM.setTimeout)(100*s);r("waitForReady timeout")});handleFragmentHandshake(t){let e=t.filter(r=>r.fragment_length!==r.length?(this.bufferFragmentedHandshakes.push(r),!1):!0);if(this.bufferFragmentedHandshakes.length>1){let[r]=this.bufferFragmentedHandshakes.slice(-1);r.fragment_offset+r.fragment_length===r.length&&(e=[...this.bufferFragmentedHandshakes,...e],this.bufferFragmentedHandshakes=[])}return e}send=async t=>{let e=Zm(this.dtls)([{type:23,fragment:t}],++this.dtls.recordSequenceNumber)[0];await this.transport.send(this.cipher.encryptPacket(e).serialize())};close(){this.transport.socket.close()}extractSessionKeys(t,e){let r=this.exportKeyingMaterial("EXTRACTOR-dtls_srtp",t*2+e*2),{clientKey:s,serverKey:n,clientSalt:i,serverSalt:o}=(0,ll.decode)(r,{clientKey:ll.types.buffer(t),serverKey:ll.types.buffer(t),clientSalt:ll.types.buffer(e),serverSalt:ll.types.buffer(e)});return this.sessionType===Go.CLIENT?{localKey:s,localSalt:i,remoteKey:n,remoteSalt:o}:{localKey:n,localSalt:o,remoteKey:s,remoteSalt:i}}exportKeyingMaterial(t,e){return NZ(t,e,this.cipher.masterSecret,this.cipher.localRandom.serialize(),this.cipher.remoteRandom.serialize(),this.sessionType===Go.CLIENT)}get remoteCertificate(){return this.cipher.remoteCertificate}},ET=ft("werift-dtls : packages/dtls/src/client.ts : log"),ik=class extends oA{constructor(t){super(t,Go.CLIENT),this.onHandleHandshakes=this.handleHandshakes,ET(this.dtls.sessionId,"start client")}async connect(){await new JZ(this.transport,this.dtls,this.cipher).exec(this.extensions)}flight5;handleHandshakes=async t=>{ET(this.dtls.sessionId,"handleHandshakes",t.map(e=>e.msg_type));for(let e of t)switch(e.msg_type){case 3:{let r=NM.deSerialize(e.fragment);await new ZZ(this.transport,this.dtls).exec(r)}break;case 2:{if(this.connected)return;this.flight5=new Bee(this.transport,this.dtls,this.cipher,this.srtp),this.flight5.handleHandshake(e)}break;case 11:case 12:case 13:await this.waitForReady(()=>!!this.flight5),this.flight5?.handleHandshake(e);break;case 14:{await this.waitForReady(()=>!!this.flight5),this.flight5?.handleHandshake(e);let r=[11,12,this.options.certificateRequest&&13].filter(s=>typeof s=="number");await this.waitForReady(()=>this.dtls.checkHandshakesExist(r)),await this.flight5?.exec()}break;case 20:this.dtls.flight=7,this.connected=!0,this.onConnect.execute(),ET(this.dtls.sessionId,"dtls connected");break}}},Fi=ft("werift-dtls : packages/dtls/flight/server/flight2.ts : log"),Mee=(t,e,r,s)=>n=>{Fi("dtls version",n.clientVersion),e.flight=2,e.recordSequenceNumber=0,e.sequenceNumber=0,n.extensions.forEach(l=>{switch(l.type){case sk.type:{let h=sk.fromData(l.data).data;Fi(e.sessionId,"curves",h);let p=h.filter(m=>Xk.includes(m))[0];r.namedCurve=p,Fi(e.sessionId,"curve selected",r.namedCurve)}break;case nk.type:{if(!r.signatureHashAlgorithm)throw new Error("need to set certificate");let h=nk.fromData(l.data).data;Fi(e.sessionId,"hash,signature",h);let p=h.find(_=>_.signature===r.signatureHashAlgorithm?.signature)?.signature,m=h.find(_=>_.hash===r.signatureHashAlgorithm?.hash)?.hash;if(p==null||m==null)throw new Error("invalid signatureHash")}break;case Lh.type:{if(!e.options?.srtpProfiles||e.options.srtpProfiles.length===0)return;let h=Lh.fromData(l.data);Fi(e.sessionId,"srtp profiles",h.profiles);let p=Um.findMatchingSRTPProfile(h.profiles,e.options?.srtpProfiles);if(!p)throw new Error;s.srtpProfile=p,Fi(e.sessionId,"srtp profile selected",s.srtpProfile)}break;case b1.type:e.remoteExtendedMasterSecret=!0;break;case x1.type:Fi(e.sessionId,"RenegotiationIndication",l.data);break;case 43:{let p=[...l.data.subarray(1)].map(m=>m.toString(10));Fi("dtls supported version",p)}break}}),r.localRandom=new fl,r.remoteRandom=fl.from(n.random);let i=n.cipherSuites;Fi(e.sessionId,"cipher suites",i);let o=(()=>{switch(r.signatureHashAlgorithm?.signature){case zi.ecdsa_3:return Qw.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256_49195;case zi.rsa_1:return Qw.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256_49199}})();if(o===void 0||!i.includes(o))throw new Error("dtls cipher suite negotiation failed");r.cipherSuite=o,Fi(e.sessionId,"selected cipherSuite",r.cipherSuite),r.localKeyPair=E7(r.namedCurve),e.cookie||=(0,MM.randomBytes)(20);let a=new NM({major:254,minor:253},e.cookie),c=v7(e)([a]),u=Zm(e)(c.map(l=>({type:22,fragment:l.serialize()})),++e.recordSequenceNumber).map(l=>l.serialize());for(let l of u)t.send(l)},lU=ft("werift-dtls : packages/dtls/flight/server/flight4.ts : log"),jee=class extends eg{constructor(t,e,r,s){super(t,e,4,6),this.cipher=r,this.srtp=s}async exec(t,e=!1){if(this.dtls.flight===4){lU(this.dtls.sessionId,"flight4 twice"),this.send(this.dtls.lastMessage);return}this.dtls.flight=4,this.dtls.sequenceNumber=1,this.dtls.bufferHandshakeCache([t],!1,4);let r=[this.sendServerHello(),this.sendCertificate(),this.sendServerKeyExchange(),e&&this.sendCertificateRequest(),this.sendServerHelloDone()].filter(s=>s);this.dtls.lastMessage=r,await this.transmit(r)}sendServerHello(){let t=[];this.srtp.srtpProfile&&t.push(Lh.create([this.srtp.srtpProfile],Buffer.from([0])).extension),this.dtls.options.extendedMasterSecret&&t.push({type:b1.type,data:Buffer.alloc(0)});let e=x1.createEmpty();t.push(e.extension);let r=new I7(this.dtls.version,this.cipher.localRandom,Buffer.from([0]),this.cipher.cipherSuite,0,t),s=this.createPacket([r]);return Buffer.concat(s.map(n=>n.serialize()))}sendCertificate(){let t=new e1([Buffer.from(this.cipher.localCert)]),e=this.createPacket([t]);return Buffer.concat(e.map(r=>r.serialize()))}sendServerKeyExchange(){let t=this.cipher.generateKeySignature("sha256");if(!this.cipher.signatureHashAlgorithm)throw new Error("not exist");let e=new D7(Yk.named_curve_3,this.cipher.namedCurve,this.cipher.localKeyPair.publicKey.length,this.cipher.localKeyPair.publicKey,this.cipher.signatureHashAlgorithm.hash,this.cipher.signatureHashAlgorithm.signature,t.length,t),r=this.createPacket([e]);return Buffer.concat(r.map(s=>s.serialize()))}sendCertificateRequest(){let t=new A7(o7,Jk,[]);lU(this.dtls.sessionId,"sendCertificateRequest",t);let e=this.createPacket([t]);return Buffer.concat(e.map(r=>r.serialize()))}sendServerHelloDone(){let t=new R7,e=this.createPacket([t]);return Buffer.concat(e.map(r=>r.serialize()))}},Mh=ft("werift-dtls : packages/dtls/flight/server/flight6.ts"),$ee=class extends eg{constructor(t,e,r){super(t,e,6),this.cipher=r}handleHandshake(t){this.dtls.bufferHandshakeCache([t],!1,5);let e=(()=>{switch(t.msg_type){case 11:return e1.deSerialize(t.fragment);case 15:return T7.deSerialize(t.fragment);case 16:return k7.deSerialize(t.fragment);case 20:return FT.deSerialize(t.fragment)}})();if(e){let r=ng[e.msgType];if(!r)return;r({dtls:this.dtls,cipher:this.cipher})(e)}}async exec(){if(this.dtls.flight===6){Mh(this.dtls.sessionId,"flight6 twice"),this.send(this.dtls.lastMessage);return}this.dtls.flight=6;let t=[this.sendChangeCipherSpec(),this.sendFinished()];this.dtls.lastMessage=t,await this.transmit(t)}sendChangeCipherSpec(){let t=C7.createEmpty().serialize(),e=Zm(this.dtls)([{type:20,fragment:t}],++this.dtls.recordSequenceNumber);return Buffer.concat(e.map(s=>s.serialize()))}sendFinished(){let t=Buffer.concat(this.dtls.sortedHandshakeCache.map(i=>i.serialize())),e=this.cipher.verifyData(t),r=new FT(e);this.dtls.epoch=1;let[s]=this.createPacket([r]);return this.dtls.recordSequenceNumber=0,this.cipher.encryptPacket(s).serialize()}},ng={};ng[16]=({cipher:t,dtls:e})=>r=>{if(t.remoteKeyPair={curve:t.namedCurve,publicKey:r.publicKey},!t.remoteKeyPair.publicKey||!t.localKeyPair||!t.remoteRandom||!t.localRandom)throw new Error("not exist");let s=d7(t.remoteKeyPair.publicKey,t.localKeyPair.privateKey,t.localKeyPair.curve);Mh(e.sessionId,"extendedMasterSecret",e.options.extendedMasterSecret,e.remoteExtendedMasterSecret);let n=Buffer.concat(e.sortedHandshakeCache.map(i=>i.serialize()));t.masterSecret=e.options.extendedMasterSecret&&e.remoteExtendedMasterSecret?u7(s,n):l7(s,t.remoteRandom.serialize(),t.localRandom.serialize()),t.cipher=_7(t.cipherSuite),t.cipher.init(t.masterSecret,t.localRandom.serialize(),t.remoteRandom.serialize()),Mh(e.sessionId,"setup cipher",t.cipher.summary)};ng[11]=({cipher:t,dtls:e})=>r=>{Mh(e.sessionId,"handshake certificate",r),t.remoteCertificate=r.certificateList[0]};ng[15]=({cipher:t,dtls:e})=>r=>{if(!t.remoteCertificate)throw new Error("client certificate missing before certificate verify");Mh(e.sessionId,"certificate_verify",r.algorithm)};ng[20]=({dtls:t})=>e=>{Mh(t.sessionId,"finished",e)};vh=ft("werift-dtls : packages/dtls/src/server.ts : log"),jM=class extends oA{constructor(t){super(t,Go.SERVER),this.onHandleHandshakes=this.handleHandshakes,vh(this.dtls.sessionId,"start server")}flight6;handleHandshakes=async t=>{vh(this.dtls.sessionId,"handleHandshakes",t.map(e=>e.msg_type));for(let e of t)switch(e.msg_type){case 1:{this.connected&&this.renegotiation();let r=b7.deSerialize(e.fragment);r.cookie.length===0?(vh(this.dtls.sessionId,"send flight2"),Mee(this.transport,this.dtls,this.cipher,this.srtp)(r)):this.dtls.cookie&&r.cookie.equals(this.dtls.cookie)?(vh(this.dtls.sessionId,"send flight4"),await new jee(this.transport,this.dtls,this.cipher,this.srtp).exec(e,this.options.certificateRequest)):vh("wrong state",{dtlsCookie:this.dtls.cookie?.toString("hex").slice(10),helloCookie:r.cookie.toString("hex").slice(10)})}break;case 11:case 15:case 16:{if(this.connected)return;this.flight6=new $ee(this.transport,this.dtls,this.cipher),this.flight6.handleHandshake(e)}break;case 20:{await this.waitForReady(()=>!!this.flight6),this.flight6?.handleHandshake(e);let r=[16,this.options.certificateRequest&&11,this.options.certificateRequest&&15].filter(s=>typeof s=="number");await this.waitForReady(()=>this.dtls.checkHandshakesExist(r)),await this.flight6?.exec(),this.connected=!0,this.onConnect.execute(),vh(this.dtls.sessionId,"dtls connected")}break}}},_1=554869826,$M=8,FM=1398035790,zo=20,aA=24,cA=1,dA=2,HM=6,qM=50,Fee=["FINGERPRINT","MESSAGE-INTEGRITY","CHANGE-REQUEST","PRIORITY","USERNAME","ICE-CONTROLLING","SOURCE-ADDRESS","USE-CANDIDATE","ICE-CONTROLLED","ERROR-CODE","XOR-MAPPED-ADDRESS","CHANGED-ADDRESS","LIFETIME","REQUESTED-TRANSPORT","NONCE","REALM","XOR-RELAYED-ADDRESS","CHANNEL-NUMBER","XOR-PEER-ADDRESS","DATA","SOFTWARE","MAPPED-ADDRESS","RESPONSE-ORIGIN","OTHER-ADDRESS"],lA=(t=>(t[t.REQUEST=0]="REQUEST",t[t.INDICATION=16]="INDICATION",t[t.RESPONSE=256]="RESPONSE",t[t.ERROR=272]="ERROR",t))(lA||{}),uA=(t=>(t[t.BINDING=1]="BINDING",t[t.SHARED_SECRET=2]="SHARED_SECRET",t[t.ALLOCATE=3]="ALLOCATE",t[t.REFRESH=4]="REFRESH",t[t.SEND=6]="SEND",t[t.DATA=7]="DATA",t[t.CREATE_PERMISSION=8]="CREATE_PERMISSION",t[t.CHANNEL_BIND=9]="CHANNEL_BIND",t))(uA||{});uU=class{queue=[];wait=new Ne;put(t){this.queue.push(t),this.queue.length===1&&this.wait.execute(t)}get(){let t=this.queue.shift();return t||new Promise(e=>{this.wait.subscribe(r=>{this.queue.shift(),e(r)})})}},ok=t=>{let e,r,s=new Promise((i,o)=>{e=i,r=o});s.then(()=>{n.execute(void 0),n.complete()}).catch(i=>{n.execute(i??new Error),n.complete()});let n=new Ne;return t(e,r,n).catch(()=>{}),{awaitable:s,resolve:e,reject:r}};pA=Buffer.alloc(6);pA.writeUInt16BE(_1>>16,0);pA.writeUInt32BE(_1,2);um=t=>{let e=Buffer.alloc(4);return e.writeUInt32BE(t,0),e},hm=t=>t.readUInt32BE(0),Vee=t=>{let e=Buffer.alloc(4);return e.writeUInt16BE(t,0),e},zee=t=>t.readUInt16BE(0),hU=t=>new oT(t.toString()).toBuffer(),fU=t=>{let e=new oT(t);return BigInt(e.toString())},CT=t=>Buffer.from(t,"utf8"),TT=t=>t.toString("utf8"),kT=t=>t,AT=t=>t,Wee=t=>Buffer.from([]),Kee=t=>null,WM=[[1,"MAPPED-ADDRESS",Ch,Th],[3,"CHANGE-REQUEST",um,hm],[4,"SOURCE-ADDRESS",Ch,Th],[5,"CHANGED-ADDRESS",Ch,Th],[6,"USERNAME",CT,TT],[8,"MESSAGE-INTEGRITY",kT,AT],[9,"ERROR-CODE",qee,Hee],[12,"CHANNEL-NUMBER",Vee,zee],[13,"LIFETIME",um,hm],[18,"XOR-PEER-ADDRESS",Uw,Nw],[19,"DATA",kT,AT],[20,"REALM",CT,TT],[21,"NONCE",kT,AT],[22,"XOR-RELAYED-ADDRESS",Uw,Nw],[25,"REQUESTED-TRANSPORT",um,hm],[32,"XOR-MAPPED-ADDRESS",Uw,Nw],[36,"PRIORITY",um,hm],[37,"USE-CANDIDATE",Wee,Kee],[32802,"SOFTWARE",CT,TT],[32808,"FINGERPRINT",um,hm],[32809,"ICE-CONTROLLED",hU,fU],[32810,"ICE-CONTROLLING",hU,fU],[32811,"RESPONSE-ORIGIN",Ch,Th],[32812,"OTHER-ADDRESS",Ch,Th]],KM=class{constructor(t=[]){this.attributes=t}getAttributes(){return this.attributes}setAttribute(t,e){let r=this.attributes.find(s=>s[0]===t);return r?r[1]=e:this.attributes.push([t,e]),this}getAttributeValue(t){let e=this.attributes.find(r=>r[0]===t);if(e)return e[1]}get attributesKeys(){return this.attributes.map(t=>t[0])}clear(){this.attributes=[]}},pU=WM.reduce((t,e)=>(t[e[0]]=e,t),{}),Gee=WM.reduce((t,e)=>(t[e[1]]=e,t),{});wn=class extends KM{constructor(t,e,r=VM(),s=[]){super(s),this.messageMethod=t,this.messageClass=e,this.transactionId=r}toJSON(){return this.json}get json(){return{messageMethod:uA[this.messageMethod],messageClass:lA[this.messageClass],attributes:this.attributes}}get transactionIdHex(){return this.transactionId.toString("hex")}get bytes(){let t=Buffer.from([]);for(let r of this.attributesKeys){let s=this.getAttributeValue(r),[n,,i]=Gee[r],o=i.name===Uw.name?i(s,this.transactionId):i(s),a=o.length,c=4*Math.floor((a+3)/4)-a,d=Buffer.alloc(4);d.writeUInt16BE(n,0),d.writeUInt16BE(a,2),t=Buffer.concat([t,d,o,Buffer.alloc(c,0)])}let e=Buffer.alloc(8);return e.writeUInt16BE(this.messageMethod|this.messageClass,0),e.writeUInt16BE(t.length,2),e.writeUInt32BE(_1,4),Buffer.concat([e,this.transactionId,t])}addMessageIntegrity(t){return this.setAttribute("MESSAGE-INTEGRITY",this.messageIntegrity(t)),this}messageIntegrity(t){let e=mA(this.bytes,this.bytes.length-zo+aA);return Buffer.from((0,hA.createHmac)("sha1",t).update(e).digest("hex"),"hex")}addFingerprint(){this.setAttribute("FINGERPRINT",GM(this.bytes))}},mA=(t,e)=>{let r=Buffer.alloc(t.length);return t.copy(r,0,0,2),r.writeUInt16BE(e,2),t.copy(r,4,4),r};XM=class extends Error{response;addr},YM=class extends XM{constructor(t,e){super(),this.response=t,this.addr=e}get str(){let t="STUN transaction failed",e=this.response.getAttributeValue("ERROR-CODE");if(e){let[r,s]=e;t+=` (${r} - ${s})`}return t}},Yee=class extends XM{get str(){return"STUN transaction timed out"}},IT=ft("werift-ice:packages/ice/src/stun/transaction.ts"),gA=class{constructor(t,e,r,s){this.request=t,this.addr=e,this.protocol=r,this.retransmissions=s,this.triesMax=1+(this.retransmissions?this.retransmissions:HM)}timeoutDelay=qM;ended=!1;tries=0;triesMax;onResponse=new Ne;responseReceived=(t,e)=>{this.onResponse.length>0&&(t.messageClass===256?(this.onResponse.execute(t,e),this.onResponse.complete()):this.onResponse.error(new YM(t,e)))};run=async()=>{try{return this.retry().catch(e=>{IT("retry failed",e)}),await this.onResponse.asPromise()}catch(t){throw t}finally{this.cancel()}};retry=async()=>{for(;this.tries<this.triesMax&&!this.ended&&(this.protocol.sendStun(this.request,this.addr).catch(t=>{IT("send stun failed",t)}),await new Promise(t=>setTimeout(t,this.timeoutDelay)),!this.ended);)this.timeoutDelay*=2,this.tries++;this.tries>=this.triesMax&&(IT(`retry failed times:${this.tries} maxLimit:${this.triesMax}`),this.onResponse.error(new Yee))};cancel(){this.ended=!0}},mU=ft("werift-ice : packages/ice/src/stun/protocol.ts"),r1=class JM{static type="stun";type=JM.type;transport;transactions={};get transactionsKeys(){return Object.keys(this.transactions)}localCandidate;sentMessage;localIp;onRequestReceived=new Ne;onDataReceived=new Ne;constructor(){}connectionMade=async(e,r,s)=>{e?this.transport=await Jw.init("udp4",{portRange:r,interfaceAddresses:s}):this.transport=await Jw.init("udp6",{portRange:r,interfaceAddresses:s}),this.transport.onData=(n,i)=>{this.datagramReceived(n,i)}};datagramReceived(e,r){try{let s=S1(e);if(!s){this.localCandidate&&this.onDataReceived.execute(e);return}(s.messageClass===256||s.messageClass===272)&&this.transactionsKeys.includes(s.transactionIdHex)?this.transactions[s.transactionIdHex].responseReceived(s,r):s.messageClass===0&&this.onRequestReceived.execute(s,r,e)}catch(s){mU("datagramReceived error",s)}}getExtraInfo(){let{address:e,port:r}=this.transport.address;return[e,r]}async sendStun(e,r){if(this.transport.closed)return;let s=e.bytes;await this.transport.send(s,r).catch(()=>{mU("sendStun failed",r,e)})}async sendData(e,r){this.transport.closed||await this.transport.send(e,r)}async request(e,r,s,n){if(this.transactionsKeys.includes(e.transactionIdHex))throw new Error("already request ed");s&&(e.addMessageIntegrity(s),e.addFingerprint());let i=new gA(e,r,this,n);this.transactions[e.transactionIdHex]=i;try{return await i.run()}catch(o){throw o}finally{delete this.transactions[e.transactionIdHex]}}async close(){Object.values(this.transactions).forEach(e=>{e.cancel()}),await this.transport.close(),this.onRequestReceived.complete(),this.onDataReceived.complete()}},Ls=ft("werift-ice:packages/ice/src/turn/protocol.ts"),Jee=500,Qee=600,Zee=285212672,ej=class tj{constructor(e){this.turn=e,e.onData.subscribe((r,s)=>{this.handleStunMessage(r,s)}).disposer(this.disposer)}static type="turn";type=tj.type;localCandidate;disposer=new QU;onRequestReceived=new Ne;onDataReceived=new Ne;handleStunMessage=(e,r)=>{try{let s=S1(e);if(!s){this.onDataReceived.execute(e);return}if(s.messageClass===256||s.messageClass===272){let n=this.turn.transactions[s.transactionIdHex];n&&n.responseReceived(s,r)}else s.messageClass===0&&this.onRequestReceived.execute(s,r,e)}catch(s){Ls("datagramReceived error",s)}};async request(e,r,s){if(this.turn.transactions[e.transactionIdHex])throw new Error("exist");s&&(e.addMessageIntegrity(s),e.addFingerprint());let n=new gA(e,r,this);this.turn.transactions[e.transactionIdHex]=n;try{return await n.run()}catch(i){throw i}finally{delete this.turn.transactions[e.transactionIdHex]}}async connectionMade(){}async sendData(e,r){await this.turn.sendData(e,r)}async sendStun(e,r){await this.turn.sendData(e.bytes,r)}async close(){return this.disposer.dispose(),this.turn.close()}},rj=class sj{constructor(e,r,s,n,i,o={}){this.server=e,this.username=r,this.password=s,this.lifetime=n,this.transport=i,this.options=o,this.channelRefreshTime=this.options.channelRefreshTime??Jee}static type="turn";type=sj.type;onData=new Ne;onRequestReceived=new Ne;onDataReceived=new Ne;integrityKey;nonce;realm;relayedAddress;mappedAddress;localCandidate;transactions={};refreshHandle;channelNumber=16384;channelByAddr={};addrByChannel={};channelRefreshTime;channelBinding;channelRefreshAt=0;tcpBuffer=Buffer.alloc(0);permissionByAddr={};creatingPermission=Promise.resolve();async connectionMade(){this.transport.onData=(n,i)=>{this.dataReceived(n,i)};let e=new wn(3,0);e.setAttribute("LIFETIME",this.lifetime).setAttribute("REQUESTED-TRANSPORT",Zee);let[r]=await this.requestWithRetry(e,this.server).catch(n=>{throw Ls("connect error",n),n});this.relayedAddress=r.getAttributeValue("XOR-RELAYED-ADDRESS"),this.mappedAddress=r.getAttributeValue("XOR-MAPPED-ADDRESS");let s=r.getAttributeValue("LIFETIME");Ls("connect",this.relayedAddress,this.mappedAddress,{exp:s}),this.refresh(s)}handleChannelData(e){let[r,s]=ck.jspack.Unpack("!HH",e.slice(0,4)),n=this.addrByChannel[r];if(n){let i=e.subarray(4,4+s);this.onData.execute(i,n)}}handleSTUNMessage(e,r){try{let s=S1(e);if(!s)throw new Error("not stun message");if(s.messageClass===256||s.messageClass===272){let n=this.transactions[s.transactionIdHex];n&&n.responseReceived(s,r)}else s.messageClass===0&&this.onData.execute(e,r);if(s.getAttributeValue("DATA")){let n=s.getAttributeValue("DATA");this.onData.execute(n,r)}}catch{Ls("parse error",e.toString())}}dataReceived(e,r){let s=(n,i)=>{n.length>=4&&gU(n)?this.handleChannelData(n):this.handleSTUNMessage(n,i)};if(this.transport.type==="tcp")for(this.tcpBuffer=Buffer.concat([this.tcpBuffer,e]);this.tcpBuffer.length>=4;){let[,n]=bs(this.tcpBuffer.subarray(0,4),[2,2]);n+=ak(n);let i=gU(this.tcpBuffer)?4+n:20+n;if(this.tcpBuffer.length<i)break;s(this.tcpBuffer.subarray(0,i),r),this.tcpBuffer=this.tcpBuffer.subarray(i)}else s(e,r)}async send(e,r){if(!this.transport.closed)if(this.transport.type==="tcp"){let s=ak(e.length);await this.transport.send(s>0?Buffer.concat([e,Buffer.alloc(s)]):e,r)}else await this.transport.send(e,r)}async createPermission(e){let r=new wn(8,0);r.setAttribute("XOR-PEER-ADDRESS",e).setAttribute("USERNAME",this.username).setAttribute("REALM",this.realm).setAttribute("NONCE",this.nonce),await this.request(r,this.server).catch(s=>{throw s})}refresh=e=>{this.refreshHandle=ok(async(r,s,n)=>{let i=!0;for(n.once(()=>{i=!1});i;){let o=.8333333333333334*e*1e3;Ls("refresh delay",o,{exp:e}),await(0,ZM.setTimeout)(o);let a=new wn(4,0);a.setAttribute("LIFETIME",e);try{let[c]=await this.requestWithRetry(a,this.server);e=c.getAttributeValue("LIFETIME"),Ls("refresh",{exp:e})}catch(c){Ls("refresh error",c)}}})};async request(e,r){if(this.transactions[e.transactionIdHex])throw new Error("exist");this.integrityKey&&e.setAttribute("USERNAME",this.username).setAttribute("REALM",this.realm).setAttribute("NONCE",this.nonce).addMessageIntegrity(this.integrityKey).addFingerprint();let s=new gA(e,r,this);this.transactions[e.transactionIdHex]=s;try{return await s.run()}catch(n){throw n}finally{delete this.transactions[e.transactionIdHex]}}async requestWithRetry(e,r){let s,n;try{[s,n]=await this.request(e,r)}catch(i){if(!(i instanceof YM))throw Ls("requestWithRetry error",i),i;this.server=i.addr;let[o]=i.response.getAttributeValue("ERROR-CODE"),a=i.response.getAttributeValue("NONCE"),c=i.response.getAttributeValue("REALM");if((o===401&&c||o===438&&this.realm)&&a)Ls("retry with nonce",o),this.nonce=a,o===401&&(this.realm=c),this.integrityKey=ij(this.username,this.realm,this.password),e.transactionId=VM(),[s,n]=await this.request(e,this.server);else throw i}return[s,n]}async sendData(e,r){let s=await this.getChannel(r).catch(i=>new Error("channelBind error"));if(s instanceof Error){await this.getPermission(r);let i=new wn(6,16).setAttribute("DATA",e).setAttribute("XOR-PEER-ADDRESS",r);await this.sendStun(i,this.server);return}let n=ck.jspack.Pack("!HH",[s.number,e.length]);await this.send(Buffer.concat([Buffer.from(n),e]),this.server)}async getPermission(e){await this.creatingPermission,this.permissionByAddr[e.join(":")]||(this.creatingPermission=this.createPermission(e),this.permissionByAddr[e.join(":")]=!0,await this.creatingPermission.catch(s=>{throw Ls("createPermission error",s),s}))}async getChannel(e){this.channelBinding&&await this.channelBinding;let r=this.channelByAddr[e.join(":")];return r?this.channelRefreshAt<Rh(Date.now()/1e3)&&(this.channelBinding=this.channelBind(r.number,e),this.channelRefreshAt=Rh(Date.now()/1e3)+this.channelRefreshTime,await this.channelBinding.catch(s=>{throw Ls("channelBind error",s),s}),this.channelBinding=void 0,Ls("channelBind refresh",r)):(this.channelByAddr[e.join(":")]={number:this.channelNumber++,address:e},r=this.channelByAddr[e.join(":")],this.addrByChannel[r.number]=e,this.channelBinding=this.channelBind(r.number,e),await this.channelBinding.catch(s=>{throw Ls("channelBind error",s),s}),this.channelRefreshAt=Rh(Date.now()/1e3)+this.channelRefreshTime,this.channelBinding=void 0,Ls("channelBind",r)),r}async channelBind(e,r){let s=new wn(9,0);s.setAttribute("CHANNEL-NUMBER",e).setAttribute("XOR-PEER-ADDRESS",r);let[n]=await this.requestWithRetry(s,this.server);if(n.messageMethod!==9)throw new Error("should be CHANNEL_BIND")}async sendStun(e,r){await this.send(e.bytes,r)}async close(){this.refreshHandle?.resolve?.(),await this.transport.close()}};gc=class aj{constructor(e,r,s,n,i,o,a,c,d,u,l,h){this.foundation=e,this.component=r,this.transport=s,this.priority=n,this.host=i,this.port=o,this.type=a,this.relatedAddress=c,this.relatedPort=d,this.tcptype=u,this.generation=l,this.ufrag=h}static fromSdp(e){let r=e.split(" ");if(r.length<8)throw new Error("SDP does not have enough properties");let s={foundation:r[0],component:Number(r[1]),transport:r[2],priority:Number(r[3]),host:r[4],port:Number(r[5]),type:r[7]};for(let l=8,h=r.length-1;l<h;l+=2)r[l]==="raddr"?s.related_address=r[l+1]:r[l]==="rport"?s.related_port=Number(r[l+1]):r[l]==="tcptype"?s.tcptype=r[l+1]:r[l]==="generation"?s.generation=Number(r[l+1]):r[l]==="ufrag"&&(s.ufrag=r[l+1]);let{foundation:n,component:i,transport:o,priority:a,host:c,port:d,type:u}=s;return new aj(n,i,o,a,c,d,u,s.related_address,s.related_port,s.tcptype,s.generation,s.ufrag)}canPairWith(e){let r=(0,lk.isIPv4)(this.host),s=(0,lk.isIPv4)(e.host);return this.component===e.component&&this.transport.toLowerCase()===e.transport.toLowerCase()&&r===s}toSdp(){let e=`${this.foundation} ${this.component} ${this.transport} ${this.priority} ${this.host} ${this.port} typ ${this.type}`;return this.relatedAddress&&(e+=` raddr ${this.relatedAddress}`),this.relatedPort!=null&&(e+=` rport ${this.relatedPort}`),this.tcptype&&(e+=` tcptype ${this.tcptype}`),this.generation!=null&&(e+=` generation ${this.generation}`),this.ufrag!=null&&(e+=` ufrag ${this.ufrag}`),e}};ete=class{cache=new Map;mdnsInstance=(0,dj.default)();constructor(){this.mdnsInstance.setMaxListeners(50)}lookup(t){return new Promise((e,r)=>{let s=()=>{this.mdnsInstance.removeListener("response",i),clearTimeout(n)},n=setTimeout(()=>{s(),r(new Error("No mDNS response"))},1e4),i=o=>{let a=o.answers?.[0];a?.type==="A"&&a.name===t&&(s(),e(a.data))};this.mdnsInstance.on("response",i),this.mdnsInstance.query(t,"A")})}close(){this.mdnsInstance.destroy()}},tte=ft("werift-ice : packages/ice/src/ice.ts : log"),fk=class{constructor(t,e,r){this.protocol=t,this.remoteCandidate=e,this.iceControlling=r}id=(0,lj.randomUUID)().toString();handle;nominated=!1;remoteNominated=!1;_state=0;get state(){return this._state}packetsSent=0;packetsReceived=0;bytesSent=0;bytesReceived=0;rtt;totalRoundTripTime=0;roundTripTimeMeasurements=0;toJSON(){return this.json}get json(){return{protocol:this.protocol.type,localCandidate:this.localCandidate.toSdp(),remoteCandidate:this.remoteCandidate.toSdp()}}updateState(t){this._state=t}get localCandidate(){if(!this.protocol.localCandidate)throw new Error("localCandidate not exist");return this.protocol.localCandidate}get remoteAddr(){return[this.remoteCandidate.host,this.remoteCandidate.port]}get component(){return this.localCandidate.component}get priority(){return n1(this.localCandidate,this.remoteCandidate,this.iceControlling)}get foundation(){return this.localCandidate.foundation}},pk=1,Tm=2,uj=5,mk=6,hj=(t=>(t[t.FROZEN=0]="FROZEN",t[t.WAITING=1]="WAITING",t[t.IN_PROGRESS=2]="IN_PROGRESS",t[t.SUCCEEDED=3]="SUCCEEDED",t[t.FAILED=4]="FAILED",t))(hj||{}),fj={useIpv4:!0,useIpv6:!0};rte=ft("werift-ice : packages/ice/src/utils.ts");nte=t=>{if(!t)return;let[e,r]=t.split(":");return[e,Number.parseInt(r)]},jt=ft("werift-ice : packages/ice/src/ice.ts : log"),wj=class{constructor(t,e){this._iceControlling=t,this.options={...fj,...e};let{stunServer:r,turnServer:s}=this.options;this.stunServer=yk(r)??["stun.l.google.com",19302],this.turnServer=yk(s),this.restart(),jt("new Connection",this.options)}localUsername=lm(4);localPassword=lm(22);remoteIsLite=!1;remotePassword="";remoteUsername="";checkList=[];localCandidates=[];stunServer;turnServer;options;remoteCandidatesEnd=!1;localCandidatesEnd=!1;generation=-1;userHistory={};tieBreaker=BigInt(new Sw((0,cj.randomBytes)(64)).toString());state="new";lookup;_remoteCandidates=[];nominated;nominating=!1;checkListDone=!1;checkListState=new uU;earlyChecks=[];earlyChecksDone=!1;localCandidatesStart=!1;protocols=[];queryConsentHandle;onData=new Ne;stateChanged=new Ne;onIceCandidate=new Ne;get iceControlling(){return this._iceControlling}set iceControlling(t){if(!(this.generation>0||this.nominated)){this._iceControlling=t;for(let e of this.checkList)e.iceControlling=t}}async restart(){this.generation++,this.localUsername=lm(4),this.localPassword=lm(22),this.options.localPasswordPrefix&&(this.localPassword=this.options.localPasswordPrefix+this.localPassword.slice(this.options.localPasswordPrefix.length)),this.userHistory[this.localUsername]=this.localPassword,this.remoteUsername="",this.remotePassword="",this.localCandidates=[],this._remoteCandidates=[],this.remoteCandidatesEnd=!1,this.localCandidatesEnd=!1,this.state="new",this.lookup?.close?.(),this.lookup=void 0,this.nominated=void 0,this.nominating=!1,this.checkList=[],this.checkListDone=!1,this.checkListState=new uU,this.earlyChecks=[],this.earlyChecksDone=!1,this.localCandidatesStart=!1;for(let t of this.protocols)t.localCandidate&&(t.localCandidate.generation=this.generation,t.localCandidate.ufrag=this.localUsername);this.queryConsentHandle?.resolve?.(),this.queryConsentHandle=void 0}resetNominatedPair(){jt("resetNominatedPair"),this.nominated=void 0,this.nominating=!1}setRemoteParams({iceLite:t,usernameFragment:e,password:r}){jt("setRemoteParams",{iceLite:t,usernameFragment:e,password:r}),this.remoteIsLite=t,this.remoteUsername=e,this.remotePassword=r}async gatherCandidates(){if(!this.localCandidatesStart){this.localCandidatesStart=!0;let t=xj(this.options.useIpv4,this.options.useIpv6,{useLinkLocalAddress:this.options.useLinkLocalAddress}),{interfaceAddresses:e}=this.options;if(e){let s=t.filter(n=>Object.values(e).includes(n));s.length&&(t=s)}this.options.additionalHostAddresses&&(t=Array.from(new Set([...this.options.additionalHostAddresses,...t])));let r=this.getCandidatePromises(t,5);await Promise.allSettled(r),this.localCandidatesEnd=!0}this.setState("completed")}appendLocalCandidate(t){this.localCandidates.push(t),this.onIceCandidate.execute(t)}ensureProtocol(t){t.onRequestReceived.subscribe((e,r,s)=>{if(e.messageMethod!==1){this.respondError(e,r,t,[400,"Bad Request"]);return}let n=e.getAttributeValue("USERNAME"),{remoteUsername:i}=yU(n),o=this.userHistory[i]??this.localPassword,{iceControlling:a}=this;if(a&&e.attributesKeys.includes("ICE-CONTROLLING"))if(this.tieBreaker>=e.getAttributeValue("ICE-CONTROLLING")){this.respondError(e,r,t,[487,"Role Conflict"]);return}else this.switchRole(!1);else if(!a&&e.attributesKeys.includes("ICE-CONTROLLED"))if(this.tieBreaker<e.getAttributeValue("ICE-CONTROLLED"))this.respondError(e,r,t,[487,"Role Conflict"]);else{this.switchRole(!0);return}if(this.options.filterStunResponse&&!this.options.filterStunResponse(e,r,t))return;let c=new wn(1,256,e.transactionId);c.setAttribute("XOR-MAPPED-ADDRESS",r).addMessageIntegrity(Buffer.from(o,"utf8")).addFingerprint(),t.sendStun(c,r).catch(d=>{jt("sendStun error",d)}),this.checkList.length===0&&!this.earlyChecksDone?this.earlyChecks.push([e,r,t]):this.checkIncoming(e,r,t)}),t.onDataReceived.subscribe(e=>{try{let r=this.nominated;r&&r.protocol===t&&(r.packetsReceived++,r.bytesReceived+=e.length),this.onData.execute(e)}catch(r){jt("dataReceived",r)}})}getCandidatePromises(t,e=5){let r=[];t=t.filter(c=>!this.protocols.find(d=>d.localIp===c));let s=t.map(async c=>{let d=new r1;this.ensureProtocol(d);try{await d.connectionMade((0,uk.isIPv4)(c),this.options.portRange,this.options.interfaceAddresses),d.localIp=c,this.protocols.push(d),jt("protocol",d.localIp);let u=[c,d.getExtraInfo()[1]];return d.localCandidate=new gc(s1("host","udp",u[0]),1,"udp",Rm("host"),u[0],u[1],"host",void 0,void 0,void 0,this.generation,this.localUsername),this.pairLocalProtocol(d),this.appendLocalCandidate(d.localCandidate),d}catch(u){jt("error protocol STUN",u)}});r.push(...s.map(c=>c.then(d=>d?.localCandidate)));let{stunServer:n,turnServer:i}=this;if(n){let c=s.map(async d=>{let u=await d;return u?new Promise(async(h,p)=>{let m=setTimeout(p,e*1e3);if(u.localCandidate?.host&&(0,uk.isIPv4)(u.localCandidate?.host)){let _=await mj(u,n).catch(f=>{jt("error",f)});_&&this.appendLocalCandidate(_),clearTimeout(m),h(_)}else clearTimeout(m),h()}).catch(h=>{jt("query STUN server",h)}):void 0});r.push(...c)}let{turnUsername:o,turnPassword:a}=this.options;if(i&&o&&a){let c=(async()=>{let d=await dk({address:i,username:o,password:a},{portRange:this.options.portRange,interfaceAddresses:this.options.interfaceAddresses,transport:this.options.turnTransport==="tcp"?"tcp":"udp"}).catch(async h=>{if(this.options.turnTransport!=="tcp")return await dk({address:i,username:o,password:a},{portRange:this.options.portRange,interfaceAddresses:this.options.interfaceAddresses,transport:"tcp"});throw h});this.ensureProtocol(d),this.protocols.push(d);let u=d.turn.relayedAddress,l=d.turn.mappedAddress;return jt("turn candidateAddress",u),d.localCandidate=new gc(s1("relay","udp",u[0]),1,"udp",Rm("relay"),u[0],u[1],"relay",l[0],l[1],void 0,this.generation,this.localUsername),this.appendLocalCandidate(d.localCandidate),d.localCandidate})().catch(d=>{jt("query TURN server",d)});this.options.forceTurn&&(r=[]),r.push(c)}return r}async connect(){if(jt("start connect ice"),!this.localCandidatesEnd&&!this.localCandidatesStart)throw new Error("Local candidates gathering was not performed");if(!this.remoteUsername||!this.remotePassword)throw new Error("Remote username or password is missing");for(let e of this.remoteCandidates)this.pairRemoteCandidate(e);this.sortCheckList(),this.unfreezeInitial(),jt("earlyChecks",this.localPassword,this.earlyChecks.length);for(let e of this.earlyChecks)this.checkIncoming(...e);for(this.earlyChecks=[],this.earlyChecksDone=!0;!(this.state==="closed"||!this.schedulingChecks());)await hk.setTimeout(20);let t=Tm;for(;this.checkList.length>0&&t===Tm;)t=await this.checkListState.get(),jt("checkListState",t);for(let e of this.checkList)e.handle?.resolve?.();if(t!==pk)throw new Error("ICE negotiation failed");this.queryConsent(),this.setState("connected")}unfreezeInitial(){let[t]=this.checkList;if(!t)return;t.state===0&&t.updateState(1);let e=new Set(t.localCandidate.foundation);for(let r of this.checkList)r.component===t.component&&!e.has(r.localCandidate.foundation)&&r.state===0&&(r.updateState(1),e.add(r.localCandidate.foundation))}schedulingChecks(){{let t=this.checkList.filter(e=>!(this.options.forceTurn&&e.protocol.type===r1.type)).find(e=>e.state===1);if(t)return t.handle=this.checkStart(t),!0}{let t=this.checkList.find(e=>e.state===0);if(t)return t.handle=this.checkStart(t),!0}return this.remoteCandidatesEnd?!1:!this.checkListDone}queryConsent=()=>{this.queryConsentHandle&&this.queryConsentHandle.resolve(),this.queryConsentHandle=ok(async(t,e,r)=>{let s=0,n=!1,i=new AbortController;r.once(()=>{n=!0,s+=mk,i.abort(),this.queryConsentHandle=void 0});let{localUsername:o,remoteUsername:a,iceControlling:c}=this;try{for(;this.state!=="closed"&&!n;){await hk.setTimeout(uj*(.8+.4*Math.random())*1e3,void 0,{signal:i.signal});let d=this.nominated;if(!d||n)break;let u=this.buildRequest({nominate:!1,localUsername:o,remoteUsername:a,iceControlling:c});try{await d.protocol.request(u,d.remoteAddr,Buffer.from(this.remotePassword,"utf8"),0),s=0,this.state==="disconnected"&&this.setState("connected")}catch{if(d.id===this.nominated?.id){jt("no stun response"),s++,this.setState("disconnected");break}}if(s>=mk){jt("Consent to send expired"),this.queryConsentHandle=void 0,this.setState("closed");break}}}catch{}})};async close(){this.setState("closed"),this.queryConsentHandle?.resolve?.(),this.checkList&&!this.checkListDone&&this.checkListState.put(new Promise(t=>{t(Tm)})),this.nominated=void 0;for(let t of this.protocols)t.close&&await t.close();this.protocols=[],this.localCandidates=[],this.lookup?.close?.(),this.lookup=void 0}setState(t){this.state=t,this.stateChanged.execute(t)}async addRemoteCandidate(t){if(!t){this.remoteCandidatesEnd=!0;return}if(t.host.includes(".local"))try{this.lookup||(this.lookup=new ete);let e=await this.lookup.lookup(t.host);t.host=e}catch{return}try{gk(t)}catch{return}jt("addRemoteCandidate",t),this._remoteCandidates.push(t),this.pairRemoteCandidate(t),this.sortCheckList()}send=async t=>{let e=this.nominated;if(e)await e.protocol.sendData(t,e.remoteAddr),e.packetsSent++,e.bytesSent+=t.length;else return};getDefaultCandidate(){let t=this.localCandidates.sort((r,s)=>r.priority-s.priority),[e]=t;return e}set remoteCandidates(t){if(this.remoteCandidatesEnd)throw new Error("Cannot set remote candidates after end-of-candidates.");this._remoteCandidates=[];for(let e of t){try{gk(e)}catch{continue}this._remoteCandidates.push(e)}this.remoteCandidatesEnd=!0}get remoteCandidates(){return this._remoteCandidates}get candidatePairs(){return this.checkList}sortCheckList(){pj(this.checkList,this.iceControlling)}findPair(t,e){return this.checkList.find(s=>(0,Mw.default)(s.protocol,t)&&(0,Mw.default)(s.remoteCandidate,e))}switchRole(t){jt("switch role",t),this.iceControlling=t,this.sortCheckList()}checkComplete(t){if(t.handle=void 0,t.state===3){if(t.nominated&&(t.remoteCandidate.generation==null||t.remoteCandidate.generation===this.generation)&&this.nominated==null){jt("nominated",t.toJSON()),this.nominated=t,this.nominating=!1;for(let e of this.checkList)e.component===t.component&&[1,0].includes(e.state)&&e.updateState(4)}if(this.nominated){this.checkListDone||(jt("ICE completed"),this.checkListState.put(new Promise(e=>e(pk))),this.checkListDone=!0);return}jt("not completed",t.toJSON());for(let e of this.checkList)e.localCandidate.foundation===t.localCandidate.foundation&&e.state===0&&e.updateState(1)}{let e=[3,4];if(this.checkList.find(({state:r})=>!e.includes(r)))return}!this.iceControlling&&this.checkList.find(({state:r})=>r===3)||this.checkListDone||(jt("ICE failed"),this.checkListState.put(new Promise(e=>{e(Tm)})))}checkStart=t=>ok(async e=>{jt("check start",t.toJSON()),t.updateState(2);let r={},{remotePassword:s,remoteUsername:n,generation:i}=this,o=t.localCandidate.ufrag??this.localUsername,a=this.iceControlling&&!this.remoteIsLite,c=this.buildRequest({nominate:a,localUsername:o,remoteUsername:n,iceControlling:this.iceControlling}),d=performance.now();try{let[u,l]=await t.protocol.request(c,t.remoteAddr,Buffer.from(s,"utf8"),4),p=(performance.now()-d)/1e3;t.rtt=p,t.totalRoundTripTime+=p,t.roundTripTimeMeasurements++,jt("response received",c.toJSON(),u.toJSON(),l,{localUsername:o,remoteUsername:n,remotePassword:s,generation:i,rtt:p}),r.response=u,r.addr=l}catch(u){let l=u;if(jt("failure case",c.toJSON(),l.response?JSON.stringify(l.response.toJSON(),null,2):u,{localUsername:o,remoteUsername:n,remotePassword:s,generation:i},t.remoteAddr),l.response?.getAttributeValue("ERROR-CODE")[0]===487){c.attributesKeys.includes("ICE-CONTROLLED")?this.switchRole(!0):c.attributesKeys.includes("ICE-CONTROLLING")&&this.switchRole(!1),await this.checkStart(t).awaitable,e();return}if(l.response?.getAttributeValue("ERROR-CODE")[0]===401){jt("retry 401",t.toJSON()),await this.checkStart(t).awaitable,e();return}else{jt("checkStart CandidatePairState.FAILED",t.toJSON()),t.updateState(4),this.checkComplete(t),e();return}}if(!(0,Mw.default)(r.addr,t.remoteAddr)){t.updateState(4),this.checkComplete(t),e();return}if(a||t.remoteNominated)t.nominated=!0;else if(this.iceControlling&&!this.nominating){this.nominating=!0;let u=this.buildRequest({nominate:!0,localUsername:o,remoteUsername:n,iceControlling:this.iceControlling});try{await t.protocol.request(u,t.remoteAddr,Buffer.from(this.remotePassword,"utf8"))}catch{t.updateState(4),this.checkComplete(t);return}t.nominated=!0}t.updateState(3),this.checkComplete(t),e()});addPair(t){this.checkList.push(t),this.sortCheckList()}checkIncoming(t,e,r){let s=t.getAttributeValue("USERNAME"),{remoteUsername:n}=yU(s),i,[o,a]=e;for(let d of this.remoteCandidates)if(d.host===o&&d.port===a){i=d;break}i||(i=new gc(lm(10),1,"udp",t.getAttributeValue("PRIORITY"),o,a,"prflx",void 0,void 0,void 0,void 0,void 0),this._remoteCandidates.push(i));let c=this.findPair(r,i);c||(c=new fk(r,i,this.iceControlling),c.updateState(1),this.addPair(c)),c.localCandidate.ufrag=n,jt("Triggered Checks",t.toJSON(),c.toJSON(),{localUsername:this.localUsername,remoteUsername:this.remoteUsername,localPassword:this.localPassword,remotePassword:this.remotePassword,generation:this.generation}),[1,4].includes(c.state)&&(c.handle=this.checkStart(c)),t.attributesKeys.includes("USE-CANDIDATE")&&!this.iceControlling&&(c.remoteNominated=!0,c.state===3&&(c.nominated=!0,this.checkComplete(c)))}tryPair(t,e){if(t.localCandidate?.canPairWith(e)&&!this.findPair(t,e)){let r=new fk(t,e,this.iceControlling);if(this.options.filterCandidatePair&&!this.options.filterCandidatePair(r))return;r.updateState(1),this.addPair(r)}}pairLocalProtocol(t){for(let e of this.remoteCandidates)this.tryPair(t,e)}pairRemoteCandidate=t=>{for(let e of this.protocols)this.tryPair(e,t)};buildRequest({nominate:t,remoteUsername:e,localUsername:r,iceControlling:s}){let n=ite({remoteUsername:e,localUsername:r}),i=new wn(1,0);return i.setAttribute("USERNAME",n).setAttribute("PRIORITY",Rm("prflx")),s?(i.setAttribute("ICE-CONTROLLING",this.tieBreaker),t&&i.setAttribute("USE-CANDIDATE",null)):i.setAttribute("ICE-CONTROLLED",this.tieBreaker),i}respondError(t,e,r,s){let n=new wn(t.messageMethod,272,t.transactionId);n.setAttribute("ERROR-CODE",s).addMessageIntegrity(Buffer.from(this.localPassword,"utf8")).addFingerprint(),r.sendStun(n,e).catch(i=>{jt("sendStun error",i)})}},ite=({remoteUsername:t,localUsername:e})=>`${t}:${e}`,yU=t=>{let[e,r]=t.split(":");return{remoteUsername:e,localUsername:r}};yA=class extends vj.EventEmitter{addEventListener=(t,e)=>{this.addListener(t,e)};removeEventListener=(t,e)=>{this.removeListener(t,e)}},ote=ft("werift:packages/webrtc/src/dataChannel.ts");bA=class extends yA{constructor(t,e,r=!0){if(super(),this.sctp=t,this.parameters=e,this.sendOpen=r,this.id=this.parameters.id,e.negotiated){if(this.id==null||this.id<0||this.id>65534)throw new Error("ID must be in range 0-65534 if data channel is negotiated out-of-band");this.sctp.dataChannelAddNegotiated(this)}else r&&(this.sendOpen=!1,this.sctp.dataChannelOpen(this))}stateChange=new Ne;stateChanged=new Ne;onMessage=new Ne;error=new Ne;bufferedAmountLow=new Ne;onopen;onclose;onclosing;onmessage;onerror;isCreatedByRemote=!1;id;readyState="connecting";bufferedAmount=0;_bufferedAmountLowThreshold=0;messagesSent=0;bytesSent=0;messagesReceived=0;bytesReceived=0;get ordered(){return this.parameters.ordered}get maxRetransmits(){return this.parameters.maxRetransmits}get maxPacketLifeTime(){return this.parameters.maxPacketLifeTime}get label(){return this.parameters.label}get protocol(){return this.parameters.protocol}get negotiated(){return this.parameters.negotiated}get bufferedAmountLowThreshold(){return this._bufferedAmountLowThreshold}set bufferedAmountLowThreshold(t){if(t<0||t>4294967295)throw new Error("bufferedAmountLowThreshold must be in range 0 - 4294967295");this._bufferedAmountLowThreshold=t}setId(t){this.id=t}setReadyState(t){if(t!==this.readyState){switch(this.readyState=t,this.stateChange.execute(t),this.stateChanged.execute(t),t){case"open":this.onopen&&this.onopen(),this.emit("open");break;case"closed":this.onclose&&this.onclose(),this.emit("close");break;case"closing":this.onclosing&&this.onclosing();break}ote("change state",t)}}addBufferedAmount(t){let e=this.bufferedAmount>this.bufferedAmountLowThreshold&&this.bufferedAmount+t<=this.bufferedAmountLowThreshold;this.bufferedAmount+=t,e&&(this.bufferedAmountLow.execute(),this.emit("bufferedamountlow"))}send(t){let e=this.sctp.datachannelSend(this,t);this.messagesSent++,this.bytesSent+=e}close(){this.sctp.dataChannelClose(this)}},xA=class{label="";maxPacketLifeTime;maxRetransmits;ordered=!0;protocol="";negotiated=!1;id;constructor(t={}){Object.assign(this,t)}},ate=()=>({type:"ccm",parameter:"fir"}),ig=()=>({type:"nack"}),Vh=()=>({type:"nack",parameter:"pli"}),og=()=>({type:"goog-remb"}),Sj=()=>({type:"transport-cc"}),yc=class{payloadType;mimeType;clockRate;channels;rtcpFeedback=[];parameters;direction="all";constructor(t){Object.assign(this,t)}get name(){return this.mimeType.split("/")[1]}get contentType(){return this.mimeType.split("/")[0]}get str(){let t=`${this.name}/${this.clockRate}`;return this.channels===2&&(t+="/2"),t}},Wi=class{id;uri;constructor(t){Object.assign(this,t)}},cte=class{cname;mux=!1;ssrc;constructor(t={}){Object.assign(this,t)}},Ej=class{type;parameter;constructor(t={}){Object.assign(this,t)}},Cj=class{ssrc;constructor(t={}){Object.assign(this,t)}},Tj=class{ssrc;payloadType;rtx;constructor(t){Object.assign(this,t)}},wA=class{rid;direction;constructor(t){Object.assign(this,t)}},kj=(t={})=>new yc({mimeType:"video/h264",clockRate:9e4,rtcpFeedback:[ig(),Vh(),og()],parameters:"profile-level-id=42e01f;packetization-mode=1;level-asymmetry-allowed=1",...t}),vA=(t={})=>new yc({mimeType:"video/VP8",clockRate:9e4,rtcpFeedback:[ig(),Vh(),og()],...t}),Aj=(t={})=>new yc({mimeType:"video/VP9",clockRate:9e4,rtcpFeedback:[ig(),Vh(),og()],...t}),Ij=(t={})=>new yc({mimeType:"video/AV1X",clockRate:9e4,rtcpFeedback:[ig(),Vh(),og()],...t}),_A=(t={})=>new yc({mimeType:"audio/OPUS",clockRate:48e3,channels:2,...t}),SA=(t={})=>new yc({mimeType:"audio/PCMU",clockRate:8e3,channels:1,payloadType:0,...t}),EA=[Ij(),Aj(),vA(),kj(),_A(),SA()].map(t=>t.mimeType),dte=EA.filter(t=>t.toLowerCase().startsWith("video/")),lte=EA.filter(t=>t.toLowerCase().startsWith("audio/"));xU=2,wU=3,xte=0,Aw=50,vU=51,_U=53,wte=56,vte=57,_te="0.0.0.0",SU=9,wk={auto:"actpass",client:"active",server:"passive"},EU=Object.keys(wk).reduce((t,e)=>{let r=wk[e];return t[r]=e,t},{}),Ste=["apt","max-fr","max-fs","maxplaybackrate","minptime","stereo","useinbandfec"],Lj=["cname","msid","mslabel","label"],CU={SRTP_AES128_CM_HMAC_SHA1_80:Hh,SRTP_AEAD_AES_128_GCM:_l},$w=["sendonly","sendrecv"],Ete=["sendrecv","recvonly"],Oj=class extends Map{constructor(t){if(super(),t)for(let e of t)this.set(e.id,e)}};Nj=class{constructor(t,e,r,s,n){this.kind=t,this.receiver=r,this.sender=s,this._direction=n,e&&this.setDtlsTransport(e)}id=(0,Bj.randomUUID)().toString();onTrack=new Ne;mid;mLineIndex;usedForSender=!1;_currentDirection;offerDirection;_codecs=[];set codecs(t){this._codecs=t}get codecs(){return this._codecs}headerExtensions=[];options={};stopping=!1;stopped=!1;get dtlsTransport(){return this.receiver.dtlsTransport}get direction(){return this._direction}setDirection(t){this._direction=t,$w.includes(this._currentDirection??"")&&(this.usedForSender=!0)}get currentDirection(){return this._currentDirection}setCurrentDirection(t){this._currentDirection=t}setDtlsTransport(t){this.receiver.setDtlsTransport(t),this.sender.setDtlsTransport(t)}get msid(){return`${this.sender.streamId} ${this.sender.trackId}`}addTrack(t){this.receiver.addTrack(t)&&this.onTrack.execute(t,this)}stop(){this.stopping||(this.stopping=!0)}getPayloadType(t){return this.codecs.find(e=>e.mimeType.toLowerCase().includes(t.toLowerCase()))?.payloadType}getCodecStats(){let t=bc(),e=[];if(!this.dtlsTransport)return e;let r=zt("transport",this.dtlsTransport.id);for(let s of this.codecs){let n={type:"codec",id:zt("codec",s.payloadType,r),timestamp:t,payloadType:s.payloadType,transportId:r,mimeType:s.mimeType,clockRate:s.clockRate,channels:s.channels,sdpFmtpLine:s.parameters};e.push(n)}return e}},Uj="inactive",CA="sendonly",TA="recvonly",kA="sendrecv",Fw=[Uj,CA,TA,kA],Km=class extends yA{uuid=(0,AA.randomUUID)().toString();streamId;remote=!1;label;kind;id;ssrc;rid;header;codec;enabled=!0;onReceiveRtp=new Ne;onReceiveRtcp=new Ne;onSourceChanged=new Ne;stopped=!1;muted=!0;constructor(t){super(),Object.assign(this,t),this.onReceiveRtp.subscribe(e=>{this.muted=!1,this.header=e.header}),this.label=`${this.remote?"remote":"local"} ${this.kind}`}stop=()=>{this.stopped=!0,this.muted=!0,this.onReceiveRtp.complete(),this.emit("ended")};writeRtp=t=>{if(this.remote)throw new Error("this is remoteTrack");if(this.stopped)return;let e=Buffer.isBuffer(t)?Jo.deSerialize(t):t;e.header.payloadType=this.codec?.payloadType??e.header.payloadType,this.onReceiveRtp.execute(e)}},Mj=class{id;tracks=[];constructor(t){Array.isArray(t)?this.tracks=t:Object.assign(this,t),this.id??=(0,AA.randomUUID)().toString()}addTrack(t){t.streamId=this.id,this.tracks.push(t)}getTracks(){return this.tracks}getAudioTracks(){return this.tracks.filter(t=>t.kind==="audio")}getVideoTracks(){return this.tracks.filter(t=>t.kind==="video")}},Cte=ft("werift:packages/webrtc/src/utils.ts");Tte={sha1:"sha1","sha-1":"sha1",sha224:"sha224","sha-224":"sha224",sha256:"sha256","sha-256":"sha256",sha384:"sha384","sha-384":"sha384",sha512:"sha512","sha-512":"sha512"};PA=(t,e)=>Fw[Fw.indexOf(t)&Fw.indexOf(e)];DA=Date.now,Ate=BigInt(Date.now())*1000n-process.hrtime.bigint()/1000n,Fj=()=>Ate+process.hrtime.bigint()/1000n,Gm=()=>Date.now()/1e3,Hj=()=>{let e=(xk.performance.timeOrigin+xk.performance.now()-Date.UTC(1900,0,1))/1e3,[r,s]=e.toString().split(".").map(Number);return nr([4,4],[r,s]).readBigUInt64BE()},BA=t=>{let e=nr([8],[t]),[,r,s]=bs(e,[2,2,2,2]);return nr([2,2],[r,s]).readUInt32BE()};Ite=Nm.createSelfSignedCertificateWithKey,Rte=class{static async rtpSource({port:t,kind:e,cb:r}){t??=await Gk();let s=new Km({kind:e}),n=(0,Dj.createSocket)("udp4");n.bind(t);let i=a=>{r&&(a=r(a)),s.writeRtp(a)};return n.addListener("message",i),[s,t,()=>{n.removeListener("message",i);try{n.close()}catch{}}]}},Vj=(t,e)=>{if(!t||typeof t!="object")return e!==null&&typeof e=="object"?e:t;if(!e||typeof e!="object")return e??t;for(let r in e)if(Object.prototype.hasOwnProperty.call(e,r)){let s=e[r];s!=null&&(t[r]=s)}return t},Pte=ft("werift:packages/webrtc/src/media/receiver/nack.ts"),TU=150,Dte=class{constructor(t){this.receiver=t}newEstSeqNum=0;_lost={};nackLoop;onPacketLost=new Ne;mediaSourceSsrc;retryCount=10;closed=!1;get lostSeqNumbers(){return Object.keys(this._lost).map(Number).sort()}getLost(t){return this._lost[t]}setLost(t,e){this._lost[t]=e,!(this.nackLoop||this.closed)&&(this.nackLoop=setInterval(async()=>{try{await this.sendNack(),Object.keys(this._lost).length||(clearInterval(this.nackLoop),this.nackLoop=void 0)}catch(r){Pte("failed to send nack",r)}},5))}removeLost(t){delete this._lost[t]}addPacket(t){let{sequenceNumber:e,ssrc:r}=t.header;if(this.mediaSourceSsrc=r,this.newEstSeqNum===0){this.newEstSeqNum=e;return}if(this.getLost(e)){this.removeLost(e);return}if(e===Jr(this.newEstSeqNum,1))this.newEstSeqNum=e;else if(e>Jr(this.newEstSeqNum,1)){for(let s=Jr(this.newEstSeqNum,1);s<e;s=Jr(s,1))this.setLost(s,1);this.newEstSeqNum=e,this.pruneLost()}}pruneLost(){this.lostSeqNumbers.length>TU&&(this._lost=Object.entries(this._lost).slice(-TU).reduce((t,[e,r])=>(t[e]=r,t),{}))}close(){this.closed=!0,clearInterval(this.nackLoop),this._lost={}}updateRetryCount(){this.lostSeqNumbers.forEach(t=>{if(this._lost[t]++>this.retryCount)return this.removeLost(t),t})}sendNack=()=>new Promise((t,e)=>{if(this.lostSeqNumbers.length>0&&this.mediaSourceSsrc){let r=new Hm({senderSsrc:this.receiver.rtcpSsrc,mediaSourceSsrc:this.mediaSourceSsrc,lost:this.lostSeqNumbers}),s=new yl({feedback:r});this.receiver.dtlsTransport.sendRtcp([s]).then(t).catch(e),this.updateRetryCount(),this.onPacketLost.execute(r)}})},Bte=ft("werift:packages/webrtc/media/receiver/receiverTwcc"),Lte=class{constructor(t,e,r){this.dtlsTransport=t,this.rtcpSsrc=e,this.mediaSourceSsrc=r,this.runTWCC()}extensionInfo={};twccRunning=!1;fbPktCount=0;lastTimestamp;handleTWCC(t){this.extensionInfo[t]={tsn:t,timestamp:Fj()},Object.keys(this.extensionInfo).length>10&&this.sendTWCC()}async runTWCC(){for(;this.twccRunning;)this.sendTWCC(),await(0,zj.setTimeout)(100)}sendTWCC(){if(Object.keys(this.extensionInfo).length===0)return;let t=Object.values(this.extensionInfo).sort((u,l)=>u.tsn-l.tsn),e=t[0].tsn,r=t.slice(-1)[0].tsn,s=[],n=t[0].tsn,i=Jr(r-e,1),o,a,c=[];for(let u=e;u<=r;u++){let l=this.extensionInfo[u]?.timestamp;if(l){this.lastTimestamp||(this.lastTimestamp=l),o||(o=this.lastTimestamp);let h=l-this.lastTimestamp;this.lastTimestamp=l;let p=new Im({delta:Number(h)});p.parseDelta(),c.push(p),a!=null&&a.status!==p.type&&(s.push(new Dh({packetStatus:a.status,runLength:u-a.minTSN})),a={minTSN:u,status:p.type}),u===r&&(a!=null?s.push(new Dh({packetStatus:a.status,runLength:u-a.minTSN+1})):s.push(new Dh({packetStatus:p.type,runLength:1}))),a==null&&(a={minTSN:u,status:p.type})}}if(!o)return;let d=new yl({feedback:new qm({senderSsrc:this.rtcpSsrc,mediaSourceSsrc:this.mediaSourceSsrc,baseSequenceNumber:n,packetStatusCount:i,referenceTime:XU(Math.floor(Number(o/1000n/64n))),fbPktCount:this.fbPktCount,recvDeltas:c,packetChunks:s})});this.dtlsTransport.sendRtcp([d]).catch(u=>{Bte(u)}),this.extensionInfo={},this.fbPktCount=GU(this.fbPktCount,1)}},Ote=class{base_seq;max_seq;cycles=0;packets_received=0;clockRate;jitter_q4=0;last_arrival;last_timestamp;expected_prior=0;received_prior=0;constructor(t){this.clockRate=t}add(t,e=Date.now()/1e3){let r=this.max_seq==null||h1(t.header.sequenceNumber,this.max_seq);if(this.packets_received++,this.base_seq==null&&(this.base_seq=t.header.sequenceNumber),r){let s=Rh(e*this.clockRate);if(this.max_seq!=null&&t.header.sequenceNumber<this.max_seq&&(this.cycles+=65536),this.max_seq=t.header.sequenceNumber,t.header.timestamp!==this.last_timestamp&&this.packets_received>1){let n=Math.abs(s-(this.last_arrival??0)-(t.header.timestamp-(this.last_timestamp??0)));this.jitter_q4+=n-(this.jitter_q4+8>>4)}this.last_arrival=s,this.last_timestamp=t.header.timestamp}}get fraction_lost(){let t=this.packets_expected-this.expected_prior;this.expected_prior=this.packets_expected;let e=this.packets_received-this.received_prior;this.received_prior=this.packets_received;let r=t-e;return t==0||r<=0?0:Math.floor((r<<8)/t)}get jitter(){return this.jitter_q4>>4}get packets_expected(){return this.cycles+(this.max_seq??0)-(this.base_seq??0)+1}get packets_lost(){let t=this.packets_expected-this.packets_received;return t<0?0:t}},qn=ft("werift:packages/webrtc/src/transport/dtls.ts"),vk=class Yj{constructor(e,r,s,n=[]){this.config=e,this.iceTransport=r,this.localCertificate=s,this.srtpProfiles=n,this.localCertificate??=Yj.localCertificate}id=(0,Gj.randomUUID)().toString();state="new";role="auto";srtpStarted=!1;transportSequenceNumber=0;bytesSent=0;bytesReceived=0;packetsSent=0;packetsReceived=0;dataReceiver=()=>{};dtls;srtp;srtcp;onStateChange=new Ne;onRtcp=new Ne;onRtp=new Ne;static localCertificate;static localCertificatePromise;remoteParameters;get localParameters(){return new a1(this.localCertificate?this.localCertificate.getFingerprints():[],this.role)}static async SetupCertificate(){return this.localCertificate?this.localCertificate:this.localCertificatePromise?this.localCertificatePromise:(this.localCertificatePromise=(async()=>{let{certPem:e,keyPem:r,signatureHash:s}=await Nm.createSelfSignedCertificateWithKey({signature:zi.ecdsa_3,hash:Om.sha256_4},Xo.secp256r1_23);return this.localCertificate=new LA(r,e,s),this.localCertificate})(),this.localCertificatePromise)}setRemoteParams(e){let r=Ute([...this.remoteParameters?.fingerprints??[],...e.fingerprints]),s=e.role==="auto"&&this.remoteParameters?.role?this.remoteParameters.role:e.role;this.remoteParameters=new a1(r,s)}async start(){if(this.state!=="new")throw new Error("state must be new");if(!this.remoteParameters||this.remoteParameters.fingerprints.length===0)throw new Error("remote fingerprint not exist");this.role==="auto"&&(this.iceTransport.role==="controlling"?this.role="server":this.role="client"),this.setState("connecting"),await new Promise(async(e,r)=>{this.role==="server"?this.dtls=new jM({cert:this.localCertificate?.certPem,key:this.localCertificate?.privateKey,signatureHash:this.localCertificate?.signatureHash,transport:kU(this.iceTransport.connection),srtpProfiles:this.srtpProfiles,extendedMasterSecret:!0,certificateRequest:!0}):this.dtls=new ik({cert:this.localCertificate?.certPem,key:this.localCertificate?.privateKey,signatureHash:this.localCertificate?.signatureHash,transport:kU(this.iceTransport.connection),srtpProfiles:this.srtpProfiles,extendedMasterSecret:!0}),this.dtls.onData.subscribe(s=>{this.config.debug.inboundPacketLoss&&this.config.debug.inboundPacketLoss/100<Math.random()||this.dataReceiver(s)}),this.dtls.onClose.subscribe(()=>{this.state!=="failed"&&this.setState("closed")}),this.dtls.onConnect.once(e),this.dtls.onError.once(s=>{this.setState("failed"),qn("dtls failed",s),r(s)}),this.dtls instanceof ik&&(await(0,Xj.setTimeout)(100),this.dtls.connect().catch(s=>{this.setState("failed"),qn("dtls connect failed",s),r(s)}))});try{this.verifyRemoteCertificateFingerprint()}catch(e){throw this.setState("failed"),this.dtls?.close(),e}this.srtpProfiles.length>0&&this.startSrtp(),this.setState("connected"),qn("dtls connected")}verifyRemoteCertificateFingerprint(){if(!this.remoteParameters||this.remoteParameters.fingerprints.length===0)throw new Error("remote fingerprint not exist");let e=this.dtls?.remoteCertificate;if(!e)throw new Error("remote certificate not available");let r=this.remoteParameters.fingerprints.flatMap(({algorithm:a,value:c})=>{let d=RA(a);if(!d)return[];let u=i1(c);if(!u)throw new Error("remote fingerprint value is empty");return[{normalizedAlgorithm:d,normalizedValue:u}]});if(r.length===0)throw new Error("no supported remote fingerprint algorithms");let s=jte(r),n=r.filter(({normalizedAlgorithm:a})=>a===s),i=n.reduce((a,{normalizedAlgorithm:c})=>(a.has(c)||a.set(c,i1(IA(e,c))),a),new Map);if(!n.some(({normalizedAlgorithm:a,normalizedValue:c})=>i.get(a)===c))throw new Error("remote certificate fingerprint mismatch")}updateSrtpSession(){if(!this.dtls)throw new Error;let e=this.dtls.srtp.srtpProfile;if(!e)throw new Error("need srtpProfile");qn("selected SRTP Profile",e);let{localKey:r,localSalt:s,remoteKey:n,remoteSalt:i}=this.dtls.extractSessionKeys(B7(e),L7(e)),o={keys:{localMasterKey:r,localMasterSalt:s,remoteMasterKey:n,remoteMasterSalt:i},profile:e};this.srtp=new OM(o),this.srtcp=new LM(o)}startSrtp(){this.srtpStarted||(this.srtpStarted=!0,this.updateSrtpSession(),this.iceTransport.connection.onData.subscribe(e=>{if(!(this.config.debug.inboundPacketLoss&&this.config.debug.inboundPacketLoss/100<Math.random())&&X7(e))if(this.bytesReceived+=e.length,this.packetsReceived++,dM(e)){let r;try{r=this.srtcp.decrypt(e)}catch(n){if(n instanceof xl){qn("dropping invalid SRTCP packet",n);return}throw n}let s;try{s=cM.deSerialize(r)}catch(n){qn("dropping malformed SRTCP packet",n);return}for(let n of s)try{this.onRtcp.execute(n)}catch(i){qn("RTCP error",i)}}else{let r;try{r=this.srtp.decrypt(e)}catch(n){if(n instanceof xl){qn("dropping invalid SRTP packet",n);return}throw n}let s;try{s=Jo.deSerialize(r)}catch(n){qn("dropping malformed SRTP packet",n);return}try{this.onRtp.execute(s)}catch(n){qn("RTP error",n)}}}))}sendData=async e=>{if(!(this.config.debug.outboundPacketLoss&&this.config.debug.outboundPacketLoss/100<Math.random())){if(!this.dtls)throw new Error("dtls not established");await this.dtls.send(e)}};async sendRtp(e,r){try{let s=this.srtp.encrypt(e,r);return this.config.debug.outboundPacketLoss&&this.config.debug.outboundPacketLoss/100<Math.random()||(this.bytesSent+=s.length,this.packetsSent++,await this.iceTransport.connection.send(s).catch(()=>{})),s.length}catch(s){return qn("failed to send",s),0}}async sendRtcp(e){let r=Buffer.concat(e.map(n=>n.serialize())),s=this.srtcp.encrypt(r);if(this.config.debug.outboundPacketLoss&&this.config.debug.outboundPacketLoss/100<Math.random())return s.length;this.bytesSent+=s.length,this.packetsSent++,await this.iceTransport.connection.send(s).catch(()=>{})}setState(e){e!=this.state&&(this.state=e,this.onStateChange.execute(e))}async stop(){this.setState("closed"),await this.iceTransport.stop()}async getStats(){let e=bc(),r=[],n={type:"transport",id:zt("transport",this.id),timestamp:e,bytesSent:this.bytesSent,bytesReceived:this.bytesReceived,packetsSent:this.packetsSent,packetsReceived:this.packetsReceived,dtlsState:this.state,iceState:this.iceTransport.state,selectedCandidatePairId:this.iceTransport.connection.nominated?zt("candidate-pair",this.iceTransport.connection.nominated.localCandidate.foundation,this.iceTransport.connection.nominated.remoteCandidate.foundation):void 0,localCertificateId:this.localCertificate?zt("certificate","local"):void 0,remoteCertificateId:this.remoteParameters?zt("certificate","remote"):void 0,dtlsRole:this.role==="auto"?void 0:this.role};if(r.push(n),this.localCertificate){let o=this.localCertificate.getFingerprints();if(o.length>0){let a={type:"certificate",id:zt("certificate","local"),timestamp:e,fingerprint:o[0].value,fingerprintAlgorithm:o[0].algorithm,base64Certificate:Buffer.from(this.localCertificate.certPem).toString("base64")};r.push(a)}}if(this.remoteParameters&&this.remoteParameters.fingerprints.length>0){let o={type:"certificate",id:zt("certificate","remote"),timestamp:e,fingerprint:this.remoteParameters.fingerprints[0].value,fingerprintAlgorithm:this.remoteParameters.fingerprints[0].algorithm,base64Certificate:""};r.push(o)}let i=await this.iceTransport.getStats();return r.push(...i),r}},Nte=["new","connecting","connected","closed","failed"],LA=class{constructor(t,e,r){this.certPem=e,this.signatureHash=r;let s=Xm.Certificate.fromPEM(Buffer.from(e));this.publicKey=s.publicKey.toPEM(),this.privateKey=Xm.PrivateKey.fromPEM(Buffer.from(t)).toPEM()}publicKey;privateKey;getFingerprints(){return[new o1("sha-256",IA(Xm.Certificate.fromPEM(Buffer.from(this.certPem)).raw,"sha256"))]}},o1=class{constructor(t,e){this.algorithm=t,this.value=e}},a1=class{constructor(t=[],e){this.fingerprints=t,this.role=e}},Ute=t=>{let e=new Set;return t.filter(({algorithm:r,value:s})=>{let n=`${RA(r)??r.trim().toLowerCase()}:${i1(s)}`;return e.has(n)?!1:(e.add(n),!0)})},Mte=["sha512","sha384","sha256","sha224","sha1"],jte=t=>Mte.find(e=>t.some(({normalizedAlgorithm:r})=>r===e))??t[0].normalizedAlgorithm,$te=class{constructor(t){this.ice=t,t.onData.subscribe(e=>{jj(e)&&this.onData&&this.onData(e)})}closed=!1;onData=()=>{};get address(){return{}}type="ice";send=t=>this.ice.send(t);async close(){this.closed=!0,this.ice.close()}},kU=t=>new $te(t),AU=ft("werift:packages/webrtc/src/transport/ice.ts"),Qj=class{constructor(t){this.iceGather=t,this.connection=this.iceGather.connection,this.connection.stateChanged.subscribe(e=>{this.setState(e)}),this.iceGather.onIceCandidate=e=>{this.onIceCandidate.execute(e)}}id=(0,Jj.randomUUID)().toString();connection;state="new";waitStart;renominating=!1;onStateChange=new Ne;onIceCandidate=new Ne;onNegotiationNeeded=new Ne;get role(){return this.connection.iceControlling?"controlling":"controlled"}get gatheringState(){return this.iceGather.gatheringState}get localCandidates(){return this.iceGather.localCandidates}get localParameters(){return this.iceGather.localParameters}setState(t){t!==this.state&&(this.state=t,this.onStateChange.execute(t))}gather(){return this.iceGather.gather()}addRemoteCandidate=t=>{if(!this.connection.remoteCandidatesEnd)return t?this.connection.addRemoteCandidate(e$(t)):this.connection.addRemoteCandidate(void 0)};setRemoteParams(t,e=!1){e&&(this.renominating=!0),this.connection.remoteUsername&&this.connection.remotePassword&&(this.connection.remoteUsername!==t.usernameFragment||this.connection.remotePassword!==t.password)&&(this.renominating?(AU("renomination",t),this.connection.resetNominatedPair(),this.renominating=!1):(AU("restart",t),this.restart())),this.connection.setRemoteParams(t)}restart(){this.connection.restart(),this.setState("new"),this.iceGather.gatheringState="new",this.waitStart=void 0,this.onNegotiationNeeded.execute()}async start(){if(this.state==="closed")throw new Error("RTCIceTransport is closed");if(!this.connection.remotePassword||!this.connection.remoteUsername)throw new Error("remoteParams missing");this.waitStart&&await this.waitStart.asPromise(),this.waitStart=new Ne,this.setState("checking");try{await this.connection.connect()}catch(t){throw this.setState("failed"),t}this.waitStart.execute(),this.waitStart.complete(),this.waitStart=void 0}async stop(){this.state!=="closed"&&(this.setState("closed"),await this.connection.close()),this.onStateChange.complete(),this.onIceCandidate.complete(),this.onNegotiationNeeded.complete()}async getStats(){let t=bc(),e=[];for(let s of this.localCandidates){let n={type:"local-candidate",id:zt("local-candidate",s.foundation),timestamp:t,transportId:zt("transport",this.id),address:s.ip,port:s.port,protocol:s.protocol,candidateType:s.type,priority:s.priority,foundation:s.foundation};e.push(n)}for(let s of this.connection.remoteCandidates){let n=jh(s),i={type:"remote-candidate",id:zt("remote-candidate",n.foundation),timestamp:t,transportId:zt("transport",this.id),address:n.ip,port:n.port,protocol:n.protocol,candidateType:n.type,priority:n.priority,foundation:n.foundation};e.push(i)}let r=this.connection?.candidatePairs?[...this.connection.candidatePairs.filter(s=>s.nominated),...this.connection.candidatePairs.filter(s=>!s.nominated)]:[];for(let s of r){let n={type:"candidate-pair",id:zt("candidate-pair",s.foundation),timestamp:t,transportId:zt("transport",this.id),localCandidateId:zt("local-candidate",s.localCandidate.foundation),remoteCandidateId:zt("remote-candidate",s.remoteCandidate.foundation),state:s.state,nominated:s.nominated,packetsSent:s.packetsSent,packetsReceived:s.packetsReceived,bytesSent:s.bytesSent,bytesReceived:s.bytesReceived,currentRoundTripTime:s.rtt};e.push(n)}return e}},Fte=["new","checking","connected","completed","disconnected","failed","closed"],Hte=["new","gathering","complete"],Zj=class{constructor(t={}){this.options=t,this.connection=new wj(!1,this.options),this.connection.onIceCandidate.subscribe(e=>{this.onIceCandidate(jh(e))})}onIceCandidate=()=>{};gatheringState="new";connection;onGatheringStateChange=new Ne;async gather(){this.gatheringState==="new"&&(this.setState("gathering"),await this.connection.gatherCandidates(),this.onIceCandidate(void 0),this.setState("complete"))}get localCandidates(){return this.connection.localCandidates.map(jh)}get localParameters(){return new NA({usernameFragment:this.connection.localUsername,password:this.connection.localPassword})}setState(t){t!==this.gatheringState&&(this.gatheringState=t,this.onGatheringStateChange.execute(t))}};t$=class{candidate;sdpMid;sdpMLineIndex;usernameFragment;constructor(t){Object.assign(this,t)}static fromSdp(t){let e=gc.fromSdp(t);return jh(e).toJSON()}static isThis(t){if(typeof t?.candidate=="string")return!0}toJSON(){return{candidate:this.candidate,sdpMid:this.sdpMid,sdpMLineIndex:this.sdpMLineIndex,usernameFragment:this.usernameFragment}}},OA=class{constructor(t,e,r,s,n,i,o,a,c){this.component=t,this.foundation=e,this.ip=r,this.port=s,this.priority=n,this.protocol=i,this.type=o,this.generation=a,this.ufrag=c}relatedAddress;relatedPort;sdpMid;sdpMLineIndex;tcpType;toJSON(){return new t$({candidate:jA(this),sdpMLineIndex:this.sdpMLineIndex,sdpMid:this.sdpMid,usernameFragment:this.ufrag})}static fromJSON(t){try{if(!t.candidate)throw new Error("candidate is required");let e=$A(t.candidate);return e.sdpMLineIndex=t.sdpMLineIndex??void 0,e.sdpMid=t.sdpMid??void 0,e}catch{}}},NA=class{iceLite=!1;usernameFragment;password;constructor(t={}){Object.assign(this,t)}},Ki=class s${constructor(e=0,r=Buffer.from("")){this.flags=e,this._body=r}get body(){return this._body}set body(e){this._body=e}static type=-1;get type(){return s$.type}get bytes(){if(!this.body)throw new Error;let e=Buffer.alloc(4);return e.writeUInt8(this.type,0),e.writeUInt8(this.flags,1),e.writeUInt16BE(this.body.length+4,2),Buffer.concat([e,this.body,...[...Array(cg(this.body.length))].map(()=>Buffer.from("\0"))])}},UA=class extends Ki{constructor(t=0,e){super(t,e),this.flags=t,e?(this.initiateTag=e.readUInt32BE(0),this.advertisedRwnd=e.readUInt32BE(4),this.outboundStreams=e.readUInt16BE(8),this.inboundStreams=e.readUInt16BE(10),this.initialTsn=e.readUInt32BE(12),this.params=E$(e.slice(16))):(this.initiateTag=0,this.advertisedRwnd=0,this.outboundStreams=0,this.inboundStreams=0,this.initialTsn=0,this.params=[])}initiateTag;advertisedRwnd;outboundStreams;inboundStreams;initialTsn;params;get body(){let t=Buffer.alloc(16);return t.writeUInt32BE(this.initiateTag,0),t.writeUInt32BE(this.advertisedRwnd,4),t.writeUInt16BE(this.outboundStreams,8),t.writeUInt16BE(this.inboundStreams,10),t.writeUInt32BE(this.initialTsn,12),Buffer.concat([t,S$(this.params)])}},Vw=class n$ extends UA{static type=1;get type(){return n$.type}},_k=class i$ extends UA{static type=2;get type(){return i$.type}},qte=class o$ extends UA{static type=130;get type(){return o$.type}},zw=class a$ extends Ki{constructor(e=0,r){if(super(e,r),this.flags=e,r){this.cumulativeTsn=r.readUInt32BE(0);let s=4;for(;s<r.length;)this.streams.push([r.readUInt16BE(s),r.readUInt16BE(s+2)]),s+=4}else this.cumulativeTsn=0}static type=192;streams=[];cumulativeTsn;get type(){return a$.type}set body(e){}get body(){let e=Buffer.alloc(4);return e.writeUInt32BE(this.cumulativeTsn,0),Buffer.concat([e,...this.streams.map(([r,s])=>{let n=Buffer.alloc(4);return n.writeUInt16BE(r,0),n.writeUInt16BE(s,2),n})])}},Ww=class c$ extends Ki{constructor(e=0,r){super(e,r),this.flags=e,r&&(this.tsn=r.readUInt32BE(0),this.streamId=r.readUInt16BE(4),this.streamSeqNum=r.readUInt16BE(6),this.protocol=r.readUInt32BE(8),this.userData=r.slice(12))}static type=0;get type(){return c$.type}tsn=0;streamId=0;streamSeqNum=0;protocol=0;userData=Buffer.from("");abandoned=!1;acked=!1;misses=0;retransmit=!1;sentCount=0;bookSize=0;expiry;maxRetransmits;sentTime;get bytes(){let e=16+this.userData.length,r=Buffer.alloc(16);r.writeUInt8(this.type,0),r.writeUInt8(this.flags,1),r.writeUInt16BE(e,2),r.writeUInt32BE(this.tsn,4),r.writeUInt16BE(this.streamId,8),r.writeUInt16BE(this.streamSeqNum,10),r.writeUInt32BE(this.protocol,12);let s=Buffer.concat([r,this.userData]);return e%4&&(s=Buffer.concat([s,...[...Array(cg(e))].map(()=>Buffer.from("\0"))])),s}},Sk=class d$ extends Ki{static type=10;get type(){return d$.type}},Ek=class l$ extends Ki{static type=11;get type(){return l$.type}},ag=class extends Ki{constructor(t=0,e=void 0){super(t,e),this.flags=t,e&&(this.params=E$(e))}params=[];get body(){return S$(this.params)}},Ck=class u$ extends ag{static type=6;get type(){return u$.type}},Kw=class Tk extends ag{static type=9;static CODE={InvalidStreamIdentifier:1,MissingMandatoryParameter:2,StaleCookieError:3,OutofResource:4,UnresolvableAddress:5,UnrecognizedChunkType:6,InvalidMandatoryParameter:7,UnrecognizedParameters:8,NoUserData:9,CookieReceivedWhileShuttingDown:10,RestartofanAssociationwithNewAddresses:11,UserInitiatedAbort:12,ProtocolViolation:13};get type(){return Tk.type}get descriptions(){return this.params.map(([e,r])=>({name:(Object.entries(Tk.CODE).find(([,n])=>n===e)||[])[0],body:r}))}},kk=class h$ extends ag{static type=4;get type(){return h$.type}},f$=class p$ extends ag{static type=5;get type(){return p$.type}},Ak=class m$ extends ag{static type=130;get type(){return m$.type}},Ik=class g$ extends Ki{constructor(e=0,r){if(super(e,r),this.flags=e,r){this.cumulativeTsn=r.readUInt32BE(0),this.advertisedRwnd=r.readUInt32BE(4);let s=r.readUInt16BE(8),n=r.readUInt16BE(10),i=12;[...Array(s)].forEach(()=>{this.gaps.push([r.readUInt16BE(i),r.readUInt16BE(i+2)]),i+=4}),[...Array(n)].forEach(()=>{this.duplicates.push(r.readUInt32BE(i)),i+=4})}}static type=3;get type(){return g$.type}gaps=[];duplicates=[];cumulativeTsn=0;advertisedRwnd=0;get bytes(){let e=16+4*(this.gaps.length+this.duplicates.length),r=Buffer.alloc(16);r.writeUInt8(this.type,0),r.writeUInt8(this.flags,1),r.writeUInt16BE(e,2),r.writeUInt32BE(this.cumulativeTsn,4),r.writeUInt32BE(this.advertisedRwnd,8),r.writeUInt16BE(this.gaps.length,12),r.writeUInt16BE(this.duplicates.length,14);let s=Buffer.concat([r,...this.gaps.map(n=>{let i=Buffer.alloc(4);return i.writeUInt16BE(n[0],0),i.writeUInt16BE(n[1],2),i})]);return s=Buffer.concat([s,...this.duplicates.map(n=>{let i=Buffer.alloc(4);return i.writeUInt32BE(n,0),i})]),s}},y$=class b$ extends Ki{constructor(e=0,r){super(e,r),this.flags=e,r&&(this.cumulativeTsn=r.readUInt32BE(0))}static type=7;get type(){return b$.type}cumulativeTsn=0;get body(){let e=Buffer.alloc(4);return e.writeUInt32BE(this.cumulativeTsn,0),e}},x$=class w$ extends Ki{static type=8;get type(){return w$.type}},v$=class _$ extends Ki{static type=14;get type(){return _$.type}},Vte=[Ww,Vw,_k,Ik,kk,f$,Ck,y$,x$,Kw,Sk,Ek,v$,Ak,zw],zte=Vte.reduce((t,e)=>(t[e.type]=e,t),{});Rk=class Pk{constructor(e,r,s,n){this.requestSequence=e,this.responseSequence=r,this.lastTsn=s,this.streams=n}static type=13;get type(){return Pk.type}get bytes(){let e=Buffer.from(Ko.jspack.Pack("!LLL",[this.requestSequence,this.responseSequence,this.lastTsn]));return Buffer.concat([e,...this.streams.map(r=>Buffer.from(Ko.jspack.Pack("!H",[r])))])}static parse(e){let[r,s,n]=Ko.jspack.Unpack("!LLL",e),i=[];for(let o=12;o<e.length;o+=2)i.push(Ko.jspack.Unpack("!H",e.slice(o))[0]);return new Pk(r,s,n,i)}},C$=class Dk{constructor(e,r){this.requestSequence=e,this.newStreams=r}static type=17;get type(){return Dk.type}get bytes(){return Buffer.from(Ko.jspack.Pack("!LHH",[this.requestSequence,this.newStreams,0]))}static parse(e){let[r,s]=Ko.jspack.Unpack("!LHH",e);return new Dk(r,s)}},Iw={ReconfigResultSuccessPerformed:1,BadSequenceNumber:5},Gw=class Bk{constructor(e,r){this.responseSequence=e,this.result=r}static type=16;get type(){return Bk.type}get bytes(){return Buffer.from(Ko.jspack.Pack("!LL",[this.responseSequence,this.result]))}static parse(e){let[r,s]=Ko.jspack.Unpack("!LL",e);return new Bk(r,s)}},IU={13:Rk,16:Gw,17:C$},Nt=ft("werift/sctp/sctp"),Yte=24,Jte=60,RU=65535,Vn=1200,km=1,T$=2,Lk=4,PU=10,Qte=8,DU=1/8,BU=1/4,LU=3,Zte=1,ere=60,c1=2**32,tre=200,rre=30,OU=135,NU=7,UU=32776,MU=49152,sre=["new","closed","connected","connecting"],nre=class Ok{constructor(e,r=5e3){this.transport=e,this.port=r,this.localPort=this.port,this.transport.onData=s=>{this.handleData(s)}}flush=new Ne;stateChanged=Xte(sre);onReconfigStreams=new Ne;onReceive=new Ne;onSackReceived=async()=>{};associationState=1;started=!1;state="new";isServer=!0;isStopping=!1;isClosed=!1;hmacKey=(0,Ym.randomBytes)(16);localPartialReliability=!0;localPort;localVerificationTag=Yw();remoteExtensions=[];remotePartialReliability=!0;remotePort;remoteVerificationTag=0;advertisedRwnd=1024*1024;peerAdvertisedRwnd=this.advertisedRwnd;get peerRwnd(){return Math.max(0,this.peerAdvertisedRwnd-this.flightSize)}inboundStreams={};_inboundStreamsCount=0;_inboundStreamsMax=RU;lastReceivedTsn;sackDuplicates=[];sackMisOrdered=new Set;sackNeeded=!1;sackPacketCount=0;sackHasNewDataInPacket=!1;sackImmediate=!1;sackTimeout;cwnd=3*Vn;fastRecoveryExit;fastRecoveryTransmit=!1;forwardTsnChunk;flightSize=0;outboundQueue=[];outboundStreamSeq={};_outboundStreamsCount=RU;localTsn=Number(Yw());lastSackedTsn=dl(this.localTsn);advancedPeerAckTsn=dl(this.localTsn);partialBytesAcked=0;sentQueue=[];transmitting=!1;transmitRequested=!1;reconfigRequestSeq=this.localTsn;reconfigResponseSeq=0;reconfigRequest;reconfigQueue=[];srtt;rttvar;rto=LU;timer1Handle;timer1Chunk;timer1Failures=0;timer2Handle;timer2Chunk;timer2Failures=0;timer3Handle;timerReconfigHandle;timerReconfigFailures=0;timerHeartbeatHandle;heartbeatInterval=rre;ssthresh;get isStopped(){return this.isStopping||this.isClosed}get maxChannels(){if(this._inboundStreamsCount>0)return Math.min(this._inboundStreamsCount,this._outboundStreamsCount)}static client(e,r=5e3){let s=new Ok(e,r);return s.isServer=!1,s}static server(e,r=5e3){let s=new Ok(e,r);return s.isServer=!0,s}async handleData(e){if(this.isStopped)return;let r,[,,s,n]=Wte(e);if(n.filter(o=>o.type===Vw.type).length>0){if(n.length!=1)throw new Error;r=0}else r=this.localVerificationTag;if(s===r){this.sackHasNewDataInPacket=!1;for(let o of n)await this.receiveChunk(o);this.sackNeeded&&(this.sackHasNewDataInPacket&&this.sackPacketCount++,this.sackPacketCount>=2&&(this.sackImmediate=!0),await this.scheduleSack())}}async scheduleSack(){if(!this.isStopped&&this.sackNeeded){if(this.sackImmediate){this.sackTimeout&&(clearTimeout(this.sackTimeout),this.sackTimeout=void 0),await this.sendSack();return}this.sackTimeout||(this.sackTimeout=setTimeout(()=>{this.sackTimeout=void 0,this.sendSack().catch(e=>{Nt("send delayed sack failed",e.message)})},tre))}}async sendSack(){if(this.isStopped||!this.sackNeeded)return;let e=[],r;[...this.sackMisOrdered].sort().forEach(n=>{let i=(n-this.lastReceivedTsn)%c1;n===r?e[e.length-1][1]=i:e.push([i,i]),r=kh(n)});let s=new Ik(0,void 0);s.cumulativeTsn=this.lastReceivedTsn,s.advertisedRwnd=Math.max(0,this.advertisedRwnd),s.duplicates=[...this.sackDuplicates],s.gaps=e,await this.sendChunk(s).catch(n=>{Nt("send sack failed",n.message)}),this.sackDuplicates=[],this.sackNeeded=!1,this.sackPacketCount=0,this.sackImmediate=!1}async receiveChunk(e){switch(e.type){case Ww.type:this.receiveDataChunk(e);break;case Vw.type:{if(!this.isServer)return;let r=e;Nt("receive init",r),this.lastReceivedTsn=dl(r.initialTsn),this.reconfigResponseSeq=dl(r.initialTsn),this.remoteVerificationTag=r.initiateTag,this.ssthresh=r.advertisedRwnd,this.peerAdvertisedRwnd=r.advertisedRwnd,this.getExtensions(r.params),this._inboundStreamsCount=Math.min(r.outboundStreams,this._inboundStreamsMax),this._outboundStreamsCount=Math.min(this._outboundStreamsCount,r.inboundStreams);let s=new _k;s.initiateTag=this.localVerificationTag,s.advertisedRwnd=this.advertisedRwnd,s.outboundStreams=this._outboundStreamsCount,s.inboundStreams=this._inboundStreamsCount,s.initialTsn=this.localTsn,this.setExtensions(s.params);let n=Date.now()/1e3,i=Buffer.from(qw.jspack.Pack("!L",[n]));i=Buffer.concat([i,(0,Ym.createHmac)("sha1",this.hmacKey).update(i).digest()]),s.params.push([NU,i]),Nt("send initAck",s),await this.sendChunk(s).catch(o=>{Nt("send initAck failed",o.message)})}break;case _k.type:{if(this.associationState!=2)return;let r=e;this.timer1Cancel(),this.lastReceivedTsn=dl(r.initialTsn),this.reconfigResponseSeq=dl(r.initialTsn),this.remoteVerificationTag=r.initiateTag,this.ssthresh=r.advertisedRwnd,this.peerAdvertisedRwnd=r.advertisedRwnd,this.getExtensions(r.params),this._inboundStreamsCount=Math.min(r.outboundStreams,this._inboundStreamsMax),this._outboundStreamsCount=Math.min(this._outboundStreamsCount,r.inboundStreams);let s=new Sk;for(let[n,i]of r.params)if(n===NU){s.body=i;break}await this.sendChunk(s).catch(n=>{Nt("send echo failed",n.message)}),this.timer1Start(s),this.setState(3)}break;case Ik.type:await this.receiveSackChunk(e);break;case kk.type:{let r=new f$;r.params=e.params,await this.sendChunk(r).catch(s=>{Nt("send heartbeat ack failed",s.message)})}break;case Ck.type:this.setState(1);break;case y$.type:{this.timer2Cancel(),this.setState(7);let r=new x$;await this.sendChunk(r).catch(s=>{Nt("send shutdown ack failed",s.message)}),this.t2Start(r),this.setState(6)}break;case Kw.type:Nt("ErrorChunk",e.descriptions);break;case Sk.type:{if(!this.isServer)return;let s=e.body,n=(0,Ym.createHmac)("sha1",this.hmacKey).update(s.slice(0,4)).digest();if(s?.length!=Yte||!s.slice(4).equals(n)){Nt("x State cookie is invalid");return}let i=Date.now()/1e3,o=qw.jspack.Unpack("!L",s)[0];if(o<i-Jte||o>i){let c=new Kw(0,void 0);c.params.push([Kw.CODE.StaleCookieError,Buffer.concat([...Array(8)].map(()=>Buffer.from("\0")))]),await this.sendChunk(c).catch(d=>{Nt("send errorChunk failed",d.message)});return}let a=new Ek;await this.sendChunk(a).catch(c=>{Nt("send cookieAck failed",c.message)}),this.setState(4)}break;case Ek.type:{if(this.associationState!=3)return;this.timer1Cancel(),this.setState(4)}break;case v$.type:{if(this.associationState!=8)return;this.timer2Cancel(),this.setState(1)}break;case Ak.type:{if(this.associationState!=4)return;let r=e;for(let[s,n]of r.params){let i=IU[s];i&&await this.receiveReconfigParam(i.parse(n))}}break;case zw.type:this.receiveForwardTsnChunk(e);break}}getExtensions(e){for(let[r,s]of e)r===MU?this.remotePartialReliability=!0:r===UU&&(this.remoteExtensions=[...s])}async receiveReconfigParam(e){switch(Nt("receiveReconfigParam",IU[e.type]),e.type){case Rk.type:{let r=e,s=new Gw(r.requestSequence,Iw.ReconfigResultSuccessPerformed);this.reconfigResponseSeq=r.requestSequence,await this.sendReconfigParam(s),await Promise.all(r.streams.map(async n=>{delete this.inboundStreams[n],this.outboundStreamSeq[n]&&(this.reconfigQueue.includes(n)||this.reconfigQueue.push(n))})),await this.transmitReconfigRequest(),this.onReconfigStreams.execute(r.streams)}break;case Gw.type:{let r=e;if(r.result!==Iw.ReconfigResultSuccessPerformed)Nt("OutgoingSSNResetRequestParam failed",Object.keys(Iw).find(s=>Iw[s]===r.result));else if(r.responseSequence===this.reconfigRequest?.requestSequence){let s=this.reconfigRequest.streams.map(n=>(delete this.outboundStreamSeq[n],n));this.onReconfigStreams.execute(s),this.reconfigRequest=void 0,this.timerReconfigCancel(),this.rto=LU,this.timerReconfigFailures=0,this.reconfigQueue.length>0&&await this.transmitReconfigRequest()}}break;case C$.type:{let r=e;this._inboundStreamsCount+=r.newStreams;let s=new Gw(r.requestSequence,1);this.reconfigResponseSeq=r.requestSequence,await this.sendReconfigParam(s)}break}}receiveDataChunk(e){if(this.sackNeeded=!0,this.markReceived(e.tsn)){this.sackImmediate=!0;return}this.sackHasNewDataInPacket=!0,this.sackImmediate=!0,(e.flags&km)===0&&(this.sackImmediate=!0),this.sackMisOrdered.size>0&&(this.sackImmediate=!0);let r=this.getInboundStream(e.streamId);r.addChunk(e),this.advertisedRwnd-=e.userData.length;for(let s of r.popMessages())this.advertisedRwnd+=s[2].length,this.receive(...s)}async receiveSackChunk(e){if(Hi(this.lastSackedTsn,e.cumulativeTsn))return;let r=Date.now()/1e3;this.lastSackedTsn=e.cumulativeTsn;let s=this.flightSize>=this.cwnd,n=0,i=0;for(;this.sentQueue.length>0&&Ah(this.lastSackedTsn,this.sentQueue[0].tsn);){let a=this.sentQueue.shift();n++,a?.acked||(i+=a.bookSize,this.flightSizeDecrease(a)),n===1&&a.sentCount===1&&this.updateRto(r-a.sentTime)}this.sentQueue.length||(this.sentQueue=[]);let o=!1;if(e.gaps.length>0){let a=new Set,c;e.gaps.forEach(u=>{for(let l=u[0];l<u[1]+1;l++)c=(e.cumulativeTsn+l)%c1,a.add(c)});let d=e.cumulativeTsn;for(let u of this.sentQueue){if(Hi(u.tsn,c))break;a.has(u.tsn)&&!u.acked&&(i+=u.bookSize,u.acked=!0,this.flightSizeDecrease(u),d=u.tsn)}for(let u of this.sentQueue){if(Hi(u.tsn,d))break;a.has(u.tsn)||(u.misses++,u.misses===3&&(u.misses=0,this.maybeAbandon(u)||(u.retransmit=!0),u.acked=!1,this.flightSizeDecrease(u),o=!0))}}this.fastRecoveryExit===void 0?(n&&s&&(this.cwnd<=this.ssthresh?this.cwnd+=Math.min(i,Vn):(this.partialBytesAcked+=i,this.partialBytesAcked>=this.cwnd&&(this.partialBytesAcked-=this.cwnd,this.cwnd+=Vn))),o&&(this.ssthresh=Math.max(Math.floor(this.cwnd/2),4*Vn),this.cwnd=this.ssthresh,this.partialBytesAcked=0,this.fastRecoveryExit=this.sentQueue[this.sentQueue.length-1].tsn,this.fastRecoveryTransmit=!0)):Ah(e.cumulativeTsn,this.fastRecoveryExit)&&(this.fastRecoveryExit=void 0),this.sentQueue.length===0?this.timer3Cancel():n>0&&this.timer3Restart(),this.peerAdvertisedRwnd=e.advertisedRwnd,this.updateAdvancedPeerAckPoint(),await this.onSackReceived(),await this.transmit()}receiveForwardTsnChunk(e){if(this.sackNeeded=!0,this.sackImmediate=!0,Ah(this.lastReceivedTsn,e.cumulativeTsn))return;let r=s=>Hi(s,this.lastReceivedTsn);this.lastReceivedTsn=e.cumulativeTsn,this.sackMisOrdered=new Set([...this.sackMisOrdered].filter(r));for(let s of[...this.sackMisOrdered].sort())if(s===kh(this.lastReceivedTsn))this.lastReceivedTsn=s;else break;this.sackDuplicates=this.sackDuplicates.filter(r),this.sackMisOrdered=new Set([...this.sackMisOrdered].filter(r));for(let[s,n]of e.streams){let i=this.getInboundStream(s);i.streamSequenceNumber=Jr(n,1);for(let o of i.popMessages())this.advertisedRwnd+=o[2].length,this.receive(...o)}Object.values(this.inboundStreams).forEach(s=>{this.advertisedRwnd+=s.pruneChunks(this.lastReceivedTsn)})}updateRto(e){this.srtt?(this.rttvar=(1-BU)*this.rttvar+BU*Math.abs(this.srtt-e),this.srtt=(1-DU)*this.srtt+DU*e):(this.rttvar=e/2,this.srtt=e),this.rto=Math.max(Zte,Math.min(this.srtt+4*this.rttvar,ere))}receive(e,r,s){this.onReceive.execute(e,r,s)}getInboundStream(e){return this.inboundStreams[e]||(this.inboundStreams[e]=new ire),this.inboundStreams[e]}markReceived(e){if(Ah(this.lastReceivedTsn,e)||this.sackMisOrdered.has(e))return this.sackDuplicates.push(e),!0;this.sackMisOrdered.add(e);for(let s of[...this.sackMisOrdered].sort())if(s===kh(this.lastReceivedTsn))this.lastReceivedTsn=s;else break;let r=s=>Hi(s,this.lastReceivedTsn);return this.sackDuplicates=this.sackDuplicates.filter(r),this.sackMisOrdered=new Set([...this.sackMisOrdered].filter(r)),!1}send=async(e,r,s,{expiry:n,maxRetransmits:i,ordered:o}={expiry:void 0,maxRetransmits:void 0,ordered:!0})=>{let a=o&&this.outboundStreamSeq[e]||0,c=Math.ceil(s.length/Vn),d=0,u=[];for(let l=0;l<c;l++){let h=new Ww(0,void 0);h.flags=0,o||(h.flags=Lk),l===0&&(h.flags|=T$),l===c-1&&(h.flags|=km),h.tsn=this.localTsn,h.streamId=e,h.streamSeqNum=a,h.protocol=r,h.userData=s.slice(d,d+Vn),h.bookSize=h.userData.length,h.expiry=n,h.maxRetransmits=i,d+=Vn,this.localTsn=kh(this.localTsn),u.push(h)}for(u.forEach(l=>{this.outboundQueue.push(l)}),o&&(this.outboundStreamSeq[e]=Jr(a,1)),await this.transmit();this.outboundQueue.length;)await this.flush.asPromise()};async transmit(){if(!this.isStopped){if(this.transmitting){this.transmitRequested=!0;return}this.transmitting=!0;try{do this.transmitRequested=!1,await this.transmitOnce();while(this.transmitRequested)}finally{this.transmitting=!1}}}async transmitOnce(){if(this.isStopped)return;this.forwardTsnChunk&&(await this.sendChunk(this.forwardTsnChunk).catch(n=>{Nt("send forwardTsn failed",n.message)}),this.forwardTsnChunk=void 0,this.timer3Handle||this.timer3Start());let e=this.fastRecoveryExit!=null?2*Vn:4*Vn,r=Math.min(this.flightSize+e,this.cwnd),s=!0;for(let n of this.sentQueue){if(n.retransmit){if(this.fastRecoveryTransmit)this.fastRecoveryTransmit=!1;else if(this.flightSize>=r)break;this.flightSizeIncrease(n),n.misses=0,n.retransmit=!1,n.sentCount++,await this.sendChunk(n).catch(i=>{Nt("send data failed",i.message)}),s&&this.timer3Restart()}s=!1}for(;this.outboundQueue.length>0&&this.flightSize<r&&this.peerRwnd>0;){let n=this.outboundQueue.shift();if(!n)break;if(n.bookSize>this.peerRwnd&&this.flightSize>0){this.outboundQueue.unshift(n);break}this.sentQueue.push(n),this.flightSizeIncrease(n),n.sentCount++,n.sentTime=Date.now()/1e3,await this.sendChunk(n).catch(i=>{Nt("send data outboundQueue failed",i.message)}),this.timer3Handle||this.timer3Start()}this.outboundQueue.length||(this.outboundQueue=[]),this.flush.execute()}async transmitReconfigRequest(){if(this.reconfigQueue.length>0&&this.associationState===4&&!this.reconfigRequest){let e=[...new Set(this.reconfigQueue)],r=e.slice(0,OU);this.reconfigQueue=e.slice(OU);let s=new Rk(this.reconfigRequestSeq,this.reconfigResponseSeq,dl(this.localTsn),r);this.reconfigRequestSeq=kh(this.reconfigRequestSeq),this.reconfigRequest=s,await this.sendReconfigParam(s),this.timerReconfigHandleStart()}}async sendReconfigParam(e){Nt("sendReconfigParam",e);let r=new Ak;r.params.push([e.type,e.bytes]),await this.sendChunk(r).catch(s=>{Nt("send reconfig failed",s.message)})}async sendResetRequest(e){Nt("sendResetRequest",e);let r=new Ww(0,void 0);r.streamId=e,this.outboundQueue.push(r),this.timer3Handle||await this.transmit()}flightSizeIncrease(e){this.flightSize+=e.bookSize}flightSizeDecrease(e){this.flightSize=Math.max(0,this.flightSize-e.bookSize)}timer1Start(e){if(this.timer1Handle)throw new Error;this.timer1Chunk=e,this.timer1Failures=0,this.timer1Handle=setTimeout(this.timer1Expired,this.rto*1e3)}timer1Expired=()=>{if(!this.isStopped)if(this.timer1Failures++,this.timer1Handle=void 0,this.timer1Failures>Qte)this.setState(1);else{if(setImmediate(()=>{this.isStopped||this.sendChunk(this.timer1Chunk).catch(e=>{Nt("send timer1 chunk failed",e.message)})}),this.isStopped)return;this.timer1Handle=setTimeout(this.timer1Expired,this.rto*1e3)}};timer1Cancel(){this.timer1Handle&&(clearTimeout(this.timer1Handle),this.timer1Handle=void 0,this.timer1Chunk=void 0)}t2Start(e){if(this.timer2Handle)throw new Error;this.timer2Chunk=e,this.timer2Failures=0,this.timer2Handle=setTimeout(this.timer2Expired,this.rto*1e3)}timer2Expired=()=>{if(!this.isStopped)if(this.timer2Failures++,this.timer2Handle=void 0,this.timer2Failures>PU)this.setState(1);else{if(setImmediate(()=>{this.isStopped||this.sendChunk(this.timer2Chunk).catch(e=>{Nt("send timer2Chunk failed",e.message)})}),this.isStopped)return;this.timer2Handle=setTimeout(this.timer2Expired,this.rto*1e3)}};timer2Cancel(){this.timer2Handle&&(clearTimeout(this.timer2Handle),this.timer2Handle=void 0,this.timer2Chunk=void 0)}timer3Start(){if(!this.isStopped){if(this.timer3Handle)throw new Error;this.timer3Handle=setTimeout(this.timer3Expired,this.rto*1e3)}}timer3Restart(){this.isStopped||(this.timer3Cancel(),this.timer3Handle=setTimeout(this.timer3Expired,this.rto*1e3))}timer3Expired=()=>{this.isStopped||(this.timer3Handle=void 0,this.sentQueue.forEach(e=>{this.maybeAbandon(e)||(e.retransmit=!0)}),this.updateAdvancedPeerAckPoint(),this.fastRecoveryExit=void 0,this.flightSize=0,this.partialBytesAcked=0,this.ssthresh=Math.max(Math.floor(this.cwnd/2),4*Vn),this.cwnd=Vn,this.transmit())};timer3Cancel(){this.timer3Handle&&(clearTimeout(this.timer3Handle),this.timer3Handle=void 0)}timerReconfigHandleStart(){this.isStopped||this.timerReconfigHandle||(Nt("timerReconfigHandleStart",{rto:this.rto}),this.timerReconfigFailures=0,this.timerReconfigHandle=setTimeout(this.timerReconfigHandleExpired,this.rto*1e3))}timerReconfigHandleExpired=async()=>{if(!this.isStopped){if(this.timerReconfigFailures++,this.rto=Math.ceil(this.rto*1.5),this.timerReconfigFailures>PU)Nt("timerReconfigFailures",this.timerReconfigFailures),this.setState(1),this.timerReconfigHandle=void 0;else if(this.reconfigRequest){if(Nt("timerReconfigHandleExpired",this.timerReconfigFailures,this.rto),await this.sendReconfigParam(this.reconfigRequest),this.isStopped)return;this.timerReconfigHandle=setTimeout(this.timerReconfigHandleExpired,this.rto*1e3)}}};timerReconfigCancel(){this.timerReconfigHandle&&(Nt("timerReconfigCancel"),clearTimeout(this.timerReconfigHandle),this.timerReconfigHandle=void 0,this.timerReconfigFailures=0)}heartbeatStart(){this.timerHeartbeatHandle||this.associationState!==4||(this.timerHeartbeatHandle=setTimeout(this.timerHeartbeatExpired,(this.rto+this.heartbeatInterval)*1e3))}heartbeatRestart(){this.heartbeatCancel(),this.heartbeatStart()}heartbeatCancel(){this.timerHeartbeatHandle&&(clearTimeout(this.timerHeartbeatHandle),this.timerHeartbeatHandle=void 0)}timerHeartbeatExpired=async()=>{if(this.timerHeartbeatHandle=void 0,this.associationState===4){if(this.flightSize===0&&this.outboundQueue.length===0){let e=new kk;e.params.push([1,Buffer.from(qw.jspack.Pack("!L",[Math.floor(Date.now()/1e3)]))]),await this.sendChunk(e).catch(r=>{Nt("send heartbeat failed",r.message)})}this.heartbeatStart()}};setHeartbeatInterval(e){if(e<=0)throw new Error("heartbeat interval must be > 0");this.heartbeatInterval=e,this.heartbeatRestart()}updateAdvancedPeerAckPoint(){Hi(this.lastSackedTsn,this.advancedPeerAckTsn)&&(this.advancedPeerAckTsn=this.lastSackedTsn);let e=0,r={};for(;this.sentQueue.length>0&&this.sentQueue[0].abandoned;){let s=this.sentQueue.shift();this.advancedPeerAckTsn=s.tsn,e++,s.flags&Lk||(r[s.streamId]=s.streamSeqNum)}this.sentQueue.length||(this.sentQueue=[]),e&&(this.forwardTsnChunk=new zw(0,void 0),this.forwardTsnChunk.cumulativeTsn=this.advancedPeerAckTsn,this.forwardTsnChunk.streams=Object.entries(r).map(([s,n])=>[Number(s),n]))}maybeAbandon(e){if(e.abandoned)return!0;if(!(!!e.maxRetransmits&&e.maxRetransmits<e.sentCount||!!e.expiry&&e.expiry<Date.now()/1e3))return!1;let s=this.sentQueue.findIndex(n=>n.type===e.type);for(let n=s;n>=0;n--){let i=this.sentQueue[n];if(i.abandoned=!0,i.retransmit=!1,i.flags&km)break}for(let n=s;n<this.sentQueue.length;n++){let i=this.sentQueue[n];if(i.abandoned=!0,i.retransmit=!1,i.flags&km)break}return!0}static getCapabilities(){return new ore(65536)}setRemotePort(e){this.remotePort=e}async start(e){this.started||(this.started=!0,this.setConnectionState("connecting"),e&&this.setRemotePort(e),this.isServer||await this.init())}async init(){let e=new Vw;e.initiateTag=this.localVerificationTag,e.advertisedRwnd=this.advertisedRwnd,e.outboundStreams=this._outboundStreamsCount,e.inboundStreams=this._inboundStreamsMax,e.initialTsn=this.localTsn,this.setExtensions(e.params),Nt("send init",e);try{await this.sendChunk(e),this.timer1Start(e),this.setState(2)}catch(r){Nt("send init failed",r.message)}}setExtensions(e){let r=[];this.localPartialReliability&&(e.push([MU,Buffer.from("")]),r.push(zw.type)),r.push(qte.type),e.push([UU,Buffer.from(r)])}async sendChunk(e){if(this.state==="closed")return;if(this.remotePort===void 0)throw new Error("invalid remote port");let r=Kte(this.localPort,this.remotePort,this.remoteVerificationTag,e);await this.transport.send(r)}setState(e){e!=this.associationState&&(this.associationState=e),e===4?(this.isStopping=!1,this.isClosed=!1,this.setConnectionState("connected"),this.heartbeatStart()):e===1&&(this.isClosed=!0,this.timer1Cancel(),this.timer2Cancel(),this.timer3Cancel(),this.timerReconfigCancel(),this.heartbeatCancel(),this.sackTimeout&&(clearTimeout(this.sackTimeout),this.sackTimeout=void 0),this.setConnectionState("closed"),this.removeAllListeners())}setConnectionState(e){this.state=e,Nt("setConnectionState",e),this.stateChanged[e].execute()}async stop(){if(this.isStopped){this.setState(1);return}this.isStopping=!0,this.transport.onData=void 0,this.sackTimeout&&(clearTimeout(this.sackTimeout),this.sackTimeout=void 0),this.associationState!==1&&await this.abort(),this.setState(1),clearTimeout(this.timer1Handle),clearTimeout(this.timer2Handle),clearTimeout(this.timer3Handle),clearTimeout(this.timerReconfigHandle),clearTimeout(this.timerHeartbeatHandle),clearTimeout(this.sackTimeout)}async abort(){let e=new Ck;await this.sendChunk(e).catch(r=>{Nt("send abort failed",r.message)})}removeAllListeners(){Object.values(this.stateChanged).forEach(e=>e.allUnsubscribe())}},ire=class{reassembly=[];streamSequenceNumber=0;constructor(){}addChunk(t){if(this.reassembly.length===0||Hi(t.tsn,this.reassembly[this.reassembly.length-1].tsn)){this.reassembly.push(t);return}for(let[e,r]of Gte(this.reassembly)){if(r.tsn===t.tsn)throw new Error("duplicate chunk in reassembly");if(Hi(r.tsn,t.tsn)){this.reassembly.splice(e,0,t);break}}}*popMessages(){let t=0,e,r,s;for(;t<this.reassembly.length;){let n=this.reassembly[t];if(e===void 0){if(s=!(n.flags&Lk),!(n.flags&T$)){if(s)break;t++;continue}if(s&&h1(n.streamSeqNum,this.streamSequenceNumber))break;r=n.tsn,e=t}else if(n.tsn!==r){if(s)break;e=void 0,t++;continue}if(n.flags&km){let i=this.reassembly.slice(e,t+1).map(a=>a.userData).reduce((a,c)=>(a.push(c),a.push(Buffer.from("")),a),[]);i.pop();let o=Buffer.concat(i);this.reassembly=[...this.reassembly.slice(0,e),...this.reassembly.slice(t+1)],s&&n.streamSeqNum===this.streamSequenceNumber&&(this.streamSequenceNumber=Jr(this.streamSequenceNumber,1)),t=e,yield[n.streamId,n.protocol,o]}else t++;r=kh(r)}}pruneChunks(t){let e=-1,r=0;for(let[s,n]of this.reassembly.entries())if(Ah(t,n.tsn))e=s,r+=n.userData.length;else break;return this.reassembly=this.reassembly.slice(e+1),r}},ore=class{constructor(t){this.maxMessageSize=t}};_h=ft("werift:packages/webrtc/src/transport/sctp.ts"),Ih=65536,k$=class A${constructor(e=5e3,r=Ih){this.port=e,this.maxMessageSize=r}dtlsTransport;sctp;onDataChannel=new Ne;id=(0,r$.randomUUID)().toString();mid;mLineIndex;bundled=!1;dataChannels={};remoteMaxMessageSize=Ih;dataChannelQueue=[];dataChannelId;eventDisposer=[];setDtlsTransport(e){this.dtlsTransport&&this.dtlsTransport.id===e.id||(this.eventDisposer.forEach(r=>r()),this.dtlsTransport=e,this.sctp=new nre(new are(this.dtlsTransport),this.port),this.eventDisposer=[...[this.sctp.onReceive.subscribe(this.datachannelReceive),this.sctp.onReconfigStreams.subscribe(r=>{r.forEach(s=>{let n=this.dataChannels[s];n&&(n.setReadyState("closing"),n.setReadyState("closed"),delete this.dataChannels[s])})}),this.sctp.stateChanged.connected.subscribe(()=>{Object.values(this.dataChannels).forEach(r=>{r.negotiated&&r.readyState!=="open"&&r.setReadyState("open")}),this.dataChannelFlush()}),this.sctp.stateChanged.closed.subscribe(()=>{Object.values(this.dataChannels).forEach(r=>{r.setReadyState("closed")}),this.dataChannels={}}),this.dtlsTransport.onStateChange.subscribe(r=>{r==="closed"&&this.sctp.setState(1)})].map(r=>r.unSubscribe),()=>this.sctp.onSackReceived=async()=>{}],this.sctp.onSackReceived=async()=>{await this.dataChannelFlush()})}get isServer(){return this.dtlsTransport.iceTransport.role!=="controlling"}channelByLabel(e){return Object.values(this.dataChannels).find(r=>r.label===e)}datachannelReceive=async(e,r,s)=>{if(r===Aw&&s.length>0)switch(_h("DCEP",e,r,s),s[0]){case wU:{if(s.length<12){_h("DATA_CHANNEL_OPEN data.length not enough");return}if(Object.keys(this.dataChannels).includes(e.toString()))_h("datachannel already opened","retransmit ack");else{let[,i,,o,a,c]=Hw.jspack.Unpack("!BBHLHH",s),d=12,u=s.slice(d,d+a).toString("utf8");d+=a;let l=s.slice(d,d+c).toString("utf8");_h("DATA_CHANNEL_OPEN",{channelType:i,reliability:o,streamId:e,label:u,protocol:l});let h=(i&3)===1?o:void 0,p=(i&3)===2?o:void 0,m=new xA({label:u,ordered:(i&128)===0,maxPacketLifeTime:p,maxRetransmits:h,protocol:l,id:e}),_=new bA(this,m,!1);_.isCreatedByRemote=!0,this.dataChannels[e]=_,this.onDataChannel.execute(_),_.setReadyState("open")}let n=this.dataChannels[e];this.dataChannelQueue.push([n,Aw,Buffer.from(Hw.jspack.Pack("!B",[xU]))]),await this.dataChannelFlush()}break;case xU:{_h("DATA_CHANNEL_ACK",e,r);let n=this.dataChannels[e];if(!n)throw new Error("channel not found");n.setReadyState("open")}break}else{let n=this.dataChannels[e];if(n){let i=(()=>{switch(r){case vU:return s.toString("utf8");case wte:return"";case _U:return s;case vte:return Buffer.from([]);default:throw new Error}})();n.messagesReceived++,n.bytesReceived+=s.length,n.onMessage.execute(i),n.emit("message",{data:i}),n.onmessage&&n.onmessage({data:i})}}};dataChannelAddNegotiated(e){if(e.id==null)throw new Error;if(this.dataChannels[e.id])throw new Error;this.dataChannels[e.id]=e,this.sctp.associationState===4&&e.setReadyState("open")}dataChannelOpen(e){if(e.id){if(this.dataChannels[e.id])throw new Error(`Data channel with ID ${e.id} already registered`);this.dataChannels[e.id]=e}let r=xte,s=0,n=0;e.ordered||(r=128),e.maxRetransmits?(r=1,n=e.maxRetransmits):e.maxPacketLifeTime&&(r=2,n=e.maxPacketLifeTime);let i=Hw.jspack.Pack("!BBHLHH",[wU,r,s,n,e.label.length,e.protocol.length]),o=Buffer.concat([Buffer.from(i),Buffer.from(e.label,"utf8"),Buffer.from(e.protocol,"utf8")]);this.dataChannelQueue.push([e,Aw,o]),this.dataChannelFlush()}async dataChannelFlush(){if(this.sctp.associationState==4){for(;this.dataChannelQueue.length>0;){let[e,r,s]=this.dataChannelQueue.shift(),n=e.id;if(n===void 0){for(n=this.dataChannelId;Object.keys(this.dataChannels).includes(n.toString());)n+=2;this.dataChannels[n]=e,e.setId(n)}if(r===Aw)await this.sctp.send(n,r,s,{ordered:!0});else{let i=e.maxPacketLifeTime?Date.now()+e.maxPacketLifeTime/1e3:void 0;await this.sctp.send(n,r,s,{expiry:i,maxRetransmits:e.maxRetransmits,ordered:e.ordered}),e.addBufferedAmount(-s.length)}}this.dataChannelQueue=[]}}assertSendableMessageSize(e){if(this.remoteMaxMessageSize!==0&&e>this.remoteMaxMessageSize)throw new Error(`max-message-size exceeded: ${e} > ${this.remoteMaxMessageSize}`)}datachannelSend=(e,r)=>{let s=Buffer.isBuffer(r)?r:Buffer.from(r),n=_j(r);return this.assertSendableMessageSize(n),e.addBufferedAmount(n),this.dataChannelQueue.push(typeof r=="string"?[e,vU,s]:[e,_U,s]),this.sctp.associationState!==4&&_h("sctp not established",this.sctp.associationState),this.dataChannelFlush(),n};getCapabilities(){return A$.getCapabilities(this.maxMessageSize)}static getCapabilities(e=Ih){return new MA(e)}setRemoteMaxMessageSize(e){this.remoteMaxMessageSize=e??Ih}setRemotePort(e){this.sctp.setRemotePort(e)}async start(e){this.isServer?this.dataChannelId=0:this.dataChannelId=1,this.sctp.isServer=this.isServer,await this.sctp.start(e)}async stop(){this.dtlsTransport.dataReceiver=()=>{},await this.sctp.stop()}dataChannelClose(e){["closing","closed"].includes(e.readyState)||(e.setReadyState("closing"),this.sctp.associationState===4?(this.sctp.reconfigQueue.includes(e.id)||this.sctp.reconfigQueue.push(e.id),this.sctp.reconfigQueue.length===1&&this.sctp.transmitReconfigRequest()):(this.dataChannelQueue=this.dataChannelQueue.filter(r=>r[0].id!==e.id),this.sctp.reconfigQueue=this.sctp.reconfigQueue.filter(r=>r!==e.id),e.id&&delete this.dataChannels[e.id],e.setReadyState("closed")))}},MA=class{constructor(t){this.maxMessageSize=t}},are=class{constructor(t){this.dtls=t}set onData(t){this.dtls.dataReceiver=t}send=t=>this.dtls.sendData(t);close(){}},Pm=class I${version=0;origin;name="-";time="0 0";host;group=[];extMapAllowMixed=!0;msidSemantic=[];media=[];type;dtlsRole;iceOptions;iceLite;icePassword;iceUsernameFragment;dtlsFingerprints=[];static parse(e){let[r,s]=cre(e),n=new I$;r.forEach(o=>{if(o.startsWith("v="))n.version=Number.parseInt(o.slice(2),10);else if(o.startsWith("o="))n.origin=o.slice(2);else if(o.startsWith("s="))n.name=o.slice(2);else if(o.startsWith("c="))n.host=RT(o.slice(2));else if(o.startsWith("t="))n.time=o.slice(2);else if(o.startsWith("a=")){let[a,c]=PT(o);switch(a){case"fingerprint":{let[d,u]=c?.split(" ")||[];n.dtlsFingerprints.push(new o1(d,u))}break;case"ice-lite":n.iceLite=!0;break;case"ice-options":n.iceOptions=c;break;case"ice-pwd":n.icePassword=c;break;case"ice-ufrag":n.iceUsernameFragment=c;break;case"group":Xw(n.group,c);break;case"msid-semantic":Xw(n.msidSemantic,c);break;case"setup":n.dtlsRole=EU[c];break;case"extmap-allow-mixed":n.extMapAllowMixed=!0;break}}});let i=n.group.find(o=>o.semantic==="BUNDLE");return s.forEach(o=>{let c=o[0].match(/^m=([^ ]+) ([0-9]+) ([A-Z/]+) (.+)/);if(!c)throw new Error("m line not found");let d=c[1],u=c[4].split(" "),l=["audio","video"].includes(d)?u.map(m=>Number(m)):void 0,h=new d1(d,Number.parseInt(c[2]),c[3],l||u);if(h.dtlsParams=new a1([...n.dtlsFingerprints],n.dtlsRole),h.iceParams=new NA({iceLite:n.iceLite,usernameFragment:n.iceUsernameFragment,password:n.icePassword}),h.iceOptions=n.iceOptions,n.media.push(h),o.slice(1).forEach(m=>{if(m.startsWith("c="))h.host=RT(m.slice(2));else if(m.startsWith("a=")){let[_,f]=PT(m);switch(_){case"candidate":if(!f)throw new Error;h.iceCandidates.push($A(f));break;case"end-of-candidates":h.iceCandidatesComplete=!0;break;case"extmap":{let[b,w]=f.split(" ");b.includes("/")&&([b]=b.split("/")),h.rtp.headerExtensions.push(new Wi({id:Number.parseInt(b),uri:w}))}break;case"fingerprint":{if(!f)throw new Error;let[b,w]=f.split(" ");h.dtlsParams?.fingerprints.push(new o1(b,w))}break;case"ice-options":h.iceOptions=f;break;case"ice-pwd":h.iceParams.password=f;break;case"ice-ufrag":h.iceParams.usernameFragment=f;break;case"ice-lite":h.iceParams.iceLite=!0;break;case"max-message-size":h.sctpCapabilities=new MA(Number.parseInt(f,10));break;case"mid":h.rtp.muxId=f;break;case"msid":h.msid=f;break;case"rtcp":{let[b,w]=Vo(f," ");h.rtcpPort=Number.parseInt(b),h.rtcpHost=RT(w)}break;case"rtcp-mux":h.rtcpMux=!0;break;case"setup":h.dtlsParams.role=EU[f];break;case"recvonly":case"sendonly":case"sendrecv":case"inactive":h.direction=_;break;case"rtpmap":{let[b,w]=Vo(f," "),[S,O,j]=w.split("/"),P;h.kind==="audio"&&(P=j?Number.parseInt(j):1);let k=new yc({mimeType:h.kind+"/"+S,channels:P,clockRate:Number.parseInt(O),payloadType:Number.parseInt(b)});h.rtp.codecs.push(k)}break;case"sctpmap":{if(!f)throw new Error;let[b,w]=Vo(f," ");h.sctpMap[Number.parseInt(b)]=w,h.sctpPort=Number.parseInt(b)}break;case"sctp-port":if(!f)throw new Error;h.sctpPort=Number.parseInt(f);break;case"ssrc":{let[b,w]=Vo(f," "),S=Number.parseInt(b),[O,j]=Vo(w,":"),P=h.ssrc.find(k=>k.ssrc===S);P||(P=new l1({ssrc:S}),h.ssrc.push(P)),Lj.includes(O)&&(P[O]=j)}break;case"ssrc-group":Xw(h.ssrcGroup,f);break;case"rid":{let[b,w]=Vo(f," ");h.simulcastParameters.push(new wA({rid:b,direction:w}))}break}}}),(!h.iceParams.usernameFragment||!h.iceParams.password)&&h.rtp.muxId&&i&&i.items.includes(h.rtp.muxId))for(let m=0;m<i.items.length;m++){if(!i.items.includes(m.toString()))continue;let _=n.media[m];if(_.iceParams?.usernameFragment&&_.iceParams.password){h.iceParams={..._.iceParams};break}}h.dtlsParams.role||(h.dtlsParams=void 0);let p=m=>h.rtp.codecs.find(_=>_.payloadType===m);o.slice(1).forEach(m=>{if(m.startsWith("a=")){let[_,f]=PT(m);if(_==="fmtp"){let[b,w]=Vo(f," "),S=p(Number(b));S.parameters=w}else if(_==="rtcp-fb"){let[b,w,S]=f.split(" ");h.rtp.codecs.forEach(O=>{["*",O.payloadType.toString()].includes(b)&&O.rtcpFeedback.push(new Ej({type:w,parameter:S}))})}}})}),n}webrtcTrackId(e){if(e.msid?.includes(" ")){let r=e.msid.split(" ");for(let s of this.msidSemantic)if(s.semantic==="WMS"&&(s.items.includes(r[0])||s.items.includes("*")))return r[1]}}get string(){let e=[`v=${this.version}`,`o=${this.origin}`,`s=${this.name}`];this.host&&e.push(`c=${Nk(this.host)}`),e.push(`t=${this.time}`),this.group.forEach(n=>e.push(`a=group:${n.str}`)),this.extMapAllowMixed&&e.push("a=extmap-allow-mixed"),this.msidSemantic.forEach(n=>e.push(`a=msid-semantic:${n.str}`));let r=this.media.map(n=>n.toString()).join("");return e.join(`\r
|
|
136
|
+
`)),s.forEach(n=>{n.startsWith("m=")?r.push([n]):r.length>0?r[r.length-1].push(n):e.push(n)}),[e,r]}function PT(t){if(t.includes(":")){let e=Vo(t.slice(2),":");return[e[0],e[1]]}else return[t.slice(2),void 0]}function Xw(t,e,r=s=>s.toString()){let s=e.split(" ");s.length>0&&t.push(new Bh(s[0],s.slice(1).map(r)))}function $A(t){let e=gc.fromSdp(t);return jh(e)}function Uk(t,e){let s=new Sw((0,Wj.randomBytes)(64)).toString().slice(0,8),n=0;e.origin=`- ${s} ${n} IN IP4 0.0.0.0`,e.msidSemantic.push(new Bh("WMS",["*"])),e.type=t}function J0(t){let e={};return t.split(";").forEach(r=>{if(r.includes("=")){let[s,n]=Vo(r,"=");Ste.includes(s)?e[s]=Number(n):e[s]=n}else if(r.includes(":")){let[s,n]=r.split(":");e[s]=Number.isNaN(Number(n))?n:Number(n)}else e[r]=void 0}),e}function dre(t,e="="){let r=Object.entries(t).map(([s,n])=>n?`${s}${e}${n}`:s);if(r.length>0)return r.join(";")}function O$(){return{codecs:{audio:[_A(),SA()],video:[vA()]},headerExtensions:{audio:[],video:[]},iceTransportPolicy:"all",iceServers:[{urls:"stun:stun.l.google.com:19302"}],icePortRange:void 0,iceInterfaceAddresses:void 0,iceAdditionalHostAddresses:void 0,iceUseIpv4:!0,iceUseIpv6:!0,iceFilterStunResponse:void 0,iceFilterCandidatePair:void 0,icePasswordPrefix:void 0,iceUseLinkLocalAddress:void 0,dtls:{},bundlePolicy:"max-compat",debug:{},midSuffix:!1,forceTurnTCP:!1,maxMessageSize:Ih}}var qk,Vk,Kk,JU,ZU,e7,t7,$h,p1,Ph,m1,a7,c7,Yr,Kn,m7,y7,hl,x7,Wo,y1,S7,pl,pc,ml,Fh,mc,gl,Gn,Xn,w1,Wn,P7,O7,nA,Bw,Lw,Yn,Uh,wl,ll,UM,Vi,qi,vl,MM,hA,fA,W0,QM,ck,ZM,oj,lk,cj,uk,hk,Mw,dj,lj,gj,yj,vj,Rj,jw,Pj,Dj,xk,Bj,AA,zj,Wj,Kj,X0,Gj,Xj,Jj,r$,Hw,Y0,qw,Ko,Mk,jk,$k,Fk,B$,D0,u1,SZ,EZ,fc,TZ,kZ,BT,AZ,LT,IZ,Rh,PZ,f1,BZ,ft,Ne,QU,jN,Jw,s7,zi,O0,Qw,i7,Xo,Xk,Yk,OT,o7,Jk,LZ,OZ,Go,$Z,NT,N0,U0,Qk,p7,vn,Zw,FZ,g7,HZ,M0,qZ,VZ,UT,zZ,WZ,KZ,GZ,Zk,fl,b7,XZ,w7,v7,Z0,jT,YZ,vT,eg,JZ,QZ,ZZ,g1,tg,rg,sg,iee,oee,Er,a0,c0,FN,HN,qN,VN,zN,b1,x1,Lh,e1,C7,T7,k7,FT,A7,I7,R7,D7,Hh,_l,cee,B7,L7,dee,qT,U7,$7,lee,F7,lc,uee,hee,fee,q7,z7,K7,pee,gee,bee,t1,Qo,WN,$0,F0,xee,Oh,Nh,v1,J7,H0,wee,q0,Dh,Z7,I0,tM,rM,sM,vee,yl,V0,eA,tA,bl,rA,aM,_ee,cM,Qt,Eee,sA,tk,SM,Cee,EM,uc,GN,XN,YN,JN,QN,Yo,Jo,AM,xl,ZN,Tee,kee,eU,Aee,_T,rU,DM,d0,nU,Iee,Ree,BM,LM,Pee,OM,Dee,ys,Bee,qh,NM,Lee,iU,Oee,sk,nk,oU,aU,ST,Nee,Uee,cU,dU,oA,ET,ik,Fi,Mee,lU,jee,Mh,$ee,ng,vh,jM,_1,$M,FM,zo,aA,cA,dA,HM,qM,Fee,lA,uA,uU,ok,pA,u0,h0,Vee,zee,hU,fU,CT,TT,kT,AT,Wee,Kee,WM,KM,pU,Gee,wn,mA,XM,YM,Yee,IT,gA,mU,r1,Ls,Jee,Qee,Zee,ej,rj,gc,ete,tte,fk,pk,T0,uj,mk,hj,fj,rte,nte,jt,wj,ite,yU,yA,ote,bA,xA,ate,ig,Vh,og,Sj,yc,Wi,cte,Ej,Cj,Tj,wA,kj,vA,Aj,Ij,_A,SA,EA,dte,lte,xU,wU,xte,Aw,vU,_U,wte,vte,_te,SU,wk,EU,Ste,Lj,CU,$w,Ete,Oj,Nj,Uj,CA,TA,kA,Fw,K0,Mj,Cte,Tte,PA,DA,Ate,Fj,G0,Hj,BA,Ite,Rte,Vj,Pte,TU,Dte,Bte,Lte,Ote,qn,vk,Nte,LA,o1,a1,Ute,Mte,jte,$te,kU,AU,Qj,Fte,Hte,Zj,t$,OA,NA,Ki,UA,Vw,_k,qte,zw,Ww,Sk,Ek,ag,Ck,Kw,kk,f$,Ak,Ik,y$,x$,v$,Vte,zte,Rk,C$,Iw,Gw,IU,Nt,Yte,Jte,RU,Vn,k0,T$,Lk,PU,Qte,DU,BU,LU,Zte,ere,c1,tre,rre,OU,NU,UU,MU,sre,nre,ire,ore,_h,Ih,k$,MA,are,P0,d1,Bh,R$,l1,Rw,FA,f0,P$,lre,Sh,ure,hre,DT,jU,$U,D$,fre,pre,L$,p0,mre,gre,zn,yre,Hk,bre,xre,N$,wre,vre,M$=V(()=>{"use strict";g();y();qk=require("crypto"),Vk=Le(ma(),1),Kk=require("dgram"),JU=Le(g8(),1),ZU=require("dgram"),e7=Le(require("net"),1),t7=require("net"),$h=require("crypto"),p1=Le(AS(),1);T9();Ph=Le(sr(),1),m1=require("crypto"),a7=Le(sr(),1),c7=Le(eb(),1);dN();Yr=Le(sr(),1),Kn=Le(sr(),1),m7=Le(sr(),1),y7=require("crypto"),hl=Le(sr(),1),x7=require("timers/promises"),Wo=Le(sr(),1),y1=require("crypto"),S7=Le(eb(),1),pl=Le(sr(),1),pc=Le(sr(),1),ml=Le(sr(),1),Fh=Le(sr(),1),mc=Le(sr(),1),gl=Le(sr(),1),Gn=Le(sr(),1),Xn=Le(sr(),1),w1=Le(sr(),1),Wn=Le(sr(),1),P7=Le(sr(),1),O7=Le(uN(),1),nA=Le(ma(),1),Bw=require("crypto"),Lw=Le(fN(),1),Yn=require("crypto"),Uh=require("crypto"),wl=Le(sr(),1),ll=Le(sr(),1),UM=require("timers/promises"),Vi=Le(sr(),1),qi=Le(sr(),1),vl=Le(sr(),1),MM=require("crypto"),hA=require("crypto"),fA=require("crypto");Ew();W0=Le(cT(),1),QM=require("crypto"),ck=Le(ma(),1),ZM=require("timers/promises"),oj=require("crypto"),lk=require("net"),cj=require("crypto"),uk=require("net");Ew();hk=Le(require("timers/promises"),1),Mw=Le(vN(),1),dj=Le(MN(),1),lj=require("crypto"),gj=Le(require("os"),1),yj=Le(cT(),1),vj=require("events"),Rj=require("crypto"),jw=require("timers/promises"),Pj=require("crypto"),Dj=require("dgram"),xk=require("perf_hooks"),Bj=require("crypto"),AA=require("crypto"),zj=require("timers/promises"),Wj=require("crypto"),Kj=require("net");Ew();X0=Le(AS(),1),Gj=require("crypto"),Xj=require("timers/promises"),Jj=require("crypto"),r$=require("crypto"),Hw=Le(ma(),1),Y0=require("crypto"),qw=Le(ma(),1),Ko=Le(ma(),1),Mk=require("crypto"),jk=Le(ma(),1),$k=require("crypto"),Fk=require("timers/promises"),B$=require("crypto");D0=class{constructor(t){this.bitLength=t}value=0;set(t,e,r){return r&=(1<<t)-1,this.value|=r<<this.bitLength-t-e,this}get buffer(){let t=Math.ceil(this.bitLength/8),e=Buffer.alloc(t);return e.writeUIntBE(this.value,0,t),e}},u1=class{constructor(t){if(this.bitLength=t,t>32)throw new Error}_value=0n;offset=0n;set(t,e=1){let r=BigInt(t),s=BigInt(e);return r&=(1n<<s)-1n,this._value|=r<<BigInt(this.bitLength)-s-this.offset,this.offset+=s,this}get value(){return Number(this._value)}get buffer(){let t=Math.ceil(this.bitLength/8),e=Buffer.alloc(t);return e.writeUIntBE(this.value,0,t),e}};SZ=class{buffer;constructor(t){this.buffer=Buffer.alloc(t)}writeInt16BE(t,e){return this.buffer.writeInt16BE(t,e),this}writeUInt8(t,e){return this.buffer.writeUInt8(t,e),this}},EZ=t=>"0x"+t.toString("hex").replace(/(.)(.)/g,"$1$2 ").split(" ").filter(e=>e!=null&&e.length>0).join(",0x");fc=class{constructor(t){this.uint8Array=t}position=0;bitsPending=0;writeBits(t,e){if(t==0)return this;e&=4294967295>>>32-t;let r;return this.bitsPending>0?this.bitsPending>t?(this.uint8Array[this.position-1]|=e<<this.bitsPending-t,r=t,this.bitsPending-=t):this.bitsPending==t?(this.uint8Array[this.position-1]|=e,r=t,this.bitsPending=0):(this.uint8Array[this.position-1]|=e>>t-this.bitsPending,r=this.bitsPending,this.bitsPending=0):(r=Math.min(8,t),this.bitsPending=8-r,this.uint8Array[this.position++]=e>>t-r<<this.bitsPending),t-=r,t>0&&this.writeBits(t,e),this}readBits(t){return this._readBits(t)}_readBits(t,e){if(typeof e>"u"&&(e=0),t==0)return e;let r,s;if(this.bitsPending>0){let n=this.uint8Array[this.position-1]&255>>8-this.bitsPending;s=Math.min(this.bitsPending,t),this.bitsPending-=s,r=n>>this.bitsPending}else s=Math.min(8,t),this.bitsPending=8-s,r=this.uint8Array[this.position++]>>this.bitsPending;return t-=s,e=e<<s|r,t>0?this._readBits(t,e):e}seekTo(t){this.position=t/8|0,this.bitsPending=t%8,this.bitsPending>0&&(this.bitsPending=8-this.bitsPending,this.position++)}},TZ=3988292384,kZ=2197175160;BT=qU(TZ),AZ=VU(BT),LT=qU(kZ),IZ=VU(LT);Rh=t=>Number.parseInt(t,10),PZ=class{queue=[];running=!1;push=t=>new Promise((e,r)=>{this.queue.push({promise:t,done:e,failed:r}),this.running||this.run()});async run(){let t=this.queue.shift();if(t){this.running=!0;try{let e=await t.promise();t.done(e)}catch(e){t.failed(e)}this.run()}else this.running=!1}cancel(){this.queue=[]}},f1=(t,e)=>e?e[t]:void 0;BZ=class extends Error{message;payload;path;constructor(t){super(t.message)}toJSON(){return{message:this.message,payload:JSON.parse(JSON.stringify(this.payload)),path:this.path}}},ft=JU.default.debug,Ne=class{event={stack:[],promiseStack:[],eventId:0};ended=!1;onended;onerror=t=>{};execute=(...t)=>{if(!this.ended){for(let e of this.event.stack)e.execute(...t);(async()=>{for(let e of this.event.promiseStack)await e.execute(...t)})().catch(e=>{this.onerror(e)})}};complete=()=>{if(!this.ended){for(let t of this.event.stack)t.complete&&t.complete();this.allUnsubscribe(),this.ended=!0,this.onended&&(this.onended(),this.onended=void 0)}};error=t=>{if(!this.ended){for(let e of this.event.stack)e.error&&e.error(t);this.allUnsubscribe()}};allUnsubscribe=()=>{if(this.ended)throw new Error("event completed");this.event={stack:[],promiseStack:[],eventId:0}};subscribe=(t,e,r)=>{let s=this.event.eventId;this.event.stack.push({execute:t,id:s,complete:e,error:r}),this.event.eventId++;let n=()=>{this.event.stack=this.event.stack.filter(o=>o.id!==s&&o)};return{unSubscribe:n,disposer:o=>{o.push(n)}}};pipe(t){this.subscribe((...e)=>{t.execute(...e)})}queuingSubscribe=(t,e,r)=>{if(this.ended)throw new Error("event completed");let s=this.event.eventId;this.event.promiseStack.push({execute:t,id:s,complete:e,error:r}),this.event.eventId++;let n=()=>{this.event.stack=this.event.stack.filter(o=>o.id!==s&&o)};return{unSubscribe:n,disposer:o=>{o.push(n)}}};once=(t,e,r)=>{let s=this.subscribe((...n)=>{s.unSubscribe(),t(...n)},e,r)};watch=(t,e)=>new Promise((r,s)=>{let n=e&&setTimeout(()=>{s("Event watch timeout")},e),{unSubscribe:i}=this.subscribe((...o)=>{t(...o)&&(n&&clearTimeout(n),i(),r(o))})});asPromise=t=>new Promise((e,r)=>{let s=t&&setTimeout(()=>{r("Event asPromise timeout")},t);this.once((...n)=>{s&&clearTimeout(s),e(n)},()=>{s&&clearTimeout(s),e([])},n=>{s&&clearTimeout(s),r(n)})});get returnTrigger(){let{execute:t,error:e,complete:r}=this;return{execute:t,error:e,complete:r}}get returnListener(){let{subscribe:t,once:e,asPromise:r}=this;return{subscribe:t,once:e,asPromise:r}}get length(){return this.event.stack.length}},QU=class{_disposer=[];push(t){this._disposer.push(t)}dispose(){this._disposer.forEach(t=>t()),this._disposer=[]}},jN=ft("werift-ice:packages/ice/src/transport.ts"),Jw=class r7{constructor(e,r={}){this.socketType=e,this.options=r,this.socket=(0,ZU.createSocket)(e),this.socket.on("message",(s,n)=>{L0(n.family)===6&&([n.address]=n.address.split("%")),this.rinfo=n;try{this.onData(s,[n.address,n.port])}catch(i){jN("onData error",i)}})}type="udp";socket;rinfo;onData=()=>{};closed=!1;static async init(e,r={}){let s=new r7(e,r);return await s.init(),s}async init(){let e=f1(this.socketType,this.options.interfaceAddresses);if(this.options.port)this.socket.bind({port:this.options.port,address:e});else if(this.options.portRange){let r=await YU(this.options.portRange[0],this.options.portRange[1],this.socketType,this.options.interfaceAddresses);this.socket.bind({port:r,address:e})}else this.socket.bind({address:e});await new Promise(r=>this.socket.once("listening",r))}send=async(e,r)=>{if(r&&!e7.isIP(r[0]))return new Promise((s,n)=>{this.socket.send(e,r[1],r[0],i=>{i?(jN("send error",r,e),n(i)):s()})});r=r??[this.rinfo?.address,this.rinfo?.port],this.socket.send(e,r[1],r[0])};get address(){return this.socket.address()}get host(){return this.socket.address().address}get port(){return this.socket.address().port}close=()=>new Promise(e=>{this.closed=!0,this.socket.once("close",e);try{this.socket.close()}catch{e()}})},s7=class n7{constructor(e){this.addr=e,this.connect()}type="tcp";connecting;client;onData=()=>{};closed=!1;connect(){this.closed||(this.client&&this.client.destroy(),this.connecting=new Promise((e,r)=>{try{this.client=(0,t7.connect)({port:this.addr[1],host:this.addr[0]},e)}catch(s){r(s)}}),this.client.on("data",e=>{let r=[this.client.remoteAddress,this.client.remotePort];this.onData(e,r)}),this.client.on("end",()=>{this.connect()}),this.client.on("error",e=>{E.log("error",e)}))}async init(){await this.connecting}static async init(e){let r=new n7(e);return await r.init(),r}get address(){return{}}send=async(e,r)=>{await this.connecting,this.client.write(e,s=>{s&&E.log("err",s)})};close=async()=>{this.closed=!0,this.client.destroy()}},zi={rsa_1:1,ecdsa_3:3},O0={sha256_4:4},Qw={TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256_49195:49195,TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256_49199:49199},i7=Object.values(Qw),Xo={x25519_29:29,secp256r1_23:23},Xk=Object.values(Xo),Yk={named_curve_3:3},OT={rsa_pkcs1_sha256:1025,ecdsa_secp256r1_sha256:1027},o7=[1,64],Jk=[{hash:O0.sha256_4,signature:zi.rsa_1},{hash:O0.sha256_4,signature:zi.ecdsa_3}],LZ=()=>{let t=ww.utils.randomPrivateKey(),e=ww.getPublicKey(t,!1),r=Buffer.from(t),s=Buffer.from(e);return{privateKey:r,publicKey:s}},OZ=({publicKey:t,privateKey:e})=>{let r=ww.getSharedSecret(e,t);return Buffer.from(r).subarray(1)};Go={CLIENT:1,SERVER:2},$Z=class{id=0;name;hashAlgorithm;verifyDataLength=12;blockAlgorithm;kx;init(...t){throw new Error("not implemented")}encrypt(...t){throw new Error("not implemented")}decrypt(...t){throw new Error("not implemented")}toString(){return this.name}},NT=$h.webcrypto;Sr.set(NT);N0=class{constructor(t,e,r,s){this.sessionType=t,this.certPem=e,this.keyPem=r,e&&r&&s&&this.parseX509(e,r,s)}localRandom;remoteRandom;cipherSuite;remoteCertificate;remoteKeyPair;localKeyPair;masterSecret;cipher;namedCurve;signatureHashAlgorithm;localCert;localPrivateKey;static createSelfSignedCertificateWithKey=async(t,e)=>{let r=(()=>{switch(t.signature){case zi.rsa_1:return"RSASSA-PKCS1-v1_5";case zi.ecdsa_3:return"ECDSA"}})(),s=(()=>{if(t.hash===O0.sha256_4)return"SHA-256"})(),n=(()=>{switch(e){case Xo.secp256r1_23:return"P-256";case Xo.x25519_29:return r==="ECDSA"?"P-256":"X25519";default:{if(r==="ECDSA")return"P-256";if(r==="RSASSA-PKCS1-v1_5")return"X25519"}}})(),i=(()=>{switch(r){case"ECDSA":return{name:r,hash:s,namedCurve:n};case"RSASSA-PKCS1-v1_5":return{name:r,hash:s,publicExponent:new Uint8Array([1,0,1]),modulusLength:2048}}})(),o=await NT.subtle.generateKey(i,!0,["sign","verify"]),c=(await Wx.createSelfSigned({serialNumber:(0,$h.randomBytes)(8).toString("hex"),name:"C=AU, ST=Some-State, O=Internet Widgits Pty Ltd",notBefore:new Date,notAfter:new Date(Date.now()+10*365*24*60*60*1e3),signingAlgorithm:i,keys:o})).toString("pem"),d=Wr.encode(await NT.subtle.exportKey("pkcs8",o.privateKey),"private key");return{certPem:c,keyPem:d,signatureHash:t}};encryptPacket(t){let e=t.recordLayerHeader,r=e.protocolVersion.major<<8|e.protocolVersion.minor,s=this.cipher.encrypt(this.sessionType,t.fragment,{type:e.contentType,version:r,epoch:e.epoch,sequenceNumber:e.sequenceNumber});return t.fragment=s,t.recordLayerHeader.contentLen=s.length,t}decryptPacket(t){let e=t.recordLayerHeader,r=e.protocolVersion.major<<8|e.protocolVersion.minor;return this.cipher.decrypt(this.sessionType,t.fragment,{type:e.contentType,version:r,epoch:e.epoch,sequenceNumber:e.sequenceNumber})}verifyData(t){return this.sessionType===Go.CLIENT?UZ(this.masterSecret,t):MZ(this.masterSecret,t)}signatureData(t,e){let r=(0,$h.createSign)(e).update(t),s=this.localPrivateKey.toPEM().toString();return r.sign(s)}generateKeySignature(t){let e=this.sessionType===Go.CLIENT?this.localRandom:this.remoteRandom,r=this.sessionType===Go.SERVER?this.localRandom:this.remoteRandom,s=this.valueKeySignature(e.serialize(),r.serialize(),this.localKeyPair.publicKey,this.namedCurve);return this.localPrivateKey.sign(s,t)}parseX509(t,e,r){let s=p1.Certificate.fromPEM(Buffer.from(t)),n=p1.PrivateKey.fromPEM(Buffer.from(e));this.localCert=s.raw,this.localPrivateKey=n,this.signatureHashAlgorithm=r}valueKeySignature(t,e,r,s){let n=Buffer.from((0,Ph.encode)({type:Yk.named_curve_3,curve:s,len:r.length},{type:Ph.types.uint8,curve:Ph.types.uint16be,len:Ph.types.uint8}).slice());return Buffer.concat([t,e,n,r])}},U0=class{srtpProfile;static findMatchingSRTPProfile(t,e){for(let r of e)if(t.includes(r))return r}},Qk=t=>"0x"+t.toString("hex").replace(/(.)(.)/g,"$1$2 ").split(" ").filter(e=>e!=null&&e.length>0).join(",0x"),p7=t=>Object.entries({...t}).reduce((e,[r,s])=>((typeof s=="number"||typeof s=="string")&&(e[r]=s),Buffer.isBuffer(s)&&(e[r]=Qk(s)),e),{}),vn=class ac{constructor(e,r,s,n,i,o){this.msg_type=e,this.length=r,this.message_seq=s,this.fragment_offset=n,this.fragment_length=i,this.fragment=o}static spec={msg_type:Kn.types.uint8,length:Kn.types.uint24be,message_seq:Kn.types.uint16be,fragment_offset:Kn.types.uint24be,fragment_length:Kn.types.uint24be,fragment:Kn.types.buffer(e=>e.current.fragment_length)};get summary(){return p7(this)}static createEmpty(){return new ac(void 0,void 0,void 0,void 0,void 0,void 0)}static deSerialize(e){return new ac(...Object.values((0,Kn.decode)(e,ac.spec)))}serialize(){let e=(0,Kn.encode)(this,ac.spec).slice();return Buffer.from(e)}chunk(e){let r=0,s=this.fragment.length;if(s===0)return[new ac(this.msg_type,s,this.message_seq,r,0,this.fragment)];let n=[];for(e||(e=1240);r<s;){let i=Math.min(e,s-r),o=Buffer.from(this.fragment.slice(r,r+i));if(o.length<=0)throw new Error("Zero or less bytes processed while fragmenting handshake message.");n.push(new ac(this.msg_type,s,this.message_seq,r,o.length,o)),r+=o.length}return n}static assemble(e){if(!e?.length)throw new Error("cannot reassemble handshake from empty array");e=e.sort((s,n)=>s.fragment_offset-n.fragment_offset);let r=Buffer.alloc(e[0].length);for(let s of e)s.fragment.copy(r,s.fragment_offset);return new ac(e[0].msg_type,e[0].length,e[0].message_seq,0,r.length,r)}static findAllFragments(e,r){let s=e.find(n=>n.msg_type===r);return s?e?.length?e.filter(n=>n.msg_type===s.msg_type&&n.message_seq===s.message_seq&&n.length===s.length):[]:[]}},{uint16be:Zw,uint24be:FZ,buffer:g7,array:HZ,uint8:M0,string:qZ}=m7.types,VZ={type:Zw,data:g7(Zw)},UT=HZ(VZ,Zw,"bytes"),zZ=g7(FZ),WZ=M0,KZ=qZ(Zw),GZ={hash:M0,signature:M0},Zk={major:M0,minor:M0},fl=class m0{constructor(e=Math.floor(Date.now()/1e3),r=(0,y7.randomBytes)(28)){this.gmt_unix_time=e,this.random_bytes=r}static spec={gmt_unix_time:hl.types.uint32be,random_bytes:hl.types.buffer(28)};static deSerialize(e){return new m0(...Object.values((0,hl.decode)(e,m0.spec)))}static from(e){return new m0(...Object.values(e))}serialize(){let e=(0,hl.encode)(this,m0.spec).slice();return Buffer.from(e)}},b7=class g0{constructor(e,r,s,n,i,o,a){this.clientVersion=e,this.random=r,this.sessionId=s,this.cookie=n,this.cipherSuites=i,this.compressionMethods=o,this.extensions=a}msgType=1;messageSeq=0;static spec={clientVersion:{major:Yr.types.uint8,minor:Yr.types.uint8},random:fl.spec,sessionId:Yr.types.buffer(Yr.types.uint8),cookie:Yr.types.buffer(Yr.types.uint8),cipherSuites:Yr.types.array(Yr.types.uint16be,Yr.types.uint16be,"bytes"),compressionMethods:Yr.types.array(Yr.types.uint8,Yr.types.uint8,"bytes"),extensions:UT};static createEmpty(){return new g0(void 0,void 0,void 0,void 0,void 0,void 0,void 0)}static deSerialize(e){return new g0(...Object.values((0,Yr.decode)(e,g0.spec)))}serialize(){let e=(0,Yr.encode)(this,g0.spec).slice();return Buffer.from(e)}toFragment(){let e=this.serialize();return new vn(this.msgType,e.length,this.messageSeq,0,e.length,e)}},XZ=class y0{constructor(e,r,s,n,i){this.epoch=e,this.sequenceNumber=r,this.contentType=s,this.protocolVersion=n,this.contentLen=i}static spec={epoch:Wo.types.uint16be,sequenceNumber:Wo.types.uint48be,contentType:Wo.types.uint8,protocolVersion:Zk,contentLen:Wo.types.uint16be};static createEmpty(){return new y0(void 0,void 0,void 0,void 0,void 0)}static deSerialize(e){return new y0(...Object.values((0,Wo.decode)(e,y0.spec)))}serialize(){let e=(0,Wo.encode)(this,y0.spec).slice();return Buffer.from(e)}},w7=class MT{constructor(e,r){this.recordLayerHeader=e,this.fragment=r}get summary(){return{header:this.recordLayerHeader,fragment:Qk(this.fragment)}}static createEmpty(){return new MT(void 0,void 0)}static deSerialize(e){if(e.length<13)throw new Error("Invalid DTLS record: buffer is too short");let r=e.readUInt8(0),s=e.readUInt8(1),n=e.readUInt8(2),i=e.readUInt16BE(3),o=e.slice(5,11).readUIntBE(0,6),a=e.readUInt16BE(11);if(e.length<13+a)throw new Error("Invalid DTLS record: fragment length exceeds buffer");let c=e.slice(13,13+a);return new MT({contentType:r,protocolVersion:{major:s,minor:n},epoch:i,sequenceNumber:o,contentLen:a},c)}serialize(){let e=this.fragment.length,r=13+e,s=Buffer.alloc(r);return s.writeUInt8(this.recordLayerHeader.contentType,0),s.writeUInt8(this.recordLayerHeader.protocolVersion.major,1),s.writeUInt8(this.recordLayerHeader.protocolVersion.minor,2),s.writeUInt16BE(this.recordLayerHeader.epoch,3),s.writeUIntBE(this.recordLayerHeader.sequenceNumber,5,6),s.writeUInt16BE(e,11),this.fragment.copy(s,13),s}computeMACHeader(){return new XZ(this.recordLayerHeader.epoch,this.recordLayerHeader.sequenceNumber,this.recordLayerHeader.contentType,this.recordLayerHeader.protocolVersion,this.recordLayerHeader.contentLen).serialize()}},v7=t=>e=>(t.lastFlight=e,e.flatMap(r=>(r.messageSeq=t.sequenceNumber++,r.toFragment().chunk()))),Z0=t=>(e,r)=>e.map(s=>new w7({contentType:s.type,protocolVersion:t.version,epoch:t.epoch,sequenceNumber:r,contentLen:s.fragment.length},s.fragment)),jT=(t=>(t[t.CloseNotify=0]="CloseNotify",t[t.UnexpectedMessage=10]="UnexpectedMessage",t[t.BadRecordMac=20]="BadRecordMac",t[t.DecryptionFailed=21]="DecryptionFailed",t[t.RecordOverflow=22]="RecordOverflow",t[t.DecompressionFailure=30]="DecompressionFailure",t[t.HandshakeFailure=40]="HandshakeFailure",t[t.NoCertificate=41]="NoCertificate",t[t.BadCertificate=42]="BadCertificate",t[t.UnsupportedCertificate=43]="UnsupportedCertificate",t[t.CertificateRevoked=44]="CertificateRevoked",t[t.CertificateExpired=45]="CertificateExpired",t[t.CertificateUnknown=46]="CertificateUnknown",t[t.IllegalParameter=47]="IllegalParameter",t[t.UnknownCa=48]="UnknownCa",t[t.AccessDenied=49]="AccessDenied",t[t.DecodeError=50]="DecodeError",t[t.DecryptError=51]="DecryptError",t[t.ExportRestriction=60]="ExportRestriction",t[t.ProtocolVersion=70]="ProtocolVersion",t[t.InsufficientSecurity=71]="InsufficientSecurity",t[t.InternalError=80]="InternalError",t[t.UserCanceled=90]="UserCanceled",t[t.NoRenegotiation=100]="NoRenegotiation",t[t.UnsupportedExtension=110]="UnsupportedExtension",t))(jT||{}),YZ=ft("werift-dtls : packages/dtls/src/flight/flight.ts : warn"),vT=ft("werift-dtls : packages/dtls/src/flight/flight.ts : err"),eg=class $T{constructor(e,r,s,n){this.transport=e,this.dtls=r,this.flight=s,this.nextFlight=n}state="PREPARING";static RetransmitCount=10;createPacket(e){let r=v7(this.dtls)(e);return this.dtls.bufferHandshakeCache(r,!0,this.flight),Z0(this.dtls)(r.map(n=>({type:22,fragment:n.serialize()})),++this.dtls.recordSequenceNumber)}async transmit(e){let r=0;for(;r<=$T.RetransmitCount;r++){if(this.setState("SENDING"),this.send(e).catch(s=>{vT("fail to send",vT)}),this.setState("WAITING"),this.nextFlight===void 0){this.setState("FINISHED");break}if(await(0,x7.setTimeout)(1e3*((r+1)/2)),this.dtls.flight>=this.nextFlight){this.setState("FINISHED");break}else YZ(this.dtls.sessionId,"retransmit",r,this.dtls.flight)}if(r>$T.RetransmitCount)throw vT(this.dtls.sessionId,"retransmit failed",r),new Error(`over retransmitCount : ${this.flight} ${this.nextFlight}`)}send=e=>Promise.all(e.map(r=>this.transport.send(r)));setState(e){this.state=e}},JZ=class extends eg{constructor(t,e,r){super(t,e,1,3),this.cipher=r}async exec(t){if(this.dtls.flight===1)throw new Error;this.dtls.flight=1;let e=new b7({major:254,minor:253},new fl,Buffer.from([]),Buffer.from([]),i7,[0],t);this.dtls.version=e.clientVersion,this.cipher.localRandom=fl.from(e.random);let r=this.createPacket([e]),s=Buffer.concat(r.map(n=>n.serialize()));await this.transmit([s])}},QZ=ft("werift-dtls : packages/dtls/src/flight/client/flight3.ts : log"),ZZ=class extends eg{constructor(t,e){super(t,e,3,5)}async exec(t){if(this.dtls.flight===3)throw new Error;this.dtls.flight=3,this.dtls.handshakeCache=[];let[e]=this.dtls.lastFlight;QZ("dtls version",e.clientVersion),e.cookie=t.cookie,this.dtls.cookie=t.cookie;let r=this.createPacket([e]),s=Buffer.concat(r.map(n=>n.serialize()));await this.transmit([s])}},g1={NULL:0,ECDHE:1},tg={NULL:0,RSA:1,ECDSA:2,PSK:3},rg={NULL:0,RSA:1,ECDHE_RSA:2,ECDHE_ECDSA:3,PSK:4,ECDHE_PSK:5},sg=class{id=0;name;signType;keyType;toString(){return this.name}};iee=ft("werift-dtls : packages/dtls/src/cipher/suites/aead.ts : err"),oee=class extends $Z{keyLength=0;nonceLength=0;ivLength=0;authTagLength=0;nonceImplicitLength=0;nonceExplicitLength=0;clientWriteKey;serverWriteKey;clientNonce;serverNonce;constructor(){super()}get summary(){return p7(this)}init(t,e,r){let s=jZ(t,r,e,this.keyLength,this.ivLength,this.nonceLength,this.hashAlgorithm);this.clientWriteKey=s.clientWriteKey,this.serverWriteKey=s.serverWriteKey,this.clientNonce=s.clientNonce,this.serverNonce=s.serverNonce}encrypt(t,e,r){let s=t===Go.CLIENT,n=s?this.clientNonce:this.serverNonce,i=s?this.clientWriteKey:this.serverWriteKey;if(!n||!i)throw new Error;n.writeUInt16BE(r.epoch,this.nonceImplicitLength),n.writeUIntBE(r.sequenceNumber,this.nonceImplicitLength+2,6);let o=n.slice(this.nonceImplicitLength),a=this.encodeAdditionalBuffer(r,e.length),c=(0,y1.createCipheriv)(this.blockAlgorithm,i,n,{authTagLength:this.authTagLength});c.setAAD(a,{plaintextLength:e.length});let d=c.update(e),u=c.final(),l=c.getAuthTag();return Buffer.concat([o,d,u,l])}encodeAdditionalBuffer(t,e){let r=Buffer.alloc(13);return r.writeUInt16BE(t.epoch,0),r.writeUintBE(t.sequenceNumber,2,6),r.writeUInt8(t.type,8),r.writeUInt16BE(t.version,9),r.writeUInt16BE(e,11),r}decrypt(t,e,r){let s=t===Go.CLIENT,n=s?this.serverNonce:this.clientNonce,i=s?this.serverWriteKey:this.clientWriteKey;if(!n||!i)throw new Error;e.subarray(0,this.nonceExplicitLength).copy(n,this.nonceImplicitLength);let a=e.subarray(this.nonceExplicitLength,e.length-this.authTagLength),c=e.subarray(e.length-this.authTagLength),d=this.encodeAdditionalBuffer(r,a.length),u=(0,y1.createDecipheriv)(this.blockAlgorithm,i,n,{authTagLength:this.authTagLength});u.setAuthTag(c),u.setAAD(d,{plaintextLength:a.length});let l=u.update(a);try{let h=u.final();return h.length>0?Buffer.concat([l,h]):l}catch(h){throw iee("decrypt failed",h,t,Qk(e),r,this.summary),h}}},Er={TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:49195,TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:49196,TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:49199,TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:49200,TLS_RSA_WITH_AES_128_GCM_SHA256:156,TLS_RSA_WITH_AES_256_GCM_SHA384:157,TLS_PSK_WITH_AES_128_GCM_SHA256:168,TLS_PSK_WITH_AES_256_GCM_SHA384:169,TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256:53249,TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384:53250,TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256:52396,TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256:52393,TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256:52392,TLS_PSK_WITH_CHACHA20_POLY1305_SHA256:52395},a0={K_LEN:16,N_MIN:12,N_MAX:12,P_MAX:2**36-31,A_MAX:2**53-1,C_MAX:2**36-15},c0={K_LEN:32,N_MIN:12,N_MAX:12,P_MAX:2**36-31,A_MAX:2**53-1,C_MAX:2**36-15},FN=eee(),HN=tee(),qN=ree(),VN=see(),zN=nee();b1=class{static type=23},x1=class Eh{static type=65281;static spec={type:pl.types.uint16be,data:pl.types.uint8};type=Eh.type;data=0;constructor(e={}){Object.assign(this,e)}static createEmpty(){return new Eh}static deSerialize(e){return new Eh((0,pl.decode)(e,Eh.spec))}serialize(){let e=(0,pl.encode)(this,Eh.spec).slice();return Buffer.from(e)}get extension(){return{type:this.type,data:this.serialize().slice(2)}}},Lh=class cc{static type=14;static spec={type:pc.types.uint16be,data:pc.types.buffer(pc.types.uint16be)};type=cc.type;data=Buffer.from([]);profiles=[];mki=Buffer.from([0]);constructor(e={}){Object.assign(this,e)}static create(e,r){return new cc({profiles:e,mki:r})}static deSerialize(e){let r=new cc((0,pc.decode)(e,cc.spec)),s=r.data.readUInt16BE(),n=new Array(s/2);for(let i=0;i<n.length;i++)n[i]=r.data.readUInt16BE(i*2+2);return r.profiles=n,r.mki=r.data.slice(s+2),r}serialize(){let e=Buffer.alloc(2);e.writeUInt16BE(this.profiles.length*2);let r=Buffer.concat([e,...this.profiles.map(n=>{let i=Buffer.alloc(2);return i.writeUInt16BE(n),i}),this.mki]);this.data=r;let s=(0,pc.encode)(this,cc.spec).slice();return Buffer.from(s)}static fromData(e){let r=Buffer.alloc(4);return r.writeUInt16BE(cc.type),r.writeUInt16BE(e.length,2),cc.deSerialize(Buffer.concat([r,e]))}get extension(){return{type:this.type,data:this.serialize().slice(4)}}},e1=class b0{constructor(e){this.certificateList=e}msgType=11;messageSeq;static spec={certificateList:ml.types.array(zZ,ml.types.uint24be,"bytes")};static createEmpty(){return new b0(void 0)}static deSerialize(e){return new b0(...Object.values((0,ml.decode)(e,b0.spec)))}serialize(){let e=(0,ml.encode)(this,b0.spec).slice();return Buffer.from(e)}toFragment(){let e=this.serialize();return new vn(this.msgType,e.length,this.messageSeq,0,e.length,e)}},C7=class x0{constructor(e=1){this.type=e}static spec={type:Fh.types.uint8};static createEmpty(){return new x0}static deSerialize(e){return new x0(...Object.values((0,Fh.decode)(e,x0.spec)))}serialize(){let e=(0,Fh.encode)(this,x0.spec).slice();return Buffer.from(e)}},T7=class w0{constructor(e,r){this.algorithm=e,this.signature=r}msgType=15;messageSeq;static spec={algorithm:mc.types.uint16be,signature:mc.types.buffer(mc.types.uint16be)};static createEmpty(){return new w0(void 0,void 0)}static deSerialize(e){let r=(0,mc.decode)(e,w0.spec);return new w0(...Object.values(r))}serialize(){let e=(0,mc.encode)(this,w0.spec).slice();return Buffer.from(e)}toFragment(){let e=this.serialize();return new vn(this.msgType,e.length,this.messageSeq,0,e.length,e)}},k7=class v0{constructor(e){this.publicKey=e}msgType=16;messageSeq;static spec={publicKey:gl.types.buffer(gl.types.uint8)};static createEmpty(){return new v0(void 0)}static deSerialize(e){let r=(0,gl.decode)(e,v0.spec);return new v0(...Object.values(r))}serialize(){let e=(0,gl.encode)(this,v0.spec).slice();return Buffer.from(e)}toFragment(){let e=this.serialize();return new vn(this.msgType,e.length,this.messageSeq,0,e.length,e)}},FT=class HT{constructor(e){this.verifyData=e}msgType=20;messageSeq;static createEmpty(){return new HT(void 0)}static deSerialize(e){return new HT(e)}serialize(){return this.verifyData}toFragment(){let e=this.serialize();return new vn(this.msgType,e.length,this.messageSeq,0,e.length,e)}},A7=class _0{constructor(e,r,s){this.certificateTypes=e,this.signatures=r,this.authorities=s}msgType=13;messageSeq;static spec={certificateTypes:Gn.types.array(WZ,Gn.types.uint8,"bytes"),signatures:Gn.types.array(GZ,Gn.types.uint16be,"bytes"),authorities:Gn.types.array(KZ,Gn.types.uint16be,"bytes")};static createEmpty(){return new _0(void 0,void 0,void 0)}static deSerialize(e){return new _0(...Object.values((0,Gn.decode)(e,_0.spec)))}serialize(){let e=(0,Gn.encode)(this,_0.spec).slice();return Buffer.from(e)}toFragment(){let e=this.serialize();return new vn(this.msgType,e.length,this.messageSeq,0,e.length,e)}},I7=class dc{constructor(e,r,s,n,i,o){this.serverVersion=e,this.random=r,this.sessionId=s,this.cipherSuite=n,this.compressionMethod=i,this.extensions=o}msgType=2;messageSeq;static spec={serverVersion:Zk,random:fl.spec,sessionId:Xn.types.buffer(Xn.types.uint8),cipherSuite:Xn.types.uint16be,compressionMethod:Xn.types.uint8};static createEmpty(){return new dc(void 0,void 0,void 0,void 0,void 0,void 0)}static deSerialize(e){let r=(0,Xn.decode)(e,dc.spec),s=new dc(...Object.values(r));return s.serialize().length<e.length?new dc(...Object.values((0,Xn.decode)(e,{...dc.spec,extensions:UT}))):s}serialize(){let e=this.extensions===void 0?(0,Xn.encode)(this,dc.spec).slice():(0,Xn.encode)(this,{...dc.spec,extensions:UT}).slice();return Buffer.from(e)}toFragment(){let e=this.serialize();return new vn(this.msgType,e.length,this.messageSeq,0,e.length,e)}},R7=class S0{msgType=14;messageSeq;static spec={};static createEmpty(){return new S0}static deSerialize(e){return new S0(...Object.values((0,w1.decode)(e,S0.spec)))}serialize(){let e=(0,w1.encode)(this,S0.spec).slice();return Buffer.from(e)}toFragment(){let e=this.serialize();return new vn(this.msgType,e.length,this.messageSeq,0,e.length,e)}};D7=class E0{constructor(e,r,s,n,i,o,a,c){this.ellipticCurveType=e,this.namedCurve=r,this.publicKeyLength=s,this.publicKey=n,this.hashAlgorithm=i,this.signatureAlgorithm=o,this.signatureLength=a,this.signature=c}msgType=12;messageSeq;static spec={ellipticCurveType:Wn.types.uint8,namedCurve:Wn.types.uint16be,publicKeyLength:Wn.types.uint8,publicKey:Wn.types.buffer(e=>e.current.publicKeyLength),hashAlgorithm:Wn.types.uint8,signatureAlgorithm:Wn.types.uint8,signatureLength:Wn.types.uint16be,signature:Wn.types.buffer(e=>e.current.signatureLength)};static createEmpty(){return new E0(void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0)}static deSerialize(e){let r=(0,Wn.decode)(e,E0.spec);return new E0(...Object.values(r))}serialize(){return aee(this,E0.spec)}toFragment(){let e=this.serialize();return new vn(this.msgType,e.length,this.messageSeq,0,e.length,e)}},Hh=1,_l=7,cee=[Hh,_l],B7=t=>{switch(t){case Hh:case _l:return 16}},L7=t=>{switch(t){case Hh:return 14;case _l:return 12}},dee=ft("werift-rtp : packages/rtp/src/codec/av1.ts"),qT=class N7{zBit_RtpStartsWithFragment;yBit_RtpEndsWithFragment;w_RtpNumObus;nBit_RtpStartsNewCodedVideoSequence;obu_or_fragment=[];static deSerialize=e=>{let r=new N7,s=0;if(r.zBit_RtpStartsWithFragment=Te(e[s],0),r.yBit_RtpEndsWithFragment=Te(e[s],1),r.w_RtpNumObus=Te(e[s],2,2),r.nBit_RtpStartsNewCodedVideoSequence=Te(e[s],4),s++,r.nBit_RtpStartsNewCodedVideoSequence&&r.zBit_RtpStartsWithFragment)throw new Error;[...Array(r.w_RtpNumObus-1).keys()].forEach(i=>{let[o,a]=j7(e.subarray(s)),c=s+a,d=c+o,u=!1;r.zBit_RtpStartsWithFragment&&i===0&&(u=!0),r.obu_or_fragment.push({data:e.subarray(c,d),isFragment:u}),s+=a+o});let n=!1;return(r.yBit_RtpEndsWithFragment||r.w_RtpNumObus===1&&r.zBit_RtpStartsWithFragment)&&(n=!0),r.obu_or_fragment.push({data:e.subarray(s),isFragment:n}),r};static isDetectedFinalPacketInSequence(e){return e.marker}get isKeyframe(){return this.nBit_RtpStartsNewCodedVideoSequence===1}static getFrame(e){let r=[],s=e.flatMap(a=>a.obu_or_fragment).reduce((a,c,d)=>(a[d]=c,a),{}),n=Object.keys(s).length;for(let a of Object.keys(s).map(Number)){let c=s[a];if(!c)continue;let{data:d,isFragment:u}=c;if(u){let l=[];for(let h=a;h<n;h++){let p=s[h];if(p.isFragment)l.push(p.data),delete s[h];else break}l.length<=1&&(dee("fragment lost, maybe packet lost"),l=[]),r.push(Buffer.concat(l))}else r.push(d)}let i=r.map(a=>U7.deSerialize(a)),o=i.pop();return Buffer.concat([...i.map(a=>(a.obu_has_size_field=1,a.serialize())),o.serialize()])}},U7=class M7{obu_forbidden_bit;obu_type;obu_extension_flag;obu_has_size_field;obu_reserved_1bit;payload;static deSerialize(e){let r=new M7,s=0;return r.obu_forbidden_bit=Te(e[s],0),r.obu_type=$7[Te(e[s],1,4)],r.obu_extension_flag=Te(e[s],5),r.obu_has_size_field=Te(e[s],6),r.obu_reserved_1bit=Te(e[s],7),s++,r.payload=e.subarray(s),r}serialize(){let e=new u1(8).set(this.obu_forbidden_bit).set(lee[this.obu_type],4).set(this.obu_extension_flag).set(this.obu_has_size_field).set(this.obu_reserved_1bit).buffer,r=Buffer.alloc(0);return this.obu_has_size_field&&(r=O7.LEB128.encode(this.payload.length)),Buffer.concat([e,r,this.payload])}};$7={0:"Reserved",1:"OBU_SEQUENCE_HEADER",2:"OBU_TEMPORAL_DELIMITER",3:"OBU_FRAME_HEADER",4:"OBU_TILE_GROUP",5:"OBU_METADATA",6:"OBU_FRAME",7:"OBU_REDUNDANT_FRAME_HEADER",8:"OBU_TILE_LIST",15:"OBU_PADDING"},lee=Object.entries($7).reduce((t,[e,r])=>(t[r]=Number(e),t),{}),F7=class H7{f;nri;nalUnitType;s;e;r;nalUnitPayloadType;payload;fragment;static deSerialize(e,r){let s=new H7,n=0,i=e[n];if(s.f=Te(i,0),s.nri=Te(i,1,2),s.nalUnitType=Te(i,3,5),n++,s.s=Te(e[n],0),s.e=Te(e[n],1),s.r=Te(e[n],2),s.nalUnitPayloadType=Te(e[n],3,5),n++,0<s.nalUnitType&&s.nalUnitType<lc.stap_a)s.payload=this.packaging(e);else if(s.nalUnitType===lc.stap_a){let o=hee,a=Buffer.alloc(0);for(;o<e.length;){let c=e.readUInt16BE(o);o+=fee,a=Buffer.concat([a,this.packaging(e.subarray(o,o+c))]),o+=c}s.payload=a}else if(s.nalUnitType===lc.fu_a){r||(r=Buffer.alloc(0));let o=e.subarray(n);if(s.fragment=Buffer.concat([r,o]),s.e){let a=new fc(Buffer.alloc(1)).writeBits(1,0).writeBits(2,s.nri).writeBits(5,s.nalUnitPayloadType),c=Buffer.concat([a.uint8Array,s.fragment]);s.fragment=void 0,s.payload=this.packaging(c)}}return s}static packaging(e){return Buffer.concat([uee,e])}static isDetectedFinalPacketInSequence(e){return e.marker}get isKeyframe(){return this.nalUnitType===lc.idrSlice||this.nalUnitPayloadType===lc.idrSlice}get isPartitionHead(){return this.nalUnitType===lc.fu_a||this.nalUnitType===lc.fu_b?this.s!==0:!0}},lc={idrSlice:5,stap_a:24,stap_b:25,mtap16:26,mtap24:27,fu_a:28,fu_b:29},uee=Buffer.from([0,0,0,1]),hee=1,fee=2,q7=class V7{payload;static deSerialize(e){let r=new V7;return r.payload=e,r}static isDetectedFinalPacketInSequence(e){return!0}get isKeyframe(){return!0}static createCodecPrivate(e=48e3){return Buffer.concat([Buffer.from("OpusHead"),nr([1,1],[1,2]),FU([2,4,2,1],[312,e,0,0])])}},z7=class W7{xBit;nBit;sBit;pid;iBit;lBit;tBit;kBit;mBit;pictureId;payload;size0=0;hBit;ver;pBit;size1=0;size2=0;static deSerialize(e){let r=new W7,s=0;if(r.xBit=Te(e[s],0),r.nBit=Te(e[s],2),r.sBit=Te(e[s],3),r.pid=Te(e[s],5,3),s++,r.xBit&&(r.iBit=Te(e[s],0),r.lBit=Te(e[s],1),r.tBit=Te(e[s],2),r.kBit=Te(e[s],3),s++),r.iBit)if(r.mBit=Te(e[s],0),r.mBit){let n=B0(Te(e[s],1,7)),i=B0(e[s+1]);r.pictureId=Number.parseInt(n+i,2),s+=2}else r.pictureId=Te(e[s],1,7),s++;return r.lBit&&s++,(r.lBit||r.kBit)&&(r.tBit,r.kBit,s++),r.payload=e.subarray(s),r.payloadHeaderExist&&(r.size0=Te(e[s],0,3),r.hBit=Te(e[s],3),r.ver=Te(e[s],4,3),r.pBit=Te(e[s],7),s++,r.size1=e[s],s++,r.size2=e[s]),r}static isDetectedFinalPacketInSequence(e){return e.marker}get isKeyframe(){return this.pBit===0}get isPartitionHead(){return this.sBit===1}get payloadHeaderExist(){return this.sBit===1&&this.pid===0}get size(){return this.payloadHeaderExist?this.size0+8*this.size1+2048*this.size2:0}},K7=class G7{iBit;pBit;lBit;fBit;bBit;eBit;vBit;zBit;m;pictureId;tid;u;sid;d;tl0PicIdx;pDiff=[];n_s;y;g;width=[];height=[];n_g=0;pgT=[];pgU=[];pgP_Diff=[];payload;static deSerialize(e){let{p:r,offset:s}=this.parseRtpPayload(e);return r.payload=e.subarray(s),r}static parseRtpPayload(e){let r=new G7,s=0;if(r.iBit=Te(e[s],0),r.pBit=Te(e[s],1),r.lBit=Te(e[s],2),r.fBit=Te(e[s],3),r.bBit=Te(e[s],4),r.eBit=Te(e[s],5),r.vBit=Te(e[s],6),r.zBit=Te(e[s],7),s++,r.iBit)if(r.m=Te(e[s],0),r.m){let n=B0(Te(e[s],1,7)),i=B0(e[s+1]);r.pictureId=Number.parseInt(n+i,2),s+=2}else r.pictureId=Te(e[s],1,7),s++;if(r.lBit&&(r.tid=Te(e[s],0,3),r.u=Te(e[s],3),r.sid=Te(e[s],4,3),r.d=Te(e[s],7),s++,r.fBit===0&&(r.tl0PicIdx=e[s],s++)),r.fBit&&r.pBit)for(;;){r.pDiff=[...r.pDiff,Te(e[s],0,7)];let n=Te(e[s],7);if(s++,n===0)break}return r.vBit&&(r.n_s=Te(e[s],0,3),r.y=Te(e[s],3),r.g=Te(e[s],4),s++,r.y&&[...Array(r.n_s+1)].forEach(()=>{r.width.push(e.readUInt16BE(s)),s+=2,r.height.push(e.readUInt16BE(s)),s+=2}),r.g&&(r.n_g=e[s],s++),r.n_g>0&&[...Array(r.n_g).keys()].forEach(n=>{r.pgT.push(Te(e[s],0,3)),r.pgU.push(Te(e[s],3));let i=Te(e[s],4,2);s++,r.pgP_Diff[n]=[],i>0&&[...Array(i)].forEach(()=>{r.pgP_Diff[n].push(e[s]),s++})})),{offset:s,p:r}}static isDetectedFinalPacketInSequence(e){return e.marker}get isKeyframe(){return!!(!this.pBit&&this.bBit&&(!this.sid||!this.lBit))}get isPartitionHead(){return this.bBit&&(!this.lBit||!this.d)}},pee=class{payload;fragment;static deSerialize(t,e){return{}}static isDetectedFinalPacketInSequence(t){return!0}get isKeyframe(){return!0}};gee=["MPEG4/ISO/AVC","VP8","VP9","OPUS","AV1"];bee={setTimeout:(...t)=>{let e=setTimeout(...t);return()=>clearTimeout(e)},setInterval:(...t)=>{let e=setInterval(()=>{t[0]()},...t.slice(1));return()=>clearInterval(e)}};t1=4,Qo=class zT{version=2;padding=!1;count=0;type=0;length=0;constructor(e={}){Object.assign(this,e)}static serialize(e,r,s,n){let o=new zT({type:e,count:r,version:2,length:n}).serialize();return Buffer.concat([o,s])}serialize(){let e=new D0(8);return e.set(2,0,this.version),this.padding&&e.set(1,2,1),e.set(5,3,this.count),nr([1,1,2],[e.value,this.type,this.length])}static deSerialize(e){let[r,s,n]=bs(e,[1,1,2]),i=Te(r,0,2),o=Te(r,2,1)>0,a=Te(r,3,5);return new zT({version:i,padding:o,count:a,type:s,length:n})}},WN=class WT{static count=4;count=WT.count;senderSsrc;mediaSsrc;fir=[];constructor(e={}){Object.assign(this,e)}get length(){return Math.floor(this.serialize().length/4-1)}static deSerialize(e){let[r,s]=bs(e,[4,4]),n=[];for(let i=8;i<e.length;i+=8)n.push({ssrc:e.readUInt32BE(i),sequenceNumber:e[i+4]});return new WT({senderSsrc:r,mediaSsrc:s,fir:n})}serialize(){let e=nr([4,4],[this.senderSsrc,this.mediaSsrc]),r=Buffer.alloc(this.fir.length*8);return this.fir.forEach(({ssrc:s,sequenceNumber:n},i)=>{r.writeUInt32BE(s,i*8),r[i*8+4]=n}),Buffer.concat([e,r])}},$0=class KT{static count=1;count=KT.count;length=2;senderSsrc;mediaSsrc;constructor(e={}){Object.assign(this,e)}static deSerialize(e){let[r,s]=bs(e,[4,4]);return new KT({senderSsrc:r,mediaSsrc:s})}serialize(){return nr([4,4],[this.senderSsrc,this.mediaSsrc])}},F0=class GT{static count=15;length;count=GT.count;senderSsrc;mediaSsrc;uniqueID="REMB";ssrcNum=0;brExp;brMantissa;bitrate;ssrcFeedbacks=[];constructor(e={}){Object.assign(this,e)}static deSerialize(e){let[r,s,n,i,o]=bs(e,[4,4,4,1,1]),a=Te(o,0,6),c=(Te(o,6,2)<<16)+(e[14]<<8)+e[15],d=a>46?18446744073709551615n:BigInt(c)<<BigInt(a),u=[];for(let l=16;l<e.length;l+=4){let h=e.slice(l).readUIntBE(0,4);u.push(h)}return new GT({senderSsrc:r,mediaSsrc:s,uniqueID:nr([4],[n]).toString(),ssrcNum:i,brExp:a,brMantissa:c,ssrcFeedbacks:u,bitrate:d})}serialize(){let e=Buffer.concat([nr([4,4],[this.senderSsrc,this.mediaSsrc]),Buffer.from(this.uniqueID),nr([1],[this.ssrcNum])]),r=new D0(24);r.set(6,0,this.brExp).set(18,6,this.brMantissa);let s=Buffer.concat(this.ssrcFeedbacks.map(i=>nr([4],[i]))),n=Buffer.concat([e,nr([3],[r.value]),s]);return this.length=n.length/4,n}},xee=ft("werift-rtp: /rtcp/psfb/index"),Oh=class XT{static type=206;type=XT.type;feedback;constructor(e={}){Object.assign(this,e)}serialize(){let e=this.feedback.serialize();return Qo.serialize(this.type,this.feedback.count,e,this.feedback.length)}static deSerialize(e,r){let s;switch(r.count){case WN.count:s=WN.deSerialize(e);break;case $0.count:s=$0.deSerialize(e);break;case F0.count:s=F0.deSerialize(e);break;default:xee("unknown psfb packet",r.count);break}return new XT({feedback:s})}},Nh=class Pw{ssrc=0;reports=[];static type=201;type=Pw.type;constructor(e={}){Object.assign(this,e)}serialize(){let e=nr([4],[this.ssrc]);return e=Buffer.concat([e,...this.reports.map(r=>r.serialize())]),Qo.serialize(Pw.type,this.reports.length,e,Math.floor(e.length/4))}static deSerialize(e,r){let[s]=bs(e,[4]),n=4,i=[];for(let o=0;o<r;o++)i.push(v1.deSerialize(e.slice(n,n+24))),n+=24;return new Pw({ssrc:s,reports:i})}},v1=class Y7{ssrc;fractionLost;packetsLost;highestSequence;jitter;lsr;dlsr;constructor(e={}){Object.assign(this,e)}toJSON(){return{ssrc:this.ssrc,fractionLost:this.fractionLost,packetsLost:this.packetsLost,highestSequence:this.highestSequence,jitter:this.jitter,lsr:this.lsr,dlsr:this.dlsr}}serialize(){return nr([4,1,3,4,4,4,4],[this.ssrc,this.fractionLost,this.packetsLost,this.highestSequence,this.jitter,this.lsr,this.dlsr])}static deSerialize(e){let[r,s,n,i,o,a,c]=bs(e,[4,1,3,4,4,4,4]);return new Y7({ssrc:r,fractionLost:s,packetsLost:n,highestSequence:i,jitter:o,lsr:a,dlsr:c})}},J7=205,H0=class YT{static count=1;count=YT.count;header;senderSsrc;mediaSourceSsrc;lost=[];toJSON(){return{lost:this.lost,senderSsrc:this.senderSsrc,mediaSourceSsrc:this.mediaSourceSsrc}}constructor(e={}){Object.assign(this,e),this.header||(this.header=new Qo({type:J7,count:this.count,version:2}))}static deSerialize(e,r){let[s,n]=bs(e,[4,4]),i=[];for(let o=8;o<e.length;o+=4){let[a,c]=bs(e.subarray(o),[2,2]);i.push(a);for(let d=0;d<16;d++)c>>d&1&&i.push(a+d+1)}return new YT({header:r,senderSsrc:s,mediaSourceSsrc:n,lost:i})}serialize(){let e=nr([4,4],[this.senderSsrc,this.mediaSourceSsrc]),r=[];if(this.lost.length>0){let n=this.lost[0],i=0;this.lost.slice(1).forEach(o=>{let a=o-n-1;a>=0&&a<16?i|=1<<a:(r.push(nr([2,2],[n,i])),n=o,i=0)}),r.push(nr([2,2],[n,i]))}let s=Buffer.concat([e,Buffer.concat(r)]);return this.header.length=s.length/4,Buffer.concat([this.header.serialize(),s])}},wee=ft("werift/rtp/rtcp/rtpfb/twcc"),q0=class JT{static count=15;count=JT.count;length=2;senderSsrc;mediaSourceSsrc;baseSequenceNumber;packetStatusCount;referenceTime;fbPktCount;packetChunks=[];recvDeltas=[];header;constructor(e={}){Object.assign(this,e),this.header||(this.header=new Qo({type:205,count:this.count,version:2}))}static deSerialize(e,r){let[s,n,i,o,a,c]=bs(e,[4,4,2,2,3,1]),d=[],u=[],l=16;for(let p=0;p<o;){let m=Te(e.slice(l,l+1)[0],0,1),_;switch(m){case 0:{let f=Dh.deSerialize(e.slice(l,l+2));_=f;let b=Math.min(o-p,f.runLength);if(f.packetStatus===1||f.packetStatus===2)for(let w=0;w<b;w++)u.push(new I0({type:f.packetStatus}));p+=b}break;case 1:{let f=Z7.deSerialize(e.slice(l,l+2));_=f,f.symbolSize===0&&f.symbolList.forEach(b=>{b===1&&u.push(new I0({type:1}))}),f.symbolSize===1&&f.symbolList.forEach(b=>{(b===1||b===2)&&u.push(new I0({type:b}))}),p+=f.symbolList.length}break}if(!_)throw new Error;l+=2,d.push(_)}let h=l;return u.forEach(p=>{p.type===1&&(p.deSerialize(e.slice(h,h+1)),h++),p.type===2&&(p.deSerialize(e.slice(h,h+2)),h+=2)}),new JT({senderSsrc:s,mediaSourceSsrc:n,baseSequenceNumber:i,packetStatusCount:o,referenceTime:a,fbPktCount:c,recvDeltas:u,packetChunks:d,header:r})}serialize(){let e=nr([4,4,2,2,3,1],[this.senderSsrc,this.mediaSourceSsrc,this.baseSequenceNumber,this.packetStatusCount,this.referenceTime,this.fbPktCount]),r=Buffer.concat(this.packetChunks.map(i=>i.serialize())),s=Buffer.concat(this.recvDeltas.map(i=>{try{return i.serialize()}catch(o){wee(o?.message);return}}).filter(i=>i)),n=Buffer.concat([e,r,s]);if(this.header.padding&&n.length%4!==0){let i=4-n.length%4,o=Buffer.alloc(i);return o[o.length-1]=o.length,this.header.length=Math.floor((n.length+o.length)/4),Buffer.concat([this.header.serialize(),n,o])}return this.header.length=Math.floor(n.length/4),Buffer.concat([this.header.serialize(),n])}get packetResults(){let e=this.baseSequenceNumber-1,r=this.packetChunks.filter(o=>o instanceof Dh).flatMap(o=>o.results(e)),s=0,i=BigInt(this.referenceTime)*64n;for(let o of r){let a=this.recvDeltas[s];!o.received||!a||(i+=BigInt(a.delta)/1000n,o.delta=a.delta,o.receivedAtMs=Number(i),s++)}return r}},Dh=class Q7{type;packetStatus;runLength;constructor(e={}){Object.assign(this,e),this.type=0}static deSerialize(e){let r=Te(e[0],1,2),s=(Te(e[0],3,5)<<8)+e[1];return new Q7({type:0,packetStatus:r,runLength:s})}serialize(){return new u1(16).set(0).set(this.packetStatus,2).set(this.runLength,13).buffer}results(e){let r=this.packetStatus===1||this.packetStatus===2,s=[];for(let n=0;n<=this.runLength;++n)s.push(new sM({sequenceNumber:++e,received:r}));return s}},Z7=class eM{type;symbolSize;symbolList=[];constructor(e={}){Object.assign(this,e)}static deSerialize(e){let s=Te(e[0],1,1),n=[];function i(o,a){for(let c=0;c<o;c++)a(c)}switch(s){case 0:i(6,o=>n.push(Te(e[0],2+o,1))),i(8,o=>n.push(Te(e[1],o,1)));break;case 1:i(3,o=>n.push(Te(e[0],2+o*2,2))),i(4,o=>n.push(Te(e[1],o*2,2)));break;default:s=(Te(e[0],2,6)<<8)+e[1]}return new eM({type:1,symbolSize:s,symbolList:n})}serialize(){let e=Buffer.alloc(2),r=new u1(16).set(1).set(this.symbolSize),s=this.symbolSize===0?1:2;return this.symbolList.forEach(n=>{r.set(n,s)}),e.writeUInt16BE(r.value),e}},I0=class QT{type;delta;constructor(e={}){Object.assign(this,e)}static deSerialize(e){let r,s;if(e.length===1?(r=1,s=250*e[0]):e.length===2&&(r=2,s=250*e.readInt16BE()),r===void 0||s===void 0)throw new Error;return new QT({type:r,delta:s})}deSerialize(e){let r=QT.deSerialize(e);this.delta=r.delta}parsed=!1;parseDelta(){this.delta=Math.floor(this.delta/250),this.delta<0||this.delta>255?(this.delta>32767&&(this.delta=32767),this.delta<-32768&&(this.delta=-32768),this.type||(this.type=2)):this.type||(this.type=1),this.parsed=!0}serialize(){if(this.parsed||this.parseDelta(),this.type===1){let e=Buffer.alloc(1);return e.writeUInt8(this.delta),e}else if(this.type===2){let e=Buffer.alloc(2);return e.writeInt16BE(this.delta),e}throw new Error("errDeltaExceedLimit "+this.delta+" "+this.type)}},tM=(t=>(t[t.TypeTCCRunLengthChunk=0]="TypeTCCRunLengthChunk",t[t.TypeTCCStatusVectorChunk=1]="TypeTCCStatusVectorChunk",t[t.packetStatusChunkLength=2]="packetStatusChunkLength",t))(tM||{}),rM=(t=>(t[t.TypeTCCPacketNotReceived=0]="TypeTCCPacketNotReceived",t[t.TypeTCCPacketReceivedSmallDelta=1]="TypeTCCPacketReceivedSmallDelta",t[t.TypeTCCPacketReceivedLargeDelta=2]="TypeTCCPacketReceivedLargeDelta",t[t.TypeTCCPacketReceivedWithoutDelta=3]="TypeTCCPacketReceivedWithoutDelta",t))(rM||{}),sM=class{sequenceNumber=0;delta=0;received=!1;receivedAtMs=0;constructor(t){Object.assign(this,t)}},vee=ft("werift-rtp:packages/rtp/rtcp/rtpfb/index"),yl=class ZT{static type=J7;type=ZT.type;feedback;header;constructor(e={}){Object.assign(this,e)}serialize(){return this.feedback.serialize()}static deSerialize(e,r){let s;switch(r.count){case H0.count:s=H0.deSerialize(e,r);break;case q0.count:s=q0.deSerialize(e,r);break;default:vee("unknown rtpfb packet",r.count);break}return new ZT({feedback:s,header:r})}},V0=class ek{static type=202;type=ek.type;chunks=[];constructor(e){Object.assign(this,e)}get length(){let e=0;return this.chunks.forEach(r=>e+=r.length),e}serialize(){let e=Buffer.concat(this.chunks.map(r=>r.serialize()));for(;e.length%4;)e=Buffer.concat([e,Buffer.from([0])]);return Qo.serialize(this.type,this.chunks.length,e,e.length/4)}static deSerialize(e,r){let s=[];for(let n=0;n<e.length;){let i=eA.deSerialize(e.slice(n));s.push(i),n+=i.length}return new ek({chunks:s})}},eA=class nM{source;items=[];constructor(e={}){Object.assign(this,e)}get length(){let e=4;return this.items.forEach(r=>e+=r.length),e+=1,e+=KN(e),e}serialize(){let e=Buffer.concat([nr([4],[this.source]),Buffer.concat(this.items.map(s=>s.serialize()))]);return Buffer.concat([e,Buffer.alloc(KN(e.length))])}static deSerialize(e){let r=e.readUInt32BE(),s=[];for(let n=4;n<e.length&&e[n]!==0;){let o=tA.deSerialize(e.slice(n));s.push(o),n+=o.length}return new nM({source:r,items:s})}},tA=class iM{type;text;constructor(e){Object.assign(this,e)}get length(){return 2+Buffer.from(this.text).length}serialize(){let e=Buffer.from(this.text);return Buffer.concat([nr([1,1],[this.type,e.length]),e])}static deSerialize(e){let r=e[0],s=e[1],n=e.slice(2,2+s).toString();return new iM({type:r,text:n})}};bl=class Dw{ssrc=0;senderInfo;reports=[];static type=200;type=Dw.type;constructor(e){Object.assign(this,e)}toJSON(){return{ssrc:this.ssrc,senderInfo:this.senderInfo.toJSON(),reports:this.reports.map(e=>e.toJSON())}}serialize(){let e=Buffer.alloc(4);return e.writeUInt32BE(this.ssrc),e=Buffer.concat([e,this.senderInfo.serialize()]),e=Buffer.concat([e,...this.reports.map(r=>r.serialize())]),Qo.serialize(Dw.type,this.reports.length,e,Math.floor(e.length/4))}static deSerialize(e,r){let s=e.readUInt32BE(),n=rA.deSerialize(e.subarray(4,24)),i=24,o=[];for(let c=0;c<r;c++)o.push(v1.deSerialize(e.subarray(i,i+24))),i+=24;return new Dw({ssrc:s,senderInfo:n,reports:o})}},rA=class oM{ntpTimestamp;rtpTimestamp;packetCount;octetCount;constructor(e={}){Object.assign(this,e)}toJSON(){return{ntpTimestamp:aM(this.ntpTimestamp),rtpTimestamp:this.rtpTimestamp}}serialize(){return nr([8,4,4,4],[this.ntpTimestamp,this.rtpTimestamp,this.packetCount,this.octetCount])}static deSerialize(e){let[r,s,n,i]=bs(e,[8,4,4,4]);return new oM({ntpTimestamp:r,rtpTimestamp:s,packetCount:n,octetCount:i})}},aM=t=>{let[e,r]=bs(nr([8],[t]),[4,4]);return+`${e}.${r}`},_ee=ft("werift-rtp:packages/rtp/src/rtcp/rtcp.ts"),cM=class{static deSerialize(t){let e=0,r=[];for(;e<t.length;){let s=Qo.deSerialize(t.subarray(e,e+t1));e+=t1;let n=t.subarray(e);e+=s.length*4,s.padding&&(n=n.subarray(0,n.length-n.subarray(-1)[0]));try{switch(s.type){case bl.type:r.push(bl.deSerialize(n,s.count));break;case Nh.type:r.push(Nh.deSerialize(n,s.count));break;case V0.type:r.push(V0.deSerialize(n,s));break;case yl.type:r.push(yl.deSerialize(n,s));break;case Oh.type:r.push(Oh.deSerialize(n,s));break;default:break}}catch(i){_ee("deSerialize RTCP",i)}}return r}};Qt={sdesMid:"urn:ietf:params:rtp-hdrext:sdes:mid",sdesRTPStreamID:"urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id",repairedRtpStreamId:"urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id",transportWideCC:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",absSendTime:"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time",dependencyDescriptor:"https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension",audioLevelIndication:"urn:ietf:params:rtp-hdrext:ssrc-audio-level",videoOrientation:"urn:3gpp:video-orientation"};Eee=ft("packages/rtp/src/rtp/red/packet.ts"),sA=class vM{header;blocks=[];static deSerialize(e){let r=e instanceof ArrayBuffer?Buffer.from(e):e,s=new vM,n=0;return[s.header,n]=tk.deSerialize(r),s.header.fields.forEach(({blockLength:i,timestampOffset:o,blockPT:a})=>{if(i&&o){let c=r.subarray(n,n+i);s.blocks.push({block:c,blockPT:a,timestampOffset:o}),n+=i}else{let c=r.subarray(n);s.blocks.push({block:c,blockPT:a})}}),s}serialize(){this.header=new tk;for(let{timestampOffset:r,blockPT:s,block:n}of this.blocks)r?this.header.fields.push({fBit:1,blockPT:s,blockLength:n.length,timestampOffset:r}):this.header.fields.push({fBit:0,blockPT:s});let e=this.header.serialize();for(let{block:r}of this.blocks)e=Buffer.concat([e,r]);return e}},tk=class _M{fields=[];static deSerialize(e){let r=0,s=new _M;for(;;){let n={};s.fields.push(n);let i=new fc(e.subarray(r));if(n.fBit=i.readBits(1),n.blockPT=i.readBits(7),r++,n.fBit===0)break;n.timestampOffset=i.readBits(14),n.blockLength=i.readBits(10),r+=3}return[s,r]}serialize(){let e=Buffer.alloc(0);for(let r of this.fields)try{if(r.timestampOffset&&r.blockLength){let s=new fc(Buffer.alloc(4)).writeBits(1,r.fBit).writeBits(7,r.blockPT).writeBits(14,r.timestampOffset).writeBits(10,r.blockLength);e=Buffer.concat([e,s.uint8Array])}else{let s=new fc(Buffer.alloc(1)).writeBits(1,0).writeBits(7,r.blockPT);e=Buffer.concat([e,s.uint8Array])}}catch(s){Eee(s?.message)}return e}},SM=class{constructor(t=1){this.distance=t}cache=[];cacheSize=10;push(t){this.cache.push(t),this.cache.length>this.cacheSize&&this.cache.shift()}build(){let t=new sA,e=this.cache.slice(-(this.distance+1)),r=e.pop();return r&&(e.forEach(s=>{let n=ul(r.timestamp,-s.timestamp);n>Cee||t.blocks.push({block:s.block,blockPT:s.blockPT,timestampOffset:n})}),t.blocks.push({block:r.block,blockPT:r.blockPT})),t}},Cee=16383,EM=class{size=150;sequenceNumbers=[];push(t,e){let r=[];return t.blocks.forEach(({blockPT:n,timestampOffset:i,block:o},a)=>{let c=Jr(e.header.sequenceNumber,-(t.blocks.length-(a+1)));i?r.push(new Jo(new Yo({timestamp:ul(e.header.timestamp,-i),payloadType:n,ssrc:e.header.ssrc,sequenceNumber:c,marker:!0}),o)):r.push(new Jo(new Yo({timestamp:e.header.timestamp,payloadType:n,ssrc:e.header.ssrc,sequenceNumber:c,marker:!0}),o))}),r.filter(n=>this.sequenceNumbers.includes(n.header.sequenceNumber)?!1:(this.sequenceNumbers.length>this.size&&this.sequenceNumbers.shift(),this.sequenceNumbers.push(n.header.sequenceNumber),!0))}},uc={OneByte:48862,TwoByte:4096},GN=2,XN=4,YN=8,JN=12,QN=4,Yo=class CM{version=2;padding=!1;paddingSize=0;extension=!1;marker=!1;payloadOffset=0;payloadType=0;sequenceNumber=0;timestamp=0;ssrc=0;csrcLength=0;csrc=[];extensionProfile=uc.OneByte;extensionLength;extensions=[];constructor(e={}){Object.assign(this,e)}static deSerialize(e){let r=new CM,s=0,n=e[s++];r.version=Te(n,0,2),r.padding=Te(n,2)>0,r.extension=Te(n,3)>0,r.csrcLength=Te(n,4,4),r.csrc=[...Array(r.csrcLength)].map(()=>{let o=e.readUInt32BE(s);return s+=4,o}),s+=JN-1;let i=e[1];r.marker=Te(i,0)>0,r.payloadType=Te(i,1,7),r.sequenceNumber=e.readUInt16BE(GN),r.timestamp=e.readUInt32BE(XN),r.ssrc=e.readUInt32BE(YN);for(let o=0;o<r.csrc.length;o++){let a=JN+o*QN;r.csrc[o]=e.subarray(a).readUInt32BE()}if(r.extension){r.extensionProfile=e.subarray(s).readUInt16BE(),s+=2;let o=e.subarray(s).readUInt16BE()*4;switch(r.extensionLength=o,s+=2,r.extensionProfile){case uc.OneByte:{let a=s+o;for(;s<a;){if(e[s]===0){s++;continue}let c=e[s]>>4,d=(e[s]&(e[s]^240))+1;if(s++,c===15)break;let u={id:c,payload:e.subarray(s,s+d)};r.extensions=[...r.extensions,u],s+=d}}break;case uc.TwoByte:{let a=s+o;for(;s<a;){if(e[s]===0){s++;continue}let c=e[s];s++;let d=e[s];s++;let u={id:c,payload:e.subarray(s,s+d)};r.extensions=[...r.extensions,u],s+=d}}break;default:{let a={id:0,payload:e.subarray(s,s+o)};r.extensions=[...r.extensions,a],s+=r.extensions[0].payload.length}break}}return r.payloadOffset=s,r.padding&&(r.paddingSize=e[e.length-1]),r}get serializeSize(){let{csrc:e,extensionProfile:r,extensions:s}=this,n=12+e.length*QN;if(s.length>0||this.extension===!0){let i=4;switch(r){case uc.OneByte:for(let o of s)i+=1+o.payload.length;break;case uc.TwoByte:for(let o of s)i+=2+o.payload.length;break;default:i+=s[0].payload.length}n+=Math.floor((i+3)/4)*4}return n}serialize(e){let r=Buffer.alloc(e),s=0,n=new D0(8);n.set(2,0,this.version),this.padding&&n.set(1,2,1),this.extensions.length>0&&(this.extension=!0),this.extension&&n.set(1,3,1),n.set(4,4,this.csrc.length),r.writeUInt8(n.value,s++);let i=new D0(8);this.marker&&i.set(1,0,1),i.set(7,1,this.payloadType),r.writeUInt8(i.value,s++),r.writeUInt16BE(this.sequenceNumber,GN),s+=2,r.writeUInt32BE(this.timestamp,XN),s+=4,r.writeUInt32BE(this.ssrc,YN),s+=4;for(let o of this.csrc)r.writeUInt32BE(o,s),s+=4;if(this.extension){let o=s;r.writeUInt16BE(this.extensionProfile,s),s+=4;let a=s;switch(this.extensionProfile){case uc.OneByte:for(let u of this.extensions)r.writeUInt8(u.id<<4|u.payload.length-1,s++),u.payload.copy(r,s),s+=u.payload.length;break;case uc.TwoByte:for(let u of this.extensions)r.writeUInt8(u.id,s++),r.writeUInt8(u.payload.length,s++),u.payload.copy(r,s),s+=u.payload.length;break;default:{let u=this.extensions[0].payload.length;if(u%4!=0)throw new Error;this.extensions[0].payload.copy(r,s),s+=u}}let c=s-a,d=Math.trunc((c+3)/4)*4;r.writeUInt16BE(Math.trunc(d/4),o+2);for(let u=0;u<d-c;u++)r.writeUInt8(0,s),s++}return this.payloadOffset=s,r}},Jo=class rk{constructor(e,r){this.header=e,this.payload=r}get serializeSize(){return this.header.serializeSize+this.payload.length}clone(){return new rk(new Yo({...this.header}),this.payload)}serialize(){let e=this.header.serialize(this.header.serializeSize+this.payload.length),{payloadOffset:r}=this.header;if(this.payload.copy(e,r),this.header.padding){let s=Buffer.alloc(this.header.paddingSize);s.writeUInt8(this.header.paddingSize,this.header.paddingSize-1),e=Buffer.concat([e,s])}return e}static deSerialize(e){let r=Yo.deSerialize(e);return new rk(r,e.subarray(r.payloadOffset,e.length-r.paddingSize))}clear(){this.payload=null}};AM=class{constructor(t,e,r,s){this.srtpSessionKey=t,this.srtpSessionSalt=e,this.srtcpSessionKey=r,this.srtcpSessionSalt=s}encryptRtp(t,e,r){return Buffer.from([])}decryptRtp(t,e,r){return[]}encryptRTCP(t,e){return Buffer.from([])}decryptRTCP(t){return[]}},xl=class extends Error{constructor(t){super(t),this.name="SrtpAuthenticationError"}},ZN=12,Tee=8;kee=class extends AM{constructor(t,e,r,s,n,i){super(t,e,r,s),this.srtpSessionAuthTag=n,this.srtcpSessionAuthTag=i}authTagLength=10;encryptRtp(t,e,r){let s=t.serialize(t.serializeSize),n=this.generateCounter(t.sequenceNumber,r,t.ssrc,this.srtpSessionSalt),o=(0,Yn.createCipheriv)("aes-128-ctr",this.srtpSessionKey,n).update(e),a=this.generateSrtpAuthTag(r,s,o);return Buffer.concat([s,o,a])}decryptRtp(t,e,r=iA(t,this.authTagLength)){let s=t.length-this.authTagLength,n=t.subarray(0,s),i=t.subarray(s),o=this.generateSrtpAuthTag(e,n.subarray(0,r.payloadOffset),n.subarray(r.payloadOffset));tU(i,o,"Failed to authenticate SRTP packet");let a=this.generateCounter(r.sequenceNumber,e,r.ssrc,this.srtpSessionSalt),c=(0,Yn.createDecipheriv)("aes-128-ctr",this.srtpSessionKey,a),d=n.subarray(r.payloadOffset),u=c.update(d),l=Buffer.concat([n.subarray(0,r.payloadOffset),u]);return[l,PM(r,l,"Failed to authenticate SRTP packet")]}encryptRTCP(t,e){let r=Buffer.from(t),s=r.readUInt32BE(4),n=this.generateCounter(e&65535,e>>16,s,this.srtcpSessionSalt);(0,Yn.createCipheriv)("aes-128-ctr",this.srtcpSessionKey,n).update(r.slice(8)).copy(r,8),r=Buffer.concat([r,Buffer.alloc(4)]),r.writeUInt32BE(e,r.length-4),r[r.length-4]|=128;let a=this.generateSrtcpAuthTag(r);return r=Buffer.concat([r,a]),r}decryptRTCP(t){let e=IM(t,this.authTagLength,eU),r=t.length-(this.authTagLength+eU),s=t.subarray(0,t.length-this.authTagLength),n=t.subarray(t.length-this.authTagLength),i=this.generateSrtcpAuthTag(s);tU(n,i,"Failed to authenticate SRTCP packet");let o=Buffer.from(t).slice(0,r);if(t[r]>>>7===0)return[o,e];let c=t.readUInt32BE(r);c&=~(1<<31);let d=t.readUInt32BE(4),u=this.generateCounter(c&65535,c>>16,d,this.srtcpSessionSalt);return(0,Yn.createDecipheriv)("aes-128-ctr",this.srtcpSessionKey,u).update(o.subarray(8)).copy(o,8),[o,e]}generateSrtcpAuthTag(t){return(0,Yn.createHmac)("sha1",this.srtcpSessionAuthTag).update(t).digest().slice(0,10)}generateCounter(t,e,r,s){let n=Buffer.alloc(16);n.writeUInt32BE(r,4),n.writeUInt32BE(e,8),n.writeUInt32BE(Number(BigInt(t)<<16n),12);for(let i=0;i<s.length;i++)n[i]^=s[i];return n}generateSrtpAuthTag(t,...e){let r=(0,Yn.createHmac)("sha1",this.srtpSessionAuthTag),s=Buffer.alloc(4);s.writeUInt32BE(t);for(let n of e)r.update(n);return r.update(s).digest().subarray(0,10)}},eU=4;Aee=class extends AM{aeadAuthTagLen=16;rtpIvWriter=A0([2,4,4,2],!0);rtcpIvWriter=A0([2,4,2,4],!0);aadWriter=A0([4],!0);constructor(t,e,r,s){super(t,e,r,s)}encryptRtp(t,e,r){let s=t.serialize(t.serializeSize),n=this.rtpInitializationVector(t,r),i=(0,Uh.createCipheriv)("aes-128-gcm",this.srtpSessionKey,n);i.setAAD(s);let o=i.update(e);i.final();let a=i.getAuthTag();return Buffer.concat([s,o,a])}decryptRtp(t,e,r=iA(t,this.aeadAuthTagLen)){let s=t.subarray(0,r.payloadOffset),n=t.length-this.aeadAuthTagLen,i=t.subarray(n),o=Buffer.from([]);o=VT(o,t.length-this.aeadAuthTagLen),s.copy(o);let a=this.rtpInitializationVector(r,e),c=t.slice(r.payloadOffset,n),d=(0,Uh.createDecipheriv)("aes-128-gcm",this.srtpSessionKey,a);d.setAAD(s),d.setAuthTag(i);let u=d.update(c);return sU(d,"SRTP"),u.copy(o,r.payloadOffset),[o,PM(r,o,"Failed to authenticate SRTP packet")]}encryptRTCP(t,e){let r=t.readUInt32BE(4),s=t.length+this.aeadAuthTagLen,n=Buffer.from([]);n=VT(n,s+_T),t.slice(0,8).copy(n);let i=this.rtcpInitializationVector(r,e),o=this.rtcpAdditionalAuthenticatedData(t,e),a=(0,Uh.createCipheriv)("aes-128-gcm",this.srtcpSessionKey,i);a.setAAD(o);let c=a.update(t.slice(8));return a.final(),c.copy(n,8),a.getAuthTag().copy(n,8+c.length),o.slice(8,12).copy(n,s),n}decryptRTCP(t){let e=IM(t,this.aeadAuthTagLen,_T),r=t.length-_T,s=r-this.aeadAuthTagLen,n=t.readUInt32BE(4),i=t.readUInt32BE(r),o=i>>>31===1,a=i&~(rU<<24),c=this.rtcpInitializationVector(n,a),d=o?Buffer.concat([t.subarray(0,8),t.subarray(r)]):Buffer.concat([t.subarray(0,s),t.subarray(r)]),u=o?t.slice(8,s):Buffer.alloc(0),l=o?Buffer.alloc(s):Buffer.from(t.subarray(0,s));o&&t.slice(0,8).copy(l);let h=(0,Uh.createDecipheriv)("aes-128-gcm",this.srtcpSessionKey,c);h.setAAD(d),h.setAuthTag(t.subarray(s,r));let p=h.update(u);return sU(h,"SRTCP"),o&&p.copy(l,8),[l,e]}rtpInitializationVector(t,e){let r=this.rtpIvWriter([0,t.ssrc,e,t.sequenceNumber]);for(let s=0;s<r.length;s++)r[s]^=this.srtpSessionSalt[s];return r}rtcpInitializationVector(t,e){let r=this.rtcpIvWriter([0,t,0,e]);for(let s=0;s<r.length;s++)r[s]^=this.srtcpSessionSalt[s];return r}rtcpAdditionalAuthenticatedData(t,e){let r=Buffer.concat([t.subarray(0,8),this.aadWriter([e])]);return r[8]|=rU,r}},_T=4,rU=128;DM=class{constructor(t,e,r){this.masterKey=t,this.masterSalt=e,this.profile=r;{let s=14-e.length;s>0&&(this.masterSalt=Buffer.concat([e,Buffer.alloc(s)]))}switch(this.srtpSessionKey=this.generateSessionKey(0),this.srtpSessionSalt=this.generateSessionSalt(2),this.srtpSessionAuthTag=this.generateSessionAuthTag(1),this.srtpSessionAuth=(0,Bw.createHmac)("sha1",this.srtpSessionAuthTag),this.srtcpSessionKey=this.generateSessionKey(3),this.srtcpSessionSalt=this.generateSessionSalt(5),this.srtcpSessionAuthTag=this.generateSessionAuthTag(4),this.srtcpSessionAuth=(0,Bw.createHmac)("sha1",this.srtcpSessionAuthTag),r){case Hh:this.cipher=new kee(this.srtpSessionKey,this.srtpSessionSalt,this.srtcpSessionKey,this.srtcpSessionSalt,this.srtpSessionAuthTag,this.srtcpSessionAuthTag);break;case _l:this.cipher=new Aee(this.srtpSessionKey,this.srtpSessionSalt,this.srtcpSessionKey,this.srtcpSessionSalt);break}}srtpSSRCStates={};srtpSessionKey;srtpSessionSalt;srtpSessionAuthTag;srtpSessionAuth;srtcpSSRCStates={};srtcpSessionKey;srtcpSessionSalt;srtcpSessionAuthTag;srtcpSessionAuth;cipher;generateSessionKey(t){let e=Buffer.from(this.masterSalt),r=Buffer.from([t,0,0,0,0,0,0]);for(let n=r.length-1,i=e.length-1;n>=0;n--,i--)e[i]=e[i]^r[n];e=Buffer.concat([e,Buffer.from([0,0])]);let s=new Lw.default.AES(this.masterKey);return Buffer.from(s.encrypt(e))}generateSessionSalt(t){let e=Buffer.from(this.masterSalt),r=Buffer.from([t,0,0,0,0,0,0]);for(let n=r.length-1,i=e.length-1;n>=0;n--,i--)e[i]=e[i]^r[n];e=Buffer.concat([e,Buffer.from([0,0])]);let s=new Lw.default.AES(this.masterKey);return e=Buffer.from(s.encrypt(e)),e.subarray(0,14)}generateSessionAuthTag(t){let e=Buffer.from(this.masterSalt),r=Buffer.from([t,0,0,0,0,0,0]);for(let o=r.length-1,a=e.length-1;o>=0;o--,a--)e[a]=e[a]^r[o];let s=Buffer.concat([e,Buffer.from([0,0])]),n=Buffer.concat([e,Buffer.from([0,1])]),i=new Lw.default.AES(this.masterKey);return s=Buffer.from(i.encrypt(s)),n=Buffer.from(i.encrypt(n)),Buffer.concat([s,n.subarray(0,4)])}getSrtpSsrcState(t){let e=this.srtpSSRCStates[t];return e||(e={ssrc:t,rolloverCounter:0,lastSequenceNumber:0},this.srtpSSRCStates[t]=e,e)}getSrtcpSsrcState(t){let e=this.srtcpSSRCStates[t];return e||(e={srtcpIndex:0,ssrc:t},this.srtcpSSRCStates[t]=e,e)}updateRolloverCount(t,e){e.rolloverHasProcessed?t===0?e.lastSequenceNumber>d0&&e.rolloverCounter++:e.lastSequenceNumber<d0&&t>nU-d0?e.rolloverCounter>0&&e.rolloverCounter--:t<d0&&e.lastSequenceNumber>nU-d0&&e.rolloverCounter++:e.rolloverHasProcessed=!0,e.lastSequenceNumber=t}generateSrtpAuthTag(t,e){this.srtpSessionAuth=(0,Bw.createHmac)("sha1",this.srtpSessionAuthTag);let r=Buffer.alloc(4);return r.writeUInt32BE(e),this.srtpSessionAuth.update(t).update(r).digest().slice(0,10)}index(t){let e=this.srtcpSSRCStates[t];return e?e.srtcpIndex:0}setIndex(t,e){let r=this.getSrtcpSsrcState(t);r.srtcpIndex=e%2147483647}},d0=100,nU=65535,Iee=class extends DM{constructor(t,e,r){super(t,e,r)}encryptRTCP(t){let e=t.readUInt32BE(4),r=this.getSrtcpSsrcState(e);return r.srtcpIndex++,r.srtcpIndex>>Ree&&(r.srtcpIndex=0),this.cipher.encryptRTCP(t,r.srtcpIndex)}decryptRTCP(t){return this.cipher.decryptRTCP(t)}},Ree=2147483647,BM=class{constructor(t){this.ContextCls=t}localContext;remoteContext;onData;start(t,e,r,s,n){this.localContext=new this.ContextCls(t,e,n),this.remoteContext=new this.ContextCls(r,s,n)}},LM=class extends BM{constructor(t){super(Iee),this.config=t,this.start(t.keys.localMasterKey,t.keys.localMasterSalt,t.keys.remoteMasterKey,t.keys.remoteMasterSalt,t.profile)}decrypt=t=>{let[e]=this.remoteContext.decryptRTCP(t);return e};encrypt(t){return this.localContext.encryptRTCP(t)}},Pee=class extends DM{constructor(t,e,r){super(t,e,r)}encryptRtp(t,e){let r=this.getSrtpSsrcState(e.ssrc);return this.updateRolloverCount(e.sequenceNumber,r),this.cipher.encryptRtp(e,t,r.rolloverCounter)}decryptRtp(t){let e=iA(t,this.rtpAuthTagLength),r=this.srtpSSRCStates[e.ssrc],s=r?{...r}:{ssrc:e.ssrc,rolloverCounter:0,lastSequenceNumber:0};this.updateRolloverCount(e.sequenceNumber,s);let n=this.cipher.decryptRtp(t,s.rolloverCounter,e);return r?Object.assign(r,s):this.srtpSSRCStates[e.ssrc]=s,n}get rtpAuthTagLength(){return this.profile===_l?16:10}},OM=class extends BM{constructor(t){super(Pee),this.config=t,this.start(t.keys.localMasterKey,t.keys.localMasterSalt,t.keys.remoteMasterKey,t.keys.remoteMasterSalt,t.profile)}decrypt=t=>{let[e]=this.remoteContext.decryptRtp(t);return e};encrypt(t,e){return this.localContext.encryptRtp(t,e)}},Dee=class{constructor(t){this.props=t}sequenceNumber=zk();timestamp=Yw();create(t){this.sequenceNumber=Jr(this.sequenceNumber,1);let e=this.props.between*this.props.clockRate/1e3;this.timestamp=ul(this.timestamp,e);let r=new Yo({sequenceNumber:this.sequenceNumber,timestamp:Number(this.timestamp),payloadType:96,extension:!0,marker:!1,padding:!1});return new Jo(r,t)}},ys=ft("werift-dtls : packages/dtls/src/flight/client/flight5.ts : log"),Bee=class extends eg{constructor(t,e,r,s){super(t,e,5,7),this.cipher=r,this.srtp=s}handleHandshake(t){this.dtls.bufferHandshakeCache([t],!1,4);let e=(()=>{switch(t.msg_type){case 2:return I7.deSerialize(t.fragment);case 11:return e1.deSerialize(t.fragment);case 12:return D7.deSerialize(t.fragment);case 13:return A7.deSerialize(t.fragment);case 14:return R7.deSerialize(t.fragment)}})();e&&qh[e.msgType]({dtls:this.dtls,cipher:this.cipher,srtp:this.srtp})(e)}async exec(){if(this.dtls.flight===5){ys(this.dtls.sessionId,"flight5 twice"),this.send(this.dtls.lastMessage);return}this.dtls.flight=5;let t=this.dtls.requestedCertificateTypes.length>0;ys(this.dtls.sessionId,"send flight5",t);let e=[t&&this.sendCertificate(),this.sendClientKeyExchange(),t&&this.sendCertificateVerify(),this.sendChangeCipherSpec(),this.sendFinished()].filter(r=>r);this.dtls.lastMessage=e,await this.transmit(e)}sendCertificate(){let t=new e1([Buffer.from(this.cipher.localCert)]),e=this.createPacket([t]);return Buffer.concat(e.map(s=>s.serialize()))}sendClientKeyExchange(){if(!this.cipher.localKeyPair)throw new Error;let t=new k7(this.cipher.localKeyPair.publicKey),e=this.createPacket([t]),r=Buffer.concat(e.map(a=>a.serialize())),s=this.cipher.localKeyPair,n=this.cipher.remoteKeyPair;if(!n.publicKey)throw new Error("not exist");let i=d7(n.publicKey,s.privateKey,s.curve);ys(this.dtls.sessionId,"extendedMasterSecret",this.dtls.options.extendedMasterSecret,this.dtls.remoteExtendedMasterSecret);let o=Buffer.concat(this.dtls.sortedHandshakeCache.map(a=>a.serialize()));return this.cipher.masterSecret=this.dtls.options.extendedMasterSecret&&this.dtls.remoteExtendedMasterSecret?u7(i,o):l7(i,this.cipher.localRandom.serialize(),this.cipher.remoteRandom.serialize()),this.cipher.cipher=_7(this.cipher.cipherSuite),this.cipher.cipher.init(this.cipher.masterSecret,this.cipher.remoteRandom.serialize(),this.cipher.localRandom.serialize()),ys(this.dtls.sessionId,"cipher",this.cipher.cipher.summary),r}sendCertificateVerify(){let t=Buffer.concat(this.dtls.sortedHandshakeCache.map(o=>o.serialize())),e=this.cipher.signatureData(t,"sha256"),r=(()=>{switch(this.cipher.signatureHashAlgorithm?.signature){case zi.ecdsa_3:return OT.ecdsa_secp256r1_sha256;case zi.rsa_1:return OT.rsa_pkcs1_sha256}})();if(!r)throw new Error;ys(this.dtls.sessionId,"signatureScheme",this.cipher.signatureHashAlgorithm?.signature,r);let s=new T7(r,e),n=this.createPacket([s]);return Buffer.concat(n.map(o=>o.serialize()))}sendChangeCipherSpec(){let t=C7.createEmpty().serialize(),e=Z0(this.dtls)([{type:20,fragment:t}],++this.dtls.recordSequenceNumber);return Buffer.concat(e.map(s=>s.serialize()))}sendFinished(){let t=Buffer.concat(this.dtls.sortedHandshakeCache.map(i=>i.serialize())),e=this.cipher.verifyData(t),r=new FT(e);this.dtls.epoch=1;let[s]=this.createPacket([r]);this.dtls.recordSequenceNumber=0;let n=this.cipher.encryptPacket(s).serialize();return ys(this.dtls.sessionId,"finished",this.cipher.cipher.summary),n}},qh={};qh[2]=({cipher:t,srtp:e,dtls:r})=>s=>{ys(r.sessionId,"serverHello",s.cipherSuite),t.remoteRandom=fl.from(s.random),t.cipherSuite=s.cipherSuite,ys(r.sessionId,"selected cipherSuite",t.cipherSuite),s.extensions&&s.extensions.forEach(n=>{switch(n.type){case Lh.type:{let i=Lh.fromData(n.data),o=U0.findMatchingSRTPProfile(i.profiles,r.options.srtpProfiles||[]);if(ys(r.sessionId,"selected srtp profile",o),o==null)return;e.srtpProfile=o}break;case b1.type:r.remoteExtendedMasterSecret=!0;break;case x1.type:ys(r.sessionId,"RenegotiationIndication");break}})};qh[11]=({cipher:t,dtls:e})=>r=>{ys(e.sessionId,"handshake certificate",r),t.remoteCertificate=r.certificateList[0]};qh[12]=({cipher:t,dtls:e})=>r=>{if(!t.localRandom||!t.remoteRandom)throw new Error;ys(e.sessionId,"ServerKeyExchange",r),ys(e.sessionId,"selected curve",r.namedCurve),t.remoteKeyPair={curve:r.namedCurve,publicKey:r.publicKey},t.localKeyPair=E7(r.namedCurve)};qh[13]=({dtls:t})=>e=>{ys(t.sessionId,"certificate_request",e),t.requestedCertificateTypes=e.certificateTypes,t.requestedSignatureAlgorithms=e.signatures};qh[14]=({dtls:t})=>e=>{ys(t.sessionId,"server_hello_done",e)};NM=class C0{constructor(e,r){this.serverVersion=e,this.cookie=r}msgType=3;messageSeq;static spec={serverVersion:Zk,cookie:wl.types.buffer(wl.types.uint8)};static createEmpty(){return new C0(void 0,void 0)}static deSerialize(e){return new C0(...Object.values((0,wl.decode)(e,C0.spec)))}serialize(){let e=(0,wl.encode)(this,C0.spec).slice();return Buffer.from(e)}get version(){return{major:255-this.serverVersion.major,minor:255-this.serverVersion.minor}}toFragment(){let e=this.serialize();return new vn(this.msgType,e.length,this.messageSeq,0,e.length,e)}},Lee=ft("werift-dtls : packages/dtls/src/context/dtls.ts : log"),iU=class{constructor(t,e){this.options=t,this.sessionType=e}version={major:254,minor:253};lastFlight=[];lastMessage=[];recordSequenceNumber=0;sequenceNumber=0;epoch=0;flight=0;handshakeCache={};cookie;requestedCertificateTypes=[];requestedSignatureAlgorithms=[];remoteExtendedMasterSecret=!1;get sessionId(){return this.cookie?this.cookie.toString("hex").slice(0,10):""}get sortedHandshakeCache(){return Object.entries(this.handshakeCache).sort(([t],[e])=>Number(t)-Number(e)).flatMap(([,{data:t}])=>t.sort((e,r)=>e.message_seq-r.message_seq))}checkHandshakesExist=t=>!t.find(e=>this.sortedHandshakeCache.find(r=>r.msg_type===e)==null);bufferHandshakeCache(t,e,r){this.handshakeCache[r]||(this.handshakeCache[r]={data:[],isLocal:e,flight:r});let s=t.filter(n=>{let i=this.handshakeCache[r].data.find(o=>o.msg_type===n.msg_type);return i?(Lee(this.sessionId,"exist",i.summary,e,r),!1):!0});this.handshakeCache[r].data=[...this.handshakeCache[r].data,...s]}},Oee=class{constructor(t){this.socket=t}send=t=>this.socket.send(t)},sk=class qo{static type=10;static spec={type:Vi.types.uint16be,data:Vi.types.array(Vi.types.uint16be,Vi.types.uint16be,"bytes")};type=qo.type;data=[];constructor(e={}){Object.assign(this,e)}static createEmpty(){return new qo}static fromData(e){return new qo({type:qo.type,data:(0,Vi.decode)(e,qo.spec.data)})}static deSerialize(e){return new qo((0,Vi.decode)(e,qo.spec))}serialize(){return Buffer.from((0,Vi.encode)(this,qo.spec).slice())}get extension(){return{type:this.type,data:this.serialize().slice(2)}}},nk=class hc{static type=13;static spec={type:qi.types.uint16be,data:qi.types.array({hash:qi.types.uint8,signature:qi.types.uint8},qi.types.uint16be,"bytes")};type=hc.type;data=[];constructor(e={}){Object.assign(this,e)}static createEmpty(){return new hc}static deSerialize(e){return new hc((0,qi.decode)(e,hc.spec))}serialize(){let e=(0,qi.encode)(this,hc.spec).slice();return Buffer.from(e)}static fromData(e){let r=Buffer.alloc(2);return r.writeUInt16BE(hc.type),hc.deSerialize(Buffer.concat([r,e]))}get extension(){return{type:this.type,data:this.serialize().slice(2)}}},oU=class Ow{constructor(e,r){this.level=e,this.description=r}static spec={level:vl.types.uint8,description:vl.types.uint8};static deSerialize(e){return new Ow(...Object.values((0,vl.decode)(e,Ow.spec)))}serialize(){let e=(0,vl.encode)(this,Ow.spec).slice();return Buffer.from(e)}},aU=ft("werift-dtls : packages/dtls/record/receive.ts : log"),ST=ft("werift-dtls : packages/dtls/record/receive.ts : err"),Nee=t=>{let e=0,r=[];for(;t.length>e;){let s=t.readUInt16BE(e+11);if(t.length<e+(12+s))break;let n=w7.deSerialize(t.subarray(e));r.push(n),e+=13+s}return r},Uee=(t,e)=>r=>{switch(r.recordLayerHeader.contentType){case 20:return aU(t.sessionId,"change cipher spec"),[{type:20,data:void 0}];case 22:{let n=r.fragment;try{r.recordLayerHeader.epoch>0&&(aU(t.sessionId,"decrypt handshake"),n=e.decryptPacket(r))}catch(i){throw ST(t.sessionId,"decrypt failed",i),i}try{let i=0,o=[];for(;n.length>i;){let a=vn.deSerialize(n.subarray(i));o.push({type:22,data:a}),i+=a.fragment_length+12}return o}catch(i){throw ST(t.sessionId,"decSerialize failed",i,n),i}}case 23:return[{type:23,data:e.decryptPacket(r)}];case 21:{let n=oU.deSerialize(r.fragment);if(jT[n.description]==null){let i=e.decryptPacket(r);n=oU.deSerialize(i)}if(ST(t.sessionId,"ContentType.alert",n,jT[n.description],"flight",t.flight,"lastFlight",t.lastFlight),n.level>1)throw new Error("alert fatal error");return[{type:21,data:void 0}]}default:return[{type:21,data:void 0}]}},cU=ft("werift-dtls : packages/dtls/src/socket.ts : log"),dU=ft("werift-dtls : packages/dtls/src/socket.ts : err"),oA=class{constructor(t,e){this.options=t,this.sessionType=e,this.dtls=new iU(this.options,this.sessionType),this.cipher=new N0(this.sessionType,this.options.cert,this.options.key,this.options.signatureHash),this.transport=new Oee(this.options.transport),this.setupExtensions(),this.transport.socket.onData=this.udpOnMessage}onConnect=new Ne;onData=new Ne;onError=new Ne;onClose=new Ne;transport;cipher;dtls;srtp=new U0;connected=!1;extensions=[];onHandleHandshakes;bufferFragmentedHandshakes=[];renegotiation(){cU("renegotiation",this.sessionType),this.connected=!1,this.cipher=new N0(this.sessionType,this.options.cert,this.options.key,this.options.signatureHash),this.dtls=new iU(this.options,this.sessionType),this.srtp=new U0,this.extensions=[],this.bufferFragmentedHandshakes=[]}udpOnMessage=t=>{let e=Nee(t);for(let r of e)try{let s=Uee(this.dtls,this.cipher)(r);for(let n of s)switch(n.type){case 22:{let i=n.data,o=this.handleFragmentHandshake([i]),a=Object.values(o.reduce((c,d)=>(c[d.msg_type]||(c[d.msg_type]=[]),c[d.msg_type].push(d),c),{})).map(c=>vn.assemble(c)).sort((c,d)=>c.msg_type-d.msg_type);this.onHandleHandshakes(a).catch(c=>{dU(this.dtls.sessionId,"onHandleHandshakes error",c),this.onError.execute(c)})}break;case 23:this.onData.execute(n.data);break;case 21:this.onClose.execute();break}}catch(s){dU(this.dtls.sessionId,"catch udpOnMessage error",s)}};setupExtensions(){if(cU(this.dtls.sessionId,"support srtpProfiles",this.options.srtpProfiles),this.options.srtpProfiles&&this.options.srtpProfiles.length>0){let t=Lh.create(this.options.srtpProfiles,Buffer.from([0]));this.extensions.push(t.extension)}{let t=sk.createEmpty();t.data=Xk,this.extensions.push(t.extension)}{let t=nk.createEmpty();t.data=Jk,this.extensions.push(t.extension)}this.options.extendedMasterSecret&&this.extensions.push({type:b1.type,data:Buffer.alloc(0)});{let t=x1.createEmpty();this.extensions.push(t.extension)}}waitForReady=t=>new Promise(async(e,r)=>{for(let s=0;s<10;s++)if(t()){e();break}else await(0,UM.setTimeout)(100*s);r("waitForReady timeout")});handleFragmentHandshake(t){let e=t.filter(r=>r.fragment_length!==r.length?(this.bufferFragmentedHandshakes.push(r),!1):!0);if(this.bufferFragmentedHandshakes.length>1){let[r]=this.bufferFragmentedHandshakes.slice(-1);r.fragment_offset+r.fragment_length===r.length&&(e=[...this.bufferFragmentedHandshakes,...e],this.bufferFragmentedHandshakes=[])}return e}send=async t=>{let e=Z0(this.dtls)([{type:23,fragment:t}],++this.dtls.recordSequenceNumber)[0];await this.transport.send(this.cipher.encryptPacket(e).serialize())};close(){this.transport.socket.close()}extractSessionKeys(t,e){let r=this.exportKeyingMaterial("EXTRACTOR-dtls_srtp",t*2+e*2),{clientKey:s,serverKey:n,clientSalt:i,serverSalt:o}=(0,ll.decode)(r,{clientKey:ll.types.buffer(t),serverKey:ll.types.buffer(t),clientSalt:ll.types.buffer(e),serverSalt:ll.types.buffer(e)});return this.sessionType===Go.CLIENT?{localKey:s,localSalt:i,remoteKey:n,remoteSalt:o}:{localKey:n,localSalt:o,remoteKey:s,remoteSalt:i}}exportKeyingMaterial(t,e){return NZ(t,e,this.cipher.masterSecret,this.cipher.localRandom.serialize(),this.cipher.remoteRandom.serialize(),this.sessionType===Go.CLIENT)}get remoteCertificate(){return this.cipher.remoteCertificate}},ET=ft("werift-dtls : packages/dtls/src/client.ts : log"),ik=class extends oA{constructor(t){super(t,Go.CLIENT),this.onHandleHandshakes=this.handleHandshakes,ET(this.dtls.sessionId,"start client")}async connect(){await new JZ(this.transport,this.dtls,this.cipher).exec(this.extensions)}flight5;handleHandshakes=async t=>{ET(this.dtls.sessionId,"handleHandshakes",t.map(e=>e.msg_type));for(let e of t)switch(e.msg_type){case 3:{let r=NM.deSerialize(e.fragment);await new ZZ(this.transport,this.dtls).exec(r)}break;case 2:{if(this.connected)return;this.flight5=new Bee(this.transport,this.dtls,this.cipher,this.srtp),this.flight5.handleHandshake(e)}break;case 11:case 12:case 13:await this.waitForReady(()=>!!this.flight5),this.flight5?.handleHandshake(e);break;case 14:{await this.waitForReady(()=>!!this.flight5),this.flight5?.handleHandshake(e);let r=[11,12,this.options.certificateRequest&&13].filter(s=>typeof s=="number");await this.waitForReady(()=>this.dtls.checkHandshakesExist(r)),await this.flight5?.exec()}break;case 20:this.dtls.flight=7,this.connected=!0,this.onConnect.execute(),ET(this.dtls.sessionId,"dtls connected");break}}},Fi=ft("werift-dtls : packages/dtls/flight/server/flight2.ts : log"),Mee=(t,e,r,s)=>n=>{Fi("dtls version",n.clientVersion),e.flight=2,e.recordSequenceNumber=0,e.sequenceNumber=0,n.extensions.forEach(l=>{switch(l.type){case sk.type:{let h=sk.fromData(l.data).data;Fi(e.sessionId,"curves",h);let p=h.filter(m=>Xk.includes(m))[0];r.namedCurve=p,Fi(e.sessionId,"curve selected",r.namedCurve)}break;case nk.type:{if(!r.signatureHashAlgorithm)throw new Error("need to set certificate");let h=nk.fromData(l.data).data;Fi(e.sessionId,"hash,signature",h);let p=h.find(_=>_.signature===r.signatureHashAlgorithm?.signature)?.signature,m=h.find(_=>_.hash===r.signatureHashAlgorithm?.hash)?.hash;if(p==null||m==null)throw new Error("invalid signatureHash")}break;case Lh.type:{if(!e.options?.srtpProfiles||e.options.srtpProfiles.length===0)return;let h=Lh.fromData(l.data);Fi(e.sessionId,"srtp profiles",h.profiles);let p=U0.findMatchingSRTPProfile(h.profiles,e.options?.srtpProfiles);if(!p)throw new Error;s.srtpProfile=p,Fi(e.sessionId,"srtp profile selected",s.srtpProfile)}break;case b1.type:e.remoteExtendedMasterSecret=!0;break;case x1.type:Fi(e.sessionId,"RenegotiationIndication",l.data);break;case 43:{let p=[...l.data.subarray(1)].map(m=>m.toString(10));Fi("dtls supported version",p)}break}}),r.localRandom=new fl,r.remoteRandom=fl.from(n.random);let i=n.cipherSuites;Fi(e.sessionId,"cipher suites",i);let o=(()=>{switch(r.signatureHashAlgorithm?.signature){case zi.ecdsa_3:return Qw.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256_49195;case zi.rsa_1:return Qw.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256_49199}})();if(o===void 0||!i.includes(o))throw new Error("dtls cipher suite negotiation failed");r.cipherSuite=o,Fi(e.sessionId,"selected cipherSuite",r.cipherSuite),r.localKeyPair=E7(r.namedCurve),e.cookie||=(0,MM.randomBytes)(20);let a=new NM({major:254,minor:253},e.cookie),c=v7(e)([a]),u=Z0(e)(c.map(l=>({type:22,fragment:l.serialize()})),++e.recordSequenceNumber).map(l=>l.serialize());for(let l of u)t.send(l)},lU=ft("werift-dtls : packages/dtls/flight/server/flight4.ts : log"),jee=class extends eg{constructor(t,e,r,s){super(t,e,4,6),this.cipher=r,this.srtp=s}async exec(t,e=!1){if(this.dtls.flight===4){lU(this.dtls.sessionId,"flight4 twice"),this.send(this.dtls.lastMessage);return}this.dtls.flight=4,this.dtls.sequenceNumber=1,this.dtls.bufferHandshakeCache([t],!1,4);let r=[this.sendServerHello(),this.sendCertificate(),this.sendServerKeyExchange(),e&&this.sendCertificateRequest(),this.sendServerHelloDone()].filter(s=>s);this.dtls.lastMessage=r,await this.transmit(r)}sendServerHello(){let t=[];this.srtp.srtpProfile&&t.push(Lh.create([this.srtp.srtpProfile],Buffer.from([0])).extension),this.dtls.options.extendedMasterSecret&&t.push({type:b1.type,data:Buffer.alloc(0)});let e=x1.createEmpty();t.push(e.extension);let r=new I7(this.dtls.version,this.cipher.localRandom,Buffer.from([0]),this.cipher.cipherSuite,0,t),s=this.createPacket([r]);return Buffer.concat(s.map(n=>n.serialize()))}sendCertificate(){let t=new e1([Buffer.from(this.cipher.localCert)]),e=this.createPacket([t]);return Buffer.concat(e.map(r=>r.serialize()))}sendServerKeyExchange(){let t=this.cipher.generateKeySignature("sha256");if(!this.cipher.signatureHashAlgorithm)throw new Error("not exist");let e=new D7(Yk.named_curve_3,this.cipher.namedCurve,this.cipher.localKeyPair.publicKey.length,this.cipher.localKeyPair.publicKey,this.cipher.signatureHashAlgorithm.hash,this.cipher.signatureHashAlgorithm.signature,t.length,t),r=this.createPacket([e]);return Buffer.concat(r.map(s=>s.serialize()))}sendCertificateRequest(){let t=new A7(o7,Jk,[]);lU(this.dtls.sessionId,"sendCertificateRequest",t);let e=this.createPacket([t]);return Buffer.concat(e.map(r=>r.serialize()))}sendServerHelloDone(){let t=new R7,e=this.createPacket([t]);return Buffer.concat(e.map(r=>r.serialize()))}},Mh=ft("werift-dtls : packages/dtls/flight/server/flight6.ts"),$ee=class extends eg{constructor(t,e,r){super(t,e,6),this.cipher=r}handleHandshake(t){this.dtls.bufferHandshakeCache([t],!1,5);let e=(()=>{switch(t.msg_type){case 11:return e1.deSerialize(t.fragment);case 15:return T7.deSerialize(t.fragment);case 16:return k7.deSerialize(t.fragment);case 20:return FT.deSerialize(t.fragment)}})();if(e){let r=ng[e.msgType];if(!r)return;r({dtls:this.dtls,cipher:this.cipher})(e)}}async exec(){if(this.dtls.flight===6){Mh(this.dtls.sessionId,"flight6 twice"),this.send(this.dtls.lastMessage);return}this.dtls.flight=6;let t=[this.sendChangeCipherSpec(),this.sendFinished()];this.dtls.lastMessage=t,await this.transmit(t)}sendChangeCipherSpec(){let t=C7.createEmpty().serialize(),e=Z0(this.dtls)([{type:20,fragment:t}],++this.dtls.recordSequenceNumber);return Buffer.concat(e.map(s=>s.serialize()))}sendFinished(){let t=Buffer.concat(this.dtls.sortedHandshakeCache.map(i=>i.serialize())),e=this.cipher.verifyData(t),r=new FT(e);this.dtls.epoch=1;let[s]=this.createPacket([r]);return this.dtls.recordSequenceNumber=0,this.cipher.encryptPacket(s).serialize()}},ng={};ng[16]=({cipher:t,dtls:e})=>r=>{if(t.remoteKeyPair={curve:t.namedCurve,publicKey:r.publicKey},!t.remoteKeyPair.publicKey||!t.localKeyPair||!t.remoteRandom||!t.localRandom)throw new Error("not exist");let s=d7(t.remoteKeyPair.publicKey,t.localKeyPair.privateKey,t.localKeyPair.curve);Mh(e.sessionId,"extendedMasterSecret",e.options.extendedMasterSecret,e.remoteExtendedMasterSecret);let n=Buffer.concat(e.sortedHandshakeCache.map(i=>i.serialize()));t.masterSecret=e.options.extendedMasterSecret&&e.remoteExtendedMasterSecret?u7(s,n):l7(s,t.remoteRandom.serialize(),t.localRandom.serialize()),t.cipher=_7(t.cipherSuite),t.cipher.init(t.masterSecret,t.localRandom.serialize(),t.remoteRandom.serialize()),Mh(e.sessionId,"setup cipher",t.cipher.summary)};ng[11]=({cipher:t,dtls:e})=>r=>{Mh(e.sessionId,"handshake certificate",r),t.remoteCertificate=r.certificateList[0]};ng[15]=({cipher:t,dtls:e})=>r=>{if(!t.remoteCertificate)throw new Error("client certificate missing before certificate verify");Mh(e.sessionId,"certificate_verify",r.algorithm)};ng[20]=({dtls:t})=>e=>{Mh(t.sessionId,"finished",e)};vh=ft("werift-dtls : packages/dtls/src/server.ts : log"),jM=class extends oA{constructor(t){super(t,Go.SERVER),this.onHandleHandshakes=this.handleHandshakes,vh(this.dtls.sessionId,"start server")}flight6;handleHandshakes=async t=>{vh(this.dtls.sessionId,"handleHandshakes",t.map(e=>e.msg_type));for(let e of t)switch(e.msg_type){case 1:{this.connected&&this.renegotiation();let r=b7.deSerialize(e.fragment);r.cookie.length===0?(vh(this.dtls.sessionId,"send flight2"),Mee(this.transport,this.dtls,this.cipher,this.srtp)(r)):this.dtls.cookie&&r.cookie.equals(this.dtls.cookie)?(vh(this.dtls.sessionId,"send flight4"),await new jee(this.transport,this.dtls,this.cipher,this.srtp).exec(e,this.options.certificateRequest)):vh("wrong state",{dtlsCookie:this.dtls.cookie?.toString("hex").slice(10),helloCookie:r.cookie.toString("hex").slice(10)})}break;case 11:case 15:case 16:{if(this.connected)return;this.flight6=new $ee(this.transport,this.dtls,this.cipher),this.flight6.handleHandshake(e)}break;case 20:{await this.waitForReady(()=>!!this.flight6),this.flight6?.handleHandshake(e);let r=[16,this.options.certificateRequest&&11,this.options.certificateRequest&&15].filter(s=>typeof s=="number");await this.waitForReady(()=>this.dtls.checkHandshakesExist(r)),await this.flight6?.exec(),this.connected=!0,this.onConnect.execute(),vh(this.dtls.sessionId,"dtls connected")}break}}},_1=554869826,$M=8,FM=1398035790,zo=20,aA=24,cA=1,dA=2,HM=6,qM=50,Fee=["FINGERPRINT","MESSAGE-INTEGRITY","CHANGE-REQUEST","PRIORITY","USERNAME","ICE-CONTROLLING","SOURCE-ADDRESS","USE-CANDIDATE","ICE-CONTROLLED","ERROR-CODE","XOR-MAPPED-ADDRESS","CHANGED-ADDRESS","LIFETIME","REQUESTED-TRANSPORT","NONCE","REALM","XOR-RELAYED-ADDRESS","CHANNEL-NUMBER","XOR-PEER-ADDRESS","DATA","SOFTWARE","MAPPED-ADDRESS","RESPONSE-ORIGIN","OTHER-ADDRESS"],lA=(t=>(t[t.REQUEST=0]="REQUEST",t[t.INDICATION=16]="INDICATION",t[t.RESPONSE=256]="RESPONSE",t[t.ERROR=272]="ERROR",t))(lA||{}),uA=(t=>(t[t.BINDING=1]="BINDING",t[t.SHARED_SECRET=2]="SHARED_SECRET",t[t.ALLOCATE=3]="ALLOCATE",t[t.REFRESH=4]="REFRESH",t[t.SEND=6]="SEND",t[t.DATA=7]="DATA",t[t.CREATE_PERMISSION=8]="CREATE_PERMISSION",t[t.CHANNEL_BIND=9]="CHANNEL_BIND",t))(uA||{});uU=class{queue=[];wait=new Ne;put(t){this.queue.push(t),this.queue.length===1&&this.wait.execute(t)}get(){let t=this.queue.shift();return t||new Promise(e=>{this.wait.subscribe(r=>{this.queue.shift(),e(r)})})}},ok=t=>{let e,r,s=new Promise((i,o)=>{e=i,r=o});s.then(()=>{n.execute(void 0),n.complete()}).catch(i=>{n.execute(i??new Error),n.complete()});let n=new Ne;return t(e,r,n).catch(()=>{}),{awaitable:s,resolve:e,reject:r}};pA=Buffer.alloc(6);pA.writeUInt16BE(_1>>16,0);pA.writeUInt32BE(_1,2);u0=t=>{let e=Buffer.alloc(4);return e.writeUInt32BE(t,0),e},h0=t=>t.readUInt32BE(0),Vee=t=>{let e=Buffer.alloc(4);return e.writeUInt16BE(t,0),e},zee=t=>t.readUInt16BE(0),hU=t=>new oT(t.toString()).toBuffer(),fU=t=>{let e=new oT(t);return BigInt(e.toString())},CT=t=>Buffer.from(t,"utf8"),TT=t=>t.toString("utf8"),kT=t=>t,AT=t=>t,Wee=t=>Buffer.from([]),Kee=t=>null,WM=[[1,"MAPPED-ADDRESS",Ch,Th],[3,"CHANGE-REQUEST",u0,h0],[4,"SOURCE-ADDRESS",Ch,Th],[5,"CHANGED-ADDRESS",Ch,Th],[6,"USERNAME",CT,TT],[8,"MESSAGE-INTEGRITY",kT,AT],[9,"ERROR-CODE",qee,Hee],[12,"CHANNEL-NUMBER",Vee,zee],[13,"LIFETIME",u0,h0],[18,"XOR-PEER-ADDRESS",Uw,Nw],[19,"DATA",kT,AT],[20,"REALM",CT,TT],[21,"NONCE",kT,AT],[22,"XOR-RELAYED-ADDRESS",Uw,Nw],[25,"REQUESTED-TRANSPORT",u0,h0],[32,"XOR-MAPPED-ADDRESS",Uw,Nw],[36,"PRIORITY",u0,h0],[37,"USE-CANDIDATE",Wee,Kee],[32802,"SOFTWARE",CT,TT],[32808,"FINGERPRINT",u0,h0],[32809,"ICE-CONTROLLED",hU,fU],[32810,"ICE-CONTROLLING",hU,fU],[32811,"RESPONSE-ORIGIN",Ch,Th],[32812,"OTHER-ADDRESS",Ch,Th]],KM=class{constructor(t=[]){this.attributes=t}getAttributes(){return this.attributes}setAttribute(t,e){let r=this.attributes.find(s=>s[0]===t);return r?r[1]=e:this.attributes.push([t,e]),this}getAttributeValue(t){let e=this.attributes.find(r=>r[0]===t);if(e)return e[1]}get attributesKeys(){return this.attributes.map(t=>t[0])}clear(){this.attributes=[]}},pU=WM.reduce((t,e)=>(t[e[0]]=e,t),{}),Gee=WM.reduce((t,e)=>(t[e[1]]=e,t),{});wn=class extends KM{constructor(t,e,r=VM(),s=[]){super(s),this.messageMethod=t,this.messageClass=e,this.transactionId=r}toJSON(){return this.json}get json(){return{messageMethod:uA[this.messageMethod],messageClass:lA[this.messageClass],attributes:this.attributes}}get transactionIdHex(){return this.transactionId.toString("hex")}get bytes(){let t=Buffer.from([]);for(let r of this.attributesKeys){let s=this.getAttributeValue(r),[n,,i]=Gee[r],o=i.name===Uw.name?i(s,this.transactionId):i(s),a=o.length,c=4*Math.floor((a+3)/4)-a,d=Buffer.alloc(4);d.writeUInt16BE(n,0),d.writeUInt16BE(a,2),t=Buffer.concat([t,d,o,Buffer.alloc(c,0)])}let e=Buffer.alloc(8);return e.writeUInt16BE(this.messageMethod|this.messageClass,0),e.writeUInt16BE(t.length,2),e.writeUInt32BE(_1,4),Buffer.concat([e,this.transactionId,t])}addMessageIntegrity(t){return this.setAttribute("MESSAGE-INTEGRITY",this.messageIntegrity(t)),this}messageIntegrity(t){let e=mA(this.bytes,this.bytes.length-zo+aA);return Buffer.from((0,hA.createHmac)("sha1",t).update(e).digest("hex"),"hex")}addFingerprint(){this.setAttribute("FINGERPRINT",GM(this.bytes))}},mA=(t,e)=>{let r=Buffer.alloc(t.length);return t.copy(r,0,0,2),r.writeUInt16BE(e,2),t.copy(r,4,4),r};XM=class extends Error{response;addr},YM=class extends XM{constructor(t,e){super(),this.response=t,this.addr=e}get str(){let t="STUN transaction failed",e=this.response.getAttributeValue("ERROR-CODE");if(e){let[r,s]=e;t+=` (${r} - ${s})`}return t}},Yee=class extends XM{get str(){return"STUN transaction timed out"}},IT=ft("werift-ice:packages/ice/src/stun/transaction.ts"),gA=class{constructor(t,e,r,s){this.request=t,this.addr=e,this.protocol=r,this.retransmissions=s,this.triesMax=1+(this.retransmissions?this.retransmissions:HM)}timeoutDelay=qM;ended=!1;tries=0;triesMax;onResponse=new Ne;responseReceived=(t,e)=>{this.onResponse.length>0&&(t.messageClass===256?(this.onResponse.execute(t,e),this.onResponse.complete()):this.onResponse.error(new YM(t,e)))};run=async()=>{try{return this.retry().catch(e=>{IT("retry failed",e)}),await this.onResponse.asPromise()}catch(t){throw t}finally{this.cancel()}};retry=async()=>{for(;this.tries<this.triesMax&&!this.ended&&(this.protocol.sendStun(this.request,this.addr).catch(t=>{IT("send stun failed",t)}),await new Promise(t=>setTimeout(t,this.timeoutDelay)),!this.ended);)this.timeoutDelay*=2,this.tries++;this.tries>=this.triesMax&&(IT(`retry failed times:${this.tries} maxLimit:${this.triesMax}`),this.onResponse.error(new Yee))};cancel(){this.ended=!0}},mU=ft("werift-ice : packages/ice/src/stun/protocol.ts"),r1=class JM{static type="stun";type=JM.type;transport;transactions={};get transactionsKeys(){return Object.keys(this.transactions)}localCandidate;sentMessage;localIp;onRequestReceived=new Ne;onDataReceived=new Ne;constructor(){}connectionMade=async(e,r,s)=>{e?this.transport=await Jw.init("udp4",{portRange:r,interfaceAddresses:s}):this.transport=await Jw.init("udp6",{portRange:r,interfaceAddresses:s}),this.transport.onData=(n,i)=>{this.datagramReceived(n,i)}};datagramReceived(e,r){try{let s=S1(e);if(!s){this.localCandidate&&this.onDataReceived.execute(e);return}(s.messageClass===256||s.messageClass===272)&&this.transactionsKeys.includes(s.transactionIdHex)?this.transactions[s.transactionIdHex].responseReceived(s,r):s.messageClass===0&&this.onRequestReceived.execute(s,r,e)}catch(s){mU("datagramReceived error",s)}}getExtraInfo(){let{address:e,port:r}=this.transport.address;return[e,r]}async sendStun(e,r){if(this.transport.closed)return;let s=e.bytes;await this.transport.send(s,r).catch(()=>{mU("sendStun failed",r,e)})}async sendData(e,r){this.transport.closed||await this.transport.send(e,r)}async request(e,r,s,n){if(this.transactionsKeys.includes(e.transactionIdHex))throw new Error("already request ed");s&&(e.addMessageIntegrity(s),e.addFingerprint());let i=new gA(e,r,this,n);this.transactions[e.transactionIdHex]=i;try{return await i.run()}catch(o){throw o}finally{delete this.transactions[e.transactionIdHex]}}async close(){Object.values(this.transactions).forEach(e=>{e.cancel()}),await this.transport.close(),this.onRequestReceived.complete(),this.onDataReceived.complete()}},Ls=ft("werift-ice:packages/ice/src/turn/protocol.ts"),Jee=500,Qee=600,Zee=285212672,ej=class tj{constructor(e){this.turn=e,e.onData.subscribe((r,s)=>{this.handleStunMessage(r,s)}).disposer(this.disposer)}static type="turn";type=tj.type;localCandidate;disposer=new QU;onRequestReceived=new Ne;onDataReceived=new Ne;handleStunMessage=(e,r)=>{try{let s=S1(e);if(!s){this.onDataReceived.execute(e);return}if(s.messageClass===256||s.messageClass===272){let n=this.turn.transactions[s.transactionIdHex];n&&n.responseReceived(s,r)}else s.messageClass===0&&this.onRequestReceived.execute(s,r,e)}catch(s){Ls("datagramReceived error",s)}};async request(e,r,s){if(this.turn.transactions[e.transactionIdHex])throw new Error("exist");s&&(e.addMessageIntegrity(s),e.addFingerprint());let n=new gA(e,r,this);this.turn.transactions[e.transactionIdHex]=n;try{return await n.run()}catch(i){throw i}finally{delete this.turn.transactions[e.transactionIdHex]}}async connectionMade(){}async sendData(e,r){await this.turn.sendData(e,r)}async sendStun(e,r){await this.turn.sendData(e.bytes,r)}async close(){return this.disposer.dispose(),this.turn.close()}},rj=class sj{constructor(e,r,s,n,i,o={}){this.server=e,this.username=r,this.password=s,this.lifetime=n,this.transport=i,this.options=o,this.channelRefreshTime=this.options.channelRefreshTime??Jee}static type="turn";type=sj.type;onData=new Ne;onRequestReceived=new Ne;onDataReceived=new Ne;integrityKey;nonce;realm;relayedAddress;mappedAddress;localCandidate;transactions={};refreshHandle;channelNumber=16384;channelByAddr={};addrByChannel={};channelRefreshTime;channelBinding;channelRefreshAt=0;tcpBuffer=Buffer.alloc(0);permissionByAddr={};creatingPermission=Promise.resolve();async connectionMade(){this.transport.onData=(n,i)=>{this.dataReceived(n,i)};let e=new wn(3,0);e.setAttribute("LIFETIME",this.lifetime).setAttribute("REQUESTED-TRANSPORT",Zee);let[r]=await this.requestWithRetry(e,this.server).catch(n=>{throw Ls("connect error",n),n});this.relayedAddress=r.getAttributeValue("XOR-RELAYED-ADDRESS"),this.mappedAddress=r.getAttributeValue("XOR-MAPPED-ADDRESS");let s=r.getAttributeValue("LIFETIME");Ls("connect",this.relayedAddress,this.mappedAddress,{exp:s}),this.refresh(s)}handleChannelData(e){let[r,s]=ck.jspack.Unpack("!HH",e.slice(0,4)),n=this.addrByChannel[r];if(n){let i=e.subarray(4,4+s);this.onData.execute(i,n)}}handleSTUNMessage(e,r){try{let s=S1(e);if(!s)throw new Error("not stun message");if(s.messageClass===256||s.messageClass===272){let n=this.transactions[s.transactionIdHex];n&&n.responseReceived(s,r)}else s.messageClass===0&&this.onData.execute(e,r);if(s.getAttributeValue("DATA")){let n=s.getAttributeValue("DATA");this.onData.execute(n,r)}}catch{Ls("parse error",e.toString())}}dataReceived(e,r){let s=(n,i)=>{n.length>=4&&gU(n)?this.handleChannelData(n):this.handleSTUNMessage(n,i)};if(this.transport.type==="tcp")for(this.tcpBuffer=Buffer.concat([this.tcpBuffer,e]);this.tcpBuffer.length>=4;){let[,n]=bs(this.tcpBuffer.subarray(0,4),[2,2]);n+=ak(n);let i=gU(this.tcpBuffer)?4+n:20+n;if(this.tcpBuffer.length<i)break;s(this.tcpBuffer.subarray(0,i),r),this.tcpBuffer=this.tcpBuffer.subarray(i)}else s(e,r)}async send(e,r){if(!this.transport.closed)if(this.transport.type==="tcp"){let s=ak(e.length);await this.transport.send(s>0?Buffer.concat([e,Buffer.alloc(s)]):e,r)}else await this.transport.send(e,r)}async createPermission(e){let r=new wn(8,0);r.setAttribute("XOR-PEER-ADDRESS",e).setAttribute("USERNAME",this.username).setAttribute("REALM",this.realm).setAttribute("NONCE",this.nonce),await this.request(r,this.server).catch(s=>{throw s})}refresh=e=>{this.refreshHandle=ok(async(r,s,n)=>{let i=!0;for(n.once(()=>{i=!1});i;){let o=.8333333333333334*e*1e3;Ls("refresh delay",o,{exp:e}),await(0,ZM.setTimeout)(o);let a=new wn(4,0);a.setAttribute("LIFETIME",e);try{let[c]=await this.requestWithRetry(a,this.server);e=c.getAttributeValue("LIFETIME"),Ls("refresh",{exp:e})}catch(c){Ls("refresh error",c)}}})};async request(e,r){if(this.transactions[e.transactionIdHex])throw new Error("exist");this.integrityKey&&e.setAttribute("USERNAME",this.username).setAttribute("REALM",this.realm).setAttribute("NONCE",this.nonce).addMessageIntegrity(this.integrityKey).addFingerprint();let s=new gA(e,r,this);this.transactions[e.transactionIdHex]=s;try{return await s.run()}catch(n){throw n}finally{delete this.transactions[e.transactionIdHex]}}async requestWithRetry(e,r){let s,n;try{[s,n]=await this.request(e,r)}catch(i){if(!(i instanceof YM))throw Ls("requestWithRetry error",i),i;this.server=i.addr;let[o]=i.response.getAttributeValue("ERROR-CODE"),a=i.response.getAttributeValue("NONCE"),c=i.response.getAttributeValue("REALM");if((o===401&&c||o===438&&this.realm)&&a)Ls("retry with nonce",o),this.nonce=a,o===401&&(this.realm=c),this.integrityKey=ij(this.username,this.realm,this.password),e.transactionId=VM(),[s,n]=await this.request(e,this.server);else throw i}return[s,n]}async sendData(e,r){let s=await this.getChannel(r).catch(i=>new Error("channelBind error"));if(s instanceof Error){await this.getPermission(r);let i=new wn(6,16).setAttribute("DATA",e).setAttribute("XOR-PEER-ADDRESS",r);await this.sendStun(i,this.server);return}let n=ck.jspack.Pack("!HH",[s.number,e.length]);await this.send(Buffer.concat([Buffer.from(n),e]),this.server)}async getPermission(e){await this.creatingPermission,this.permissionByAddr[e.join(":")]||(this.creatingPermission=this.createPermission(e),this.permissionByAddr[e.join(":")]=!0,await this.creatingPermission.catch(s=>{throw Ls("createPermission error",s),s}))}async getChannel(e){this.channelBinding&&await this.channelBinding;let r=this.channelByAddr[e.join(":")];return r?this.channelRefreshAt<Rh(Date.now()/1e3)&&(this.channelBinding=this.channelBind(r.number,e),this.channelRefreshAt=Rh(Date.now()/1e3)+this.channelRefreshTime,await this.channelBinding.catch(s=>{throw Ls("channelBind error",s),s}),this.channelBinding=void 0,Ls("channelBind refresh",r)):(this.channelByAddr[e.join(":")]={number:this.channelNumber++,address:e},r=this.channelByAddr[e.join(":")],this.addrByChannel[r.number]=e,this.channelBinding=this.channelBind(r.number,e),await this.channelBinding.catch(s=>{throw Ls("channelBind error",s),s}),this.channelRefreshAt=Rh(Date.now()/1e3)+this.channelRefreshTime,this.channelBinding=void 0,Ls("channelBind",r)),r}async channelBind(e,r){let s=new wn(9,0);s.setAttribute("CHANNEL-NUMBER",e).setAttribute("XOR-PEER-ADDRESS",r);let[n]=await this.requestWithRetry(s,this.server);if(n.messageMethod!==9)throw new Error("should be CHANNEL_BIND")}async sendStun(e,r){await this.send(e.bytes,r)}async close(){this.refreshHandle?.resolve?.(),await this.transport.close()}};gc=class aj{constructor(e,r,s,n,i,o,a,c,d,u,l,h){this.foundation=e,this.component=r,this.transport=s,this.priority=n,this.host=i,this.port=o,this.type=a,this.relatedAddress=c,this.relatedPort=d,this.tcptype=u,this.generation=l,this.ufrag=h}static fromSdp(e){let r=e.split(" ");if(r.length<8)throw new Error("SDP does not have enough properties");let s={foundation:r[0],component:Number(r[1]),transport:r[2],priority:Number(r[3]),host:r[4],port:Number(r[5]),type:r[7]};for(let l=8,h=r.length-1;l<h;l+=2)r[l]==="raddr"?s.related_address=r[l+1]:r[l]==="rport"?s.related_port=Number(r[l+1]):r[l]==="tcptype"?s.tcptype=r[l+1]:r[l]==="generation"?s.generation=Number(r[l+1]):r[l]==="ufrag"&&(s.ufrag=r[l+1]);let{foundation:n,component:i,transport:o,priority:a,host:c,port:d,type:u}=s;return new aj(n,i,o,a,c,d,u,s.related_address,s.related_port,s.tcptype,s.generation,s.ufrag)}canPairWith(e){let r=(0,lk.isIPv4)(this.host),s=(0,lk.isIPv4)(e.host);return this.component===e.component&&this.transport.toLowerCase()===e.transport.toLowerCase()&&r===s}toSdp(){let e=`${this.foundation} ${this.component} ${this.transport} ${this.priority} ${this.host} ${this.port} typ ${this.type}`;return this.relatedAddress&&(e+=` raddr ${this.relatedAddress}`),this.relatedPort!=null&&(e+=` rport ${this.relatedPort}`),this.tcptype&&(e+=` tcptype ${this.tcptype}`),this.generation!=null&&(e+=` generation ${this.generation}`),this.ufrag!=null&&(e+=` ufrag ${this.ufrag}`),e}};ete=class{cache=new Map;mdnsInstance=(0,dj.default)();constructor(){this.mdnsInstance.setMaxListeners(50)}lookup(t){return new Promise((e,r)=>{let s=()=>{this.mdnsInstance.removeListener("response",i),clearTimeout(n)},n=setTimeout(()=>{s(),r(new Error("No mDNS response"))},1e4),i=o=>{let a=o.answers?.[0];a?.type==="A"&&a.name===t&&(s(),e(a.data))};this.mdnsInstance.on("response",i),this.mdnsInstance.query(t,"A")})}close(){this.mdnsInstance.destroy()}},tte=ft("werift-ice : packages/ice/src/ice.ts : log"),fk=class{constructor(t,e,r){this.protocol=t,this.remoteCandidate=e,this.iceControlling=r}id=(0,lj.randomUUID)().toString();handle;nominated=!1;remoteNominated=!1;_state=0;get state(){return this._state}packetsSent=0;packetsReceived=0;bytesSent=0;bytesReceived=0;rtt;totalRoundTripTime=0;roundTripTimeMeasurements=0;toJSON(){return this.json}get json(){return{protocol:this.protocol.type,localCandidate:this.localCandidate.toSdp(),remoteCandidate:this.remoteCandidate.toSdp()}}updateState(t){this._state=t}get localCandidate(){if(!this.protocol.localCandidate)throw new Error("localCandidate not exist");return this.protocol.localCandidate}get remoteAddr(){return[this.remoteCandidate.host,this.remoteCandidate.port]}get component(){return this.localCandidate.component}get priority(){return n1(this.localCandidate,this.remoteCandidate,this.iceControlling)}get foundation(){return this.localCandidate.foundation}},pk=1,T0=2,uj=5,mk=6,hj=(t=>(t[t.FROZEN=0]="FROZEN",t[t.WAITING=1]="WAITING",t[t.IN_PROGRESS=2]="IN_PROGRESS",t[t.SUCCEEDED=3]="SUCCEEDED",t[t.FAILED=4]="FAILED",t))(hj||{}),fj={useIpv4:!0,useIpv6:!0};rte=ft("werift-ice : packages/ice/src/utils.ts");nte=t=>{if(!t)return;let[e,r]=t.split(":");return[e,Number.parseInt(r)]},jt=ft("werift-ice : packages/ice/src/ice.ts : log"),wj=class{constructor(t,e){this._iceControlling=t,this.options={...fj,...e};let{stunServer:r,turnServer:s}=this.options;this.stunServer=yk(r)??["stun.l.google.com",19302],this.turnServer=yk(s),this.restart(),jt("new Connection",this.options)}localUsername=l0(4);localPassword=l0(22);remoteIsLite=!1;remotePassword="";remoteUsername="";checkList=[];localCandidates=[];stunServer;turnServer;options;remoteCandidatesEnd=!1;localCandidatesEnd=!1;generation=-1;userHistory={};tieBreaker=BigInt(new Sw((0,cj.randomBytes)(64)).toString());state="new";lookup;_remoteCandidates=[];nominated;nominating=!1;checkListDone=!1;checkListState=new uU;earlyChecks=[];earlyChecksDone=!1;localCandidatesStart=!1;protocols=[];queryConsentHandle;onData=new Ne;stateChanged=new Ne;onIceCandidate=new Ne;get iceControlling(){return this._iceControlling}set iceControlling(t){if(!(this.generation>0||this.nominated)){this._iceControlling=t;for(let e of this.checkList)e.iceControlling=t}}async restart(){this.generation++,this.localUsername=l0(4),this.localPassword=l0(22),this.options.localPasswordPrefix&&(this.localPassword=this.options.localPasswordPrefix+this.localPassword.slice(this.options.localPasswordPrefix.length)),this.userHistory[this.localUsername]=this.localPassword,this.remoteUsername="",this.remotePassword="",this.localCandidates=[],this._remoteCandidates=[],this.remoteCandidatesEnd=!1,this.localCandidatesEnd=!1,this.state="new",this.lookup?.close?.(),this.lookup=void 0,this.nominated=void 0,this.nominating=!1,this.checkList=[],this.checkListDone=!1,this.checkListState=new uU,this.earlyChecks=[],this.earlyChecksDone=!1,this.localCandidatesStart=!1;for(let t of this.protocols)t.localCandidate&&(t.localCandidate.generation=this.generation,t.localCandidate.ufrag=this.localUsername);this.queryConsentHandle?.resolve?.(),this.queryConsentHandle=void 0}resetNominatedPair(){jt("resetNominatedPair"),this.nominated=void 0,this.nominating=!1}setRemoteParams({iceLite:t,usernameFragment:e,password:r}){jt("setRemoteParams",{iceLite:t,usernameFragment:e,password:r}),this.remoteIsLite=t,this.remoteUsername=e,this.remotePassword=r}async gatherCandidates(){if(!this.localCandidatesStart){this.localCandidatesStart=!0;let t=xj(this.options.useIpv4,this.options.useIpv6,{useLinkLocalAddress:this.options.useLinkLocalAddress}),{interfaceAddresses:e}=this.options;if(e){let s=t.filter(n=>Object.values(e).includes(n));s.length&&(t=s)}this.options.additionalHostAddresses&&(t=Array.from(new Set([...this.options.additionalHostAddresses,...t])));let r=this.getCandidatePromises(t,5);await Promise.allSettled(r),this.localCandidatesEnd=!0}this.setState("completed")}appendLocalCandidate(t){this.localCandidates.push(t),this.onIceCandidate.execute(t)}ensureProtocol(t){t.onRequestReceived.subscribe((e,r,s)=>{if(e.messageMethod!==1){this.respondError(e,r,t,[400,"Bad Request"]);return}let n=e.getAttributeValue("USERNAME"),{remoteUsername:i}=yU(n),o=this.userHistory[i]??this.localPassword,{iceControlling:a}=this;if(a&&e.attributesKeys.includes("ICE-CONTROLLING"))if(this.tieBreaker>=e.getAttributeValue("ICE-CONTROLLING")){this.respondError(e,r,t,[487,"Role Conflict"]);return}else this.switchRole(!1);else if(!a&&e.attributesKeys.includes("ICE-CONTROLLED"))if(this.tieBreaker<e.getAttributeValue("ICE-CONTROLLED"))this.respondError(e,r,t,[487,"Role Conflict"]);else{this.switchRole(!0);return}if(this.options.filterStunResponse&&!this.options.filterStunResponse(e,r,t))return;let c=new wn(1,256,e.transactionId);c.setAttribute("XOR-MAPPED-ADDRESS",r).addMessageIntegrity(Buffer.from(o,"utf8")).addFingerprint(),t.sendStun(c,r).catch(d=>{jt("sendStun error",d)}),this.checkList.length===0&&!this.earlyChecksDone?this.earlyChecks.push([e,r,t]):this.checkIncoming(e,r,t)}),t.onDataReceived.subscribe(e=>{try{let r=this.nominated;r&&r.protocol===t&&(r.packetsReceived++,r.bytesReceived+=e.length),this.onData.execute(e)}catch(r){jt("dataReceived",r)}})}getCandidatePromises(t,e=5){let r=[];t=t.filter(c=>!this.protocols.find(d=>d.localIp===c));let s=t.map(async c=>{let d=new r1;this.ensureProtocol(d);try{await d.connectionMade((0,uk.isIPv4)(c),this.options.portRange,this.options.interfaceAddresses),d.localIp=c,this.protocols.push(d),jt("protocol",d.localIp);let u=[c,d.getExtraInfo()[1]];return d.localCandidate=new gc(s1("host","udp",u[0]),1,"udp",R0("host"),u[0],u[1],"host",void 0,void 0,void 0,this.generation,this.localUsername),this.pairLocalProtocol(d),this.appendLocalCandidate(d.localCandidate),d}catch(u){jt("error protocol STUN",u)}});r.push(...s.map(c=>c.then(d=>d?.localCandidate)));let{stunServer:n,turnServer:i}=this;if(n){let c=s.map(async d=>{let u=await d;return u?new Promise(async(h,p)=>{let m=setTimeout(p,e*1e3);if(u.localCandidate?.host&&(0,uk.isIPv4)(u.localCandidate?.host)){let _=await mj(u,n).catch(f=>{jt("error",f)});_&&this.appendLocalCandidate(_),clearTimeout(m),h(_)}else clearTimeout(m),h()}).catch(h=>{jt("query STUN server",h)}):void 0});r.push(...c)}let{turnUsername:o,turnPassword:a}=this.options;if(i&&o&&a){let c=(async()=>{let d=await dk({address:i,username:o,password:a},{portRange:this.options.portRange,interfaceAddresses:this.options.interfaceAddresses,transport:this.options.turnTransport==="tcp"?"tcp":"udp"}).catch(async h=>{if(this.options.turnTransport!=="tcp")return await dk({address:i,username:o,password:a},{portRange:this.options.portRange,interfaceAddresses:this.options.interfaceAddresses,transport:"tcp"});throw h});this.ensureProtocol(d),this.protocols.push(d);let u=d.turn.relayedAddress,l=d.turn.mappedAddress;return jt("turn candidateAddress",u),d.localCandidate=new gc(s1("relay","udp",u[0]),1,"udp",R0("relay"),u[0],u[1],"relay",l[0],l[1],void 0,this.generation,this.localUsername),this.appendLocalCandidate(d.localCandidate),d.localCandidate})().catch(d=>{jt("query TURN server",d)});this.options.forceTurn&&(r=[]),r.push(c)}return r}async connect(){if(jt("start connect ice"),!this.localCandidatesEnd&&!this.localCandidatesStart)throw new Error("Local candidates gathering was not performed");if(!this.remoteUsername||!this.remotePassword)throw new Error("Remote username or password is missing");for(let e of this.remoteCandidates)this.pairRemoteCandidate(e);this.sortCheckList(),this.unfreezeInitial(),jt("earlyChecks",this.localPassword,this.earlyChecks.length);for(let e of this.earlyChecks)this.checkIncoming(...e);for(this.earlyChecks=[],this.earlyChecksDone=!0;!(this.state==="closed"||!this.schedulingChecks());)await hk.setTimeout(20);let t=T0;for(;this.checkList.length>0&&t===T0;)t=await this.checkListState.get(),jt("checkListState",t);for(let e of this.checkList)e.handle?.resolve?.();if(t!==pk)throw new Error("ICE negotiation failed");this.queryConsent(),this.setState("connected")}unfreezeInitial(){let[t]=this.checkList;if(!t)return;t.state===0&&t.updateState(1);let e=new Set(t.localCandidate.foundation);for(let r of this.checkList)r.component===t.component&&!e.has(r.localCandidate.foundation)&&r.state===0&&(r.updateState(1),e.add(r.localCandidate.foundation))}schedulingChecks(){{let t=this.checkList.filter(e=>!(this.options.forceTurn&&e.protocol.type===r1.type)).find(e=>e.state===1);if(t)return t.handle=this.checkStart(t),!0}{let t=this.checkList.find(e=>e.state===0);if(t)return t.handle=this.checkStart(t),!0}return this.remoteCandidatesEnd?!1:!this.checkListDone}queryConsent=()=>{this.queryConsentHandle&&this.queryConsentHandle.resolve(),this.queryConsentHandle=ok(async(t,e,r)=>{let s=0,n=!1,i=new AbortController;r.once(()=>{n=!0,s+=mk,i.abort(),this.queryConsentHandle=void 0});let{localUsername:o,remoteUsername:a,iceControlling:c}=this;try{for(;this.state!=="closed"&&!n;){await hk.setTimeout(uj*(.8+.4*Math.random())*1e3,void 0,{signal:i.signal});let d=this.nominated;if(!d||n)break;let u=this.buildRequest({nominate:!1,localUsername:o,remoteUsername:a,iceControlling:c});try{await d.protocol.request(u,d.remoteAddr,Buffer.from(this.remotePassword,"utf8"),0),s=0,this.state==="disconnected"&&this.setState("connected")}catch{if(d.id===this.nominated?.id){jt("no stun response"),s++,this.setState("disconnected");break}}if(s>=mk){jt("Consent to send expired"),this.queryConsentHandle=void 0,this.setState("closed");break}}}catch{}})};async close(){this.setState("closed"),this.queryConsentHandle?.resolve?.(),this.checkList&&!this.checkListDone&&this.checkListState.put(new Promise(t=>{t(T0)})),this.nominated=void 0;for(let t of this.protocols)t.close&&await t.close();this.protocols=[],this.localCandidates=[],this.lookup?.close?.(),this.lookup=void 0}setState(t){this.state=t,this.stateChanged.execute(t)}async addRemoteCandidate(t){if(!t){this.remoteCandidatesEnd=!0;return}if(t.host.includes(".local"))try{this.lookup||(this.lookup=new ete);let e=await this.lookup.lookup(t.host);t.host=e}catch{return}try{gk(t)}catch{return}jt("addRemoteCandidate",t),this._remoteCandidates.push(t),this.pairRemoteCandidate(t),this.sortCheckList()}send=async t=>{let e=this.nominated;if(e)await e.protocol.sendData(t,e.remoteAddr),e.packetsSent++,e.bytesSent+=t.length;else return};getDefaultCandidate(){let t=this.localCandidates.sort((r,s)=>r.priority-s.priority),[e]=t;return e}set remoteCandidates(t){if(this.remoteCandidatesEnd)throw new Error("Cannot set remote candidates after end-of-candidates.");this._remoteCandidates=[];for(let e of t){try{gk(e)}catch{continue}this._remoteCandidates.push(e)}this.remoteCandidatesEnd=!0}get remoteCandidates(){return this._remoteCandidates}get candidatePairs(){return this.checkList}sortCheckList(){pj(this.checkList,this.iceControlling)}findPair(t,e){return this.checkList.find(s=>(0,Mw.default)(s.protocol,t)&&(0,Mw.default)(s.remoteCandidate,e))}switchRole(t){jt("switch role",t),this.iceControlling=t,this.sortCheckList()}checkComplete(t){if(t.handle=void 0,t.state===3){if(t.nominated&&(t.remoteCandidate.generation==null||t.remoteCandidate.generation===this.generation)&&this.nominated==null){jt("nominated",t.toJSON()),this.nominated=t,this.nominating=!1;for(let e of this.checkList)e.component===t.component&&[1,0].includes(e.state)&&e.updateState(4)}if(this.nominated){this.checkListDone||(jt("ICE completed"),this.checkListState.put(new Promise(e=>e(pk))),this.checkListDone=!0);return}jt("not completed",t.toJSON());for(let e of this.checkList)e.localCandidate.foundation===t.localCandidate.foundation&&e.state===0&&e.updateState(1)}{let e=[3,4];if(this.checkList.find(({state:r})=>!e.includes(r)))return}!this.iceControlling&&this.checkList.find(({state:r})=>r===3)||this.checkListDone||(jt("ICE failed"),this.checkListState.put(new Promise(e=>{e(T0)})))}checkStart=t=>ok(async e=>{jt("check start",t.toJSON()),t.updateState(2);let r={},{remotePassword:s,remoteUsername:n,generation:i}=this,o=t.localCandidate.ufrag??this.localUsername,a=this.iceControlling&&!this.remoteIsLite,c=this.buildRequest({nominate:a,localUsername:o,remoteUsername:n,iceControlling:this.iceControlling}),d=performance.now();try{let[u,l]=await t.protocol.request(c,t.remoteAddr,Buffer.from(s,"utf8"),4),p=(performance.now()-d)/1e3;t.rtt=p,t.totalRoundTripTime+=p,t.roundTripTimeMeasurements++,jt("response received",c.toJSON(),u.toJSON(),l,{localUsername:o,remoteUsername:n,remotePassword:s,generation:i,rtt:p}),r.response=u,r.addr=l}catch(u){let l=u;if(jt("failure case",c.toJSON(),l.response?JSON.stringify(l.response.toJSON(),null,2):u,{localUsername:o,remoteUsername:n,remotePassword:s,generation:i},t.remoteAddr),l.response?.getAttributeValue("ERROR-CODE")[0]===487){c.attributesKeys.includes("ICE-CONTROLLED")?this.switchRole(!0):c.attributesKeys.includes("ICE-CONTROLLING")&&this.switchRole(!1),await this.checkStart(t).awaitable,e();return}if(l.response?.getAttributeValue("ERROR-CODE")[0]===401){jt("retry 401",t.toJSON()),await this.checkStart(t).awaitable,e();return}else{jt("checkStart CandidatePairState.FAILED",t.toJSON()),t.updateState(4),this.checkComplete(t),e();return}}if(!(0,Mw.default)(r.addr,t.remoteAddr)){t.updateState(4),this.checkComplete(t),e();return}if(a||t.remoteNominated)t.nominated=!0;else if(this.iceControlling&&!this.nominating){this.nominating=!0;let u=this.buildRequest({nominate:!0,localUsername:o,remoteUsername:n,iceControlling:this.iceControlling});try{await t.protocol.request(u,t.remoteAddr,Buffer.from(this.remotePassword,"utf8"))}catch{t.updateState(4),this.checkComplete(t);return}t.nominated=!0}t.updateState(3),this.checkComplete(t),e()});addPair(t){this.checkList.push(t),this.sortCheckList()}checkIncoming(t,e,r){let s=t.getAttributeValue("USERNAME"),{remoteUsername:n}=yU(s),i,[o,a]=e;for(let d of this.remoteCandidates)if(d.host===o&&d.port===a){i=d;break}i||(i=new gc(l0(10),1,"udp",t.getAttributeValue("PRIORITY"),o,a,"prflx",void 0,void 0,void 0,void 0,void 0),this._remoteCandidates.push(i));let c=this.findPair(r,i);c||(c=new fk(r,i,this.iceControlling),c.updateState(1),this.addPair(c)),c.localCandidate.ufrag=n,jt("Triggered Checks",t.toJSON(),c.toJSON(),{localUsername:this.localUsername,remoteUsername:this.remoteUsername,localPassword:this.localPassword,remotePassword:this.remotePassword,generation:this.generation}),[1,4].includes(c.state)&&(c.handle=this.checkStart(c)),t.attributesKeys.includes("USE-CANDIDATE")&&!this.iceControlling&&(c.remoteNominated=!0,c.state===3&&(c.nominated=!0,this.checkComplete(c)))}tryPair(t,e){if(t.localCandidate?.canPairWith(e)&&!this.findPair(t,e)){let r=new fk(t,e,this.iceControlling);if(this.options.filterCandidatePair&&!this.options.filterCandidatePair(r))return;r.updateState(1),this.addPair(r)}}pairLocalProtocol(t){for(let e of this.remoteCandidates)this.tryPair(t,e)}pairRemoteCandidate=t=>{for(let e of this.protocols)this.tryPair(e,t)};buildRequest({nominate:t,remoteUsername:e,localUsername:r,iceControlling:s}){let n=ite({remoteUsername:e,localUsername:r}),i=new wn(1,0);return i.setAttribute("USERNAME",n).setAttribute("PRIORITY",R0("prflx")),s?(i.setAttribute("ICE-CONTROLLING",this.tieBreaker),t&&i.setAttribute("USE-CANDIDATE",null)):i.setAttribute("ICE-CONTROLLED",this.tieBreaker),i}respondError(t,e,r,s){let n=new wn(t.messageMethod,272,t.transactionId);n.setAttribute("ERROR-CODE",s).addMessageIntegrity(Buffer.from(this.localPassword,"utf8")).addFingerprint(),r.sendStun(n,e).catch(i=>{jt("sendStun error",i)})}},ite=({remoteUsername:t,localUsername:e})=>`${t}:${e}`,yU=t=>{let[e,r]=t.split(":");return{remoteUsername:e,localUsername:r}};yA=class extends vj.EventEmitter{addEventListener=(t,e)=>{this.addListener(t,e)};removeEventListener=(t,e)=>{this.removeListener(t,e)}},ote=ft("werift:packages/webrtc/src/dataChannel.ts");bA=class extends yA{constructor(t,e,r=!0){if(super(),this.sctp=t,this.parameters=e,this.sendOpen=r,this.id=this.parameters.id,e.negotiated){if(this.id==null||this.id<0||this.id>65534)throw new Error("ID must be in range 0-65534 if data channel is negotiated out-of-band");this.sctp.dataChannelAddNegotiated(this)}else r&&(this.sendOpen=!1,this.sctp.dataChannelOpen(this))}stateChange=new Ne;stateChanged=new Ne;onMessage=new Ne;error=new Ne;bufferedAmountLow=new Ne;onopen;onclose;onclosing;onmessage;onerror;isCreatedByRemote=!1;id;readyState="connecting";bufferedAmount=0;_bufferedAmountLowThreshold=0;messagesSent=0;bytesSent=0;messagesReceived=0;bytesReceived=0;get ordered(){return this.parameters.ordered}get maxRetransmits(){return this.parameters.maxRetransmits}get maxPacketLifeTime(){return this.parameters.maxPacketLifeTime}get label(){return this.parameters.label}get protocol(){return this.parameters.protocol}get negotiated(){return this.parameters.negotiated}get bufferedAmountLowThreshold(){return this._bufferedAmountLowThreshold}set bufferedAmountLowThreshold(t){if(t<0||t>4294967295)throw new Error("bufferedAmountLowThreshold must be in range 0 - 4294967295");this._bufferedAmountLowThreshold=t}setId(t){this.id=t}setReadyState(t){if(t!==this.readyState){switch(this.readyState=t,this.stateChange.execute(t),this.stateChanged.execute(t),t){case"open":this.onopen&&this.onopen(),this.emit("open");break;case"closed":this.onclose&&this.onclose(),this.emit("close");break;case"closing":this.onclosing&&this.onclosing();break}ote("change state",t)}}addBufferedAmount(t){let e=this.bufferedAmount>this.bufferedAmountLowThreshold&&this.bufferedAmount+t<=this.bufferedAmountLowThreshold;this.bufferedAmount+=t,e&&(this.bufferedAmountLow.execute(),this.emit("bufferedamountlow"))}send(t){let e=this.sctp.datachannelSend(this,t);this.messagesSent++,this.bytesSent+=e}close(){this.sctp.dataChannelClose(this)}},xA=class{label="";maxPacketLifeTime;maxRetransmits;ordered=!0;protocol="";negotiated=!1;id;constructor(t={}){Object.assign(this,t)}},ate=()=>({type:"ccm",parameter:"fir"}),ig=()=>({type:"nack"}),Vh=()=>({type:"nack",parameter:"pli"}),og=()=>({type:"goog-remb"}),Sj=()=>({type:"transport-cc"}),yc=class{payloadType;mimeType;clockRate;channels;rtcpFeedback=[];parameters;direction="all";constructor(t){Object.assign(this,t)}get name(){return this.mimeType.split("/")[1]}get contentType(){return this.mimeType.split("/")[0]}get str(){let t=`${this.name}/${this.clockRate}`;return this.channels===2&&(t+="/2"),t}},Wi=class{id;uri;constructor(t){Object.assign(this,t)}},cte=class{cname;mux=!1;ssrc;constructor(t={}){Object.assign(this,t)}},Ej=class{type;parameter;constructor(t={}){Object.assign(this,t)}},Cj=class{ssrc;constructor(t={}){Object.assign(this,t)}},Tj=class{ssrc;payloadType;rtx;constructor(t){Object.assign(this,t)}},wA=class{rid;direction;constructor(t){Object.assign(this,t)}},kj=(t={})=>new yc({mimeType:"video/h264",clockRate:9e4,rtcpFeedback:[ig(),Vh(),og()],parameters:"profile-level-id=42e01f;packetization-mode=1;level-asymmetry-allowed=1",...t}),vA=(t={})=>new yc({mimeType:"video/VP8",clockRate:9e4,rtcpFeedback:[ig(),Vh(),og()],...t}),Aj=(t={})=>new yc({mimeType:"video/VP9",clockRate:9e4,rtcpFeedback:[ig(),Vh(),og()],...t}),Ij=(t={})=>new yc({mimeType:"video/AV1X",clockRate:9e4,rtcpFeedback:[ig(),Vh(),og()],...t}),_A=(t={})=>new yc({mimeType:"audio/OPUS",clockRate:48e3,channels:2,...t}),SA=(t={})=>new yc({mimeType:"audio/PCMU",clockRate:8e3,channels:1,payloadType:0,...t}),EA=[Ij(),Aj(),vA(),kj(),_A(),SA()].map(t=>t.mimeType),dte=EA.filter(t=>t.toLowerCase().startsWith("video/")),lte=EA.filter(t=>t.toLowerCase().startsWith("audio/"));xU=2,wU=3,xte=0,Aw=50,vU=51,_U=53,wte=56,vte=57,_te="0.0.0.0",SU=9,wk={auto:"actpass",client:"active",server:"passive"},EU=Object.keys(wk).reduce((t,e)=>{let r=wk[e];return t[r]=e,t},{}),Ste=["apt","max-fr","max-fs","maxplaybackrate","minptime","stereo","useinbandfec"],Lj=["cname","msid","mslabel","label"],CU={SRTP_AES128_CM_HMAC_SHA1_80:Hh,SRTP_AEAD_AES_128_GCM:_l},$w=["sendonly","sendrecv"],Ete=["sendrecv","recvonly"],Oj=class extends Map{constructor(t){if(super(),t)for(let e of t)this.set(e.id,e)}};Nj=class{constructor(t,e,r,s,n){this.kind=t,this.receiver=r,this.sender=s,this._direction=n,e&&this.setDtlsTransport(e)}id=(0,Bj.randomUUID)().toString();onTrack=new Ne;mid;mLineIndex;usedForSender=!1;_currentDirection;offerDirection;_codecs=[];set codecs(t){this._codecs=t}get codecs(){return this._codecs}headerExtensions=[];options={};stopping=!1;stopped=!1;get dtlsTransport(){return this.receiver.dtlsTransport}get direction(){return this._direction}setDirection(t){this._direction=t,$w.includes(this._currentDirection??"")&&(this.usedForSender=!0)}get currentDirection(){return this._currentDirection}setCurrentDirection(t){this._currentDirection=t}setDtlsTransport(t){this.receiver.setDtlsTransport(t),this.sender.setDtlsTransport(t)}get msid(){return`${this.sender.streamId} ${this.sender.trackId}`}addTrack(t){this.receiver.addTrack(t)&&this.onTrack.execute(t,this)}stop(){this.stopping||(this.stopping=!0)}getPayloadType(t){return this.codecs.find(e=>e.mimeType.toLowerCase().includes(t.toLowerCase()))?.payloadType}getCodecStats(){let t=bc(),e=[];if(!this.dtlsTransport)return e;let r=zt("transport",this.dtlsTransport.id);for(let s of this.codecs){let n={type:"codec",id:zt("codec",s.payloadType,r),timestamp:t,payloadType:s.payloadType,transportId:r,mimeType:s.mimeType,clockRate:s.clockRate,channels:s.channels,sdpFmtpLine:s.parameters};e.push(n)}return e}},Uj="inactive",CA="sendonly",TA="recvonly",kA="sendrecv",Fw=[Uj,CA,TA,kA],K0=class extends yA{uuid=(0,AA.randomUUID)().toString();streamId;remote=!1;label;kind;id;ssrc;rid;header;codec;enabled=!0;onReceiveRtp=new Ne;onReceiveRtcp=new Ne;onSourceChanged=new Ne;stopped=!1;muted=!0;constructor(t){super(),Object.assign(this,t),this.onReceiveRtp.subscribe(e=>{this.muted=!1,this.header=e.header}),this.label=`${this.remote?"remote":"local"} ${this.kind}`}stop=()=>{this.stopped=!0,this.muted=!0,this.onReceiveRtp.complete(),this.emit("ended")};writeRtp=t=>{if(this.remote)throw new Error("this is remoteTrack");if(this.stopped)return;let e=Buffer.isBuffer(t)?Jo.deSerialize(t):t;e.header.payloadType=this.codec?.payloadType??e.header.payloadType,this.onReceiveRtp.execute(e)}},Mj=class{id;tracks=[];constructor(t){Array.isArray(t)?this.tracks=t:Object.assign(this,t),this.id??=(0,AA.randomUUID)().toString()}addTrack(t){t.streamId=this.id,this.tracks.push(t)}getTracks(){return this.tracks}getAudioTracks(){return this.tracks.filter(t=>t.kind==="audio")}getVideoTracks(){return this.tracks.filter(t=>t.kind==="video")}},Cte=ft("werift:packages/webrtc/src/utils.ts");Tte={sha1:"sha1","sha-1":"sha1",sha224:"sha224","sha-224":"sha224",sha256:"sha256","sha-256":"sha256",sha384:"sha384","sha-384":"sha384",sha512:"sha512","sha-512":"sha512"};PA=(t,e)=>Fw[Fw.indexOf(t)&Fw.indexOf(e)];DA=Date.now,Ate=BigInt(Date.now())*1000n-process.hrtime.bigint()/1000n,Fj=()=>Ate+process.hrtime.bigint()/1000n,G0=()=>Date.now()/1e3,Hj=()=>{let e=(xk.performance.timeOrigin+xk.performance.now()-Date.UTC(1900,0,1))/1e3,[r,s]=e.toString().split(".").map(Number);return nr([4,4],[r,s]).readBigUInt64BE()},BA=t=>{let e=nr([8],[t]),[,r,s]=bs(e,[2,2,2,2]);return nr([2,2],[r,s]).readUInt32BE()};Ite=N0.createSelfSignedCertificateWithKey,Rte=class{static async rtpSource({port:t,kind:e,cb:r}){t??=await Gk();let s=new K0({kind:e}),n=(0,Dj.createSocket)("udp4");n.bind(t);let i=a=>{r&&(a=r(a)),s.writeRtp(a)};return n.addListener("message",i),[s,t,()=>{n.removeListener("message",i);try{n.close()}catch{}}]}},Vj=(t,e)=>{if(!t||typeof t!="object")return e!==null&&typeof e=="object"?e:t;if(!e||typeof e!="object")return e??t;for(let r in e)if(Object.prototype.hasOwnProperty.call(e,r)){let s=e[r];s!=null&&(t[r]=s)}return t},Pte=ft("werift:packages/webrtc/src/media/receiver/nack.ts"),TU=150,Dte=class{constructor(t){this.receiver=t}newEstSeqNum=0;_lost={};nackLoop;onPacketLost=new Ne;mediaSourceSsrc;retryCount=10;closed=!1;get lostSeqNumbers(){return Object.keys(this._lost).map(Number).sort()}getLost(t){return this._lost[t]}setLost(t,e){this._lost[t]=e,!(this.nackLoop||this.closed)&&(this.nackLoop=setInterval(async()=>{try{await this.sendNack(),Object.keys(this._lost).length||(clearInterval(this.nackLoop),this.nackLoop=void 0)}catch(r){Pte("failed to send nack",r)}},5))}removeLost(t){delete this._lost[t]}addPacket(t){let{sequenceNumber:e,ssrc:r}=t.header;if(this.mediaSourceSsrc=r,this.newEstSeqNum===0){this.newEstSeqNum=e;return}if(this.getLost(e)){this.removeLost(e);return}if(e===Jr(this.newEstSeqNum,1))this.newEstSeqNum=e;else if(e>Jr(this.newEstSeqNum,1)){for(let s=Jr(this.newEstSeqNum,1);s<e;s=Jr(s,1))this.setLost(s,1);this.newEstSeqNum=e,this.pruneLost()}}pruneLost(){this.lostSeqNumbers.length>TU&&(this._lost=Object.entries(this._lost).slice(-TU).reduce((t,[e,r])=>(t[e]=r,t),{}))}close(){this.closed=!0,clearInterval(this.nackLoop),this._lost={}}updateRetryCount(){this.lostSeqNumbers.forEach(t=>{if(this._lost[t]++>this.retryCount)return this.removeLost(t),t})}sendNack=()=>new Promise((t,e)=>{if(this.lostSeqNumbers.length>0&&this.mediaSourceSsrc){let r=new H0({senderSsrc:this.receiver.rtcpSsrc,mediaSourceSsrc:this.mediaSourceSsrc,lost:this.lostSeqNumbers}),s=new yl({feedback:r});this.receiver.dtlsTransport.sendRtcp([s]).then(t).catch(e),this.updateRetryCount(),this.onPacketLost.execute(r)}})},Bte=ft("werift:packages/webrtc/media/receiver/receiverTwcc"),Lte=class{constructor(t,e,r){this.dtlsTransport=t,this.rtcpSsrc=e,this.mediaSourceSsrc=r,this.runTWCC()}extensionInfo={};twccRunning=!1;fbPktCount=0;lastTimestamp;handleTWCC(t){this.extensionInfo[t]={tsn:t,timestamp:Fj()},Object.keys(this.extensionInfo).length>10&&this.sendTWCC()}async runTWCC(){for(;this.twccRunning;)this.sendTWCC(),await(0,zj.setTimeout)(100)}sendTWCC(){if(Object.keys(this.extensionInfo).length===0)return;let t=Object.values(this.extensionInfo).sort((u,l)=>u.tsn-l.tsn),e=t[0].tsn,r=t.slice(-1)[0].tsn,s=[],n=t[0].tsn,i=Jr(r-e,1),o,a,c=[];for(let u=e;u<=r;u++){let l=this.extensionInfo[u]?.timestamp;if(l){this.lastTimestamp||(this.lastTimestamp=l),o||(o=this.lastTimestamp);let h=l-this.lastTimestamp;this.lastTimestamp=l;let p=new I0({delta:Number(h)});p.parseDelta(),c.push(p),a!=null&&a.status!==p.type&&(s.push(new Dh({packetStatus:a.status,runLength:u-a.minTSN})),a={minTSN:u,status:p.type}),u===r&&(a!=null?s.push(new Dh({packetStatus:a.status,runLength:u-a.minTSN+1})):s.push(new Dh({packetStatus:p.type,runLength:1}))),a==null&&(a={minTSN:u,status:p.type})}}if(!o)return;let d=new yl({feedback:new q0({senderSsrc:this.rtcpSsrc,mediaSourceSsrc:this.mediaSourceSsrc,baseSequenceNumber:n,packetStatusCount:i,referenceTime:XU(Math.floor(Number(o/1000n/64n))),fbPktCount:this.fbPktCount,recvDeltas:c,packetChunks:s})});this.dtlsTransport.sendRtcp([d]).catch(u=>{Bte(u)}),this.extensionInfo={},this.fbPktCount=GU(this.fbPktCount,1)}},Ote=class{base_seq;max_seq;cycles=0;packets_received=0;clockRate;jitter_q4=0;last_arrival;last_timestamp;expected_prior=0;received_prior=0;constructor(t){this.clockRate=t}add(t,e=Date.now()/1e3){let r=this.max_seq==null||h1(t.header.sequenceNumber,this.max_seq);if(this.packets_received++,this.base_seq==null&&(this.base_seq=t.header.sequenceNumber),r){let s=Rh(e*this.clockRate);if(this.max_seq!=null&&t.header.sequenceNumber<this.max_seq&&(this.cycles+=65536),this.max_seq=t.header.sequenceNumber,t.header.timestamp!==this.last_timestamp&&this.packets_received>1){let n=Math.abs(s-(this.last_arrival??0)-(t.header.timestamp-(this.last_timestamp??0)));this.jitter_q4+=n-(this.jitter_q4+8>>4)}this.last_arrival=s,this.last_timestamp=t.header.timestamp}}get fraction_lost(){let t=this.packets_expected-this.expected_prior;this.expected_prior=this.packets_expected;let e=this.packets_received-this.received_prior;this.received_prior=this.packets_received;let r=t-e;return t==0||r<=0?0:Math.floor((r<<8)/t)}get jitter(){return this.jitter_q4>>4}get packets_expected(){return this.cycles+(this.max_seq??0)-(this.base_seq??0)+1}get packets_lost(){let t=this.packets_expected-this.packets_received;return t<0?0:t}},qn=ft("werift:packages/webrtc/src/transport/dtls.ts"),vk=class Yj{constructor(e,r,s,n=[]){this.config=e,this.iceTransport=r,this.localCertificate=s,this.srtpProfiles=n,this.localCertificate??=Yj.localCertificate}id=(0,Gj.randomUUID)().toString();state="new";role="auto";srtpStarted=!1;transportSequenceNumber=0;bytesSent=0;bytesReceived=0;packetsSent=0;packetsReceived=0;dataReceiver=()=>{};dtls;srtp;srtcp;onStateChange=new Ne;onRtcp=new Ne;onRtp=new Ne;static localCertificate;static localCertificatePromise;remoteParameters;get localParameters(){return new a1(this.localCertificate?this.localCertificate.getFingerprints():[],this.role)}static async SetupCertificate(){return this.localCertificate?this.localCertificate:this.localCertificatePromise?this.localCertificatePromise:(this.localCertificatePromise=(async()=>{let{certPem:e,keyPem:r,signatureHash:s}=await N0.createSelfSignedCertificateWithKey({signature:zi.ecdsa_3,hash:O0.sha256_4},Xo.secp256r1_23);return this.localCertificate=new LA(r,e,s),this.localCertificate})(),this.localCertificatePromise)}setRemoteParams(e){let r=Ute([...this.remoteParameters?.fingerprints??[],...e.fingerprints]),s=e.role==="auto"&&this.remoteParameters?.role?this.remoteParameters.role:e.role;this.remoteParameters=new a1(r,s)}async start(){if(this.state!=="new")throw new Error("state must be new");if(!this.remoteParameters||this.remoteParameters.fingerprints.length===0)throw new Error("remote fingerprint not exist");this.role==="auto"&&(this.iceTransport.role==="controlling"?this.role="server":this.role="client"),this.setState("connecting"),await new Promise(async(e,r)=>{this.role==="server"?this.dtls=new jM({cert:this.localCertificate?.certPem,key:this.localCertificate?.privateKey,signatureHash:this.localCertificate?.signatureHash,transport:kU(this.iceTransport.connection),srtpProfiles:this.srtpProfiles,extendedMasterSecret:!0,certificateRequest:!0}):this.dtls=new ik({cert:this.localCertificate?.certPem,key:this.localCertificate?.privateKey,signatureHash:this.localCertificate?.signatureHash,transport:kU(this.iceTransport.connection),srtpProfiles:this.srtpProfiles,extendedMasterSecret:!0}),this.dtls.onData.subscribe(s=>{this.config.debug.inboundPacketLoss&&this.config.debug.inboundPacketLoss/100<Math.random()||this.dataReceiver(s)}),this.dtls.onClose.subscribe(()=>{this.state!=="failed"&&this.setState("closed")}),this.dtls.onConnect.once(e),this.dtls.onError.once(s=>{this.setState("failed"),qn("dtls failed",s),r(s)}),this.dtls instanceof ik&&(await(0,Xj.setTimeout)(100),this.dtls.connect().catch(s=>{this.setState("failed"),qn("dtls connect failed",s),r(s)}))});try{this.verifyRemoteCertificateFingerprint()}catch(e){throw this.setState("failed"),this.dtls?.close(),e}this.srtpProfiles.length>0&&this.startSrtp(),this.setState("connected"),qn("dtls connected")}verifyRemoteCertificateFingerprint(){if(!this.remoteParameters||this.remoteParameters.fingerprints.length===0)throw new Error("remote fingerprint not exist");let e=this.dtls?.remoteCertificate;if(!e)throw new Error("remote certificate not available");let r=this.remoteParameters.fingerprints.flatMap(({algorithm:a,value:c})=>{let d=RA(a);if(!d)return[];let u=i1(c);if(!u)throw new Error("remote fingerprint value is empty");return[{normalizedAlgorithm:d,normalizedValue:u}]});if(r.length===0)throw new Error("no supported remote fingerprint algorithms");let s=jte(r),n=r.filter(({normalizedAlgorithm:a})=>a===s),i=n.reduce((a,{normalizedAlgorithm:c})=>(a.has(c)||a.set(c,i1(IA(e,c))),a),new Map);if(!n.some(({normalizedAlgorithm:a,normalizedValue:c})=>i.get(a)===c))throw new Error("remote certificate fingerprint mismatch")}updateSrtpSession(){if(!this.dtls)throw new Error;let e=this.dtls.srtp.srtpProfile;if(!e)throw new Error("need srtpProfile");qn("selected SRTP Profile",e);let{localKey:r,localSalt:s,remoteKey:n,remoteSalt:i}=this.dtls.extractSessionKeys(B7(e),L7(e)),o={keys:{localMasterKey:r,localMasterSalt:s,remoteMasterKey:n,remoteMasterSalt:i},profile:e};this.srtp=new OM(o),this.srtcp=new LM(o)}startSrtp(){this.srtpStarted||(this.srtpStarted=!0,this.updateSrtpSession(),this.iceTransport.connection.onData.subscribe(e=>{if(!(this.config.debug.inboundPacketLoss&&this.config.debug.inboundPacketLoss/100<Math.random())&&X7(e))if(this.bytesReceived+=e.length,this.packetsReceived++,dM(e)){let r;try{r=this.srtcp.decrypt(e)}catch(n){if(n instanceof xl){qn("dropping invalid SRTCP packet",n);return}throw n}let s;try{s=cM.deSerialize(r)}catch(n){qn("dropping malformed SRTCP packet",n);return}for(let n of s)try{this.onRtcp.execute(n)}catch(i){qn("RTCP error",i)}}else{let r;try{r=this.srtp.decrypt(e)}catch(n){if(n instanceof xl){qn("dropping invalid SRTP packet",n);return}throw n}let s;try{s=Jo.deSerialize(r)}catch(n){qn("dropping malformed SRTP packet",n);return}try{this.onRtp.execute(s)}catch(n){qn("RTP error",n)}}}))}sendData=async e=>{if(!(this.config.debug.outboundPacketLoss&&this.config.debug.outboundPacketLoss/100<Math.random())){if(!this.dtls)throw new Error("dtls not established");await this.dtls.send(e)}};async sendRtp(e,r){try{let s=this.srtp.encrypt(e,r);return this.config.debug.outboundPacketLoss&&this.config.debug.outboundPacketLoss/100<Math.random()||(this.bytesSent+=s.length,this.packetsSent++,await this.iceTransport.connection.send(s).catch(()=>{})),s.length}catch(s){return qn("failed to send",s),0}}async sendRtcp(e){let r=Buffer.concat(e.map(n=>n.serialize())),s=this.srtcp.encrypt(r);if(this.config.debug.outboundPacketLoss&&this.config.debug.outboundPacketLoss/100<Math.random())return s.length;this.bytesSent+=s.length,this.packetsSent++,await this.iceTransport.connection.send(s).catch(()=>{})}setState(e){e!=this.state&&(this.state=e,this.onStateChange.execute(e))}async stop(){this.setState("closed"),await this.iceTransport.stop()}async getStats(){let e=bc(),r=[],n={type:"transport",id:zt("transport",this.id),timestamp:e,bytesSent:this.bytesSent,bytesReceived:this.bytesReceived,packetsSent:this.packetsSent,packetsReceived:this.packetsReceived,dtlsState:this.state,iceState:this.iceTransport.state,selectedCandidatePairId:this.iceTransport.connection.nominated?zt("candidate-pair",this.iceTransport.connection.nominated.localCandidate.foundation,this.iceTransport.connection.nominated.remoteCandidate.foundation):void 0,localCertificateId:this.localCertificate?zt("certificate","local"):void 0,remoteCertificateId:this.remoteParameters?zt("certificate","remote"):void 0,dtlsRole:this.role==="auto"?void 0:this.role};if(r.push(n),this.localCertificate){let o=this.localCertificate.getFingerprints();if(o.length>0){let a={type:"certificate",id:zt("certificate","local"),timestamp:e,fingerprint:o[0].value,fingerprintAlgorithm:o[0].algorithm,base64Certificate:Buffer.from(this.localCertificate.certPem).toString("base64")};r.push(a)}}if(this.remoteParameters&&this.remoteParameters.fingerprints.length>0){let o={type:"certificate",id:zt("certificate","remote"),timestamp:e,fingerprint:this.remoteParameters.fingerprints[0].value,fingerprintAlgorithm:this.remoteParameters.fingerprints[0].algorithm,base64Certificate:""};r.push(o)}let i=await this.iceTransport.getStats();return r.push(...i),r}},Nte=["new","connecting","connected","closed","failed"],LA=class{constructor(t,e,r){this.certPem=e,this.signatureHash=r;let s=X0.Certificate.fromPEM(Buffer.from(e));this.publicKey=s.publicKey.toPEM(),this.privateKey=X0.PrivateKey.fromPEM(Buffer.from(t)).toPEM()}publicKey;privateKey;getFingerprints(){return[new o1("sha-256",IA(X0.Certificate.fromPEM(Buffer.from(this.certPem)).raw,"sha256"))]}},o1=class{constructor(t,e){this.algorithm=t,this.value=e}},a1=class{constructor(t=[],e){this.fingerprints=t,this.role=e}},Ute=t=>{let e=new Set;return t.filter(({algorithm:r,value:s})=>{let n=`${RA(r)??r.trim().toLowerCase()}:${i1(s)}`;return e.has(n)?!1:(e.add(n),!0)})},Mte=["sha512","sha384","sha256","sha224","sha1"],jte=t=>Mte.find(e=>t.some(({normalizedAlgorithm:r})=>r===e))??t[0].normalizedAlgorithm,$te=class{constructor(t){this.ice=t,t.onData.subscribe(e=>{jj(e)&&this.onData&&this.onData(e)})}closed=!1;onData=()=>{};get address(){return{}}type="ice";send=t=>this.ice.send(t);async close(){this.closed=!0,this.ice.close()}},kU=t=>new $te(t),AU=ft("werift:packages/webrtc/src/transport/ice.ts"),Qj=class{constructor(t){this.iceGather=t,this.connection=this.iceGather.connection,this.connection.stateChanged.subscribe(e=>{this.setState(e)}),this.iceGather.onIceCandidate=e=>{this.onIceCandidate.execute(e)}}id=(0,Jj.randomUUID)().toString();connection;state="new";waitStart;renominating=!1;onStateChange=new Ne;onIceCandidate=new Ne;onNegotiationNeeded=new Ne;get role(){return this.connection.iceControlling?"controlling":"controlled"}get gatheringState(){return this.iceGather.gatheringState}get localCandidates(){return this.iceGather.localCandidates}get localParameters(){return this.iceGather.localParameters}setState(t){t!==this.state&&(this.state=t,this.onStateChange.execute(t))}gather(){return this.iceGather.gather()}addRemoteCandidate=t=>{if(!this.connection.remoteCandidatesEnd)return t?this.connection.addRemoteCandidate(e$(t)):this.connection.addRemoteCandidate(void 0)};setRemoteParams(t,e=!1){e&&(this.renominating=!0),this.connection.remoteUsername&&this.connection.remotePassword&&(this.connection.remoteUsername!==t.usernameFragment||this.connection.remotePassword!==t.password)&&(this.renominating?(AU("renomination",t),this.connection.resetNominatedPair(),this.renominating=!1):(AU("restart",t),this.restart())),this.connection.setRemoteParams(t)}restart(){this.connection.restart(),this.setState("new"),this.iceGather.gatheringState="new",this.waitStart=void 0,this.onNegotiationNeeded.execute()}async start(){if(this.state==="closed")throw new Error("RTCIceTransport is closed");if(!this.connection.remotePassword||!this.connection.remoteUsername)throw new Error("remoteParams missing");this.waitStart&&await this.waitStart.asPromise(),this.waitStart=new Ne,this.setState("checking");try{await this.connection.connect()}catch(t){throw this.setState("failed"),t}this.waitStart.execute(),this.waitStart.complete(),this.waitStart=void 0}async stop(){this.state!=="closed"&&(this.setState("closed"),await this.connection.close()),this.onStateChange.complete(),this.onIceCandidate.complete(),this.onNegotiationNeeded.complete()}async getStats(){let t=bc(),e=[];for(let s of this.localCandidates){let n={type:"local-candidate",id:zt("local-candidate",s.foundation),timestamp:t,transportId:zt("transport",this.id),address:s.ip,port:s.port,protocol:s.protocol,candidateType:s.type,priority:s.priority,foundation:s.foundation};e.push(n)}for(let s of this.connection.remoteCandidates){let n=jh(s),i={type:"remote-candidate",id:zt("remote-candidate",n.foundation),timestamp:t,transportId:zt("transport",this.id),address:n.ip,port:n.port,protocol:n.protocol,candidateType:n.type,priority:n.priority,foundation:n.foundation};e.push(i)}let r=this.connection?.candidatePairs?[...this.connection.candidatePairs.filter(s=>s.nominated),...this.connection.candidatePairs.filter(s=>!s.nominated)]:[];for(let s of r){let n={type:"candidate-pair",id:zt("candidate-pair",s.foundation),timestamp:t,transportId:zt("transport",this.id),localCandidateId:zt("local-candidate",s.localCandidate.foundation),remoteCandidateId:zt("remote-candidate",s.remoteCandidate.foundation),state:s.state,nominated:s.nominated,packetsSent:s.packetsSent,packetsReceived:s.packetsReceived,bytesSent:s.bytesSent,bytesReceived:s.bytesReceived,currentRoundTripTime:s.rtt};e.push(n)}return e}},Fte=["new","checking","connected","completed","disconnected","failed","closed"],Hte=["new","gathering","complete"],Zj=class{constructor(t={}){this.options=t,this.connection=new wj(!1,this.options),this.connection.onIceCandidate.subscribe(e=>{this.onIceCandidate(jh(e))})}onIceCandidate=()=>{};gatheringState="new";connection;onGatheringStateChange=new Ne;async gather(){this.gatheringState==="new"&&(this.setState("gathering"),await this.connection.gatherCandidates(),this.onIceCandidate(void 0),this.setState("complete"))}get localCandidates(){return this.connection.localCandidates.map(jh)}get localParameters(){return new NA({usernameFragment:this.connection.localUsername,password:this.connection.localPassword})}setState(t){t!==this.gatheringState&&(this.gatheringState=t,this.onGatheringStateChange.execute(t))}};t$=class{candidate;sdpMid;sdpMLineIndex;usernameFragment;constructor(t){Object.assign(this,t)}static fromSdp(t){let e=gc.fromSdp(t);return jh(e).toJSON()}static isThis(t){if(typeof t?.candidate=="string")return!0}toJSON(){return{candidate:this.candidate,sdpMid:this.sdpMid,sdpMLineIndex:this.sdpMLineIndex,usernameFragment:this.usernameFragment}}},OA=class{constructor(t,e,r,s,n,i,o,a,c){this.component=t,this.foundation=e,this.ip=r,this.port=s,this.priority=n,this.protocol=i,this.type=o,this.generation=a,this.ufrag=c}relatedAddress;relatedPort;sdpMid;sdpMLineIndex;tcpType;toJSON(){return new t$({candidate:jA(this),sdpMLineIndex:this.sdpMLineIndex,sdpMid:this.sdpMid,usernameFragment:this.ufrag})}static fromJSON(t){try{if(!t.candidate)throw new Error("candidate is required");let e=$A(t.candidate);return e.sdpMLineIndex=t.sdpMLineIndex??void 0,e.sdpMid=t.sdpMid??void 0,e}catch{}}},NA=class{iceLite=!1;usernameFragment;password;constructor(t={}){Object.assign(this,t)}},Ki=class s${constructor(e=0,r=Buffer.from("")){this.flags=e,this._body=r}get body(){return this._body}set body(e){this._body=e}static type=-1;get type(){return s$.type}get bytes(){if(!this.body)throw new Error;let e=Buffer.alloc(4);return e.writeUInt8(this.type,0),e.writeUInt8(this.flags,1),e.writeUInt16BE(this.body.length+4,2),Buffer.concat([e,this.body,...[...Array(cg(this.body.length))].map(()=>Buffer.from("\0"))])}},UA=class extends Ki{constructor(t=0,e){super(t,e),this.flags=t,e?(this.initiateTag=e.readUInt32BE(0),this.advertisedRwnd=e.readUInt32BE(4),this.outboundStreams=e.readUInt16BE(8),this.inboundStreams=e.readUInt16BE(10),this.initialTsn=e.readUInt32BE(12),this.params=E$(e.slice(16))):(this.initiateTag=0,this.advertisedRwnd=0,this.outboundStreams=0,this.inboundStreams=0,this.initialTsn=0,this.params=[])}initiateTag;advertisedRwnd;outboundStreams;inboundStreams;initialTsn;params;get body(){let t=Buffer.alloc(16);return t.writeUInt32BE(this.initiateTag,0),t.writeUInt32BE(this.advertisedRwnd,4),t.writeUInt16BE(this.outboundStreams,8),t.writeUInt16BE(this.inboundStreams,10),t.writeUInt32BE(this.initialTsn,12),Buffer.concat([t,S$(this.params)])}},Vw=class n$ extends UA{static type=1;get type(){return n$.type}},_k=class i$ extends UA{static type=2;get type(){return i$.type}},qte=class o$ extends UA{static type=130;get type(){return o$.type}},zw=class a$ extends Ki{constructor(e=0,r){if(super(e,r),this.flags=e,r){this.cumulativeTsn=r.readUInt32BE(0);let s=4;for(;s<r.length;)this.streams.push([r.readUInt16BE(s),r.readUInt16BE(s+2)]),s+=4}else this.cumulativeTsn=0}static type=192;streams=[];cumulativeTsn;get type(){return a$.type}set body(e){}get body(){let e=Buffer.alloc(4);return e.writeUInt32BE(this.cumulativeTsn,0),Buffer.concat([e,...this.streams.map(([r,s])=>{let n=Buffer.alloc(4);return n.writeUInt16BE(r,0),n.writeUInt16BE(s,2),n})])}},Ww=class c$ extends Ki{constructor(e=0,r){super(e,r),this.flags=e,r&&(this.tsn=r.readUInt32BE(0),this.streamId=r.readUInt16BE(4),this.streamSeqNum=r.readUInt16BE(6),this.protocol=r.readUInt32BE(8),this.userData=r.slice(12))}static type=0;get type(){return c$.type}tsn=0;streamId=0;streamSeqNum=0;protocol=0;userData=Buffer.from("");abandoned=!1;acked=!1;misses=0;retransmit=!1;sentCount=0;bookSize=0;expiry;maxRetransmits;sentTime;get bytes(){let e=16+this.userData.length,r=Buffer.alloc(16);r.writeUInt8(this.type,0),r.writeUInt8(this.flags,1),r.writeUInt16BE(e,2),r.writeUInt32BE(this.tsn,4),r.writeUInt16BE(this.streamId,8),r.writeUInt16BE(this.streamSeqNum,10),r.writeUInt32BE(this.protocol,12);let s=Buffer.concat([r,this.userData]);return e%4&&(s=Buffer.concat([s,...[...Array(cg(e))].map(()=>Buffer.from("\0"))])),s}},Sk=class d$ extends Ki{static type=10;get type(){return d$.type}},Ek=class l$ extends Ki{static type=11;get type(){return l$.type}},ag=class extends Ki{constructor(t=0,e=void 0){super(t,e),this.flags=t,e&&(this.params=E$(e))}params=[];get body(){return S$(this.params)}},Ck=class u$ extends ag{static type=6;get type(){return u$.type}},Kw=class Tk extends ag{static type=9;static CODE={InvalidStreamIdentifier:1,MissingMandatoryParameter:2,StaleCookieError:3,OutofResource:4,UnresolvableAddress:5,UnrecognizedChunkType:6,InvalidMandatoryParameter:7,UnrecognizedParameters:8,NoUserData:9,CookieReceivedWhileShuttingDown:10,RestartofanAssociationwithNewAddresses:11,UserInitiatedAbort:12,ProtocolViolation:13};get type(){return Tk.type}get descriptions(){return this.params.map(([e,r])=>({name:(Object.entries(Tk.CODE).find(([,n])=>n===e)||[])[0],body:r}))}},kk=class h$ extends ag{static type=4;get type(){return h$.type}},f$=class p$ extends ag{static type=5;get type(){return p$.type}},Ak=class m$ extends ag{static type=130;get type(){return m$.type}},Ik=class g$ extends Ki{constructor(e=0,r){if(super(e,r),this.flags=e,r){this.cumulativeTsn=r.readUInt32BE(0),this.advertisedRwnd=r.readUInt32BE(4);let s=r.readUInt16BE(8),n=r.readUInt16BE(10),i=12;[...Array(s)].forEach(()=>{this.gaps.push([r.readUInt16BE(i),r.readUInt16BE(i+2)]),i+=4}),[...Array(n)].forEach(()=>{this.duplicates.push(r.readUInt32BE(i)),i+=4})}}static type=3;get type(){return g$.type}gaps=[];duplicates=[];cumulativeTsn=0;advertisedRwnd=0;get bytes(){let e=16+4*(this.gaps.length+this.duplicates.length),r=Buffer.alloc(16);r.writeUInt8(this.type,0),r.writeUInt8(this.flags,1),r.writeUInt16BE(e,2),r.writeUInt32BE(this.cumulativeTsn,4),r.writeUInt32BE(this.advertisedRwnd,8),r.writeUInt16BE(this.gaps.length,12),r.writeUInt16BE(this.duplicates.length,14);let s=Buffer.concat([r,...this.gaps.map(n=>{let i=Buffer.alloc(4);return i.writeUInt16BE(n[0],0),i.writeUInt16BE(n[1],2),i})]);return s=Buffer.concat([s,...this.duplicates.map(n=>{let i=Buffer.alloc(4);return i.writeUInt32BE(n,0),i})]),s}},y$=class b$ extends Ki{constructor(e=0,r){super(e,r),this.flags=e,r&&(this.cumulativeTsn=r.readUInt32BE(0))}static type=7;get type(){return b$.type}cumulativeTsn=0;get body(){let e=Buffer.alloc(4);return e.writeUInt32BE(this.cumulativeTsn,0),e}},x$=class w$ extends Ki{static type=8;get type(){return w$.type}},v$=class _$ extends Ki{static type=14;get type(){return _$.type}},Vte=[Ww,Vw,_k,Ik,kk,f$,Ck,y$,x$,Kw,Sk,Ek,v$,Ak,zw],zte=Vte.reduce((t,e)=>(t[e.type]=e,t),{});Rk=class Pk{constructor(e,r,s,n){this.requestSequence=e,this.responseSequence=r,this.lastTsn=s,this.streams=n}static type=13;get type(){return Pk.type}get bytes(){let e=Buffer.from(Ko.jspack.Pack("!LLL",[this.requestSequence,this.responseSequence,this.lastTsn]));return Buffer.concat([e,...this.streams.map(r=>Buffer.from(Ko.jspack.Pack("!H",[r])))])}static parse(e){let[r,s,n]=Ko.jspack.Unpack("!LLL",e),i=[];for(let o=12;o<e.length;o+=2)i.push(Ko.jspack.Unpack("!H",e.slice(o))[0]);return new Pk(r,s,n,i)}},C$=class Dk{constructor(e,r){this.requestSequence=e,this.newStreams=r}static type=17;get type(){return Dk.type}get bytes(){return Buffer.from(Ko.jspack.Pack("!LHH",[this.requestSequence,this.newStreams,0]))}static parse(e){let[r,s]=Ko.jspack.Unpack("!LHH",e);return new Dk(r,s)}},Iw={ReconfigResultSuccessPerformed:1,BadSequenceNumber:5},Gw=class Bk{constructor(e,r){this.responseSequence=e,this.result=r}static type=16;get type(){return Bk.type}get bytes(){return Buffer.from(Ko.jspack.Pack("!LL",[this.responseSequence,this.result]))}static parse(e){let[r,s]=Ko.jspack.Unpack("!LL",e);return new Bk(r,s)}},IU={13:Rk,16:Gw,17:C$},Nt=ft("werift/sctp/sctp"),Yte=24,Jte=60,RU=65535,Vn=1200,k0=1,T$=2,Lk=4,PU=10,Qte=8,DU=1/8,BU=1/4,LU=3,Zte=1,ere=60,c1=2**32,tre=200,rre=30,OU=135,NU=7,UU=32776,MU=49152,sre=["new","closed","connected","connecting"],nre=class Ok{constructor(e,r=5e3){this.transport=e,this.port=r,this.localPort=this.port,this.transport.onData=s=>{this.handleData(s)}}flush=new Ne;stateChanged=Xte(sre);onReconfigStreams=new Ne;onReceive=new Ne;onSackReceived=async()=>{};associationState=1;started=!1;state="new";isServer=!0;isStopping=!1;isClosed=!1;hmacKey=(0,Y0.randomBytes)(16);localPartialReliability=!0;localPort;localVerificationTag=Yw();remoteExtensions=[];remotePartialReliability=!0;remotePort;remoteVerificationTag=0;advertisedRwnd=1024*1024;peerAdvertisedRwnd=this.advertisedRwnd;get peerRwnd(){return Math.max(0,this.peerAdvertisedRwnd-this.flightSize)}inboundStreams={};_inboundStreamsCount=0;_inboundStreamsMax=RU;lastReceivedTsn;sackDuplicates=[];sackMisOrdered=new Set;sackNeeded=!1;sackPacketCount=0;sackHasNewDataInPacket=!1;sackImmediate=!1;sackTimeout;cwnd=3*Vn;fastRecoveryExit;fastRecoveryTransmit=!1;forwardTsnChunk;flightSize=0;outboundQueue=[];outboundStreamSeq={};_outboundStreamsCount=RU;localTsn=Number(Yw());lastSackedTsn=dl(this.localTsn);advancedPeerAckTsn=dl(this.localTsn);partialBytesAcked=0;sentQueue=[];transmitting=!1;transmitRequested=!1;reconfigRequestSeq=this.localTsn;reconfigResponseSeq=0;reconfigRequest;reconfigQueue=[];srtt;rttvar;rto=LU;timer1Handle;timer1Chunk;timer1Failures=0;timer2Handle;timer2Chunk;timer2Failures=0;timer3Handle;timerReconfigHandle;timerReconfigFailures=0;timerHeartbeatHandle;heartbeatInterval=rre;ssthresh;get isStopped(){return this.isStopping||this.isClosed}get maxChannels(){if(this._inboundStreamsCount>0)return Math.min(this._inboundStreamsCount,this._outboundStreamsCount)}static client(e,r=5e3){let s=new Ok(e,r);return s.isServer=!1,s}static server(e,r=5e3){let s=new Ok(e,r);return s.isServer=!0,s}async handleData(e){if(this.isStopped)return;let r,[,,s,n]=Wte(e);if(n.filter(o=>o.type===Vw.type).length>0){if(n.length!=1)throw new Error;r=0}else r=this.localVerificationTag;if(s===r){this.sackHasNewDataInPacket=!1;for(let o of n)await this.receiveChunk(o);this.sackNeeded&&(this.sackHasNewDataInPacket&&this.sackPacketCount++,this.sackPacketCount>=2&&(this.sackImmediate=!0),await this.scheduleSack())}}async scheduleSack(){if(!this.isStopped&&this.sackNeeded){if(this.sackImmediate){this.sackTimeout&&(clearTimeout(this.sackTimeout),this.sackTimeout=void 0),await this.sendSack();return}this.sackTimeout||(this.sackTimeout=setTimeout(()=>{this.sackTimeout=void 0,this.sendSack().catch(e=>{Nt("send delayed sack failed",e.message)})},tre))}}async sendSack(){if(this.isStopped||!this.sackNeeded)return;let e=[],r;[...this.sackMisOrdered].sort().forEach(n=>{let i=(n-this.lastReceivedTsn)%c1;n===r?e[e.length-1][1]=i:e.push([i,i]),r=kh(n)});let s=new Ik(0,void 0);s.cumulativeTsn=this.lastReceivedTsn,s.advertisedRwnd=Math.max(0,this.advertisedRwnd),s.duplicates=[...this.sackDuplicates],s.gaps=e,await this.sendChunk(s).catch(n=>{Nt("send sack failed",n.message)}),this.sackDuplicates=[],this.sackNeeded=!1,this.sackPacketCount=0,this.sackImmediate=!1}async receiveChunk(e){switch(e.type){case Ww.type:this.receiveDataChunk(e);break;case Vw.type:{if(!this.isServer)return;let r=e;Nt("receive init",r),this.lastReceivedTsn=dl(r.initialTsn),this.reconfigResponseSeq=dl(r.initialTsn),this.remoteVerificationTag=r.initiateTag,this.ssthresh=r.advertisedRwnd,this.peerAdvertisedRwnd=r.advertisedRwnd,this.getExtensions(r.params),this._inboundStreamsCount=Math.min(r.outboundStreams,this._inboundStreamsMax),this._outboundStreamsCount=Math.min(this._outboundStreamsCount,r.inboundStreams);let s=new _k;s.initiateTag=this.localVerificationTag,s.advertisedRwnd=this.advertisedRwnd,s.outboundStreams=this._outboundStreamsCount,s.inboundStreams=this._inboundStreamsCount,s.initialTsn=this.localTsn,this.setExtensions(s.params);let n=Date.now()/1e3,i=Buffer.from(qw.jspack.Pack("!L",[n]));i=Buffer.concat([i,(0,Y0.createHmac)("sha1",this.hmacKey).update(i).digest()]),s.params.push([NU,i]),Nt("send initAck",s),await this.sendChunk(s).catch(o=>{Nt("send initAck failed",o.message)})}break;case _k.type:{if(this.associationState!=2)return;let r=e;this.timer1Cancel(),this.lastReceivedTsn=dl(r.initialTsn),this.reconfigResponseSeq=dl(r.initialTsn),this.remoteVerificationTag=r.initiateTag,this.ssthresh=r.advertisedRwnd,this.peerAdvertisedRwnd=r.advertisedRwnd,this.getExtensions(r.params),this._inboundStreamsCount=Math.min(r.outboundStreams,this._inboundStreamsMax),this._outboundStreamsCount=Math.min(this._outboundStreamsCount,r.inboundStreams);let s=new Sk;for(let[n,i]of r.params)if(n===NU){s.body=i;break}await this.sendChunk(s).catch(n=>{Nt("send echo failed",n.message)}),this.timer1Start(s),this.setState(3)}break;case Ik.type:await this.receiveSackChunk(e);break;case kk.type:{let r=new f$;r.params=e.params,await this.sendChunk(r).catch(s=>{Nt("send heartbeat ack failed",s.message)})}break;case Ck.type:this.setState(1);break;case y$.type:{this.timer2Cancel(),this.setState(7);let r=new x$;await this.sendChunk(r).catch(s=>{Nt("send shutdown ack failed",s.message)}),this.t2Start(r),this.setState(6)}break;case Kw.type:Nt("ErrorChunk",e.descriptions);break;case Sk.type:{if(!this.isServer)return;let s=e.body,n=(0,Y0.createHmac)("sha1",this.hmacKey).update(s.slice(0,4)).digest();if(s?.length!=Yte||!s.slice(4).equals(n)){Nt("x State cookie is invalid");return}let i=Date.now()/1e3,o=qw.jspack.Unpack("!L",s)[0];if(o<i-Jte||o>i){let c=new Kw(0,void 0);c.params.push([Kw.CODE.StaleCookieError,Buffer.concat([...Array(8)].map(()=>Buffer.from("\0")))]),await this.sendChunk(c).catch(d=>{Nt("send errorChunk failed",d.message)});return}let a=new Ek;await this.sendChunk(a).catch(c=>{Nt("send cookieAck failed",c.message)}),this.setState(4)}break;case Ek.type:{if(this.associationState!=3)return;this.timer1Cancel(),this.setState(4)}break;case v$.type:{if(this.associationState!=8)return;this.timer2Cancel(),this.setState(1)}break;case Ak.type:{if(this.associationState!=4)return;let r=e;for(let[s,n]of r.params){let i=IU[s];i&&await this.receiveReconfigParam(i.parse(n))}}break;case zw.type:this.receiveForwardTsnChunk(e);break}}getExtensions(e){for(let[r,s]of e)r===MU?this.remotePartialReliability=!0:r===UU&&(this.remoteExtensions=[...s])}async receiveReconfigParam(e){switch(Nt("receiveReconfigParam",IU[e.type]),e.type){case Rk.type:{let r=e,s=new Gw(r.requestSequence,Iw.ReconfigResultSuccessPerformed);this.reconfigResponseSeq=r.requestSequence,await this.sendReconfigParam(s),await Promise.all(r.streams.map(async n=>{delete this.inboundStreams[n],this.outboundStreamSeq[n]&&(this.reconfigQueue.includes(n)||this.reconfigQueue.push(n))})),await this.transmitReconfigRequest(),this.onReconfigStreams.execute(r.streams)}break;case Gw.type:{let r=e;if(r.result!==Iw.ReconfigResultSuccessPerformed)Nt("OutgoingSSNResetRequestParam failed",Object.keys(Iw).find(s=>Iw[s]===r.result));else if(r.responseSequence===this.reconfigRequest?.requestSequence){let s=this.reconfigRequest.streams.map(n=>(delete this.outboundStreamSeq[n],n));this.onReconfigStreams.execute(s),this.reconfigRequest=void 0,this.timerReconfigCancel(),this.rto=LU,this.timerReconfigFailures=0,this.reconfigQueue.length>0&&await this.transmitReconfigRequest()}}break;case C$.type:{let r=e;this._inboundStreamsCount+=r.newStreams;let s=new Gw(r.requestSequence,1);this.reconfigResponseSeq=r.requestSequence,await this.sendReconfigParam(s)}break}}receiveDataChunk(e){if(this.sackNeeded=!0,this.markReceived(e.tsn)){this.sackImmediate=!0;return}this.sackHasNewDataInPacket=!0,this.sackImmediate=!0,(e.flags&k0)===0&&(this.sackImmediate=!0),this.sackMisOrdered.size>0&&(this.sackImmediate=!0);let r=this.getInboundStream(e.streamId);r.addChunk(e),this.advertisedRwnd-=e.userData.length;for(let s of r.popMessages())this.advertisedRwnd+=s[2].length,this.receive(...s)}async receiveSackChunk(e){if(Hi(this.lastSackedTsn,e.cumulativeTsn))return;let r=Date.now()/1e3;this.lastSackedTsn=e.cumulativeTsn;let s=this.flightSize>=this.cwnd,n=0,i=0;for(;this.sentQueue.length>0&&Ah(this.lastSackedTsn,this.sentQueue[0].tsn);){let a=this.sentQueue.shift();n++,a?.acked||(i+=a.bookSize,this.flightSizeDecrease(a)),n===1&&a.sentCount===1&&this.updateRto(r-a.sentTime)}this.sentQueue.length||(this.sentQueue=[]);let o=!1;if(e.gaps.length>0){let a=new Set,c;e.gaps.forEach(u=>{for(let l=u[0];l<u[1]+1;l++)c=(e.cumulativeTsn+l)%c1,a.add(c)});let d=e.cumulativeTsn;for(let u of this.sentQueue){if(Hi(u.tsn,c))break;a.has(u.tsn)&&!u.acked&&(i+=u.bookSize,u.acked=!0,this.flightSizeDecrease(u),d=u.tsn)}for(let u of this.sentQueue){if(Hi(u.tsn,d))break;a.has(u.tsn)||(u.misses++,u.misses===3&&(u.misses=0,this.maybeAbandon(u)||(u.retransmit=!0),u.acked=!1,this.flightSizeDecrease(u),o=!0))}}this.fastRecoveryExit===void 0?(n&&s&&(this.cwnd<=this.ssthresh?this.cwnd+=Math.min(i,Vn):(this.partialBytesAcked+=i,this.partialBytesAcked>=this.cwnd&&(this.partialBytesAcked-=this.cwnd,this.cwnd+=Vn))),o&&(this.ssthresh=Math.max(Math.floor(this.cwnd/2),4*Vn),this.cwnd=this.ssthresh,this.partialBytesAcked=0,this.fastRecoveryExit=this.sentQueue[this.sentQueue.length-1].tsn,this.fastRecoveryTransmit=!0)):Ah(e.cumulativeTsn,this.fastRecoveryExit)&&(this.fastRecoveryExit=void 0),this.sentQueue.length===0?this.timer3Cancel():n>0&&this.timer3Restart(),this.peerAdvertisedRwnd=e.advertisedRwnd,this.updateAdvancedPeerAckPoint(),await this.onSackReceived(),await this.transmit()}receiveForwardTsnChunk(e){if(this.sackNeeded=!0,this.sackImmediate=!0,Ah(this.lastReceivedTsn,e.cumulativeTsn))return;let r=s=>Hi(s,this.lastReceivedTsn);this.lastReceivedTsn=e.cumulativeTsn,this.sackMisOrdered=new Set([...this.sackMisOrdered].filter(r));for(let s of[...this.sackMisOrdered].sort())if(s===kh(this.lastReceivedTsn))this.lastReceivedTsn=s;else break;this.sackDuplicates=this.sackDuplicates.filter(r),this.sackMisOrdered=new Set([...this.sackMisOrdered].filter(r));for(let[s,n]of e.streams){let i=this.getInboundStream(s);i.streamSequenceNumber=Jr(n,1);for(let o of i.popMessages())this.advertisedRwnd+=o[2].length,this.receive(...o)}Object.values(this.inboundStreams).forEach(s=>{this.advertisedRwnd+=s.pruneChunks(this.lastReceivedTsn)})}updateRto(e){this.srtt?(this.rttvar=(1-BU)*this.rttvar+BU*Math.abs(this.srtt-e),this.srtt=(1-DU)*this.srtt+DU*e):(this.rttvar=e/2,this.srtt=e),this.rto=Math.max(Zte,Math.min(this.srtt+4*this.rttvar,ere))}receive(e,r,s){this.onReceive.execute(e,r,s)}getInboundStream(e){return this.inboundStreams[e]||(this.inboundStreams[e]=new ire),this.inboundStreams[e]}markReceived(e){if(Ah(this.lastReceivedTsn,e)||this.sackMisOrdered.has(e))return this.sackDuplicates.push(e),!0;this.sackMisOrdered.add(e);for(let s of[...this.sackMisOrdered].sort())if(s===kh(this.lastReceivedTsn))this.lastReceivedTsn=s;else break;let r=s=>Hi(s,this.lastReceivedTsn);return this.sackDuplicates=this.sackDuplicates.filter(r),this.sackMisOrdered=new Set([...this.sackMisOrdered].filter(r)),!1}send=async(e,r,s,{expiry:n,maxRetransmits:i,ordered:o}={expiry:void 0,maxRetransmits:void 0,ordered:!0})=>{let a=o&&this.outboundStreamSeq[e]||0,c=Math.ceil(s.length/Vn),d=0,u=[];for(let l=0;l<c;l++){let h=new Ww(0,void 0);h.flags=0,o||(h.flags=Lk),l===0&&(h.flags|=T$),l===c-1&&(h.flags|=k0),h.tsn=this.localTsn,h.streamId=e,h.streamSeqNum=a,h.protocol=r,h.userData=s.slice(d,d+Vn),h.bookSize=h.userData.length,h.expiry=n,h.maxRetransmits=i,d+=Vn,this.localTsn=kh(this.localTsn),u.push(h)}for(u.forEach(l=>{this.outboundQueue.push(l)}),o&&(this.outboundStreamSeq[e]=Jr(a,1)),await this.transmit();this.outboundQueue.length;)await this.flush.asPromise()};async transmit(){if(!this.isStopped){if(this.transmitting){this.transmitRequested=!0;return}this.transmitting=!0;try{do this.transmitRequested=!1,await this.transmitOnce();while(this.transmitRequested)}finally{this.transmitting=!1}}}async transmitOnce(){if(this.isStopped)return;this.forwardTsnChunk&&(await this.sendChunk(this.forwardTsnChunk).catch(n=>{Nt("send forwardTsn failed",n.message)}),this.forwardTsnChunk=void 0,this.timer3Handle||this.timer3Start());let e=this.fastRecoveryExit!=null?2*Vn:4*Vn,r=Math.min(this.flightSize+e,this.cwnd),s=!0;for(let n of this.sentQueue){if(n.retransmit){if(this.fastRecoveryTransmit)this.fastRecoveryTransmit=!1;else if(this.flightSize>=r)break;this.flightSizeIncrease(n),n.misses=0,n.retransmit=!1,n.sentCount++,await this.sendChunk(n).catch(i=>{Nt("send data failed",i.message)}),s&&this.timer3Restart()}s=!1}for(;this.outboundQueue.length>0&&this.flightSize<r&&this.peerRwnd>0;){let n=this.outboundQueue.shift();if(!n)break;if(n.bookSize>this.peerRwnd&&this.flightSize>0){this.outboundQueue.unshift(n);break}this.sentQueue.push(n),this.flightSizeIncrease(n),n.sentCount++,n.sentTime=Date.now()/1e3,await this.sendChunk(n).catch(i=>{Nt("send data outboundQueue failed",i.message)}),this.timer3Handle||this.timer3Start()}this.outboundQueue.length||(this.outboundQueue=[]),this.flush.execute()}async transmitReconfigRequest(){if(this.reconfigQueue.length>0&&this.associationState===4&&!this.reconfigRequest){let e=[...new Set(this.reconfigQueue)],r=e.slice(0,OU);this.reconfigQueue=e.slice(OU);let s=new Rk(this.reconfigRequestSeq,this.reconfigResponseSeq,dl(this.localTsn),r);this.reconfigRequestSeq=kh(this.reconfigRequestSeq),this.reconfigRequest=s,await this.sendReconfigParam(s),this.timerReconfigHandleStart()}}async sendReconfigParam(e){Nt("sendReconfigParam",e);let r=new Ak;r.params.push([e.type,e.bytes]),await this.sendChunk(r).catch(s=>{Nt("send reconfig failed",s.message)})}async sendResetRequest(e){Nt("sendResetRequest",e);let r=new Ww(0,void 0);r.streamId=e,this.outboundQueue.push(r),this.timer3Handle||await this.transmit()}flightSizeIncrease(e){this.flightSize+=e.bookSize}flightSizeDecrease(e){this.flightSize=Math.max(0,this.flightSize-e.bookSize)}timer1Start(e){if(this.timer1Handle)throw new Error;this.timer1Chunk=e,this.timer1Failures=0,this.timer1Handle=setTimeout(this.timer1Expired,this.rto*1e3)}timer1Expired=()=>{if(!this.isStopped)if(this.timer1Failures++,this.timer1Handle=void 0,this.timer1Failures>Qte)this.setState(1);else{if(setImmediate(()=>{this.isStopped||this.sendChunk(this.timer1Chunk).catch(e=>{Nt("send timer1 chunk failed",e.message)})}),this.isStopped)return;this.timer1Handle=setTimeout(this.timer1Expired,this.rto*1e3)}};timer1Cancel(){this.timer1Handle&&(clearTimeout(this.timer1Handle),this.timer1Handle=void 0,this.timer1Chunk=void 0)}t2Start(e){if(this.timer2Handle)throw new Error;this.timer2Chunk=e,this.timer2Failures=0,this.timer2Handle=setTimeout(this.timer2Expired,this.rto*1e3)}timer2Expired=()=>{if(!this.isStopped)if(this.timer2Failures++,this.timer2Handle=void 0,this.timer2Failures>PU)this.setState(1);else{if(setImmediate(()=>{this.isStopped||this.sendChunk(this.timer2Chunk).catch(e=>{Nt("send timer2Chunk failed",e.message)})}),this.isStopped)return;this.timer2Handle=setTimeout(this.timer2Expired,this.rto*1e3)}};timer2Cancel(){this.timer2Handle&&(clearTimeout(this.timer2Handle),this.timer2Handle=void 0,this.timer2Chunk=void 0)}timer3Start(){if(!this.isStopped){if(this.timer3Handle)throw new Error;this.timer3Handle=setTimeout(this.timer3Expired,this.rto*1e3)}}timer3Restart(){this.isStopped||(this.timer3Cancel(),this.timer3Handle=setTimeout(this.timer3Expired,this.rto*1e3))}timer3Expired=()=>{this.isStopped||(this.timer3Handle=void 0,this.sentQueue.forEach(e=>{this.maybeAbandon(e)||(e.retransmit=!0)}),this.updateAdvancedPeerAckPoint(),this.fastRecoveryExit=void 0,this.flightSize=0,this.partialBytesAcked=0,this.ssthresh=Math.max(Math.floor(this.cwnd/2),4*Vn),this.cwnd=Vn,this.transmit())};timer3Cancel(){this.timer3Handle&&(clearTimeout(this.timer3Handle),this.timer3Handle=void 0)}timerReconfigHandleStart(){this.isStopped||this.timerReconfigHandle||(Nt("timerReconfigHandleStart",{rto:this.rto}),this.timerReconfigFailures=0,this.timerReconfigHandle=setTimeout(this.timerReconfigHandleExpired,this.rto*1e3))}timerReconfigHandleExpired=async()=>{if(!this.isStopped){if(this.timerReconfigFailures++,this.rto=Math.ceil(this.rto*1.5),this.timerReconfigFailures>PU)Nt("timerReconfigFailures",this.timerReconfigFailures),this.setState(1),this.timerReconfigHandle=void 0;else if(this.reconfigRequest){if(Nt("timerReconfigHandleExpired",this.timerReconfigFailures,this.rto),await this.sendReconfigParam(this.reconfigRequest),this.isStopped)return;this.timerReconfigHandle=setTimeout(this.timerReconfigHandleExpired,this.rto*1e3)}}};timerReconfigCancel(){this.timerReconfigHandle&&(Nt("timerReconfigCancel"),clearTimeout(this.timerReconfigHandle),this.timerReconfigHandle=void 0,this.timerReconfigFailures=0)}heartbeatStart(){this.timerHeartbeatHandle||this.associationState!==4||(this.timerHeartbeatHandle=setTimeout(this.timerHeartbeatExpired,(this.rto+this.heartbeatInterval)*1e3))}heartbeatRestart(){this.heartbeatCancel(),this.heartbeatStart()}heartbeatCancel(){this.timerHeartbeatHandle&&(clearTimeout(this.timerHeartbeatHandle),this.timerHeartbeatHandle=void 0)}timerHeartbeatExpired=async()=>{if(this.timerHeartbeatHandle=void 0,this.associationState===4){if(this.flightSize===0&&this.outboundQueue.length===0){let e=new kk;e.params.push([1,Buffer.from(qw.jspack.Pack("!L",[Math.floor(Date.now()/1e3)]))]),await this.sendChunk(e).catch(r=>{Nt("send heartbeat failed",r.message)})}this.heartbeatStart()}};setHeartbeatInterval(e){if(e<=0)throw new Error("heartbeat interval must be > 0");this.heartbeatInterval=e,this.heartbeatRestart()}updateAdvancedPeerAckPoint(){Hi(this.lastSackedTsn,this.advancedPeerAckTsn)&&(this.advancedPeerAckTsn=this.lastSackedTsn);let e=0,r={};for(;this.sentQueue.length>0&&this.sentQueue[0].abandoned;){let s=this.sentQueue.shift();this.advancedPeerAckTsn=s.tsn,e++,s.flags&Lk||(r[s.streamId]=s.streamSeqNum)}this.sentQueue.length||(this.sentQueue=[]),e&&(this.forwardTsnChunk=new zw(0,void 0),this.forwardTsnChunk.cumulativeTsn=this.advancedPeerAckTsn,this.forwardTsnChunk.streams=Object.entries(r).map(([s,n])=>[Number(s),n]))}maybeAbandon(e){if(e.abandoned)return!0;if(!(!!e.maxRetransmits&&e.maxRetransmits<e.sentCount||!!e.expiry&&e.expiry<Date.now()/1e3))return!1;let s=this.sentQueue.findIndex(n=>n.type===e.type);for(let n=s;n>=0;n--){let i=this.sentQueue[n];if(i.abandoned=!0,i.retransmit=!1,i.flags&k0)break}for(let n=s;n<this.sentQueue.length;n++){let i=this.sentQueue[n];if(i.abandoned=!0,i.retransmit=!1,i.flags&k0)break}return!0}static getCapabilities(){return new ore(65536)}setRemotePort(e){this.remotePort=e}async start(e){this.started||(this.started=!0,this.setConnectionState("connecting"),e&&this.setRemotePort(e),this.isServer||await this.init())}async init(){let e=new Vw;e.initiateTag=this.localVerificationTag,e.advertisedRwnd=this.advertisedRwnd,e.outboundStreams=this._outboundStreamsCount,e.inboundStreams=this._inboundStreamsMax,e.initialTsn=this.localTsn,this.setExtensions(e.params),Nt("send init",e);try{await this.sendChunk(e),this.timer1Start(e),this.setState(2)}catch(r){Nt("send init failed",r.message)}}setExtensions(e){let r=[];this.localPartialReliability&&(e.push([MU,Buffer.from("")]),r.push(zw.type)),r.push(qte.type),e.push([UU,Buffer.from(r)])}async sendChunk(e){if(this.state==="closed")return;if(this.remotePort===void 0)throw new Error("invalid remote port");let r=Kte(this.localPort,this.remotePort,this.remoteVerificationTag,e);await this.transport.send(r)}setState(e){e!=this.associationState&&(this.associationState=e),e===4?(this.isStopping=!1,this.isClosed=!1,this.setConnectionState("connected"),this.heartbeatStart()):e===1&&(this.isClosed=!0,this.timer1Cancel(),this.timer2Cancel(),this.timer3Cancel(),this.timerReconfigCancel(),this.heartbeatCancel(),this.sackTimeout&&(clearTimeout(this.sackTimeout),this.sackTimeout=void 0),this.setConnectionState("closed"),this.removeAllListeners())}setConnectionState(e){this.state=e,Nt("setConnectionState",e),this.stateChanged[e].execute()}async stop(){if(this.isStopped){this.setState(1);return}this.isStopping=!0,this.transport.onData=void 0,this.sackTimeout&&(clearTimeout(this.sackTimeout),this.sackTimeout=void 0),this.associationState!==1&&await this.abort(),this.setState(1),clearTimeout(this.timer1Handle),clearTimeout(this.timer2Handle),clearTimeout(this.timer3Handle),clearTimeout(this.timerReconfigHandle),clearTimeout(this.timerHeartbeatHandle),clearTimeout(this.sackTimeout)}async abort(){let e=new Ck;await this.sendChunk(e).catch(r=>{Nt("send abort failed",r.message)})}removeAllListeners(){Object.values(this.stateChanged).forEach(e=>e.allUnsubscribe())}},ire=class{reassembly=[];streamSequenceNumber=0;constructor(){}addChunk(t){if(this.reassembly.length===0||Hi(t.tsn,this.reassembly[this.reassembly.length-1].tsn)){this.reassembly.push(t);return}for(let[e,r]of Gte(this.reassembly)){if(r.tsn===t.tsn)throw new Error("duplicate chunk in reassembly");if(Hi(r.tsn,t.tsn)){this.reassembly.splice(e,0,t);break}}}*popMessages(){let t=0,e,r,s;for(;t<this.reassembly.length;){let n=this.reassembly[t];if(e===void 0){if(s=!(n.flags&Lk),!(n.flags&T$)){if(s)break;t++;continue}if(s&&h1(n.streamSeqNum,this.streamSequenceNumber))break;r=n.tsn,e=t}else if(n.tsn!==r){if(s)break;e=void 0,t++;continue}if(n.flags&k0){let i=this.reassembly.slice(e,t+1).map(a=>a.userData).reduce((a,c)=>(a.push(c),a.push(Buffer.from("")),a),[]);i.pop();let o=Buffer.concat(i);this.reassembly=[...this.reassembly.slice(0,e),...this.reassembly.slice(t+1)],s&&n.streamSeqNum===this.streamSequenceNumber&&(this.streamSequenceNumber=Jr(this.streamSequenceNumber,1)),t=e,yield[n.streamId,n.protocol,o]}else t++;r=kh(r)}}pruneChunks(t){let e=-1,r=0;for(let[s,n]of this.reassembly.entries())if(Ah(t,n.tsn))e=s,r+=n.userData.length;else break;return this.reassembly=this.reassembly.slice(e+1),r}},ore=class{constructor(t){this.maxMessageSize=t}};_h=ft("werift:packages/webrtc/src/transport/sctp.ts"),Ih=65536,k$=class A${constructor(e=5e3,r=Ih){this.port=e,this.maxMessageSize=r}dtlsTransport;sctp;onDataChannel=new Ne;id=(0,r$.randomUUID)().toString();mid;mLineIndex;bundled=!1;dataChannels={};remoteMaxMessageSize=Ih;dataChannelQueue=[];dataChannelId;eventDisposer=[];setDtlsTransport(e){this.dtlsTransport&&this.dtlsTransport.id===e.id||(this.eventDisposer.forEach(r=>r()),this.dtlsTransport=e,this.sctp=new nre(new are(this.dtlsTransport),this.port),this.eventDisposer=[...[this.sctp.onReceive.subscribe(this.datachannelReceive),this.sctp.onReconfigStreams.subscribe(r=>{r.forEach(s=>{let n=this.dataChannels[s];n&&(n.setReadyState("closing"),n.setReadyState("closed"),delete this.dataChannels[s])})}),this.sctp.stateChanged.connected.subscribe(()=>{Object.values(this.dataChannels).forEach(r=>{r.negotiated&&r.readyState!=="open"&&r.setReadyState("open")}),this.dataChannelFlush()}),this.sctp.stateChanged.closed.subscribe(()=>{Object.values(this.dataChannels).forEach(r=>{r.setReadyState("closed")}),this.dataChannels={}}),this.dtlsTransport.onStateChange.subscribe(r=>{r==="closed"&&this.sctp.setState(1)})].map(r=>r.unSubscribe),()=>this.sctp.onSackReceived=async()=>{}],this.sctp.onSackReceived=async()=>{await this.dataChannelFlush()})}get isServer(){return this.dtlsTransport.iceTransport.role!=="controlling"}channelByLabel(e){return Object.values(this.dataChannels).find(r=>r.label===e)}datachannelReceive=async(e,r,s)=>{if(r===Aw&&s.length>0)switch(_h("DCEP",e,r,s),s[0]){case wU:{if(s.length<12){_h("DATA_CHANNEL_OPEN data.length not enough");return}if(Object.keys(this.dataChannels).includes(e.toString()))_h("datachannel already opened","retransmit ack");else{let[,i,,o,a,c]=Hw.jspack.Unpack("!BBHLHH",s),d=12,u=s.slice(d,d+a).toString("utf8");d+=a;let l=s.slice(d,d+c).toString("utf8");_h("DATA_CHANNEL_OPEN",{channelType:i,reliability:o,streamId:e,label:u,protocol:l});let h=(i&3)===1?o:void 0,p=(i&3)===2?o:void 0,m=new xA({label:u,ordered:(i&128)===0,maxPacketLifeTime:p,maxRetransmits:h,protocol:l,id:e}),_=new bA(this,m,!1);_.isCreatedByRemote=!0,this.dataChannels[e]=_,this.onDataChannel.execute(_),_.setReadyState("open")}let n=this.dataChannels[e];this.dataChannelQueue.push([n,Aw,Buffer.from(Hw.jspack.Pack("!B",[xU]))]),await this.dataChannelFlush()}break;case xU:{_h("DATA_CHANNEL_ACK",e,r);let n=this.dataChannels[e];if(!n)throw new Error("channel not found");n.setReadyState("open")}break}else{let n=this.dataChannels[e];if(n){let i=(()=>{switch(r){case vU:return s.toString("utf8");case wte:return"";case _U:return s;case vte:return Buffer.from([]);default:throw new Error}})();n.messagesReceived++,n.bytesReceived+=s.length,n.onMessage.execute(i),n.emit("message",{data:i}),n.onmessage&&n.onmessage({data:i})}}};dataChannelAddNegotiated(e){if(e.id==null)throw new Error;if(this.dataChannels[e.id])throw new Error;this.dataChannels[e.id]=e,this.sctp.associationState===4&&e.setReadyState("open")}dataChannelOpen(e){if(e.id){if(this.dataChannels[e.id])throw new Error(`Data channel with ID ${e.id} already registered`);this.dataChannels[e.id]=e}let r=xte,s=0,n=0;e.ordered||(r=128),e.maxRetransmits?(r=1,n=e.maxRetransmits):e.maxPacketLifeTime&&(r=2,n=e.maxPacketLifeTime);let i=Hw.jspack.Pack("!BBHLHH",[wU,r,s,n,e.label.length,e.protocol.length]),o=Buffer.concat([Buffer.from(i),Buffer.from(e.label,"utf8"),Buffer.from(e.protocol,"utf8")]);this.dataChannelQueue.push([e,Aw,o]),this.dataChannelFlush()}async dataChannelFlush(){if(this.sctp.associationState==4){for(;this.dataChannelQueue.length>0;){let[e,r,s]=this.dataChannelQueue.shift(),n=e.id;if(n===void 0){for(n=this.dataChannelId;Object.keys(this.dataChannels).includes(n.toString());)n+=2;this.dataChannels[n]=e,e.setId(n)}if(r===Aw)await this.sctp.send(n,r,s,{ordered:!0});else{let i=e.maxPacketLifeTime?Date.now()+e.maxPacketLifeTime/1e3:void 0;await this.sctp.send(n,r,s,{expiry:i,maxRetransmits:e.maxRetransmits,ordered:e.ordered}),e.addBufferedAmount(-s.length)}}this.dataChannelQueue=[]}}assertSendableMessageSize(e){if(this.remoteMaxMessageSize!==0&&e>this.remoteMaxMessageSize)throw new Error(`max-message-size exceeded: ${e} > ${this.remoteMaxMessageSize}`)}datachannelSend=(e,r)=>{let s=Buffer.isBuffer(r)?r:Buffer.from(r),n=_j(r);return this.assertSendableMessageSize(n),e.addBufferedAmount(n),this.dataChannelQueue.push(typeof r=="string"?[e,vU,s]:[e,_U,s]),this.sctp.associationState!==4&&_h("sctp not established",this.sctp.associationState),this.dataChannelFlush(),n};getCapabilities(){return A$.getCapabilities(this.maxMessageSize)}static getCapabilities(e=Ih){return new MA(e)}setRemoteMaxMessageSize(e){this.remoteMaxMessageSize=e??Ih}setRemotePort(e){this.sctp.setRemotePort(e)}async start(e){this.isServer?this.dataChannelId=0:this.dataChannelId=1,this.sctp.isServer=this.isServer,await this.sctp.start(e)}async stop(){this.dtlsTransport.dataReceiver=()=>{},await this.sctp.stop()}dataChannelClose(e){["closing","closed"].includes(e.readyState)||(e.setReadyState("closing"),this.sctp.associationState===4?(this.sctp.reconfigQueue.includes(e.id)||this.sctp.reconfigQueue.push(e.id),this.sctp.reconfigQueue.length===1&&this.sctp.transmitReconfigRequest()):(this.dataChannelQueue=this.dataChannelQueue.filter(r=>r[0].id!==e.id),this.sctp.reconfigQueue=this.sctp.reconfigQueue.filter(r=>r!==e.id),e.id&&delete this.dataChannels[e.id],e.setReadyState("closed")))}},MA=class{constructor(t){this.maxMessageSize=t}},are=class{constructor(t){this.dtls=t}set onData(t){this.dtls.dataReceiver=t}send=t=>this.dtls.sendData(t);close(){}},P0=class I${version=0;origin;name="-";time="0 0";host;group=[];extMapAllowMixed=!0;msidSemantic=[];media=[];type;dtlsRole;iceOptions;iceLite;icePassword;iceUsernameFragment;dtlsFingerprints=[];static parse(e){let[r,s]=cre(e),n=new I$;r.forEach(o=>{if(o.startsWith("v="))n.version=Number.parseInt(o.slice(2),10);else if(o.startsWith("o="))n.origin=o.slice(2);else if(o.startsWith("s="))n.name=o.slice(2);else if(o.startsWith("c="))n.host=RT(o.slice(2));else if(o.startsWith("t="))n.time=o.slice(2);else if(o.startsWith("a=")){let[a,c]=PT(o);switch(a){case"fingerprint":{let[d,u]=c?.split(" ")||[];n.dtlsFingerprints.push(new o1(d,u))}break;case"ice-lite":n.iceLite=!0;break;case"ice-options":n.iceOptions=c;break;case"ice-pwd":n.icePassword=c;break;case"ice-ufrag":n.iceUsernameFragment=c;break;case"group":Xw(n.group,c);break;case"msid-semantic":Xw(n.msidSemantic,c);break;case"setup":n.dtlsRole=EU[c];break;case"extmap-allow-mixed":n.extMapAllowMixed=!0;break}}});let i=n.group.find(o=>o.semantic==="BUNDLE");return s.forEach(o=>{let c=o[0].match(/^m=([^ ]+) ([0-9]+) ([A-Z/]+) (.+)/);if(!c)throw new Error("m line not found");let d=c[1],u=c[4].split(" "),l=["audio","video"].includes(d)?u.map(m=>Number(m)):void 0,h=new d1(d,Number.parseInt(c[2]),c[3],l||u);if(h.dtlsParams=new a1([...n.dtlsFingerprints],n.dtlsRole),h.iceParams=new NA({iceLite:n.iceLite,usernameFragment:n.iceUsernameFragment,password:n.icePassword}),h.iceOptions=n.iceOptions,n.media.push(h),o.slice(1).forEach(m=>{if(m.startsWith("c="))h.host=RT(m.slice(2));else if(m.startsWith("a=")){let[_,f]=PT(m);switch(_){case"candidate":if(!f)throw new Error;h.iceCandidates.push($A(f));break;case"end-of-candidates":h.iceCandidatesComplete=!0;break;case"extmap":{let[b,w]=f.split(" ");b.includes("/")&&([b]=b.split("/")),h.rtp.headerExtensions.push(new Wi({id:Number.parseInt(b),uri:w}))}break;case"fingerprint":{if(!f)throw new Error;let[b,w]=f.split(" ");h.dtlsParams?.fingerprints.push(new o1(b,w))}break;case"ice-options":h.iceOptions=f;break;case"ice-pwd":h.iceParams.password=f;break;case"ice-ufrag":h.iceParams.usernameFragment=f;break;case"ice-lite":h.iceParams.iceLite=!0;break;case"max-message-size":h.sctpCapabilities=new MA(Number.parseInt(f,10));break;case"mid":h.rtp.muxId=f;break;case"msid":h.msid=f;break;case"rtcp":{let[b,w]=Vo(f," ");h.rtcpPort=Number.parseInt(b),h.rtcpHost=RT(w)}break;case"rtcp-mux":h.rtcpMux=!0;break;case"setup":h.dtlsParams.role=EU[f];break;case"recvonly":case"sendonly":case"sendrecv":case"inactive":h.direction=_;break;case"rtpmap":{let[b,w]=Vo(f," "),[S,O,j]=w.split("/"),P;h.kind==="audio"&&(P=j?Number.parseInt(j):1);let k=new yc({mimeType:h.kind+"/"+S,channels:P,clockRate:Number.parseInt(O),payloadType:Number.parseInt(b)});h.rtp.codecs.push(k)}break;case"sctpmap":{if(!f)throw new Error;let[b,w]=Vo(f," ");h.sctpMap[Number.parseInt(b)]=w,h.sctpPort=Number.parseInt(b)}break;case"sctp-port":if(!f)throw new Error;h.sctpPort=Number.parseInt(f);break;case"ssrc":{let[b,w]=Vo(f," "),S=Number.parseInt(b),[O,j]=Vo(w,":"),P=h.ssrc.find(k=>k.ssrc===S);P||(P=new l1({ssrc:S}),h.ssrc.push(P)),Lj.includes(O)&&(P[O]=j)}break;case"ssrc-group":Xw(h.ssrcGroup,f);break;case"rid":{let[b,w]=Vo(f," ");h.simulcastParameters.push(new wA({rid:b,direction:w}))}break}}}),(!h.iceParams.usernameFragment||!h.iceParams.password)&&h.rtp.muxId&&i&&i.items.includes(h.rtp.muxId))for(let m=0;m<i.items.length;m++){if(!i.items.includes(m.toString()))continue;let _=n.media[m];if(_.iceParams?.usernameFragment&&_.iceParams.password){h.iceParams={..._.iceParams};break}}h.dtlsParams.role||(h.dtlsParams=void 0);let p=m=>h.rtp.codecs.find(_=>_.payloadType===m);o.slice(1).forEach(m=>{if(m.startsWith("a=")){let[_,f]=PT(m);if(_==="fmtp"){let[b,w]=Vo(f," "),S=p(Number(b));S.parameters=w}else if(_==="rtcp-fb"){let[b,w,S]=f.split(" ");h.rtp.codecs.forEach(O=>{["*",O.payloadType.toString()].includes(b)&&O.rtcpFeedback.push(new Ej({type:w,parameter:S}))})}}})}),n}webrtcTrackId(e){if(e.msid?.includes(" ")){let r=e.msid.split(" ");for(let s of this.msidSemantic)if(s.semantic==="WMS"&&(s.items.includes(r[0])||s.items.includes("*")))return r[1]}}get string(){let e=[`v=${this.version}`,`o=${this.origin}`,`s=${this.name}`];this.host&&e.push(`c=${Nk(this.host)}`),e.push(`t=${this.time}`),this.group.forEach(n=>e.push(`a=group:${n.str}`)),this.extMapAllowMixed&&e.push("a=extmap-allow-mixed"),this.msidSemantic.forEach(n=>e.push(`a=msid-semantic:${n.str}`));let r=this.media.map(n=>n.toString()).join("");return e.join(`\r
|
|
137
137
|
`)+`\r
|
|
138
138
|
`+r}toJSON(){return new R$(this.string,this.type)}toSdp(){return{type:this.type,sdp:this.string}}},d1=class{constructor(t,e,r,s){this.kind=t,this.port=e,this.profile=r,this.fmt=s}host;direction;msid;rtcpPort;rtcpHost;rtcpMux=!1;ssrc=[];ssrcGroup=[];rtp={codecs:[],headerExtensions:[]};sctpCapabilities;sctpMap={};sctpPort;dtlsParams;iceParams;iceCandidates=[];iceCandidatesComplete=!1;iceOptions;simulcastParameters=[];toString(){let t=[];if(t.push(`m=${this.kind} ${this.port} ${this.profile} ${this.fmt.map(e=>e.toString()).join(" ")}`),this.host&&t.push(`c=${Nk(this.host)}`),this.iceCandidates.forEach(e=>{t.push(`a=candidate:${jA(e)}`)}),this.iceCandidatesComplete&&t.push("a=end-of-candidates"),this.iceParams?.usernameFragment&&t.push(`a=ice-ufrag:${this.iceParams.usernameFragment}`),this.iceParams?.password&&t.push(`a=ice-pwd:${this.iceParams.password}`),this.iceParams?.iceLite&&t.push("a=ice-lite"),this.iceOptions&&t.push(`a=ice-options:${this.iceOptions}`),this.dtlsParams&&(this.dtlsParams.fingerprints.forEach(e=>{t.push(`a=fingerprint:${e.algorithm} ${e.value}`)}),t.push(`a=setup:${wk[this.dtlsParams.role]}`)),this.direction&&t.push(`a=${this.direction}`),this.rtp.muxId&&t.push(`a=mid:${this.rtp.muxId}`),this.msid&&t.push(`a=msid:${this.msid}`),this.rtcpPort&&this.rtcpHost&&(t.push(`a=rtcp:${this.rtcpPort} ${Nk(this.rtcpHost)}`),this.rtcpMux&&t.push("a=rtcp-mux")),this.ssrcGroup.forEach(e=>{t.push(`a=ssrc-group:${e.str}`)}),this.ssrc.forEach(e=>{Lj.forEach(r=>{let s=e[r];s!==void 0&&t.push(`a=ssrc:${e.ssrc} ${r}:${s}`)})}),this.rtp.codecs.forEach(e=>{t.push(`a=rtpmap:${e.payloadType} ${e.str}`),e.rtcpFeedback.forEach(r=>{let s=r.type;r.parameter&&(s+=` ${r.parameter}`),t.push(`a=rtcp-fb:${e.payloadType} ${s}`)}),e.parameters&&t.push(`a=fmtp:${e.payloadType} ${e.parameters}`)}),Object.keys(this.sctpMap).forEach(e=>{let r=this.sctpMap[Number(e)];t.push(`a=sctpmap:${e} ${r}`)}),this.sctpPort&&t.push(`a=sctp-port:${this.sctpPort}`),this.sctpCapabilities&&t.push(`a=max-message-size:${this.sctpCapabilities.maxMessageSize}`),this.rtp.headerExtensions.forEach(e=>t.push(`a=extmap:${e.id} ${e.uri}`)),this.simulcastParameters.length){this.simulcastParameters.forEach(n=>{t.push(`a=rid:${n.rid} ${n.direction}`)});let e="a=simulcast:",r=this.simulcastParameters.filter(n=>n.direction==="recv");r.length&&(e+=`recv ${r.map(n=>n.rid).join(";")} `);let s=this.simulcastParameters.filter(n=>n.direction==="send");s.length&&(e+=`send ${s.map(n=>n.rid).join(";")}`),t.push(e)}return t.join(`\r
|
|
139
139
|
`)+`\r
|
|
140
|
-
`}},Bh=class{constructor(t,e){this.semantic=t,this.items=e}get str(){return`${this.semantic} ${this.items.join(" ")}`}};R$=class{constructor(t,e){this.sdp=t,this.type=e}static isThis(t){if(typeof t?.sdp=="string")return!0}toSdp(){return{sdp:this.sdp,type:this.type}}};l1=class{ssrc;cname;msid;msLabel;label;constructor(t){Object.assign(this,t)}},Rw=ft("werift:packages/webrtc/src/media/rtpReceiver.ts"),FA=class{constructor(t,e,r){this.config=t,this.kind=e,this.rtcpSsrc=r}codecs={};get codecArray(){return Object.values(this.codecs).sort((t,e)=>t.payloadType-e.payloadType)}ssrcByRtx={};nack=new Dte(this);audioRedHandler=new EM;type="receiver";uuid=(0,Rj.randomUUID)().toString();tracks=[];trackBySSRC={};trackByRID={};lastSRtimestamp={};receiveLastSRTimestamp={};onPacketLost=this.nack.onPacketLost;onRtcp=new Ne;dtlsTransport;sdesMid;latestRid;latestRepairedRid;receiverTWCC;stopped=!1;remoteStreamId;remoteTrackId;rtcpRunning=!1;rtcpCancel=new AbortController;remoteStreams={};setDtlsTransport(t){this.dtlsTransport=t}get track(){return this.tracks[0]??new Km({kind:this.kind})}get nackEnabled(){return this.codecArray[0]?.rtcpFeedback.find(t=>t.type==="nack")}get twccEnabled(){return this.codecArray[0]?.rtcpFeedback.find(t=>t.type===Sj().type)}get pliEnabled(){return this.codecArray[0]?.rtcpFeedback.find(t=>t.type===Vh().type)}prepareReceive(t){t.codecs.forEach(e=>{this.codecs[e.payloadType]=e}),t.encodings.forEach(e=>{e.rtx&&(this.ssrcByRtx[e.rtx.ssrc]=e.ssrc)})}setupTWCC(t){this.twccEnabled&&!this.receiverTWCC&&(this.receiverTWCC=new Lte(this.dtlsTransport,this.rtcpSsrc,t))}addTrack(t){return this.tracks.find(r=>{if(r.rid)return r.rid===t.rid;if(r.ssrc)return r.ssrc===t.ssrc})?!1:(this.tracks.push(t),t.ssrc&&(this.trackBySSRC[t.ssrc]=t),t.rid&&(this.trackByRID[t.rid]=t),!0)}stop(){this.stopped=!0,this.rtcpRunning=!1,this.rtcpCancel.abort(),this.receiverTWCC&&(this.receiverTWCC.twccRunning=!1),this.nack.close()}async runRtcp(){if(!(this.rtcpRunning||this.stopped)){this.rtcpRunning=!0;try{for(;this.rtcpRunning;){await(0,jw.setTimeout)(500+Math.random()*1e3,void 0,{signal:this.rtcpCancel.signal});let t=Object.entries(this.remoteStreams).map(([r,s])=>{let n=0,i=0;if(this.lastSRtimestamp[r]){n=this.lastSRtimestamp[r];let o=Gm()-this.receiveLastSRTimestamp[r];o>0&&o<65536&&(i=Rh(o*65536))}return new v1({ssrc:Number(r),fractionLost:s.fraction_lost,packetsLost:s.packets_lost,highestSequence:s.max_seq,jitter:s.jitter,lsr:n,dlsr:i})}),e=new Nh({ssrc:this.rtcpSsrc,reports:t});try{this.config.debug.receiverReportDelay&&await(0,jw.setTimeout)(this.config.debug.receiverReportDelay),await this.dtlsTransport.sendRtcp([e])}catch(r){Rw("sendRtcp failed",r),await(0,jw.setTimeout)(500+Math.random()*1e3)}}}catch{}}}async getStats(){let t=bc(),e=[];if(!this.dtlsTransport)return e;let r=zt("transport",this.dtlsTransport.id);for(let s of this.tracks){if(!s.ssrc)continue;let n=this.remoteStreams[s.ssrc];if(!n)continue;let i={type:"inbound-rtp",id:zt("inbound-rtp",s.ssrc),timestamp:t,ssrc:s.ssrc,kind:this.kind,transportId:r,codecId:this.codecs[0]?zt("codec",this.codecs[0].payloadType,r):void 0,mid:this.sdesMid,trackIdentifier:s.id,packetsReceived:n.packets_received,packetsLost:n.packets_lost,jitter:n.jitter};if(e.push(i),this.lastSRtimestamp[s.ssrc]){let o={type:"remote-outbound-rtp",id:zt("remote-outbound-rtp",s.ssrc),timestamp:t,ssrc:s.ssrc,kind:this.kind,transportId:r,codecId:i.codecId,localId:i.id,remoteTimestamp:this.receiveLastSRTimestamp[s.ssrc]*1e3};e.push(o)}}return e}async sendRtcpPLI(t){if(!this.pliEnabled){Rw("pli not supported",{mediaSsrc:t});return}if(this.stopped)return;Rw("sendRtcpPLI",{mediaSsrc:t});let e=new Oh({feedback:new $m({senderSsrc:this.rtcpSsrc,mediaSsrc:t})});try{await this.dtlsTransport.sendRtcp([e])}catch(r){Rw(r)}}handleRtcpPacket(t){switch(t.type){case bl.type:{let e=t;this.lastSRtimestamp[e.ssrc]=BA(e.senderInfo.ntpTimestamp),this.receiveLastSRTimestamp[e.ssrc]=Gm();let r=this.trackBySSRC[t.ssrc];r&&r.onReceiveRtcp.execute(t)}break}this.onRtcp.execute(t)}handleRtpBySsrc=(t,e)=>{let r=this.trackBySSRC[t.header.ssrc];this.handleRTP(t,e,r)};handleRtpByRid=(t,e,r)=>{let s=this.trackByRID[e];this.trackBySSRC[t.header.ssrc]||(this.trackBySSRC[t.header.ssrc]=s),this.handleRTP(t,r,s)};handleRTP(t,e,r){if(this.stopped)return;let s=this.codecs[t.header.payloadType];if(!s)return;if(this.remoteStreams[t.header.ssrc]=this.remoteStreams[t.header.ssrc]??new Ote(s.clockRate),this.remoteStreams[t.header.ssrc].add(t),this.receiverTWCC){let i=e[Qt.transportWideCC];if(!i==null)throw new Error("undefined");this.receiverTWCC.handleTWCC(i)}else this.twccEnabled&&this.setupTWCC(t.header.ssrc);if(s.name.toLowerCase()==="rtx"){let i=this.ssrcByRtx[t.header.ssrc],o=Jm(s.parameters??""),a=this.codecs[o.apt];if(t.payload.length<2)return;t=TM(t,a.payloadType,i),r=this.trackBySSRC[i]}let n;if(!(s.name.toLowerCase()==="red"&&(n=sA.deSerialize(t.payload),!Object.keys(this.codecs).includes(n.header.fields[0].blockPT.toString())))){if(r?.kind==="video"&&this.nackEnabled&&this.nack.addPacket(t),r)if(n){if(r.kind==="audio"){let i=this.audioRedHandler.push(n,t);for(let o of i)r.onReceiveRtp.execute(o.clone(),e)}}else r.onReceiveRtp.execute(t.clone(),e);this.runRtcp()}}},fm=ft("werift:packages/webrtc/src/media/router.ts"),P$=class{ssrcTable={};ridTable={};extIdUriMap={};constructor(){}registerRtpSender(t){this.ssrcTable[t.ssrc]=t}registerRtpReceiver(t,e){fm("registerRtpReceiver",e),this.ssrcTable[e]=t}registerRtpReceiverBySsrc(t,e){fm("registerRtpReceiverBySsrc",e),e.encodings.filter(r=>r.ssrc!=null).forEach((r,s)=>{this.registerRtpReceiver(t.receiver,r.ssrc),t.addTrack(new Km({ssrc:r.ssrc,kind:t.kind,id:t.sender.trackId,remote:!0,codec:e.codecs[s]})),r.rtx&&this.registerRtpReceiver(t.receiver,r.rtx.ssrc)}),e.headerExtensions.forEach(r=>{this.extIdUriMap[r.id]=r.uri})}registerRtpReceiverByRid(t,e,r){let[s]=r.codecs;fm("registerRtpReceiverByRid",e),t.addTrack(new Km({rid:e.rid,kind:t.kind,id:t.sender.trackId,remote:!0,codec:s})),this.ridTable[e.rid]=t.receiver}routeRtp=t=>{let e=lM(t.header.extensions,this.extIdUriMap),r=this.ssrcTable[t.header.ssrc],s=e[Qt.sdesRTPStreamID];if(typeof s=="string"?(r=this.ridTable[s],r.latestRid=s,r.handleRtpByRid(t,s,e)):r?r.handleRtpBySsrc(t,e):(r=Object.values(this.ridTable).filter(o=>o instanceof FA).find(o=>o.trackBySSRC[t.header.ssrc]),r&&(fm("simulcast register receiver by ssrc",t.header.ssrc),this.registerRtpReceiver(r,t.header.ssrc),r.handleRtpBySsrc(t,e))),!r){fm("ssrcReceiver not found");return}let n=e[Qt.sdesMid];typeof n=="string"&&(r.sdesMid=n);let i=e[Qt.repairedRtpStreamId];typeof i=="string"&&(r.latestRepairedRid=i)};routeRtcp=t=>{let e=[];switch(t.type){case bl.type:t=t,e.push(this.ssrcTable[t.ssrc]);break;case Nh.type:t=t,t.reports.forEach(r=>{e.push(this.ssrcTable[r.ssrc])});break;case Vm.type:{let r=t}break;case yl.type:{let r=t;r.feedback&&e.push(this.ssrcTable[r.feedback.mediaSourceSsrc])}break;case Oh.type:{let r=t;switch(r.feedback.count){case Fm.count:{let s=r.feedback;e.push(this.ssrcTable[s.ssrcFeedbacks[0]])}break;default:e.push(this.ssrcTable[r.feedback.senderSsrc]||this.ssrcTable[r.feedback.mediaSsrc])}}break}e.filter(r=>r).forEach(r=>r.handleRtcpPacket(t))}},lre=class{numPackets=0;totalSize=0;firstPacketSentAtMs=0;lastPacketSentAtMs=0;firstPacketReceivedAtMs=0;lastPacketReceivedAtMs=0;addPacket(t,e,r){this.numPackets===0?(this.firstPacketSentAtMs=e,this.firstPacketReceivedAtMs=r,this.lastPacketSentAtMs=e,this.lastPacketReceivedAtMs=r):(e<this.firstPacketSentAtMs&&(this.firstPacketSentAtMs=e),r<this.firstPacketReceivedAtMs&&(this.firstPacketReceivedAtMs=r),e>this.lastPacketSentAtMs&&(this.lastPacketSentAtMs=e),r>this.lastPacketReceivedAtMs&&(this.lastPacketReceivedAtMs=r)),this.numPackets++,this.totalSize+=t}reset(){this.numPackets=0,this.totalSize=0,this.firstPacketSentAtMs=0,this.lastPacketSentAtMs=0,this.firstPacketReceivedAtMs=0,this.lastPacketReceivedAtMs=0}get receiveBitrate(){let t=this.lastPacketReceivedAtMs-this.firstPacketReceivedAtMs,e=this.totalSize/t*8*1e3;return jm(e)}get sendBitrate(){let t=this.lastPacketSentAtMs-this.firstPacketSentAtMs,e=this.totalSize/t*8*1e3;return jm(e)}},Sh=20,ure=10,hre=class{congestion=!1;onAvailableBitrate=new Ne;onCongestion=new Ne;onCongestionScore=new Ne;congestionCounter=0;cumulativeResult=new lre;sentInfos={};_congestionScore=1;get congestionScore(){return this._congestionScore}set congestionScore(t){this._congestionScore=t,this.onCongestionScore.execute(t)}_availableBitrate=0;get availableBitrate(){return this._availableBitrate}set availableBitrate(t){this._availableBitrate=t,this.onAvailableBitrate.execute(t)}constructor(){}receiveTWCC(t){let r=DA()-this.cumulativeResult.firstPacketSentAtMs;r>1e3&&(this.cumulativeResult.reset(),this.congestionCounter<Sh?this.congestionCounter++:this.congestionScore<ure&&this.congestionScore++,this.congestionCounter>=Sh&&!this.congestion&&(this.congestion=!0,this.onCongestion.execute(this.congestion)));for(let s of t.packetResults){if(!s.received)continue;let n=s.sequenceNumber,i=this.sentInfos[n];i&&s.receivedAtMs&&this.cumulativeResult.addPacket(i.size,i.sendingAtMs,s.receivedAtMs)}if(r>=100&&this.cumulativeResult.numPackets>=20){if(this.availableBitrate=Math.min(this.cumulativeResult.sendBitrate,this.cumulativeResult.receiveBitrate),this.cumulativeResult.reset(),this.congestionCounter>-Sh){let s=jm(Sh/2)+1,n=jm(Sh/4)+1,i=s-(s-n)/10*this.congestionScore;this.congestionCounter=this.congestionCounter-i}this.congestionCounter<=-Sh&&(this.congestionScore>1&&(this.congestionScore--,this.onCongestion.execute(!1)),this.congestionCounter=0),this.congestionCounter<=0&&this.congestion&&(this.congestion=!1,this.onCongestion.execute(this.congestion))}}rtpPacketSent(t){Object.keys(t).map(e=>Number(e)).sort().filter(e=>e<t.wideSeq).forEach(e=>{delete this.sentInfos[e]}),this.sentInfos[t.wideSeq]=t}},DT=ft("werift:packages/webrtc/src/media/rtpSender.ts"),jU=128,$U=.85,D$=class{constructor(t){this.trackOrKind=t,this.kind=typeof this.trackOrKind=="string"?this.trackOrKind:this.trackOrKind.kind,typeof t!="string"&&(t.streamId&&(this.streamId=t.streamId),this.registerTrack(t))}type="sender";kind;ssrc=jk.jspack.Unpack("!L",(0,Mk.randomBytes)(4))[0];rtxSsrc=jk.jspack.Unpack("!L",(0,Mk.randomBytes)(4))[0];streamId=(0,$k.randomUUID)().toString();trackId=(0,$k.randomUUID)().toString();onReady=new Ne;onRtcp=new Ne;onPictureLossIndication=new Ne;onGenericNack=new Ne;senderBWE=new hre;cname;mid;rtpStreamId;repairedRtpStreamId;rtxPayloadType;rtxSequenceNumber=zk();redRedundantPayloadType;_redDistance=2;redEncoder=new SM(this._redDistance);headerExtensions=[];disposeTrack;lastSRtimestamp;lastSentSRTimestamp;ntpTimestamp=0n;rtpTimestamp=0;octetCount=0;packetCount=0;rtt;receiverEstimatedMaxBitrate=0n;sequenceNumber;timestamp;timestampOffset=0;seqOffset=0;rtpCache=[];codec;dtlsTransport;dtlsDisposer=[];track;stopped=!1;rtcpRunning=!1;rtcpCancel=new AbortController;setDtlsTransport(t){this.dtlsTransport&&this.dtlsDisposer.forEach(e=>e()),this.dtlsTransport=t,this.dtlsDisposer=[this.dtlsTransport.onStateChange.subscribe(e=>{e==="connected"&&this.onReady.execute()}).unSubscribe]}get redDistance(){return this._redDistance}set redDistance(t){this._redDistance=t,this.redEncoder.distance=t}prepareSend(t){this.cname=t.rtcp?.cname,this.mid=t.muxId,this.headerExtensions=t.headerExtensions,this.rtpStreamId=t.rtpStreamId,this.repairedRtpStreamId=t.repairedRtpStreamId,this.codec=t.codecs[0],this.track&&(this.track.codec=this.codec),t.codecs.forEach(e=>{let r=Jm(e.parameters??"");e.name.toLowerCase()==="rtx"&&r.apt===this.codec?.payloadType&&(this.rtxPayloadType=e.payloadType),e.name.toLowerCase()==="red"&&(this.redRedundantPayloadType=Number((e.parameters??"").split("/")[0]))})}registerTrack(t){if(t.stopped)throw new Error("track is ended");this.disposeTrack&&this.disposeTrack(),t.id=this.trackId;let{unSubscribe:e}=t.onReceiveRtp.subscribe(async r=>{await this.sendRtp(r)});this.track=t,this.disposeTrack=e,this.codec&&(t.codec=this.codec),t.onSourceChanged.subscribe(r=>{this.replaceRTP(r)})}async replaceTrack(t){if(t!==null){if(t.stopped)throw new Error("track is ended");if(this.sequenceNumber!=null){let e=t.header||(await t.onReceiveRtp.asPromise())[0].header;this.replaceRTP(e)}this.registerTrack(t),DT("replaceTrack","ssrc",t.ssrc,"rid",t.rid)}}stop(){this.stopped=!0,this.rtcpRunning=!1,this.rtcpCancel.abort(),this.disposeTrack&&this.disposeTrack(),this.track=void 0}async runRtcp(){if(!(this.rtcpRunning||this.stopped)){this.rtcpRunning=!0;try{for(;this.rtcpRunning;){await(0,Fk.setTimeout)(500+Math.random()*1e3,void 0,{signal:this.rtcpCancel.signal});let t=[new bl({ssrc:this.ssrc,senderInfo:new rA({ntpTimestamp:this.ntpTimestamp,rtpTimestamp:this.rtpTimestamp,packetCount:this.packetCount,octetCount:this.octetCount})})];this.lastSRtimestamp=BA(this.ntpTimestamp),this.lastSentSRTimestamp=Gm(),this.cname&&t.push(new Vm({chunks:[new eA({source:this.ssrc,items:[new tA({type:1,text:this.cname})]})]}));try{await this.dtlsTransport.sendRtcp(t)}catch(e){DT("sendRtcp failed",e),await(0,Fk.setTimeout)(500+Math.random()*1e3)}}}catch{}}}replaceRTP({sequenceNumber:t,timestamp:e},r=!1){this.sequenceNumber!=null&&(this.seqOffset=Jr(this.sequenceNumber,-t),r&&(this.seqOffset=Jr(this.seqOffset,2))),this.timestamp!=null&&(this.timestampOffset=ul(this.timestamp,-e),r&&(this.timestampOffset=Jr(this.timestampOffset,1))),this.rtpCache=[],DT("replaceRTP",this.sequenceNumber,t,this.seqOffset)}async sendRtp(t){if(this.dtlsTransport.state!=="connected"||!this.codec)return;t=Buffer.isBuffer(t)?Jo.deSerialize(t):t;let{header:e,payload:r}=t;e.ssrc=this.ssrc,e.payloadType=this.codec.payloadType,e.timestamp=ul(e.timestamp,this.timestampOffset),e.sequenceNumber=Jr(e.sequenceNumber,this.seqOffset),this.timestamp=e.timestamp,this.sequenceNumber=e.sequenceNumber;let s=Hj(),n=[...e.extensions];e.extensions=this.headerExtensions.map(d=>{let u=(()=>{switch(d.uri){case Qt.sdesMid:return this.mid?uM(this.mid):void 0;case Qt.sdesRTPStreamID:return this.rtpStreamId?hM(this.rtpStreamId):void 0;case Qt.repairedRtpStreamId:return this.repairedRtpStreamId?fM(this.repairedRtpStreamId):void 0;case Qt.transportWideCC:return this.dtlsTransport.transportSequenceNumber=Jr(this.dtlsTransport.transportSequenceNumber,1),pM(this.dtlsTransport.transportSequenceNumber);case Qt.absSendTime:return mM(s)}})();if(u)return{id:d.id,payload:u}}).filter(d=>d);for(let d of n){let u=e.extensions.find(l=>l.id===d.id);u?u.payload=d.payload:e.extensions.push(d)}e.extensions=e.extensions.sort((d,u)=>d.id-u.id),this.ntpTimestamp=s,this.rtpTimestamp=e.timestamp,this.octetCount+=r.length,this.packetCount=ul(this.packetCount,1),this.rtpCache[e.sequenceNumber%jU]=t;let i=r;this.redRedundantPayloadType&&(this.redEncoder.push({block:i,timestamp:e.timestamp,blockPT:this.redRedundantPayloadType}),i=this.redEncoder.build().serialize());let o=await this.dtlsTransport.sendRtp(i,e);this.runRtcp();let a=DA(),c={wideSeq:this.dtlsTransport.transportSequenceNumber,size:o,sendingAtMs:a,sentAtMs:a};this.senderBWE.rtpPacketSent(c)}handleRtcpPacket(t){switch(t.type){case bl.type:case Nh.type:t.reports.filter(r=>r.ssrc===this.ssrc).forEach(r=>{if(this.lastSRtimestamp===r.lsr&&r.dlsr&&this.lastSentSRTimestamp){let s=Gm()-this.lastSentSRTimestamp-r.dlsr/65536;this.rtt===void 0?this.rtt=s:this.rtt=$U*this.rtt+(1-$U)*s}});break;case yl.type:{let e=t;switch(e.feedback.count){case qm.count:{let r=e.feedback;this.senderBWE.receiveTWCC(r)}break;case Hm.count:{let r=e.feedback;r.lost.forEach(async s=>{let n=this.rtpCache[s%jU];n&&n.header.sequenceNumber!==s&&(n=void 0),n&&(this.rtxPayloadType!=null&&(n=kM(n,this.rtxPayloadType,this.rtxSequenceNumber,this.rtxSsrc),this.rtxSequenceNumber=Jr(this.rtxSequenceNumber,1)),await this.dtlsTransport.sendRtp(n.payload,n.header))}),this.onGenericNack.execute(r)}break}}break;case Oh.type:{let e=t;switch(e.feedback.count){case Fm.count:{let r=e.feedback;this.receiverEstimatedMaxBitrate=r.bitrate}break;case $m.count:this.onPictureLossIndication.execute();break}}break}this.onRtcp.execute(t)}getParameters(){return{encodings:[]}}setParameters(t){}async getStats(){let t=bc(),e=[];if(!this.dtlsTransport)return e;let r=zt("transport",this.dtlsTransport.id),s={type:"outbound-rtp",id:zt("outbound-rtp",this.ssrc),timestamp:t,ssrc:this.ssrc,kind:this.kind,transportId:r,codecId:this.codec?zt("codec",this.codec.payloadType,r):void 0,mid:this.mid,packetsSent:this.packetCount,bytesSent:this.octetCount,rtxSsrc:this.rtxPayloadType?this.rtxSsrc:void 0};if(e.push(s),this.track){let n={type:"media-source",id:zt("media-source",this.trackId),timestamp:t,trackIdentifier:this.trackId,kind:this.kind};e.push(n)}if(this.rtt!==void 0){let n={type:"remote-inbound-rtp",id:zt("remote-inbound-rtp",this.ssrc),timestamp:t,ssrc:this.ssrc,kind:this.kind,transportId:r,codecId:s.codecId,localId:s.id,roundTripTime:this.rtt};e.push(n)}return e}},fre=ft("werift:packages/webrtc/src/transport/sctpManager.ts"),pre=class{sctpTransport;sctpRemotePort;dataChannelsOpened=0;dataChannelsClosed=0;dataChannels=[];onDataChannel=new Ne;constructor(){}createSctpTransport(t){let e=new k$(5e3,t);return e.mid=void 0,e.onDataChannel.subscribe(r=>{this.dataChannelsOpened++,this.dataChannels.push(r),this.onDataChannel.execute(r)}),this.sctpTransport=e,e}createDataChannel(t,e={}){let s={...{protocol:"",ordered:!0,negotiated:!1},...e};if(s.maxPacketLifeTime&&s.maxRetransmits)throw new Error("can not select both");this.sctpTransport||(this.sctpTransport=this.createSctpTransport());let n=new xA({id:s.id,label:t,maxPacketLifeTime:s.maxPacketLifeTime,maxRetransmits:s.maxRetransmits,negotiated:s.negotiated,ordered:s.ordered,protocol:s.protocol}),i=new bA(this.sctpTransport,n);return this.dataChannelsOpened++,this.dataChannels.push(i),i.stateChange.subscribe(o=>{if(o==="closed"){this.dataChannelsClosed++;let a=this.dataChannels.indexOf(i);a!==-1&&this.dataChannels.splice(a,1)}}),i}async connectSctp(){!this.sctpTransport||!this.sctpRemotePort||(await this.sctpTransport.start(this.sctpRemotePort),await this.sctpTransport.sctp.stateChanged.connected.asPromise(),fre("sctp connected"))}setRemoteSCTP(t,e){if(this.sctpTransport){if(this.sctpTransport.setRemoteMaxMessageSize(t.sctpCapabilities?.maxMessageSize),this.sctpRemotePort=t.sctpPort,!this.sctpRemotePort)throw new Error("sctpRemotePort not exist");this.sctpTransport.setRemotePort(this.sctpRemotePort),this.sctpTransport.mLineIndex=e,this.sctpTransport.mid||(this.sctpTransport.mid=t.rtp.muxId)}}async close(){this.sctpTransport&&await this.sctpTransport.stop(),this.onDataChannel.allUnsubscribe()}async getStats(){let t=bc(),e=[];for(let r of this.dataChannels){let s={type:"data-channel",id:zt("data-channel",r.id),timestamp:t,label:r.label,protocol:r.protocol,dataChannelIdentifier:r.id,state:r.readyState,messagesSent:r.messagesSent||0,bytesSent:r.bytesSent||0,messagesReceived:r.messagesReceived||0,bytesReceived:r.bytesReceived||0};e.push(s)}return e}},L$=class{currentLocalDescription;currentRemoteDescription;pendingLocalDescription;pendingRemoteDescription;cname;midSuffix;bundlePolicy;seenMid=new Set;constructor({cname:t,midSuffix:e,bundlePolicy:r}){this.cname=t,this.midSuffix=e??!1,this.bundlePolicy=r}get localDescription(){if(this._localDescription)return this._localDescription.toJSON()}get remoteDescription(){if(this._remoteDescription)return this._remoteDescription.toJSON()}get _localDescription(){return this.pendingLocalDescription||this.currentLocalDescription}get _remoteDescription(){return this.pendingRemoteDescription||this.currentRemoteDescription}get inactiveRemoteMedia(){return this._remoteDescription?.media?.find?.(t=>t.direction==="inactive")}createMediaDescriptionForTransceiver(t,e){let r=new d1(t.kind,9,"UDP/TLS/RTP/SAVPF",t.codecs.map(s=>s.payloadType));return r.direction=e,r.msid=t.msid,r.rtp={codecs:t.codecs,headerExtensions:t.headerExtensions,muxId:t.mid},r.rtcpHost="0.0.0.0",r.rtcpPort=9,r.rtcpMux=!0,r.ssrc=[new l1({ssrc:t.sender.ssrc,cname:this.cname})],t.options.simulcast&&(r.simulcastParameters=t.options.simulcast.map(s=>new wA(s))),r.rtp.codecs.find(s=>s.name.toLowerCase()==="rtx")&&(r.ssrc.push(new l1({ssrc:t.sender.rtxSsrc,cname:this.cname})),r.ssrcGroup=[new Bh("FID",[t.sender.ssrc.toString(),t.sender.rtxSsrc.toString()])]),this.addTransportDescription(r,t.dtlsTransport),r}createMediaDescriptionForSctp(t){let e=new d1("application",SU,"UDP/DTLS/SCTP",["webrtc-datachannel"]);return e.sctpPort=t.port,e.rtp.muxId=t.mid,e.sctpCapabilities=t.getCapabilities(),this.addTransportDescription(e,t.dtlsTransport),e}addTransportDescription(t,e){let r=e.iceTransport;t.iceCandidates=r.localCandidates,t.iceCandidatesComplete=r.gatheringState==="complete",t.iceParams=r.localParameters,t.iceOptions="trickle",t.host=_te,t.port=SU,t.direction==="inactive"&&(t.port=0,t.msid=void 0),t.dtlsParams||(t.dtlsParams=e.localParameters,t.dtlsParams.fingerprints||(t.dtlsParams.fingerprints=e.localParameters.fingerprints))}allocateMid(t=""){let e="";for(let r=0;e=(r++).toString()+t,!!this.seenMid.has(e););return this.seenMid.add(e),e}parseSdp({sdp:t,isLocal:e,signalingState:r,type:s}){let n=Pm.parse(t);return this.validateDescription({description:n,isLocal:e,signalingState:r}),n.type=s,n}validateDescription({description:t,isLocal:e,signalingState:r}){if(e){if(t.type==="offer"){if(!["stable","have-local-offer"].includes(r))throw new Error("Cannot handle offer in signaling state")}else if(t.type==="answer"&&!["have-remote-offer","have-local-pranswer"].includes(r))throw new Error("Cannot handle answer in signaling state")}else if(t.type==="offer"){if(!["stable","have-remote-offer"].includes(r))throw new Error("Cannot handle offer in signaling state")}else if(t.type==="answer"&&!["have-local-offer","have-remote-pranswer"].includes(r))throw new Error("Cannot handle answer in signaling state")}buildOfferSdp(t,e){let r=new Pm;Uk("offer",r),(this.currentLocalDescription?.media??[]).forEach((n,i)=>{let o=n.rtp.muxId;if(o)if(n.kind==="application"){if(!e)throw new Error("sctpTransport not found");e.mLineIndex=i,r.media.push(this.createMediaDescriptionForSctp(e))}else{let a=t.find(c=>c.mid===o);if(!a){if(n.direction==="inactive"){r.media.push(n);return}throw new Error("transceiver not found")}a.mLineIndex=i,r.media.push(this.createMediaDescriptionForTransceiver(a,a.direction))}});for(let n of t.filter(i=>!r.media.find(o=>o.rtp.muxId===i.mid))){n.mid==null&&(n.mid=this.allocateMid(this.midSuffix?"av":""));let i=this.createMediaDescriptionForTransceiver(n,n.direction);n.mLineIndex===void 0?(n.mLineIndex=r.media.length,r.media.push(i)):r.media[n.mLineIndex]=i}if(e&&!r.media.find(n=>n.kind==="application")&&(e.mLineIndex=r.media.length,e.mid==null&&(e.mid=this.allocateMid(this.midSuffix?"dc":"")),r.media.push(this.createMediaDescriptionForSctp(e))),this.bundlePolicy!=="disable"){let n=r.media.map(i=>i.rtp.muxId).filter(i=>i);if(n.length){let i=new Bh("BUNDLE",n);r.group.push(i)}}return r}buildAnswerSdp({transceivers:t,sctpTransport:e,signalingState:r}){if(!["have-remote-offer","have-local-pranswer"].includes(r))throw new Error("createAnswer failed");if(!this._remoteDescription)throw new Error("wrong state");let s=new Pm;Uk("answer",s);for(let n of this._remoteDescription.media){let i,o;if(["audio","video"].includes(n.kind)){let a=t.find(c=>c.mid===n.rtp.muxId);if(!a)throw new Error(`Transceiver with mid=${n.rtp.muxId} not found`);o=this.createMediaDescriptionForTransceiver(a,PA(a.direction,a.offerDirection)),i=a.dtlsTransport}else if(n.kind==="application"){if(!e||!e.mid)throw new Error("sctpTransport not found");o=this.createMediaDescriptionForSctp(e),i=e.dtlsTransport}else throw new Error("invalid kind");o.dtlsParams&&(i.role==="auto"?o.dtlsParams.role="client":o.dtlsParams.role=i.role),n.simulcastParameters&&n.simulcastParameters.length>0&&(o.simulcastParameters=n.simulcastParameters.map(a=>({...a,direction:a.direction==="send"?"recv":"send"}))),s.media.push(o)}if(this.bundlePolicy!=="disable"){let n=new Bh("BUNDLE",[]);for(let i of s.media)i.rtp.muxId&&n.items.push(i.rtp.muxId);s.group.push(n)}return s}setLocalDescription(t){this.currentLocalDescription=t,t.type==="answer"?this.pendingLocalDescription=void 0:this.pendingLocalDescription=t}setRemoteDescription(t,e){if(!t.sdp||!t.type||t.type==="rollback"||t.type==="pranswer")throw new Error("invalid sessionDescription");let r=this.parseSdp({sdp:t.sdp,isLocal:!1,signalingState:e,type:t.type});return r.type==="answer"?(this.currentRemoteDescription=r,this.pendingRemoteDescription=void 0):this.pendingRemoteDescription=r,r}registerMid(t){this.seenMid.add(t)}get remoteIsBundled(){let t=this._remoteDescription;return t?t.group.find(r=>r.semantic==="BUNDLE"&&this.bundlePolicy!=="disable"):void 0}setLocal(t,e,r){let s=new Map(e.map(o=>[o?.mLineIndex,o])),n=e.find(o=>o?.dtlsTransport)?.dtlsTransport??r?.dtlsTransport;t.media.filter(o=>["audio","video"].includes(o.kind)).forEach((o,a)=>{let d=(s.get(a)??e[a])?.dtlsTransport??n;if(!d)throw new Error(`dtls transport not found for media index ${a}`);this.addTransportDescription(o,d)});let i=t.media.find(o=>o.kind==="application");r&&i&&this.addTransportDescription(i,r.dtlsTransport),this.setLocalDescription(t)}},pm=ft("werift:packages/webrtc/src/transport/secureTransportManager.ts"),mre=class{connectionState="new";iceConnectionState="new";iceGatheringState="new";certificate;iceGatheringStateChange=new Ne;iceConnectionStateChange=new Ne;onIceCandidate=new Ne;connectionStateChange=new Ne;config;transceiverManager;sctpManager;constructor({config:t,transceiverManager:e,sctpManager:r}){if(this.config=t,this.transceiverManager=e,this.sctpManager=r,this.config.dtls){let{keys:s}=this.config.dtls;s&&this.setupCertificate(s)}}get dtlsTransports(){return[...this.transceiverManager.getTransceivers().map(e=>e?.dtlsTransport),this.sctpManager.sctpTransport?.dtlsTransport].filter(e=>e!=null).reduce((e,r)=>(e.map(s=>s.id).includes(r.id)||e.push(r),e),[])}get iceTransports(){return this.dtlsTransports.map(t=>t.iceTransport)}setupCertificate(t){this.certificate=new LA(t.keyPem,t.certPem,t.signatureHash)}createTransport(){let t=this.iceTransports.find(n=>n.state!=="closed"),e=new Zj({...qj(this.config.iceServers),forceTurn:this.config.iceTransportPolicy==="relay",portRange:this.config.icePortRange,interfaceAddresses:this.config.iceInterfaceAddresses,additionalHostAddresses:this.config.iceAdditionalHostAddresses,filterStunResponse:this.config.iceFilterStunResponse,filterCandidatePair:this.config.iceFilterCandidatePair,localPasswordPrefix:this.config.icePasswordPrefix,useIpv4:this.config.iceUseIpv4,useIpv6:this.config.iceUseIpv6,turnTransport:this.config.forceTurnTCP===!0?"tcp":"udp",useLinkLocalAddress:this.config.iceUseLinkLocalAddress});t&&(e.connection.localUsername=t.connection.localUsername,e.connection.localPassword=t.connection.localPassword),e.onGatheringStateChange.subscribe(()=>{this.updateIceGatheringState()}),this.updateIceGatheringState();let r=new Qj(e);return r.onStateChange.subscribe(()=>{this.updateIceConnectionState()}),new vk(this.config,r,this.certificate,gre)}handleNewIceCandidate({candidate:t,media:e,remoteIsBundled:r,transceiver:s,sctpTransport:n,bundlePolicy:i}){return i==="max-bundle"||r?(t.sdpMLineIndex=0,e&&(t.sdpMid=e.rtp.muxId)):(s&&(t.sdpMLineIndex=s.mLineIndex,t.sdpMid=s.mid),n&&(t.sdpMLineIndex=n.mLineIndex,t.sdpMid=n.mid)),t.foundation&&!t.foundation.startsWith("candidate:")&&(t.foundation="candidate:"+t.foundation),this.onIceCandidate.execute(t),t}async addIceCandidate(t,e){let r=OA.fromJSON(e);if(!r)return;let s;typeof r.sdpMid=="number"&&(s=this.getTransportByMid(r.sdpMid)),!s&&typeof r.sdpMLineIndex=="number"&&(s=this.getTransportByMLineIndex(t,r.sdpMLineIndex)),s||(s=this.iceTransports[0]),s?await s.addRemoteCandidate(r):pm("iceTransport not found for candidate",r)}getTransportByMid(t){let e,r=this.transceiverManager.getTransceivers().find(s=>s.mid===t);return r?e=r.dtlsTransport.iceTransport:!e&&this.sctpManager.sctpTransport?.mid===t&&(e=this.sctpManager.sctpTransport.dtlsTransport.iceTransport),e}getTransportByMLineIndex(t,e){let r=t.media[e];return r?this.getTransportByMid(r.rtp.muxId):void 0}restartIce(){for(let t of this.iceTransports)t.restart()}setLocalRole({type:t,role:e}){for(let r of this.dtlsTransports){let s=r.iceTransport;t==="offer"?s.connection.iceControlling=!0:s.connection.iceControlling=!1,s.connection.remoteIsLite&&(s.connection.iceControlling=!0),t==="answer"&&e&&(r.role=e)}}updateIceGatheringState(){let t=this.iceTransports;function e(...s){return t.filter(n=>s.includes(n.gatheringState)).length===t.length}let r;t.length&&e("complete")?r="complete":!t.length||e("new","complete")?r="new":t.map(s=>s.gatheringState).includes("gathering")?r="gathering":r="new",this.iceGatheringState!==r&&(this.iceGatheringState=r,this.iceGatheringStateChange.execute(r))}updateIceConnectionState(){let t=this.iceTransports,e;function r(...n){return t.filter(i=>n.includes(i.state)).length===t.length}function s(...n){return t.some(i=>n.includes(i.state))}this.connectionState==="closed"?e="closed":s("failed")?e="failed":s("disconnected")?e="disconnected":r("new","closed")?e="new":s("new","checking")?e="checking":r("completed","closed")?e="completed":r("connected","completed","closed")?e="connected":e="new",this.iceConnectionState!==e&&(pm("iceConnectionStateChange",e),this.iceConnectionState=e,this.iceConnectionStateChange.execute(e))}async gatherCandidates(t){let e=this.iceTransports.find(r=>r.state==="connected"||r.state==="completed");t&&e?pm("skipping ICE gathering for bundled connection"):await Promise.allSettled(this.iceTransports.map(r=>r.gather())).catch(r=>{pm("gatherCandidates failed",r)})}setConnectionState(t){pm("connectionStateChange",t),this.connectionState=t,this.connectionStateChange.execute(t)}async getStats(){let t=[];for(let e of this.dtlsTransports){let r=await e.getStats();r&&t.push(...r)}return t}async ensureCerts(){this.certificate||(this.certificate=await vk.SetupCertificate());for(let t of this.dtlsTransports)t.localCertificate=this.certificate}async close(){this.setConnectionState("closed"),await Promise.allSettled([...this.dtlsTransports.map(t=>t.stop())]),this.iceGatheringStateChange.allUnsubscribe(),this.iceConnectionStateChange.allUnsubscribe(),this.onIceCandidate.allUnsubscribe(),this.connectionStateChange.allUnsubscribe()}},gre=[CU.SRTP_AEAD_AES_128_GCM,CU.SRTP_AES128_CM_HMAC_SHA1_80],zn=ft("werift:packages/webrtc/src/peerConnection.ts"),yre=class extends yA{cname=(0,B$.randomUUID)().toString();config=O$();signalingState="stable";negotiationneeded=!1;needRestart=!1;router=new P$;sdpManager;transceiverManager;sctpManager;secureManager;isClosed=!1;shouldNegotiationneeded=!1;remoteBundleNegotiated=!1;iceGatheringStateChange=new Ne;iceConnectionStateChange=new Ne;signalingStateChange=new Ne;connectionStateChange=new Ne;onDataChannel=new Ne;onRemoteTransceiverAdded=new Ne;onTransceiverAdded=new Ne;onIceCandidate=new Ne;onNegotiationneeded=new Ne;onTrack=new Ne;ondatachannel;onicecandidate;onicecandidateerror;onicegatheringstatechange;onnegotiationneeded;onsignalingstatechange;ontrack;onconnectionstatechange;oniceconnectionstatechange;constructor(t={}){super(),this.setConfiguration(t),this.sdpManager=new L$({cname:this.cname,bundlePolicy:this.config.bundlePolicy}),this.transceiverManager=new N$(this.cname,this.config,this.router),this.transceiverManager.onTransceiverAdded.pipe(this.onTransceiverAdded),this.transceiverManager.onRemoteTransceiverAdded.pipe(this.onRemoteTransceiverAdded),this.transceiverManager.onTrack.subscribe(({track:e,stream:r,transceiver:s})=>{let n={track:e,streams:[r],transceiver:s,receiver:s.receiver};this.onTrack.execute(e),this.emit("track",n),this.ontrack&&this.ontrack(n)}),this.transceiverManager.onNegotiationNeeded.subscribe(()=>this.needNegotiation()),this.sctpManager=new pre,this.sctpManager.onDataChannel.subscribe(e=>{this.onDataChannel.execute(e);let r={channel:e};this.ondatachannel?.(r),this.emit("datachannel",r)}),this.secureManager=new mre({config:this.config,sctpManager:this.sctpManager,transceiverManager:this.transceiverManager}),this.secureManager.iceGatheringStateChange.pipe(this.iceGatheringStateChange),this.secureManager.iceConnectionStateChange.subscribe(e=>{e==="closed"&&this.close(),this.iceConnectionStateChange.execute(e)}),this.secureManager.connectionStateChange.subscribe(e=>{this.connectionStateChange.execute(e),this.onconnectionstatechange?.(),this.emit("connectionstatechange")}),this.secureManager.onIceCandidate.subscribe(e=>{let r=e?e.toJSON():void 0;this.onIceCandidate.execute(r),this.onicecandidate?.({candidate:r}),this.emit("icecandidate",{candidate:r})})}get connectionState(){return this.secureManager.connectionState}get iceConnectionState(){return this.secureManager.iceConnectionState}get iceGathererState(){return this.secureManager.iceGatheringState}get iceGatheringState(){return this.secureManager.iceGatheringState}get dtlsTransports(){return this.secureManager.dtlsTransports}get sctpTransport(){return this.sctpManager.sctpTransport}get sctpRemotePort(){return this.sctpManager.sctpRemotePort}get iceTransports(){return this.secureManager.iceTransports}get extIdUriMap(){return this.router.extIdUriMap}get iceGeneration(){return this.iceTransports[0].connection.generation}get localDescription(){return this.sdpManager.localDescription}get remoteDescription(){return this.sdpManager.remoteDescription}get remoteIsBundled(){return this.sdpManager.remoteIsBundled}get _localDescription(){return this.sdpManager._localDescription}get _remoteDescription(){return this.sdpManager._remoteDescription}getTransceivers(){return this.transceiverManager.getTransceivers()}getSenders(){return this.transceiverManager.getSenders()}getReceivers(){return this.transceiverManager.getReceivers()}setConfiguration(t){if(Vj(this.config,t),this.config.icePortRange){let[e,r]=this.config.icePortRange;if(e===r)throw new Error("should not be same value");if(e>=r)throw new Error("The min must be less than max")}if(!Number.isInteger(this.config.maxMessageSize)||this.config.maxMessageSize<0)throw new Error("maxMessageSize must be a non-negative integer");this.sctpManager?.sctpTransport&&(this.sctpManager.sctpTransport.maxMessageSize=this.config.maxMessageSize);for(let[e,r]of bU([...this.config.codecs.audio||[],...this.config.codecs.video||[]]))if(r.payloadType==null)switch(r.payloadType=96+e,r.name.toLowerCase()){case"rtx":r.parameters=`apt=${r.payloadType-1}`;break;case"red":if(r.contentType==="audio"){let s=r.payloadType+1;r.parameters=`${s}/${s}`,r.payloadType=63}break}[...this.config.headerExtensions.audio||[],...this.config.headerExtensions.video||[]].forEach((e,r)=>{e.id=1+r})}getConfiguration(){return this.config}async createOffer({iceRestart:t}={}){(t||this.needRestart)&&(this.needRestart=!1,this.secureManager.restartIce()),await this.secureManager.ensureCerts();for(let r of this.transceiverManager.getTransceivers())r.codecs.length===0&&this.transceiverManager.assignTransceiverCodecs(r),r.headerExtensions.length===0&&(r.headerExtensions=this.config.headerExtensions[r.kind]??[]);return this.sdpManager.buildOfferSdp(this.transceiverManager.getTransceivers(),this.sctpTransport).toJSON()}createSctpTransport(){let t=this.sctpManager.createSctpTransport(this.config.maxMessageSize),e=this.findOrCreateTransport();return t.setDtlsTransport(e),t}createDataChannel(t,e={}){this.sctpTransport||(this.createSctpTransport(),this.needNegotiation());let r=this.sctpManager.createDataChannel(t,e);if(!r.sctp.dtlsTransport){let s=this.findOrCreateTransport();r.sctp.setDtlsTransport(s)}return r}removeTrack(t){if(this.isClosed)throw new Error("peer closed");this.transceiverManager.removeTrack(t),this.needNegotiation()}needNegotiation=async()=>{this.shouldNegotiationneeded=!0,!(this.negotiationneeded||this.signalingState!=="stable")&&(this.shouldNegotiationneeded=!1,setImmediate(()=>{this.negotiationneeded=!0,this.onNegotiationneeded.execute(),this.onnegotiationneeded&&this.onnegotiationneeded({})}))};findOrCreateTransport(){let t=this.dtlsTransports.find(n=>n.state!=="closed"),e=t?.iceTransport;if((this.sdpManager.bundlePolicy==="max-bundle"||this.sdpManager.bundlePolicy!=="disable"&&(this.remoteIsBundled||this.remoteBundleNegotiated))&&t)return t;let r=this.secureManager.createTransport();r.onRtp.subscribe(n=>{this.router.routeRtp(n)}),r.onRtcp.subscribe(n=>{this.router.routeRtcp(n)});let s=r.iceTransport;return s.onNegotiationNeeded.subscribe(()=>{this.needNegotiation()}),s.onIceCandidate.subscribe(n=>{if(!this.localDescription){zn("localDescription not found when ice candidate was gathered");return}if(!n){this.sdpManager.setLocal(this._localDescription,this.transceiverManager.getTransceivers(),this.sctpTransport),this.onIceCandidate.execute(void 0),this.onicecandidate&&this.onicecandidate({candidate:void 0}),this.emit("icecandidate",{candidate:void 0});return}if(!this._localDescription){zn("localDescription not found when ice candidate was gathered");return}this.secureManager.handleNewIceCandidate({candidate:n,bundlePolicy:this.sdpManager.bundlePolicy,remoteIsBundled:!!this.sdpManager.remoteIsBundled,media:this._localDescription.media[0],transceiver:this.transceiverManager.getTransceivers().find(i=>i?.dtlsTransport?.iceTransport.id===s.id),sctpTransport:this.sctpTransport?.dtlsTransport.iceTransport.id===s.id?this.sctpTransport:void 0})}),r}async setLocalDescription(t){t=t??(["stable","have-local-offer","have-remote-pranswer"].includes(this.signalingState)?await this.createOffer():await this.createAnswer());let r=this.sdpManager.parseSdp({sdp:t.sdp,isLocal:!0,signalingState:this.signalingState,type:t.type});r.type==="offer"?this.setSignalingState("have-local-offer"):r.type==="answer"&&this.setSignalingState("stable");for(let[n,i]of bU(r.media)){let o=i.rtp.muxId;if(this.sdpManager.registerMid(o),["audio","video"].includes(i.kind)){let a=this.transceiverManager.getTransceiverByMLineIndex(n);a&&(a.mid=o)}i.kind==="application"&&this.sctpTransport&&(this.sctpTransport.mid=o)}let s=r.media.find(n=>n.dtlsParams)?.dtlsParams?.role;if(this.secureManager.setLocalRole({type:r.type,role:s}),["answer","pranswer"].includes(r.type))for(let n of this.transceiverManager.getTransceivers()){let i=PA(n.direction,n.offerDirection);n.setCurrentDirection(i)}return this.sdpManager.setLocal(r,this.transceiverManager.getTransceivers(),this.sctpTransport),await this.gatherCandidates().catch(n=>{zn("gatherCandidates failed",n)}),r.type==="answer"&&this.connect().catch(n=>{zn("connect failed",n),this.secureManager.setConnectionState("failed")}),this.sdpManager.setLocal(r,this.transceiverManager.getTransceivers(),this.sctpTransport),this.shouldNegotiationneeded&&this.needNegotiation(),r}async gatherCandidates(){await this.secureManager.gatherCandidates(!!this.sdpManager.remoteIsBundled)}async addIceCandidate(t){let e=this.sdpManager.buildOfferSdp(this.transceiverManager.getTransceivers(),this.sctpTransport);await this.secureManager.addIceCandidate(e,t)}async connect(){zn("start connect"),(await Promise.allSettled(this.dtlsTransports.map(async e=>{let{iceTransport:r}=e;if(r.state==="connected")return;let s=()=>e.state==="connected";s()||(this.secureManager.setConnectionState("connecting"),await r.start().catch(n=>{throw zn("iceTransport.start failed",n),n}),!s()&&(await e.start().catch(n=>{throw zn("dtlsTransport.start failed",n),n}),this.sctpTransport&&this.sctpTransport.dtlsTransport.id===e.id&&await this.sctpManager.connectSctp()))}))).find(e=>e.status==="rejected")?this.secureManager.setConnectionState("failed"):this.secureManager.setConnectionState("connected")}restartIce(){this.needRestart=!0,this.needNegotiation()}async setRemoteDescription(t){t instanceof Pm&&(t=t.toSdp());let e=this.sdpManager.setRemoteDescription(t,this.signalingState);e.group.some(o=>o.semantic==="BUNDLE"&&o.items.length>0)&&(this.remoteBundleNegotiated=!0);let r,s=(o,a)=>o.kind===a.kind&&[void 0,a.rtp.muxId].includes(o.mid),n=e.media.map((o,a)=>{let c;if(["audio","video"].includes(o.kind)){let u=this.transceiverManager.getTransceivers().find(l=>s(l,o));if(!u)u=this.addTransceiver(o.kind,{direction:"recvonly"}),u.mid=o.rtp.muxId,this.onRemoteTransceiverAdded.execute(u);else if(u.direction==="inactive"&&u.stopping){u.stopped=!0,t.type==="answer"&&u.setCurrentDirection("inactive");return}this.sdpManager.remoteIsBundled&&(r?u.setDtlsTransport(r):r=u.dtlsTransport),c=u.dtlsTransport,this.transceiverManager.setRemoteRTP(u,o,e.type,a)}else if(o.kind==="application"){let u=this.sctpTransport;u||(u=this.createSctpTransport(),u.mid=o.rtp.muxId),this.sdpManager.remoteIsBundled&&(r?u.setDtlsTransport(r):r=u.dtlsTransport),c=u.dtlsTransport,this.sctpManager.setRemoteSCTP(o,a)}else throw new Error("invalid media kind");let d=c.iceTransport;if(o.iceParams){let u=!!this.sdpManager.inactiveRemoteMedia;d.setRemoteParams(o.iceParams,u),o.iceParams?.iceLite&&(d.connection.iceControlling=!0)}return o.dtlsParams&&c.setRemoteParams(o.dtlsParams),o.iceCandidates.forEach(d.addRemoteCandidate),o.iceCandidatesComplete&&d.addRemoteCandidate(void 0),e.type==="answer"&&o.dtlsParams?.role&&(c.role=o.dtlsParams.role==="client"?"server":"client"),d});n=n.filter(o=>!!o);let i=this.transceiverManager.getTransceivers().filter(o=>e.media.find(a=>s(o,a))==null);if(t.type==="answer")for(let o of i)o.stop(),o.stopped=!0;e.type==="offer"?this.setSignalingState("have-remote-offer"):e.type==="answer"&&this.setSignalingState("stable"),e.type==="answer"&&(zn("caller start connect"),this.connect().catch(o=>{zn("connect failed",o),this.secureManager.setConnectionState("failed")})),this.negotiationneeded=!1,this.shouldNegotiationneeded&&this.needNegotiation()}addTransceiver(t,e={}){let r=this.findOrCreateTransport(),s=this.transceiverManager.addTransceiver(t,r,e);return this.secureManager.updateIceConnectionState(),this.needNegotiation(),s}addTrack(t,e){if(this.isClosed)throw new Error("is closed");let r=this.transceiverManager.addTrack(t,e);if(!r.dtlsTransport){let s=this.findOrCreateTransport();r.setDtlsTransport(s)}return this.needNegotiation(),r.sender}async createAnswer(){return this.assertNotClosed(),await this.secureManager.ensureCerts(),this.sdpManager.buildAnswerSdp({transceivers:this.transceiverManager.getTransceivers(),sctpTransport:this.sctpTransport,signalingState:this.signalingState}).toJSON()}assertNotClosed(){if(this.isClosed)throw new Error("RTCPeerConnection is closed")}setSignalingState(t){zn("signalingStateChange",t),this.signalingState=t,this.signalingStateChange.execute(t),this.onsignalingstatechange&&this.onsignalingstatechange({})}createPeerConnectionStats(){let t=bc();return{type:"peer-connection",id:zt("peer-connection"),timestamp:t,dataChannelsOpened:this.sctpManager.dataChannelsOpened,dataChannelsClosed:this.sctpManager.dataChannelsClosed}}async getStats(t){let e=[];e.push(this.createPeerConnectionStats());let r=await this.transceiverManager.getStats(t);e.push(...r);let s=await this.secureManager.getStats();if(e.push(...s),this.sctpTransport){let n=await this.sctpManager.getStats();n&&e.push(...n)}return new Oj(e)}async close(){this.isClosed||(this.isClosed=!0,this.setSignalingState("closed"),this.transceiverManager.close(),await this.secureManager.close(),await this.sctpManager.close(),this.onDataChannel.allUnsubscribe(),this.iceGatheringStateChange.allUnsubscribe(),this.iceConnectionStateChange.allUnsubscribe(),this.signalingStateChange.allUnsubscribe(),this.onTransceiverAdded.allUnsubscribe(),this.onRemoteTransceiverAdded.allUnsubscribe(),this.onIceCandidate.allUnsubscribe(),zn("peerConnection closed"))}},Hk=(t,e)=>t.find(r=>r.mimeType.toLowerCase()===e.mimeType.toLowerCase())?e:void 0;bre=O$(),xre=ft("werift:packages/webrtc/src/media/rtpTransceiverManager.ts"),N$=class{constructor(t,e,r){this.cname=t,this.config=e,this.router=r}transceivers=[];onTransceiverAdded=new Ne;onRemoteTransceiverAdded=new Ne;onTrack=new Ne;onNegotiationNeeded=new Ne;getTransceivers(){return this.transceivers}getSenders(){return this.getTransceivers().map(t=>t.sender)}getReceivers(){return this.getTransceivers().map(t=>t.receiver)}getTransceiverByMLineIndex(t){return this.transceivers.find(e=>e.mLineIndex===t)}pushTransceiver(t){this.transceivers.push(t)}replaceTransceiver(t,e){this.transceivers[e]=t}addTransceiver(t,e,r={}){let s=typeof t=="string"?t:t.kind,n=r.direction||"sendrecv",i=new D$(t),o=new FA(this.config,s,i.ssrc),a=new Nj(s,e,o,i,n);a.options=r,this.router.registerRtpSender(a.sender);let c=this.transceivers.findIndex(u=>u.currentDirection==="inactive"&&!u.usedForSender),d=this.transceivers.find(u=>u.currentDirection==="inactive"&&!u.usedForSender);return c>-1&&d?(this.replaceTransceiver(a,c),a.mLineIndex=d.mLineIndex,a.mid=d.mid,d.setCurrentDirection(void 0)):this.pushTransceiver(a),this.onTransceiverAdded.execute(a),a}addTrack(t,e){if(this.getSenders().find(n=>n.track?.uuid===t.uuid))throw new Error("Track already added");let r=this.transceivers.find(n=>n.sender.track==null&&n.kind===t.kind&&$w.includes(n.direction)===!0);if(r)return r.sender.registerTrack(t),r;let s=this.transceivers.find(n=>n.sender.track==null&&n.kind===t.kind&&$w.includes(n.direction)===!1&&!n.usedForSender);if(s){switch(s.sender.registerTrack(t),s.direction){case"recvonly":s.setDirection("sendrecv");break;case"inactive":s.setDirection("sendonly");break}return s}else return this.addTransceiver(t,void 0,{direction:"sendrecv"})}removeTrack(t){if(!this.getSenders().find(({ssrc:r})=>t.ssrc===r))throw new Error("Sender does not exist");let e=this.transceivers.find(({sender:{ssrc:r}})=>t.ssrc===r);if(!e)throw new Error("No matching transceiver found");if(t.stop(),e.currentDirection==="recvonly"){this.onNegotiationNeeded.execute();return}e.stopping||e.stopped?e.setDirection("inactive"):e.direction==="sendrecv"?e.setDirection("recvonly"):(e.direction==="sendonly"||e.direction==="recvonly")&&e.setDirection("inactive")}assignTransceiverCodecs(t){let e=this.config.codecs[t.kind].filter(r=>{switch(r.direction){case"recvonly":return!!Ete.includes(t.direction);case"sendonly":return!!$w.includes(t.direction);case"sendrecv":return!![kA,TA,CA].includes(t.direction);case"all":return!0;default:return!1}});t.codecs=e}getLocalRtpParams(t){if(t.mid==null)throw new Error("mid not assigned");return{codecs:t.codecs,muxId:t.mid,headerExtensions:t.headerExtensions,rtcp:{cname:this.cname,ssrc:t.sender.ssrc,mux:!0}}}getRemoteRtpParams(t,e){return{muxId:t.rtp.muxId,rtcp:t.rtp.rtcp,codecs:e.codecs,headerExtensions:e.headerExtensions,encodings:Object.values(e.codecs.reduce((s,n)=>{if(n.name.toLowerCase()==="rtx"){let i=Jm(n.parameters??""),o=s[i.apt];return o&&t.ssrc.length===2&&(o.rtx=new Cj({ssrc:t.ssrc[1].ssrc})),s}return s[n.payloadType]=new Tj({ssrc:t.ssrc[0]?.ssrc,payloadType:n.payloadType}),s},{}))}}setRemoteRTP(t,e,r,s){if(t.mid||(t.mid=e.rtp.muxId),t.mLineIndex=s,t.codecs=e.rtp.codecs.filter(a=>{let c=this.config.codecs[e.kind]||[],d=Hk(c,a);if(!d)return!1;if(d?.name.toLowerCase()==="rtx"){let l=Jm(d.parameters??"").apt,h=e.rtp.codecs.find(p=>p.payloadType===l);return h?!!Hk(c,h):!1}return!0}),xre("negotiated codecs",t.codecs),t.codecs.length===0)throw new Error("negotiate codecs failed.");t.headerExtensions=e.rtp.headerExtensions.filter(a=>(this.config.headerExtensions[e.kind]||[]).find(c=>c.uri===a.uri));let n=e.direction??"inactive",i=$j(n);["answer","pranswer"].includes(r)?t.setCurrentDirection(i):t.offerDirection=i;let o=this.getLocalRtpParams(t);if(t.sender.prepareSend(o),["recvonly","sendrecv"].includes(t.direction)){let a=this.getRemoteRtpParams(e,t);for(let c of e.simulcastParameters)this.router.registerRtpReceiverByRid(t,c,a);t.receiver.prepareReceive(a),this.router.registerRtpReceiverBySsrc(t,a)}if(["sendonly","sendrecv"].includes(n)){if(e.msid){let[a,c]=e.msid.split(" ");t.receiver.remoteStreamId=a,t.receiver.remoteTrackId=c}this.onTrack.execute({track:t.receiver.track,transceiver:t,stream:new Mj({id:t.receiver.remoteStreamId,tracks:[t.receiver.track]})})}e.ssrc[0]?.ssrc&&t.receiver.setupTWCC(e.ssrc[0].ssrc)}async getStats(t){let e=[];for(let r of this.transceivers){let s=!t||r.sender.track===t||r.receiver.track===t;if(r.sender){let n=await r.sender.getStats();if(n)for(let i of n)i.type==="outbound-rtp"||i.type==="media-source"?s&&e.push(i):e.push(i)}if(r.receiver){let n=await r.receiver.getStats();if(n)for(let i of n)i.type==="inbound-rtp"||i.type==="remote-outbound-rtp"?s&&e.push(i):e.push(i)}if(s){let n=r.getCodecStats();n&&e.push(...n)}}return e}close(){for(let t of this.transceivers)t.receiver.stop(),t.sender.stop();this.onTransceiverAdded.allUnsubscribe(),this.onRemoteTransceiverAdded.allUnsubscribe(),this.onTrack.allUnsubscribe(),this.onNegotiationNeeded.allUnsubscribe()}},wre=["stable","have-local-offer","have-remote-offer","have-local-pranswer","have-remote-pranswer","closed"],vre=["closed","failed","disconnected","new","connecting","connected"]});var bae={};sa(bae,{SessionPool:()=>gv,URUN_API:()=>yR,applyServeUsage:()=>Sq,coalesceSameRole:()=>_q,createFileDiagnosticSink:()=>xq,createUrunExtension:()=>xv,default:()=>yae,makeSessionFactory:()=>bv,makeStreamSimple:()=>Eq,notify:()=>gR,piDiagnosticLogPath:()=>Mg,resolveSessionEnv:()=>bq,toResponsesInput:()=>vq});module.exports=Sv(bae);g();y();var _Ue=Le(Tv(),1);var fR={};sa(fR,{ACTIVATION_COLD_BOOT_AFTER_MS:()=>RH,ACTIVATION_DEGRADED_AFTER_MS:()=>PH,ACTIVATION_HINT_PATH:()=>SI,ACTIVATION_STILL_AFTER_MS:()=>IH,ACTIVITY_DOM_EVENTS:()=>av,ACTIVITY_FIELD:()=>LI,ACTIVITY_STAMP_MIN_INTERVAL_MS:()=>UH,ActivationMonitor:()=>TI,App:()=>KH,BACKOFF_BASE_MS:()=>G1,BACKOFF_MAX_ATTEMPTS:()=>Wh,BACKOFF_MAX_MS:()=>vg,COLD_BOOT_WHEN_LIVE_TIMEOUT_MS:()=>L1,CaptureController:()=>nq,CaptureUnavailableError:()=>sq,ClientTokenError:()=>Dg,CreditsClient:()=>rq,CreditsError:()=>hv,CreditsUnauthorizedError:()=>uR,DATA_CHANNEL_MESSAGE_CEILING:()=>Boe,DEFAULT_DOC_SYNC_TIMEOUT_MS:()=>sR,DEFAULT_GATEWAY_URL:()=>eq,DEFAULT_PRODUCE_ACK_TIMEOUT_MS:()=>fg,DEFAULT_REFERENCE_JPEG_QUALITY:()=>Doe,DEFAULT_REFERENCE_MAX_SIZE:()=>Poe,DEFAULT_WHEN_LIVE_TIMEOUT_MS:()=>QA,DERIVED_LEG_SEP:()=>Xh,DGRAM_HEADER_BYTES:()=>ei,FOCUS_FIELD:()=>MI,FOREGROUND_COALESCE_MS:()=>jH,FrameReassembler:()=>GI,GENERATION_TICK_EMIT_INTERVAL_MS:()=>OH,GENERATION_TICK_MAX_EXTRAPOLATION_MS:()=>NH,INPUT_PRESENCE_DEFAULT_HZ:()=>Ioe,INPUT_PRESENCE_FIELD:()=>iq,InvalidDurationError:()=>Pg,LEGACY_ACTIVATION_HINT_PATH:()=>EI,PLATFORM_DOC_NAME:()=>_I,PermanentLockedError:()=>DI,PinRequiresActiveTempError:()=>PI,PresenceTracker:()=>jI,ProduceAckTimeoutError:()=>JA,RecordingNotFoundError:()=>II,RecordingsClient:()=>lv,RecordingsError:()=>Xi,RecordingsUnauthorizedError:()=>cv,RequestAbortError:()=>wg,RequestCancelledError:()=>V1,RequestDocSyncError:()=>H1,RequestError:()=>ta,RequestTimeoutError:()=>F1,RetainNotTempError:()=>RI,RuntimeArtifactNotFoundError:()=>AI,RuntimeArtifactsClient:()=>Rg,RuntimeArtifactsError:()=>Ys,RuntimeArtifactsUnauthorizedError:()=>kI,SIGNALING_PROTOCOL_VERSION:()=>iI,STREAM_END:()=>Cl,Session:()=>nR,SessionAllocationError:()=>Cr,SessionDirectory:()=>aR,SessionDirectoryError:()=>Gi,SessionEndError:()=>Sn,SessionEndUnavailableError:()=>El,SessionFailedError:()=>Sl,StreamDirectionConflict:()=>q1,TransportNegotiator:()=>eR,TransportSessionMismatchError:()=>B1,TransportSessionSignaling:()=>tR,URUN_DEV_ENV:()=>tq,USER_ACTIVITY_FIELD:()=>UI,USER_ACTIVITY_MIN_INTERVAL_MS:()=>MH,VISIBILITY_FIELD:()=>OI,WIRE_MESSAGE_BUDGET:()=>Loe,WT_CONTROL_FRAME_MAX:()=>VI,WT_DATA_STREAM_VERSION:()=>XI,WebRtcSession:()=>rR,WebTransportSession:()=>ZI,WtControlDecoder:()=>WI,WtDataStreamParser:()=>YI,activationHintFrom:()=>CI,cameraCaptureAvailable:()=>$oe,captureStillFromVideo:()=>Foe,computeBackoffDelay:()=>_g,consumeWtDataStreams:()=>JI,createActivityTracker:()=>NI,createCameraWarp:()=>qoe,createClientToken:()=>yoe,createCreditsClient:()=>Eoe,createInputPresencePublisher:()=>Roe,createRecordingsClient:()=>LH,createRuntimeArtifactsClient:()=>DH,createStore:()=>xoe,decodeStreamEnvelope:()=>Z1,derivedLegName:()=>KF,derivedLegRole:()=>U1,describeSessionFailure:()=>z1,describeSessionPhase:()=>AF,encodeStreamEnvelope:()=>Q1,encodeWtControlFrame:()=>zI,fitWithin:()=>hR,isDurationString:()=>dv,isPausedPhase:()=>kF,isPendingRecording:()=>_oe,isRetryableSessionError:()=>X1,isWakingPhase:()=>xc,mediaRecorderChunkSource:()=>qI,normalizeReferenceImage:()=>Moe,normalizeRetention:()=>BH,observeLeaveConfirm:()=>HI,observePageLifecycle:()=>$I,observePageTeardown:()=>FI,parseDgramHeader:()=>uv,prewake:()=>FF,referenceImageErrorMessage:()=>joe,releaseSessionBeacon:()=>Eg,sessionDirectory:()=>WH,sessionFailureFromMediaError:()=>TF,sharedCaptureController:()=>Aoe,videoStream:()=>voe,watchGenerationTick:()=>BI,whenLive:()=>W1,writeDgramHeader:()=>KI});g();y();var ZH=require("module");g();y();var AH=require("module");g();y();var fF=require("module");g();y();var CR=require("module"),Dl=globalThis.require??(0,CR.createRequire)(L),Pq=Object.create,jg=Object.defineProperty,Dq=Object.getOwnPropertyDescriptor,Bq=Object.getOwnPropertyNames,Lq=Object.getPrototypeOf,Oq=Object.prototype.hasOwnProperty,kv=(t=>typeof Dl<"u"?Dl:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof Dl<"u"?Dl:e)[r]}):t)(function(t){if(typeof Dl<"u")return Dl.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')}),TR=(t,e,r)=>()=>{if(r)throw r[0];try{return t&&(e=t(t=0)),e}catch(s){throw r=[s],s}},nt=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(r){throw e=0,r}},kR=(t,e)=>{for(var r in e)jg(t,r,{get:e[r],enumerable:!0})},AR=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Bq(e))!Oq.call(t,n)&&n!==r&&jg(t,n,{get:()=>e[n],enumerable:!(s=Dq(e,n))||s.enumerable});return t},Av=(t,e,r)=>(r=t!=null?Pq(Lq(t)):{},AR(e||!t||!t.__esModule?jg(r,"default",{value:t,enumerable:!0}):r,t)),IR=t=>AR(jg({},"__esModule",{value:!0}),t);var j1=Le(require("process"),1),gF=Le(require("os"),1),qA=Le(require("tty"),1);g();y();var pde=Le(ru(),1);g();y();lf();Hg();e_();Vv();var B6=new Map,N_=class{constructor(e){this.room=e,this.onmessage=null,this._onChange=r=>r.key===e&&this.onmessage!==null&&this.onmessage({data:m3(r.newValue||"")}),e3(this._onChange)}postMessage(e){ey.setItem(this.room,p3(f3(e)))}close(){t3(this._onChange)}},tW=typeof BroadcastChannel>"u"?N_:BroadcastChannel,U_=t=>Br(B6,t,()=>{let e=ri(),r=new tW(t);return r.onmessage=s=>e.forEach(n=>n(s.data,"broadcastchannel")),{bc:r,subs:e}}),L6=(t,e)=>(U_(t).subs.add(e),e),O6=(t,e)=>{let r=U_(t),s=r.subs.delete(e);return s&&r.subs.size===0&&(r.bc.close(),B6.delete(t)),s},Vc=(t,e,r=null)=>{let s=U_(t);s.bc.postMessage(e),s.subs.forEach(n=>n(e,r))};wf();gf();Kl();g();y();gf();Kl();var su=Le(ru(),1),N6=0,Ay=1,U6=2,Iy=(t,e)=>{De(t,N6);let r=su.encodeStateVector(e);er(t,r)},M_=(t,e,r)=>{De(t,Ay),er(t,su.encodeStateAsUpdate(e,r))},sW=(t,e,r)=>M_(e,r,Ar(t)),M6=(t,e,r,s)=>{try{su.applyUpdate(e,Ar(t),r)}catch(n){s?.(n),E.error("Caught error while handling a Yjs update",n)}},j6=(t,e)=>{De(t,U6),er(t,e)},nW=M6,$6=(t,e,r,s,n)=>{let i=st(t);switch(i){case N6:sW(t,e,r);break;case Ay:M6(t,r,s,n);break;case U6:nW(t,r,s,n);break;default:throw new Error("Unknown message type")}return i};g();y();var ide=Le(ru(),1);Kl();var oW=0;var F6=(t,e,r)=>{st(t)===oW&&r(e,en(t))};g();y();gf();Kl();wf();Tc();Wg();Sf();var dde=Le(ru(),1),j_=3e4,nu=class extends zg{constructor(e){super(),this.doc=e,this.clientID=e.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{let r=Ms();this.getLocalState()!==null&&j_/2<=r-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());let s=[];this.meta.forEach((n,i)=>{i!==this.clientID&&j_<=r-n.lastUpdated&&this.states.has(i)&&s.push(i)}),s.length>0&&Ry(this,s,"timeout")},ws(j_/10)),e.on("destroy",()=>{this.destroy()}),this.setLocalState({})}destroy(){this.emit("destroy",[this]),this.setLocalState(null),super.destroy(),clearInterval(this._checkInterval)}getLocalState(){return this.states.get(this.clientID)||null}setLocalState(e){let r=this.clientID,s=this.meta.get(r),n=s===void 0?0:s.clock+1,i=this.states.get(r);e===null?this.states.delete(r):this.states.set(r,e),this.meta.set(r,{clock:n,lastUpdated:Ms()});let o=[],a=[],c=[],d=[];e===null?d.push(r):i==null?e!=null&&o.push(r):(a.push(r),Gl(i,e)||c.push(r)),(o.length>0||c.length>0||d.length>0)&&this.emit("change",[{added:o,updated:c,removed:d},"local"]),this.emit("update",[{added:o,updated:a,removed:d},"local"])}setLocalStateField(e,r){let s=this.getLocalState();s!==null&&this.setLocalState({...s,[e]:r})}getStates(){return this.states}},Ry=(t,e,r)=>{let s=[];for(let n=0;n<e.length;n++){let i=e[n];if(t.states.has(i)){if(t.states.delete(i),i===t.clientID){let o=t.meta.get(i);t.meta.set(i,{clock:o.clock+1,lastUpdated:Ms()})}s.push(i)}}s.length>0&&(t.emit("change",[{added:[],updated:[],removed:s},r]),t.emit("update",[{added:[],updated:[],removed:s},r]))},iu=(t,e,r=t.states)=>{let s=e.length,n=pr();De(n,s);for(let i=0;i<s;i++){let o=e[i],a=r.get(o)||null,c=t.meta.get(o).clock;De(n,o),De(n,c),si(n,JSON.stringify(a))}return Ft(n)};var H6=(t,e,r)=>{let s=mr(e),n=Ms(),i=[],o=[],a=[],c=[],d=st(s);for(let u=0;u<d;u++){let l=st(s),h=st(s),p=JSON.parse(en(s)),m=t.meta.get(l),_=t.states.get(l),f=m===void 0?0:m.clock;(f<h||f===h&&p===null&&t.states.has(l))&&(p===null?l===t.clientID&&t.getLocalState()!=null?h++:t.states.delete(l):t.states.set(l,p),t.meta.set(l,{clock:h,lastUpdated:n}),m===void 0&&p!==null?i.push(l):m!==void 0&&p===null?c.push(l):p!==null&&(Gl(p,_)||a.push(l),o.push(l)))}(i.length>0||a.length>0||c.length>0)&&t.emit("change",[{added:i,updated:a,removed:c},r]),(i.length>0||o.length>0||c.length>0)&&t.emit("update",[{added:i,updated:o,removed:c},r])};Wg();Tc();g();y();ry();var q6=t=>a3(t,(e,r)=>`${encodeURIComponent(r)}=${encodeURIComponent(e)}`).join("&");Cf();var zc=0,z6=3,ou=1,lW=2,Hf=[];Hf[zc]=(t,e,r,s,n)=>{De(t,zc);let i=$6(e,t,r.doc,r);s&&i===Ay&&!r.synced&&(r.synced=!0)};Hf[z6]=(t,e,r,s,n)=>{De(t,ou),er(t,iu(r.awareness,Array.from(r.awareness.getStates().keys())))};Hf[ou]=(t,e,r,s,n)=>{H6(r.awareness,Ar(e),r)};Hf[lW]=(t,e,r,s,n)=>{F6(e,r.doc,(i,o)=>uW(r,o))};var V6=3e4,uW=(t,e)=>E.warn(`Permission denied to access ${t.url}.
|
|
140
|
+
`}},Bh=class{constructor(t,e){this.semantic=t,this.items=e}get str(){return`${this.semantic} ${this.items.join(" ")}`}};R$=class{constructor(t,e){this.sdp=t,this.type=e}static isThis(t){if(typeof t?.sdp=="string")return!0}toSdp(){return{sdp:this.sdp,type:this.type}}};l1=class{ssrc;cname;msid;msLabel;label;constructor(t){Object.assign(this,t)}},Rw=ft("werift:packages/webrtc/src/media/rtpReceiver.ts"),FA=class{constructor(t,e,r){this.config=t,this.kind=e,this.rtcpSsrc=r}codecs={};get codecArray(){return Object.values(this.codecs).sort((t,e)=>t.payloadType-e.payloadType)}ssrcByRtx={};nack=new Dte(this);audioRedHandler=new EM;type="receiver";uuid=(0,Rj.randomUUID)().toString();tracks=[];trackBySSRC={};trackByRID={};lastSRtimestamp={};receiveLastSRTimestamp={};onPacketLost=this.nack.onPacketLost;onRtcp=new Ne;dtlsTransport;sdesMid;latestRid;latestRepairedRid;receiverTWCC;stopped=!1;remoteStreamId;remoteTrackId;rtcpRunning=!1;rtcpCancel=new AbortController;remoteStreams={};setDtlsTransport(t){this.dtlsTransport=t}get track(){return this.tracks[0]??new K0({kind:this.kind})}get nackEnabled(){return this.codecArray[0]?.rtcpFeedback.find(t=>t.type==="nack")}get twccEnabled(){return this.codecArray[0]?.rtcpFeedback.find(t=>t.type===Sj().type)}get pliEnabled(){return this.codecArray[0]?.rtcpFeedback.find(t=>t.type===Vh().type)}prepareReceive(t){t.codecs.forEach(e=>{this.codecs[e.payloadType]=e}),t.encodings.forEach(e=>{e.rtx&&(this.ssrcByRtx[e.rtx.ssrc]=e.ssrc)})}setupTWCC(t){this.twccEnabled&&!this.receiverTWCC&&(this.receiverTWCC=new Lte(this.dtlsTransport,this.rtcpSsrc,t))}addTrack(t){return this.tracks.find(r=>{if(r.rid)return r.rid===t.rid;if(r.ssrc)return r.ssrc===t.ssrc})?!1:(this.tracks.push(t),t.ssrc&&(this.trackBySSRC[t.ssrc]=t),t.rid&&(this.trackByRID[t.rid]=t),!0)}stop(){this.stopped=!0,this.rtcpRunning=!1,this.rtcpCancel.abort(),this.receiverTWCC&&(this.receiverTWCC.twccRunning=!1),this.nack.close()}async runRtcp(){if(!(this.rtcpRunning||this.stopped)){this.rtcpRunning=!0;try{for(;this.rtcpRunning;){await(0,jw.setTimeout)(500+Math.random()*1e3,void 0,{signal:this.rtcpCancel.signal});let t=Object.entries(this.remoteStreams).map(([r,s])=>{let n=0,i=0;if(this.lastSRtimestamp[r]){n=this.lastSRtimestamp[r];let o=G0()-this.receiveLastSRTimestamp[r];o>0&&o<65536&&(i=Rh(o*65536))}return new v1({ssrc:Number(r),fractionLost:s.fraction_lost,packetsLost:s.packets_lost,highestSequence:s.max_seq,jitter:s.jitter,lsr:n,dlsr:i})}),e=new Nh({ssrc:this.rtcpSsrc,reports:t});try{this.config.debug.receiverReportDelay&&await(0,jw.setTimeout)(this.config.debug.receiverReportDelay),await this.dtlsTransport.sendRtcp([e])}catch(r){Rw("sendRtcp failed",r),await(0,jw.setTimeout)(500+Math.random()*1e3)}}}catch{}}}async getStats(){let t=bc(),e=[];if(!this.dtlsTransport)return e;let r=zt("transport",this.dtlsTransport.id);for(let s of this.tracks){if(!s.ssrc)continue;let n=this.remoteStreams[s.ssrc];if(!n)continue;let i={type:"inbound-rtp",id:zt("inbound-rtp",s.ssrc),timestamp:t,ssrc:s.ssrc,kind:this.kind,transportId:r,codecId:this.codecs[0]?zt("codec",this.codecs[0].payloadType,r):void 0,mid:this.sdesMid,trackIdentifier:s.id,packetsReceived:n.packets_received,packetsLost:n.packets_lost,jitter:n.jitter};if(e.push(i),this.lastSRtimestamp[s.ssrc]){let o={type:"remote-outbound-rtp",id:zt("remote-outbound-rtp",s.ssrc),timestamp:t,ssrc:s.ssrc,kind:this.kind,transportId:r,codecId:i.codecId,localId:i.id,remoteTimestamp:this.receiveLastSRTimestamp[s.ssrc]*1e3};e.push(o)}}return e}async sendRtcpPLI(t){if(!this.pliEnabled){Rw("pli not supported",{mediaSsrc:t});return}if(this.stopped)return;Rw("sendRtcpPLI",{mediaSsrc:t});let e=new Oh({feedback:new $0({senderSsrc:this.rtcpSsrc,mediaSsrc:t})});try{await this.dtlsTransport.sendRtcp([e])}catch(r){Rw(r)}}handleRtcpPacket(t){switch(t.type){case bl.type:{let e=t;this.lastSRtimestamp[e.ssrc]=BA(e.senderInfo.ntpTimestamp),this.receiveLastSRTimestamp[e.ssrc]=G0();let r=this.trackBySSRC[t.ssrc];r&&r.onReceiveRtcp.execute(t)}break}this.onRtcp.execute(t)}handleRtpBySsrc=(t,e)=>{let r=this.trackBySSRC[t.header.ssrc];this.handleRTP(t,e,r)};handleRtpByRid=(t,e,r)=>{let s=this.trackByRID[e];this.trackBySSRC[t.header.ssrc]||(this.trackBySSRC[t.header.ssrc]=s),this.handleRTP(t,r,s)};handleRTP(t,e,r){if(this.stopped)return;let s=this.codecs[t.header.payloadType];if(!s)return;if(this.remoteStreams[t.header.ssrc]=this.remoteStreams[t.header.ssrc]??new Ote(s.clockRate),this.remoteStreams[t.header.ssrc].add(t),this.receiverTWCC){let i=e[Qt.transportWideCC];if(!i==null)throw new Error("undefined");this.receiverTWCC.handleTWCC(i)}else this.twccEnabled&&this.setupTWCC(t.header.ssrc);if(s.name.toLowerCase()==="rtx"){let i=this.ssrcByRtx[t.header.ssrc],o=J0(s.parameters??""),a=this.codecs[o.apt];if(t.payload.length<2)return;t=TM(t,a.payloadType,i),r=this.trackBySSRC[i]}let n;if(!(s.name.toLowerCase()==="red"&&(n=sA.deSerialize(t.payload),!Object.keys(this.codecs).includes(n.header.fields[0].blockPT.toString())))){if(r?.kind==="video"&&this.nackEnabled&&this.nack.addPacket(t),r)if(n){if(r.kind==="audio"){let i=this.audioRedHandler.push(n,t);for(let o of i)r.onReceiveRtp.execute(o.clone(),e)}}else r.onReceiveRtp.execute(t.clone(),e);this.runRtcp()}}},f0=ft("werift:packages/webrtc/src/media/router.ts"),P$=class{ssrcTable={};ridTable={};extIdUriMap={};constructor(){}registerRtpSender(t){this.ssrcTable[t.ssrc]=t}registerRtpReceiver(t,e){f0("registerRtpReceiver",e),this.ssrcTable[e]=t}registerRtpReceiverBySsrc(t,e){f0("registerRtpReceiverBySsrc",e),e.encodings.filter(r=>r.ssrc!=null).forEach((r,s)=>{this.registerRtpReceiver(t.receiver,r.ssrc),t.addTrack(new K0({ssrc:r.ssrc,kind:t.kind,id:t.sender.trackId,remote:!0,codec:e.codecs[s]})),r.rtx&&this.registerRtpReceiver(t.receiver,r.rtx.ssrc)}),e.headerExtensions.forEach(r=>{this.extIdUriMap[r.id]=r.uri})}registerRtpReceiverByRid(t,e,r){let[s]=r.codecs;f0("registerRtpReceiverByRid",e),t.addTrack(new K0({rid:e.rid,kind:t.kind,id:t.sender.trackId,remote:!0,codec:s})),this.ridTable[e.rid]=t.receiver}routeRtp=t=>{let e=lM(t.header.extensions,this.extIdUriMap),r=this.ssrcTable[t.header.ssrc],s=e[Qt.sdesRTPStreamID];if(typeof s=="string"?(r=this.ridTable[s],r.latestRid=s,r.handleRtpByRid(t,s,e)):r?r.handleRtpBySsrc(t,e):(r=Object.values(this.ridTable).filter(o=>o instanceof FA).find(o=>o.trackBySSRC[t.header.ssrc]),r&&(f0("simulcast register receiver by ssrc",t.header.ssrc),this.registerRtpReceiver(r,t.header.ssrc),r.handleRtpBySsrc(t,e))),!r){f0("ssrcReceiver not found");return}let n=e[Qt.sdesMid];typeof n=="string"&&(r.sdesMid=n);let i=e[Qt.repairedRtpStreamId];typeof i=="string"&&(r.latestRepairedRid=i)};routeRtcp=t=>{let e=[];switch(t.type){case bl.type:t=t,e.push(this.ssrcTable[t.ssrc]);break;case Nh.type:t=t,t.reports.forEach(r=>{e.push(this.ssrcTable[r.ssrc])});break;case V0.type:{let r=t}break;case yl.type:{let r=t;r.feedback&&e.push(this.ssrcTable[r.feedback.mediaSourceSsrc])}break;case Oh.type:{let r=t;switch(r.feedback.count){case F0.count:{let s=r.feedback;e.push(this.ssrcTable[s.ssrcFeedbacks[0]])}break;default:e.push(this.ssrcTable[r.feedback.senderSsrc]||this.ssrcTable[r.feedback.mediaSsrc])}}break}e.filter(r=>r).forEach(r=>r.handleRtcpPacket(t))}},lre=class{numPackets=0;totalSize=0;firstPacketSentAtMs=0;lastPacketSentAtMs=0;firstPacketReceivedAtMs=0;lastPacketReceivedAtMs=0;addPacket(t,e,r){this.numPackets===0?(this.firstPacketSentAtMs=e,this.firstPacketReceivedAtMs=r,this.lastPacketSentAtMs=e,this.lastPacketReceivedAtMs=r):(e<this.firstPacketSentAtMs&&(this.firstPacketSentAtMs=e),r<this.firstPacketReceivedAtMs&&(this.firstPacketReceivedAtMs=r),e>this.lastPacketSentAtMs&&(this.lastPacketSentAtMs=e),r>this.lastPacketReceivedAtMs&&(this.lastPacketReceivedAtMs=r)),this.numPackets++,this.totalSize+=t}reset(){this.numPackets=0,this.totalSize=0,this.firstPacketSentAtMs=0,this.lastPacketSentAtMs=0,this.firstPacketReceivedAtMs=0,this.lastPacketReceivedAtMs=0}get receiveBitrate(){let t=this.lastPacketReceivedAtMs-this.firstPacketReceivedAtMs,e=this.totalSize/t*8*1e3;return j0(e)}get sendBitrate(){let t=this.lastPacketSentAtMs-this.firstPacketSentAtMs,e=this.totalSize/t*8*1e3;return j0(e)}},Sh=20,ure=10,hre=class{congestion=!1;onAvailableBitrate=new Ne;onCongestion=new Ne;onCongestionScore=new Ne;congestionCounter=0;cumulativeResult=new lre;sentInfos={};_congestionScore=1;get congestionScore(){return this._congestionScore}set congestionScore(t){this._congestionScore=t,this.onCongestionScore.execute(t)}_availableBitrate=0;get availableBitrate(){return this._availableBitrate}set availableBitrate(t){this._availableBitrate=t,this.onAvailableBitrate.execute(t)}constructor(){}receiveTWCC(t){let r=DA()-this.cumulativeResult.firstPacketSentAtMs;r>1e3&&(this.cumulativeResult.reset(),this.congestionCounter<Sh?this.congestionCounter++:this.congestionScore<ure&&this.congestionScore++,this.congestionCounter>=Sh&&!this.congestion&&(this.congestion=!0,this.onCongestion.execute(this.congestion)));for(let s of t.packetResults){if(!s.received)continue;let n=s.sequenceNumber,i=this.sentInfos[n];i&&s.receivedAtMs&&this.cumulativeResult.addPacket(i.size,i.sendingAtMs,s.receivedAtMs)}if(r>=100&&this.cumulativeResult.numPackets>=20){if(this.availableBitrate=Math.min(this.cumulativeResult.sendBitrate,this.cumulativeResult.receiveBitrate),this.cumulativeResult.reset(),this.congestionCounter>-Sh){let s=j0(Sh/2)+1,n=j0(Sh/4)+1,i=s-(s-n)/10*this.congestionScore;this.congestionCounter=this.congestionCounter-i}this.congestionCounter<=-Sh&&(this.congestionScore>1&&(this.congestionScore--,this.onCongestion.execute(!1)),this.congestionCounter=0),this.congestionCounter<=0&&this.congestion&&(this.congestion=!1,this.onCongestion.execute(this.congestion))}}rtpPacketSent(t){Object.keys(t).map(e=>Number(e)).sort().filter(e=>e<t.wideSeq).forEach(e=>{delete this.sentInfos[e]}),this.sentInfos[t.wideSeq]=t}},DT=ft("werift:packages/webrtc/src/media/rtpSender.ts"),jU=128,$U=.85,D$=class{constructor(t){this.trackOrKind=t,this.kind=typeof this.trackOrKind=="string"?this.trackOrKind:this.trackOrKind.kind,typeof t!="string"&&(t.streamId&&(this.streamId=t.streamId),this.registerTrack(t))}type="sender";kind;ssrc=jk.jspack.Unpack("!L",(0,Mk.randomBytes)(4))[0];rtxSsrc=jk.jspack.Unpack("!L",(0,Mk.randomBytes)(4))[0];streamId=(0,$k.randomUUID)().toString();trackId=(0,$k.randomUUID)().toString();onReady=new Ne;onRtcp=new Ne;onPictureLossIndication=new Ne;onGenericNack=new Ne;senderBWE=new hre;cname;mid;rtpStreamId;repairedRtpStreamId;rtxPayloadType;rtxSequenceNumber=zk();redRedundantPayloadType;_redDistance=2;redEncoder=new SM(this._redDistance);headerExtensions=[];disposeTrack;lastSRtimestamp;lastSentSRTimestamp;ntpTimestamp=0n;rtpTimestamp=0;octetCount=0;packetCount=0;rtt;receiverEstimatedMaxBitrate=0n;sequenceNumber;timestamp;timestampOffset=0;seqOffset=0;rtpCache=[];codec;dtlsTransport;dtlsDisposer=[];track;stopped=!1;rtcpRunning=!1;rtcpCancel=new AbortController;setDtlsTransport(t){this.dtlsTransport&&this.dtlsDisposer.forEach(e=>e()),this.dtlsTransport=t,this.dtlsDisposer=[this.dtlsTransport.onStateChange.subscribe(e=>{e==="connected"&&this.onReady.execute()}).unSubscribe]}get redDistance(){return this._redDistance}set redDistance(t){this._redDistance=t,this.redEncoder.distance=t}prepareSend(t){this.cname=t.rtcp?.cname,this.mid=t.muxId,this.headerExtensions=t.headerExtensions,this.rtpStreamId=t.rtpStreamId,this.repairedRtpStreamId=t.repairedRtpStreamId,this.codec=t.codecs[0],this.track&&(this.track.codec=this.codec),t.codecs.forEach(e=>{let r=J0(e.parameters??"");e.name.toLowerCase()==="rtx"&&r.apt===this.codec?.payloadType&&(this.rtxPayloadType=e.payloadType),e.name.toLowerCase()==="red"&&(this.redRedundantPayloadType=Number((e.parameters??"").split("/")[0]))})}registerTrack(t){if(t.stopped)throw new Error("track is ended");this.disposeTrack&&this.disposeTrack(),t.id=this.trackId;let{unSubscribe:e}=t.onReceiveRtp.subscribe(async r=>{await this.sendRtp(r)});this.track=t,this.disposeTrack=e,this.codec&&(t.codec=this.codec),t.onSourceChanged.subscribe(r=>{this.replaceRTP(r)})}async replaceTrack(t){if(t!==null){if(t.stopped)throw new Error("track is ended");if(this.sequenceNumber!=null){let e=t.header||(await t.onReceiveRtp.asPromise())[0].header;this.replaceRTP(e)}this.registerTrack(t),DT("replaceTrack","ssrc",t.ssrc,"rid",t.rid)}}stop(){this.stopped=!0,this.rtcpRunning=!1,this.rtcpCancel.abort(),this.disposeTrack&&this.disposeTrack(),this.track=void 0}async runRtcp(){if(!(this.rtcpRunning||this.stopped)){this.rtcpRunning=!0;try{for(;this.rtcpRunning;){await(0,Fk.setTimeout)(500+Math.random()*1e3,void 0,{signal:this.rtcpCancel.signal});let t=[new bl({ssrc:this.ssrc,senderInfo:new rA({ntpTimestamp:this.ntpTimestamp,rtpTimestamp:this.rtpTimestamp,packetCount:this.packetCount,octetCount:this.octetCount})})];this.lastSRtimestamp=BA(this.ntpTimestamp),this.lastSentSRTimestamp=G0(),this.cname&&t.push(new V0({chunks:[new eA({source:this.ssrc,items:[new tA({type:1,text:this.cname})]})]}));try{await this.dtlsTransport.sendRtcp(t)}catch(e){DT("sendRtcp failed",e),await(0,Fk.setTimeout)(500+Math.random()*1e3)}}}catch{}}}replaceRTP({sequenceNumber:t,timestamp:e},r=!1){this.sequenceNumber!=null&&(this.seqOffset=Jr(this.sequenceNumber,-t),r&&(this.seqOffset=Jr(this.seqOffset,2))),this.timestamp!=null&&(this.timestampOffset=ul(this.timestamp,-e),r&&(this.timestampOffset=Jr(this.timestampOffset,1))),this.rtpCache=[],DT("replaceRTP",this.sequenceNumber,t,this.seqOffset)}async sendRtp(t){if(this.dtlsTransport.state!=="connected"||!this.codec)return;t=Buffer.isBuffer(t)?Jo.deSerialize(t):t;let{header:e,payload:r}=t;e.ssrc=this.ssrc,e.payloadType=this.codec.payloadType,e.timestamp=ul(e.timestamp,this.timestampOffset),e.sequenceNumber=Jr(e.sequenceNumber,this.seqOffset),this.timestamp=e.timestamp,this.sequenceNumber=e.sequenceNumber;let s=Hj(),n=[...e.extensions];e.extensions=this.headerExtensions.map(d=>{let u=(()=>{switch(d.uri){case Qt.sdesMid:return this.mid?uM(this.mid):void 0;case Qt.sdesRTPStreamID:return this.rtpStreamId?hM(this.rtpStreamId):void 0;case Qt.repairedRtpStreamId:return this.repairedRtpStreamId?fM(this.repairedRtpStreamId):void 0;case Qt.transportWideCC:return this.dtlsTransport.transportSequenceNumber=Jr(this.dtlsTransport.transportSequenceNumber,1),pM(this.dtlsTransport.transportSequenceNumber);case Qt.absSendTime:return mM(s)}})();if(u)return{id:d.id,payload:u}}).filter(d=>d);for(let d of n){let u=e.extensions.find(l=>l.id===d.id);u?u.payload=d.payload:e.extensions.push(d)}e.extensions=e.extensions.sort((d,u)=>d.id-u.id),this.ntpTimestamp=s,this.rtpTimestamp=e.timestamp,this.octetCount+=r.length,this.packetCount=ul(this.packetCount,1),this.rtpCache[e.sequenceNumber%jU]=t;let i=r;this.redRedundantPayloadType&&(this.redEncoder.push({block:i,timestamp:e.timestamp,blockPT:this.redRedundantPayloadType}),i=this.redEncoder.build().serialize());let o=await this.dtlsTransport.sendRtp(i,e);this.runRtcp();let a=DA(),c={wideSeq:this.dtlsTransport.transportSequenceNumber,size:o,sendingAtMs:a,sentAtMs:a};this.senderBWE.rtpPacketSent(c)}handleRtcpPacket(t){switch(t.type){case bl.type:case Nh.type:t.reports.filter(r=>r.ssrc===this.ssrc).forEach(r=>{if(this.lastSRtimestamp===r.lsr&&r.dlsr&&this.lastSentSRTimestamp){let s=G0()-this.lastSentSRTimestamp-r.dlsr/65536;this.rtt===void 0?this.rtt=s:this.rtt=$U*this.rtt+(1-$U)*s}});break;case yl.type:{let e=t;switch(e.feedback.count){case q0.count:{let r=e.feedback;this.senderBWE.receiveTWCC(r)}break;case H0.count:{let r=e.feedback;r.lost.forEach(async s=>{let n=this.rtpCache[s%jU];n&&n.header.sequenceNumber!==s&&(n=void 0),n&&(this.rtxPayloadType!=null&&(n=kM(n,this.rtxPayloadType,this.rtxSequenceNumber,this.rtxSsrc),this.rtxSequenceNumber=Jr(this.rtxSequenceNumber,1)),await this.dtlsTransport.sendRtp(n.payload,n.header))}),this.onGenericNack.execute(r)}break}}break;case Oh.type:{let e=t;switch(e.feedback.count){case F0.count:{let r=e.feedback;this.receiverEstimatedMaxBitrate=r.bitrate}break;case $0.count:this.onPictureLossIndication.execute();break}}break}this.onRtcp.execute(t)}getParameters(){return{encodings:[]}}setParameters(t){}async getStats(){let t=bc(),e=[];if(!this.dtlsTransport)return e;let r=zt("transport",this.dtlsTransport.id),s={type:"outbound-rtp",id:zt("outbound-rtp",this.ssrc),timestamp:t,ssrc:this.ssrc,kind:this.kind,transportId:r,codecId:this.codec?zt("codec",this.codec.payloadType,r):void 0,mid:this.mid,packetsSent:this.packetCount,bytesSent:this.octetCount,rtxSsrc:this.rtxPayloadType?this.rtxSsrc:void 0};if(e.push(s),this.track){let n={type:"media-source",id:zt("media-source",this.trackId),timestamp:t,trackIdentifier:this.trackId,kind:this.kind};e.push(n)}if(this.rtt!==void 0){let n={type:"remote-inbound-rtp",id:zt("remote-inbound-rtp",this.ssrc),timestamp:t,ssrc:this.ssrc,kind:this.kind,transportId:r,codecId:s.codecId,localId:s.id,roundTripTime:this.rtt};e.push(n)}return e}},fre=ft("werift:packages/webrtc/src/transport/sctpManager.ts"),pre=class{sctpTransport;sctpRemotePort;dataChannelsOpened=0;dataChannelsClosed=0;dataChannels=[];onDataChannel=new Ne;constructor(){}createSctpTransport(t){let e=new k$(5e3,t);return e.mid=void 0,e.onDataChannel.subscribe(r=>{this.dataChannelsOpened++,this.dataChannels.push(r),this.onDataChannel.execute(r)}),this.sctpTransport=e,e}createDataChannel(t,e={}){let s={...{protocol:"",ordered:!0,negotiated:!1},...e};if(s.maxPacketLifeTime&&s.maxRetransmits)throw new Error("can not select both");this.sctpTransport||(this.sctpTransport=this.createSctpTransport());let n=new xA({id:s.id,label:t,maxPacketLifeTime:s.maxPacketLifeTime,maxRetransmits:s.maxRetransmits,negotiated:s.negotiated,ordered:s.ordered,protocol:s.protocol}),i=new bA(this.sctpTransport,n);return this.dataChannelsOpened++,this.dataChannels.push(i),i.stateChange.subscribe(o=>{if(o==="closed"){this.dataChannelsClosed++;let a=this.dataChannels.indexOf(i);a!==-1&&this.dataChannels.splice(a,1)}}),i}async connectSctp(){!this.sctpTransport||!this.sctpRemotePort||(await this.sctpTransport.start(this.sctpRemotePort),await this.sctpTransport.sctp.stateChanged.connected.asPromise(),fre("sctp connected"))}setRemoteSCTP(t,e){if(this.sctpTransport){if(this.sctpTransport.setRemoteMaxMessageSize(t.sctpCapabilities?.maxMessageSize),this.sctpRemotePort=t.sctpPort,!this.sctpRemotePort)throw new Error("sctpRemotePort not exist");this.sctpTransport.setRemotePort(this.sctpRemotePort),this.sctpTransport.mLineIndex=e,this.sctpTransport.mid||(this.sctpTransport.mid=t.rtp.muxId)}}async close(){this.sctpTransport&&await this.sctpTransport.stop(),this.onDataChannel.allUnsubscribe()}async getStats(){let t=bc(),e=[];for(let r of this.dataChannels){let s={type:"data-channel",id:zt("data-channel",r.id),timestamp:t,label:r.label,protocol:r.protocol,dataChannelIdentifier:r.id,state:r.readyState,messagesSent:r.messagesSent||0,bytesSent:r.bytesSent||0,messagesReceived:r.messagesReceived||0,bytesReceived:r.bytesReceived||0};e.push(s)}return e}},L$=class{currentLocalDescription;currentRemoteDescription;pendingLocalDescription;pendingRemoteDescription;cname;midSuffix;bundlePolicy;seenMid=new Set;constructor({cname:t,midSuffix:e,bundlePolicy:r}){this.cname=t,this.midSuffix=e??!1,this.bundlePolicy=r}get localDescription(){if(this._localDescription)return this._localDescription.toJSON()}get remoteDescription(){if(this._remoteDescription)return this._remoteDescription.toJSON()}get _localDescription(){return this.pendingLocalDescription||this.currentLocalDescription}get _remoteDescription(){return this.pendingRemoteDescription||this.currentRemoteDescription}get inactiveRemoteMedia(){return this._remoteDescription?.media?.find?.(t=>t.direction==="inactive")}createMediaDescriptionForTransceiver(t,e){let r=new d1(t.kind,9,"UDP/TLS/RTP/SAVPF",t.codecs.map(s=>s.payloadType));return r.direction=e,r.msid=t.msid,r.rtp={codecs:t.codecs,headerExtensions:t.headerExtensions,muxId:t.mid},r.rtcpHost="0.0.0.0",r.rtcpPort=9,r.rtcpMux=!0,r.ssrc=[new l1({ssrc:t.sender.ssrc,cname:this.cname})],t.options.simulcast&&(r.simulcastParameters=t.options.simulcast.map(s=>new wA(s))),r.rtp.codecs.find(s=>s.name.toLowerCase()==="rtx")&&(r.ssrc.push(new l1({ssrc:t.sender.rtxSsrc,cname:this.cname})),r.ssrcGroup=[new Bh("FID",[t.sender.ssrc.toString(),t.sender.rtxSsrc.toString()])]),this.addTransportDescription(r,t.dtlsTransport),r}createMediaDescriptionForSctp(t){let e=new d1("application",SU,"UDP/DTLS/SCTP",["webrtc-datachannel"]);return e.sctpPort=t.port,e.rtp.muxId=t.mid,e.sctpCapabilities=t.getCapabilities(),this.addTransportDescription(e,t.dtlsTransport),e}addTransportDescription(t,e){let r=e.iceTransport;t.iceCandidates=r.localCandidates,t.iceCandidatesComplete=r.gatheringState==="complete",t.iceParams=r.localParameters,t.iceOptions="trickle",t.host=_te,t.port=SU,t.direction==="inactive"&&(t.port=0,t.msid=void 0),t.dtlsParams||(t.dtlsParams=e.localParameters,t.dtlsParams.fingerprints||(t.dtlsParams.fingerprints=e.localParameters.fingerprints))}allocateMid(t=""){let e="";for(let r=0;e=(r++).toString()+t,!!this.seenMid.has(e););return this.seenMid.add(e),e}parseSdp({sdp:t,isLocal:e,signalingState:r,type:s}){let n=P0.parse(t);return this.validateDescription({description:n,isLocal:e,signalingState:r}),n.type=s,n}validateDescription({description:t,isLocal:e,signalingState:r}){if(e){if(t.type==="offer"){if(!["stable","have-local-offer"].includes(r))throw new Error("Cannot handle offer in signaling state")}else if(t.type==="answer"&&!["have-remote-offer","have-local-pranswer"].includes(r))throw new Error("Cannot handle answer in signaling state")}else if(t.type==="offer"){if(!["stable","have-remote-offer"].includes(r))throw new Error("Cannot handle offer in signaling state")}else if(t.type==="answer"&&!["have-local-offer","have-remote-pranswer"].includes(r))throw new Error("Cannot handle answer in signaling state")}buildOfferSdp(t,e){let r=new P0;Uk("offer",r),(this.currentLocalDescription?.media??[]).forEach((n,i)=>{let o=n.rtp.muxId;if(o)if(n.kind==="application"){if(!e)throw new Error("sctpTransport not found");e.mLineIndex=i,r.media.push(this.createMediaDescriptionForSctp(e))}else{let a=t.find(c=>c.mid===o);if(!a){if(n.direction==="inactive"){r.media.push(n);return}throw new Error("transceiver not found")}a.mLineIndex=i,r.media.push(this.createMediaDescriptionForTransceiver(a,a.direction))}});for(let n of t.filter(i=>!r.media.find(o=>o.rtp.muxId===i.mid))){n.mid==null&&(n.mid=this.allocateMid(this.midSuffix?"av":""));let i=this.createMediaDescriptionForTransceiver(n,n.direction);n.mLineIndex===void 0?(n.mLineIndex=r.media.length,r.media.push(i)):r.media[n.mLineIndex]=i}if(e&&!r.media.find(n=>n.kind==="application")&&(e.mLineIndex=r.media.length,e.mid==null&&(e.mid=this.allocateMid(this.midSuffix?"dc":"")),r.media.push(this.createMediaDescriptionForSctp(e))),this.bundlePolicy!=="disable"){let n=r.media.map(i=>i.rtp.muxId).filter(i=>i);if(n.length){let i=new Bh("BUNDLE",n);r.group.push(i)}}return r}buildAnswerSdp({transceivers:t,sctpTransport:e,signalingState:r}){if(!["have-remote-offer","have-local-pranswer"].includes(r))throw new Error("createAnswer failed");if(!this._remoteDescription)throw new Error("wrong state");let s=new P0;Uk("answer",s);for(let n of this._remoteDescription.media){let i,o;if(["audio","video"].includes(n.kind)){let a=t.find(c=>c.mid===n.rtp.muxId);if(!a)throw new Error(`Transceiver with mid=${n.rtp.muxId} not found`);o=this.createMediaDescriptionForTransceiver(a,PA(a.direction,a.offerDirection)),i=a.dtlsTransport}else if(n.kind==="application"){if(!e||!e.mid)throw new Error("sctpTransport not found");o=this.createMediaDescriptionForSctp(e),i=e.dtlsTransport}else throw new Error("invalid kind");o.dtlsParams&&(i.role==="auto"?o.dtlsParams.role="client":o.dtlsParams.role=i.role),n.simulcastParameters&&n.simulcastParameters.length>0&&(o.simulcastParameters=n.simulcastParameters.map(a=>({...a,direction:a.direction==="send"?"recv":"send"}))),s.media.push(o)}if(this.bundlePolicy!=="disable"){let n=new Bh("BUNDLE",[]);for(let i of s.media)i.rtp.muxId&&n.items.push(i.rtp.muxId);s.group.push(n)}return s}setLocalDescription(t){this.currentLocalDescription=t,t.type==="answer"?this.pendingLocalDescription=void 0:this.pendingLocalDescription=t}setRemoteDescription(t,e){if(!t.sdp||!t.type||t.type==="rollback"||t.type==="pranswer")throw new Error("invalid sessionDescription");let r=this.parseSdp({sdp:t.sdp,isLocal:!1,signalingState:e,type:t.type});return r.type==="answer"?(this.currentRemoteDescription=r,this.pendingRemoteDescription=void 0):this.pendingRemoteDescription=r,r}registerMid(t){this.seenMid.add(t)}get remoteIsBundled(){let t=this._remoteDescription;return t?t.group.find(r=>r.semantic==="BUNDLE"&&this.bundlePolicy!=="disable"):void 0}setLocal(t,e,r){let s=new Map(e.map(o=>[o?.mLineIndex,o])),n=e.find(o=>o?.dtlsTransport)?.dtlsTransport??r?.dtlsTransport;t.media.filter(o=>["audio","video"].includes(o.kind)).forEach((o,a)=>{let d=(s.get(a)??e[a])?.dtlsTransport??n;if(!d)throw new Error(`dtls transport not found for media index ${a}`);this.addTransportDescription(o,d)});let i=t.media.find(o=>o.kind==="application");r&&i&&this.addTransportDescription(i,r.dtlsTransport),this.setLocalDescription(t)}},p0=ft("werift:packages/webrtc/src/transport/secureTransportManager.ts"),mre=class{connectionState="new";iceConnectionState="new";iceGatheringState="new";certificate;iceGatheringStateChange=new Ne;iceConnectionStateChange=new Ne;onIceCandidate=new Ne;connectionStateChange=new Ne;config;transceiverManager;sctpManager;constructor({config:t,transceiverManager:e,sctpManager:r}){if(this.config=t,this.transceiverManager=e,this.sctpManager=r,this.config.dtls){let{keys:s}=this.config.dtls;s&&this.setupCertificate(s)}}get dtlsTransports(){return[...this.transceiverManager.getTransceivers().map(e=>e?.dtlsTransport),this.sctpManager.sctpTransport?.dtlsTransport].filter(e=>e!=null).reduce((e,r)=>(e.map(s=>s.id).includes(r.id)||e.push(r),e),[])}get iceTransports(){return this.dtlsTransports.map(t=>t.iceTransport)}setupCertificate(t){this.certificate=new LA(t.keyPem,t.certPem,t.signatureHash)}createTransport(){let t=this.iceTransports.find(n=>n.state!=="closed"),e=new Zj({...qj(this.config.iceServers),forceTurn:this.config.iceTransportPolicy==="relay",portRange:this.config.icePortRange,interfaceAddresses:this.config.iceInterfaceAddresses,additionalHostAddresses:this.config.iceAdditionalHostAddresses,filterStunResponse:this.config.iceFilterStunResponse,filterCandidatePair:this.config.iceFilterCandidatePair,localPasswordPrefix:this.config.icePasswordPrefix,useIpv4:this.config.iceUseIpv4,useIpv6:this.config.iceUseIpv6,turnTransport:this.config.forceTurnTCP===!0?"tcp":"udp",useLinkLocalAddress:this.config.iceUseLinkLocalAddress});t&&(e.connection.localUsername=t.connection.localUsername,e.connection.localPassword=t.connection.localPassword),e.onGatheringStateChange.subscribe(()=>{this.updateIceGatheringState()}),this.updateIceGatheringState();let r=new Qj(e);return r.onStateChange.subscribe(()=>{this.updateIceConnectionState()}),new vk(this.config,r,this.certificate,gre)}handleNewIceCandidate({candidate:t,media:e,remoteIsBundled:r,transceiver:s,sctpTransport:n,bundlePolicy:i}){return i==="max-bundle"||r?(t.sdpMLineIndex=0,e&&(t.sdpMid=e.rtp.muxId)):(s&&(t.sdpMLineIndex=s.mLineIndex,t.sdpMid=s.mid),n&&(t.sdpMLineIndex=n.mLineIndex,t.sdpMid=n.mid)),t.foundation&&!t.foundation.startsWith("candidate:")&&(t.foundation="candidate:"+t.foundation),this.onIceCandidate.execute(t),t}async addIceCandidate(t,e){let r=OA.fromJSON(e);if(!r)return;let s;typeof r.sdpMid=="number"&&(s=this.getTransportByMid(r.sdpMid)),!s&&typeof r.sdpMLineIndex=="number"&&(s=this.getTransportByMLineIndex(t,r.sdpMLineIndex)),s||(s=this.iceTransports[0]),s?await s.addRemoteCandidate(r):p0("iceTransport not found for candidate",r)}getTransportByMid(t){let e,r=this.transceiverManager.getTransceivers().find(s=>s.mid===t);return r?e=r.dtlsTransport.iceTransport:!e&&this.sctpManager.sctpTransport?.mid===t&&(e=this.sctpManager.sctpTransport.dtlsTransport.iceTransport),e}getTransportByMLineIndex(t,e){let r=t.media[e];return r?this.getTransportByMid(r.rtp.muxId):void 0}restartIce(){for(let t of this.iceTransports)t.restart()}setLocalRole({type:t,role:e}){for(let r of this.dtlsTransports){let s=r.iceTransport;t==="offer"?s.connection.iceControlling=!0:s.connection.iceControlling=!1,s.connection.remoteIsLite&&(s.connection.iceControlling=!0),t==="answer"&&e&&(r.role=e)}}updateIceGatheringState(){let t=this.iceTransports;function e(...s){return t.filter(n=>s.includes(n.gatheringState)).length===t.length}let r;t.length&&e("complete")?r="complete":!t.length||e("new","complete")?r="new":t.map(s=>s.gatheringState).includes("gathering")?r="gathering":r="new",this.iceGatheringState!==r&&(this.iceGatheringState=r,this.iceGatheringStateChange.execute(r))}updateIceConnectionState(){let t=this.iceTransports,e;function r(...n){return t.filter(i=>n.includes(i.state)).length===t.length}function s(...n){return t.some(i=>n.includes(i.state))}this.connectionState==="closed"?e="closed":s("failed")?e="failed":s("disconnected")?e="disconnected":r("new","closed")?e="new":s("new","checking")?e="checking":r("completed","closed")?e="completed":r("connected","completed","closed")?e="connected":e="new",this.iceConnectionState!==e&&(p0("iceConnectionStateChange",e),this.iceConnectionState=e,this.iceConnectionStateChange.execute(e))}async gatherCandidates(t){let e=this.iceTransports.find(r=>r.state==="connected"||r.state==="completed");t&&e?p0("skipping ICE gathering for bundled connection"):await Promise.allSettled(this.iceTransports.map(r=>r.gather())).catch(r=>{p0("gatherCandidates failed",r)})}setConnectionState(t){p0("connectionStateChange",t),this.connectionState=t,this.connectionStateChange.execute(t)}async getStats(){let t=[];for(let e of this.dtlsTransports){let r=await e.getStats();r&&t.push(...r)}return t}async ensureCerts(){this.certificate||(this.certificate=await vk.SetupCertificate());for(let t of this.dtlsTransports)t.localCertificate=this.certificate}async close(){this.setConnectionState("closed"),await Promise.allSettled([...this.dtlsTransports.map(t=>t.stop())]),this.iceGatheringStateChange.allUnsubscribe(),this.iceConnectionStateChange.allUnsubscribe(),this.onIceCandidate.allUnsubscribe(),this.connectionStateChange.allUnsubscribe()}},gre=[CU.SRTP_AEAD_AES_128_GCM,CU.SRTP_AES128_CM_HMAC_SHA1_80],zn=ft("werift:packages/webrtc/src/peerConnection.ts"),yre=class extends yA{cname=(0,B$.randomUUID)().toString();config=O$();signalingState="stable";negotiationneeded=!1;needRestart=!1;router=new P$;sdpManager;transceiverManager;sctpManager;secureManager;isClosed=!1;shouldNegotiationneeded=!1;remoteBundleNegotiated=!1;iceGatheringStateChange=new Ne;iceConnectionStateChange=new Ne;signalingStateChange=new Ne;connectionStateChange=new Ne;onDataChannel=new Ne;onRemoteTransceiverAdded=new Ne;onTransceiverAdded=new Ne;onIceCandidate=new Ne;onNegotiationneeded=new Ne;onTrack=new Ne;ondatachannel;onicecandidate;onicecandidateerror;onicegatheringstatechange;onnegotiationneeded;onsignalingstatechange;ontrack;onconnectionstatechange;oniceconnectionstatechange;constructor(t={}){super(),this.setConfiguration(t),this.sdpManager=new L$({cname:this.cname,bundlePolicy:this.config.bundlePolicy}),this.transceiverManager=new N$(this.cname,this.config,this.router),this.transceiverManager.onTransceiverAdded.pipe(this.onTransceiverAdded),this.transceiverManager.onRemoteTransceiverAdded.pipe(this.onRemoteTransceiverAdded),this.transceiverManager.onTrack.subscribe(({track:e,stream:r,transceiver:s})=>{let n={track:e,streams:[r],transceiver:s,receiver:s.receiver};this.onTrack.execute(e),this.emit("track",n),this.ontrack&&this.ontrack(n)}),this.transceiverManager.onNegotiationNeeded.subscribe(()=>this.needNegotiation()),this.sctpManager=new pre,this.sctpManager.onDataChannel.subscribe(e=>{this.onDataChannel.execute(e);let r={channel:e};this.ondatachannel?.(r),this.emit("datachannel",r)}),this.secureManager=new mre({config:this.config,sctpManager:this.sctpManager,transceiverManager:this.transceiverManager}),this.secureManager.iceGatheringStateChange.pipe(this.iceGatheringStateChange),this.secureManager.iceConnectionStateChange.subscribe(e=>{e==="closed"&&this.close(),this.iceConnectionStateChange.execute(e)}),this.secureManager.connectionStateChange.subscribe(e=>{this.connectionStateChange.execute(e),this.onconnectionstatechange?.(),this.emit("connectionstatechange")}),this.secureManager.onIceCandidate.subscribe(e=>{let r=e?e.toJSON():void 0;this.onIceCandidate.execute(r),this.onicecandidate?.({candidate:r}),this.emit("icecandidate",{candidate:r})})}get connectionState(){return this.secureManager.connectionState}get iceConnectionState(){return this.secureManager.iceConnectionState}get iceGathererState(){return this.secureManager.iceGatheringState}get iceGatheringState(){return this.secureManager.iceGatheringState}get dtlsTransports(){return this.secureManager.dtlsTransports}get sctpTransport(){return this.sctpManager.sctpTransport}get sctpRemotePort(){return this.sctpManager.sctpRemotePort}get iceTransports(){return this.secureManager.iceTransports}get extIdUriMap(){return this.router.extIdUriMap}get iceGeneration(){return this.iceTransports[0].connection.generation}get localDescription(){return this.sdpManager.localDescription}get remoteDescription(){return this.sdpManager.remoteDescription}get remoteIsBundled(){return this.sdpManager.remoteIsBundled}get _localDescription(){return this.sdpManager._localDescription}get _remoteDescription(){return this.sdpManager._remoteDescription}getTransceivers(){return this.transceiverManager.getTransceivers()}getSenders(){return this.transceiverManager.getSenders()}getReceivers(){return this.transceiverManager.getReceivers()}setConfiguration(t){if(Vj(this.config,t),this.config.icePortRange){let[e,r]=this.config.icePortRange;if(e===r)throw new Error("should not be same value");if(e>=r)throw new Error("The min must be less than max")}if(!Number.isInteger(this.config.maxMessageSize)||this.config.maxMessageSize<0)throw new Error("maxMessageSize must be a non-negative integer");this.sctpManager?.sctpTransport&&(this.sctpManager.sctpTransport.maxMessageSize=this.config.maxMessageSize);for(let[e,r]of bU([...this.config.codecs.audio||[],...this.config.codecs.video||[]]))if(r.payloadType==null)switch(r.payloadType=96+e,r.name.toLowerCase()){case"rtx":r.parameters=`apt=${r.payloadType-1}`;break;case"red":if(r.contentType==="audio"){let s=r.payloadType+1;r.parameters=`${s}/${s}`,r.payloadType=63}break}[...this.config.headerExtensions.audio||[],...this.config.headerExtensions.video||[]].forEach((e,r)=>{e.id=1+r})}getConfiguration(){return this.config}async createOffer({iceRestart:t}={}){(t||this.needRestart)&&(this.needRestart=!1,this.secureManager.restartIce()),await this.secureManager.ensureCerts();for(let r of this.transceiverManager.getTransceivers())r.codecs.length===0&&this.transceiverManager.assignTransceiverCodecs(r),r.headerExtensions.length===0&&(r.headerExtensions=this.config.headerExtensions[r.kind]??[]);return this.sdpManager.buildOfferSdp(this.transceiverManager.getTransceivers(),this.sctpTransport).toJSON()}createSctpTransport(){let t=this.sctpManager.createSctpTransport(this.config.maxMessageSize),e=this.findOrCreateTransport();return t.setDtlsTransport(e),t}createDataChannel(t,e={}){this.sctpTransport||(this.createSctpTransport(),this.needNegotiation());let r=this.sctpManager.createDataChannel(t,e);if(!r.sctp.dtlsTransport){let s=this.findOrCreateTransport();r.sctp.setDtlsTransport(s)}return r}removeTrack(t){if(this.isClosed)throw new Error("peer closed");this.transceiverManager.removeTrack(t),this.needNegotiation()}needNegotiation=async()=>{this.shouldNegotiationneeded=!0,!(this.negotiationneeded||this.signalingState!=="stable")&&(this.shouldNegotiationneeded=!1,setImmediate(()=>{this.negotiationneeded=!0,this.onNegotiationneeded.execute(),this.onnegotiationneeded&&this.onnegotiationneeded({})}))};findOrCreateTransport(){let t=this.dtlsTransports.find(n=>n.state!=="closed"),e=t?.iceTransport;if((this.sdpManager.bundlePolicy==="max-bundle"||this.sdpManager.bundlePolicy!=="disable"&&(this.remoteIsBundled||this.remoteBundleNegotiated))&&t)return t;let r=this.secureManager.createTransport();r.onRtp.subscribe(n=>{this.router.routeRtp(n)}),r.onRtcp.subscribe(n=>{this.router.routeRtcp(n)});let s=r.iceTransport;return s.onNegotiationNeeded.subscribe(()=>{this.needNegotiation()}),s.onIceCandidate.subscribe(n=>{if(!this.localDescription){zn("localDescription not found when ice candidate was gathered");return}if(!n){this.sdpManager.setLocal(this._localDescription,this.transceiverManager.getTransceivers(),this.sctpTransport),this.onIceCandidate.execute(void 0),this.onicecandidate&&this.onicecandidate({candidate:void 0}),this.emit("icecandidate",{candidate:void 0});return}if(!this._localDescription){zn("localDescription not found when ice candidate was gathered");return}this.secureManager.handleNewIceCandidate({candidate:n,bundlePolicy:this.sdpManager.bundlePolicy,remoteIsBundled:!!this.sdpManager.remoteIsBundled,media:this._localDescription.media[0],transceiver:this.transceiverManager.getTransceivers().find(i=>i?.dtlsTransport?.iceTransport.id===s.id),sctpTransport:this.sctpTransport?.dtlsTransport.iceTransport.id===s.id?this.sctpTransport:void 0})}),r}async setLocalDescription(t){t=t??(["stable","have-local-offer","have-remote-pranswer"].includes(this.signalingState)?await this.createOffer():await this.createAnswer());let r=this.sdpManager.parseSdp({sdp:t.sdp,isLocal:!0,signalingState:this.signalingState,type:t.type});r.type==="offer"?this.setSignalingState("have-local-offer"):r.type==="answer"&&this.setSignalingState("stable");for(let[n,i]of bU(r.media)){let o=i.rtp.muxId;if(this.sdpManager.registerMid(o),["audio","video"].includes(i.kind)){let a=this.transceiverManager.getTransceiverByMLineIndex(n);a&&(a.mid=o)}i.kind==="application"&&this.sctpTransport&&(this.sctpTransport.mid=o)}let s=r.media.find(n=>n.dtlsParams)?.dtlsParams?.role;if(this.secureManager.setLocalRole({type:r.type,role:s}),["answer","pranswer"].includes(r.type))for(let n of this.transceiverManager.getTransceivers()){let i=PA(n.direction,n.offerDirection);n.setCurrentDirection(i)}return this.sdpManager.setLocal(r,this.transceiverManager.getTransceivers(),this.sctpTransport),await this.gatherCandidates().catch(n=>{zn("gatherCandidates failed",n)}),r.type==="answer"&&this.connect().catch(n=>{zn("connect failed",n),this.secureManager.setConnectionState("failed")}),this.sdpManager.setLocal(r,this.transceiverManager.getTransceivers(),this.sctpTransport),this.shouldNegotiationneeded&&this.needNegotiation(),r}async gatherCandidates(){await this.secureManager.gatherCandidates(!!this.sdpManager.remoteIsBundled)}async addIceCandidate(t){let e=this.sdpManager.buildOfferSdp(this.transceiverManager.getTransceivers(),this.sctpTransport);await this.secureManager.addIceCandidate(e,t)}async connect(){zn("start connect"),(await Promise.allSettled(this.dtlsTransports.map(async e=>{let{iceTransport:r}=e;if(r.state==="connected")return;let s=()=>e.state==="connected";s()||(this.secureManager.setConnectionState("connecting"),await r.start().catch(n=>{throw zn("iceTransport.start failed",n),n}),!s()&&(await e.start().catch(n=>{throw zn("dtlsTransport.start failed",n),n}),this.sctpTransport&&this.sctpTransport.dtlsTransport.id===e.id&&await this.sctpManager.connectSctp()))}))).find(e=>e.status==="rejected")?this.secureManager.setConnectionState("failed"):this.secureManager.setConnectionState("connected")}restartIce(){this.needRestart=!0,this.needNegotiation()}async setRemoteDescription(t){t instanceof P0&&(t=t.toSdp());let e=this.sdpManager.setRemoteDescription(t,this.signalingState);e.group.some(o=>o.semantic==="BUNDLE"&&o.items.length>0)&&(this.remoteBundleNegotiated=!0);let r,s=(o,a)=>o.kind===a.kind&&[void 0,a.rtp.muxId].includes(o.mid),n=e.media.map((o,a)=>{let c;if(["audio","video"].includes(o.kind)){let u=this.transceiverManager.getTransceivers().find(l=>s(l,o));if(!u)u=this.addTransceiver(o.kind,{direction:"recvonly"}),u.mid=o.rtp.muxId,this.onRemoteTransceiverAdded.execute(u);else if(u.direction==="inactive"&&u.stopping){u.stopped=!0,t.type==="answer"&&u.setCurrentDirection("inactive");return}this.sdpManager.remoteIsBundled&&(r?u.setDtlsTransport(r):r=u.dtlsTransport),c=u.dtlsTransport,this.transceiverManager.setRemoteRTP(u,o,e.type,a)}else if(o.kind==="application"){let u=this.sctpTransport;u||(u=this.createSctpTransport(),u.mid=o.rtp.muxId),this.sdpManager.remoteIsBundled&&(r?u.setDtlsTransport(r):r=u.dtlsTransport),c=u.dtlsTransport,this.sctpManager.setRemoteSCTP(o,a)}else throw new Error("invalid media kind");let d=c.iceTransport;if(o.iceParams){let u=!!this.sdpManager.inactiveRemoteMedia;d.setRemoteParams(o.iceParams,u),o.iceParams?.iceLite&&(d.connection.iceControlling=!0)}return o.dtlsParams&&c.setRemoteParams(o.dtlsParams),o.iceCandidates.forEach(d.addRemoteCandidate),o.iceCandidatesComplete&&d.addRemoteCandidate(void 0),e.type==="answer"&&o.dtlsParams?.role&&(c.role=o.dtlsParams.role==="client"?"server":"client"),d});n=n.filter(o=>!!o);let i=this.transceiverManager.getTransceivers().filter(o=>e.media.find(a=>s(o,a))==null);if(t.type==="answer")for(let o of i)o.stop(),o.stopped=!0;e.type==="offer"?this.setSignalingState("have-remote-offer"):e.type==="answer"&&this.setSignalingState("stable"),e.type==="answer"&&(zn("caller start connect"),this.connect().catch(o=>{zn("connect failed",o),this.secureManager.setConnectionState("failed")})),this.negotiationneeded=!1,this.shouldNegotiationneeded&&this.needNegotiation()}addTransceiver(t,e={}){let r=this.findOrCreateTransport(),s=this.transceiverManager.addTransceiver(t,r,e);return this.secureManager.updateIceConnectionState(),this.needNegotiation(),s}addTrack(t,e){if(this.isClosed)throw new Error("is closed");let r=this.transceiverManager.addTrack(t,e);if(!r.dtlsTransport){let s=this.findOrCreateTransport();r.setDtlsTransport(s)}return this.needNegotiation(),r.sender}async createAnswer(){return this.assertNotClosed(),await this.secureManager.ensureCerts(),this.sdpManager.buildAnswerSdp({transceivers:this.transceiverManager.getTransceivers(),sctpTransport:this.sctpTransport,signalingState:this.signalingState}).toJSON()}assertNotClosed(){if(this.isClosed)throw new Error("RTCPeerConnection is closed")}setSignalingState(t){zn("signalingStateChange",t),this.signalingState=t,this.signalingStateChange.execute(t),this.onsignalingstatechange&&this.onsignalingstatechange({})}createPeerConnectionStats(){let t=bc();return{type:"peer-connection",id:zt("peer-connection"),timestamp:t,dataChannelsOpened:this.sctpManager.dataChannelsOpened,dataChannelsClosed:this.sctpManager.dataChannelsClosed}}async getStats(t){let e=[];e.push(this.createPeerConnectionStats());let r=await this.transceiverManager.getStats(t);e.push(...r);let s=await this.secureManager.getStats();if(e.push(...s),this.sctpTransport){let n=await this.sctpManager.getStats();n&&e.push(...n)}return new Oj(e)}async close(){this.isClosed||(this.isClosed=!0,this.setSignalingState("closed"),this.transceiverManager.close(),await this.secureManager.close(),await this.sctpManager.close(),this.onDataChannel.allUnsubscribe(),this.iceGatheringStateChange.allUnsubscribe(),this.iceConnectionStateChange.allUnsubscribe(),this.signalingStateChange.allUnsubscribe(),this.onTransceiverAdded.allUnsubscribe(),this.onRemoteTransceiverAdded.allUnsubscribe(),this.onIceCandidate.allUnsubscribe(),zn("peerConnection closed"))}},Hk=(t,e)=>t.find(r=>r.mimeType.toLowerCase()===e.mimeType.toLowerCase())?e:void 0;bre=O$(),xre=ft("werift:packages/webrtc/src/media/rtpTransceiverManager.ts"),N$=class{constructor(t,e,r){this.cname=t,this.config=e,this.router=r}transceivers=[];onTransceiverAdded=new Ne;onRemoteTransceiverAdded=new Ne;onTrack=new Ne;onNegotiationNeeded=new Ne;getTransceivers(){return this.transceivers}getSenders(){return this.getTransceivers().map(t=>t.sender)}getReceivers(){return this.getTransceivers().map(t=>t.receiver)}getTransceiverByMLineIndex(t){return this.transceivers.find(e=>e.mLineIndex===t)}pushTransceiver(t){this.transceivers.push(t)}replaceTransceiver(t,e){this.transceivers[e]=t}addTransceiver(t,e,r={}){let s=typeof t=="string"?t:t.kind,n=r.direction||"sendrecv",i=new D$(t),o=new FA(this.config,s,i.ssrc),a=new Nj(s,e,o,i,n);a.options=r,this.router.registerRtpSender(a.sender);let c=this.transceivers.findIndex(u=>u.currentDirection==="inactive"&&!u.usedForSender),d=this.transceivers.find(u=>u.currentDirection==="inactive"&&!u.usedForSender);return c>-1&&d?(this.replaceTransceiver(a,c),a.mLineIndex=d.mLineIndex,a.mid=d.mid,d.setCurrentDirection(void 0)):this.pushTransceiver(a),this.onTransceiverAdded.execute(a),a}addTrack(t,e){if(this.getSenders().find(n=>n.track?.uuid===t.uuid))throw new Error("Track already added");let r=this.transceivers.find(n=>n.sender.track==null&&n.kind===t.kind&&$w.includes(n.direction)===!0);if(r)return r.sender.registerTrack(t),r;let s=this.transceivers.find(n=>n.sender.track==null&&n.kind===t.kind&&$w.includes(n.direction)===!1&&!n.usedForSender);if(s){switch(s.sender.registerTrack(t),s.direction){case"recvonly":s.setDirection("sendrecv");break;case"inactive":s.setDirection("sendonly");break}return s}else return this.addTransceiver(t,void 0,{direction:"sendrecv"})}removeTrack(t){if(!this.getSenders().find(({ssrc:r})=>t.ssrc===r))throw new Error("Sender does not exist");let e=this.transceivers.find(({sender:{ssrc:r}})=>t.ssrc===r);if(!e)throw new Error("No matching transceiver found");if(t.stop(),e.currentDirection==="recvonly"){this.onNegotiationNeeded.execute();return}e.stopping||e.stopped?e.setDirection("inactive"):e.direction==="sendrecv"?e.setDirection("recvonly"):(e.direction==="sendonly"||e.direction==="recvonly")&&e.setDirection("inactive")}assignTransceiverCodecs(t){let e=this.config.codecs[t.kind].filter(r=>{switch(r.direction){case"recvonly":return!!Ete.includes(t.direction);case"sendonly":return!!$w.includes(t.direction);case"sendrecv":return!![kA,TA,CA].includes(t.direction);case"all":return!0;default:return!1}});t.codecs=e}getLocalRtpParams(t){if(t.mid==null)throw new Error("mid not assigned");return{codecs:t.codecs,muxId:t.mid,headerExtensions:t.headerExtensions,rtcp:{cname:this.cname,ssrc:t.sender.ssrc,mux:!0}}}getRemoteRtpParams(t,e){return{muxId:t.rtp.muxId,rtcp:t.rtp.rtcp,codecs:e.codecs,headerExtensions:e.headerExtensions,encodings:Object.values(e.codecs.reduce((s,n)=>{if(n.name.toLowerCase()==="rtx"){let i=J0(n.parameters??""),o=s[i.apt];return o&&t.ssrc.length===2&&(o.rtx=new Cj({ssrc:t.ssrc[1].ssrc})),s}return s[n.payloadType]=new Tj({ssrc:t.ssrc[0]?.ssrc,payloadType:n.payloadType}),s},{}))}}setRemoteRTP(t,e,r,s){if(t.mid||(t.mid=e.rtp.muxId),t.mLineIndex=s,t.codecs=e.rtp.codecs.filter(a=>{let c=this.config.codecs[e.kind]||[],d=Hk(c,a);if(!d)return!1;if(d?.name.toLowerCase()==="rtx"){let l=J0(d.parameters??"").apt,h=e.rtp.codecs.find(p=>p.payloadType===l);return h?!!Hk(c,h):!1}return!0}),xre("negotiated codecs",t.codecs),t.codecs.length===0)throw new Error("negotiate codecs failed.");t.headerExtensions=e.rtp.headerExtensions.filter(a=>(this.config.headerExtensions[e.kind]||[]).find(c=>c.uri===a.uri));let n=e.direction??"inactive",i=$j(n);["answer","pranswer"].includes(r)?t.setCurrentDirection(i):t.offerDirection=i;let o=this.getLocalRtpParams(t);if(t.sender.prepareSend(o),["recvonly","sendrecv"].includes(t.direction)){let a=this.getRemoteRtpParams(e,t);for(let c of e.simulcastParameters)this.router.registerRtpReceiverByRid(t,c,a);t.receiver.prepareReceive(a),this.router.registerRtpReceiverBySsrc(t,a)}if(["sendonly","sendrecv"].includes(n)){if(e.msid){let[a,c]=e.msid.split(" ");t.receiver.remoteStreamId=a,t.receiver.remoteTrackId=c}this.onTrack.execute({track:t.receiver.track,transceiver:t,stream:new Mj({id:t.receiver.remoteStreamId,tracks:[t.receiver.track]})})}e.ssrc[0]?.ssrc&&t.receiver.setupTWCC(e.ssrc[0].ssrc)}async getStats(t){let e=[];for(let r of this.transceivers){let s=!t||r.sender.track===t||r.receiver.track===t;if(r.sender){let n=await r.sender.getStats();if(n)for(let i of n)i.type==="outbound-rtp"||i.type==="media-source"?s&&e.push(i):e.push(i)}if(r.receiver){let n=await r.receiver.getStats();if(n)for(let i of n)i.type==="inbound-rtp"||i.type==="remote-outbound-rtp"?s&&e.push(i):e.push(i)}if(s){let n=r.getCodecStats();n&&e.push(...n)}}return e}close(){for(let t of this.transceivers)t.receiver.stop(),t.sender.stop();this.onTransceiverAdded.allUnsubscribe(),this.onRemoteTransceiverAdded.allUnsubscribe(),this.onTrack.allUnsubscribe(),this.onNegotiationNeeded.allUnsubscribe()}},wre=["stable","have-local-offer","have-remote-offer","have-local-pranswer","have-remote-pranswer","closed"],vre=["closed","failed","disconnected","new","connecting","connected"]});var bae={};sa(bae,{SessionPool:()=>gv,URUN_API:()=>yR,applyServeUsage:()=>Sq,coalesceSameRole:()=>_q,createFileDiagnosticSink:()=>xq,createUrunExtension:()=>xv,default:()=>yae,makeSessionFactory:()=>bv,makeStreamSimple:()=>Eq,notify:()=>gR,piDiagnosticLogPath:()=>Mg,resolveSessionEnv:()=>bq,toResponsesInput:()=>vq});module.exports=Sv(bae);g();y();var _Ue=Le(Tv(),1);var fR={};sa(fR,{ACTIVATION_COLD_BOOT_AFTER_MS:()=>RH,ACTIVATION_DEGRADED_AFTER_MS:()=>PH,ACTIVATION_HINT_PATH:()=>SI,ACTIVATION_STILL_AFTER_MS:()=>IH,ACTIVITY_DOM_EVENTS:()=>av,ACTIVITY_FIELD:()=>LI,ACTIVITY_STAMP_MIN_INTERVAL_MS:()=>UH,ActivationMonitor:()=>TI,App:()=>KH,BACKOFF_BASE_MS:()=>G1,BACKOFF_MAX_ATTEMPTS:()=>Wh,BACKOFF_MAX_MS:()=>vg,COLD_BOOT_WHEN_LIVE_TIMEOUT_MS:()=>L1,CaptureController:()=>nq,CaptureUnavailableError:()=>sq,ClientTokenError:()=>Dg,CreditsClient:()=>rq,CreditsError:()=>hv,CreditsUnauthorizedError:()=>uR,DATA_CHANNEL_MESSAGE_CEILING:()=>Boe,DEFAULT_DOC_SYNC_TIMEOUT_MS:()=>sR,DEFAULT_GATEWAY_URL:()=>eq,DEFAULT_PRODUCE_ACK_TIMEOUT_MS:()=>fg,DEFAULT_REFERENCE_JPEG_QUALITY:()=>Doe,DEFAULT_REFERENCE_MAX_SIZE:()=>Poe,DEFAULT_WHEN_LIVE_TIMEOUT_MS:()=>QA,DERIVED_LEG_SEP:()=>Xh,DGRAM_HEADER_BYTES:()=>ei,FOCUS_FIELD:()=>MI,FOREGROUND_COALESCE_MS:()=>jH,FrameReassembler:()=>GI,GENERATION_TICK_EMIT_INTERVAL_MS:()=>OH,GENERATION_TICK_MAX_EXTRAPOLATION_MS:()=>NH,INPUT_PRESENCE_DEFAULT_HZ:()=>Ioe,INPUT_PRESENCE_FIELD:()=>iq,InvalidDurationError:()=>Pg,LEGACY_ACTIVATION_HINT_PATH:()=>EI,PLATFORM_DOC_NAME:()=>_I,PermanentLockedError:()=>DI,PinRequiresActiveTempError:()=>PI,PresenceTracker:()=>jI,ProduceAckTimeoutError:()=>JA,RecordingNotFoundError:()=>II,RecordingsClient:()=>lv,RecordingsError:()=>Xi,RecordingsUnauthorizedError:()=>cv,RequestAbortError:()=>wg,RequestCancelledError:()=>V1,RequestDocSyncError:()=>H1,RequestError:()=>ta,RequestTimeoutError:()=>F1,RetainNotTempError:()=>RI,RuntimeArtifactNotFoundError:()=>AI,RuntimeArtifactsClient:()=>Rg,RuntimeArtifactsError:()=>Ys,RuntimeArtifactsUnauthorizedError:()=>kI,SIGNALING_PROTOCOL_VERSION:()=>iI,STREAM_END:()=>Cl,Session:()=>nR,SessionAllocationError:()=>Cr,SessionDirectory:()=>aR,SessionDirectoryError:()=>Gi,SessionEndError:()=>Sn,SessionEndUnavailableError:()=>El,SessionFailedError:()=>Sl,StreamDirectionConflict:()=>q1,TransportNegotiator:()=>eR,TransportSessionMismatchError:()=>B1,TransportSessionSignaling:()=>tR,URUN_DEV_ENV:()=>tq,USER_ACTIVITY_FIELD:()=>UI,USER_ACTIVITY_MIN_INTERVAL_MS:()=>MH,VISIBILITY_FIELD:()=>OI,WIRE_MESSAGE_BUDGET:()=>Loe,WT_CONTROL_FRAME_MAX:()=>VI,WT_DATA_STREAM_VERSION:()=>XI,WebRtcSession:()=>rR,WebTransportSession:()=>ZI,WtControlDecoder:()=>WI,WtDataStreamParser:()=>YI,activationHintFrom:()=>CI,cameraCaptureAvailable:()=>$oe,captureStillFromVideo:()=>Foe,computeBackoffDelay:()=>_g,consumeWtDataStreams:()=>JI,createActivityTracker:()=>NI,createCameraWarp:()=>qoe,createClientToken:()=>yoe,createCreditsClient:()=>Eoe,createInputPresencePublisher:()=>Roe,createRecordingsClient:()=>LH,createRuntimeArtifactsClient:()=>DH,createStore:()=>xoe,decodeStreamEnvelope:()=>Z1,derivedLegName:()=>KF,derivedLegRole:()=>U1,describeSessionFailure:()=>z1,describeSessionPhase:()=>AF,encodeStreamEnvelope:()=>Q1,encodeWtControlFrame:()=>zI,fitWithin:()=>hR,isDurationString:()=>dv,isPausedPhase:()=>kF,isPendingRecording:()=>_oe,isRetryableSessionError:()=>X1,isWakingPhase:()=>xc,mediaRecorderChunkSource:()=>qI,normalizeReferenceImage:()=>Moe,normalizeRetention:()=>BH,observeLeaveConfirm:()=>HI,observePageLifecycle:()=>$I,observePageTeardown:()=>FI,parseDgramHeader:()=>uv,prewake:()=>FF,referenceImageErrorMessage:()=>joe,releaseSessionBeacon:()=>Eg,sessionDirectory:()=>WH,sessionFailureFromMediaError:()=>TF,sharedCaptureController:()=>Aoe,videoStream:()=>voe,watchGenerationTick:()=>BI,whenLive:()=>W1,writeDgramHeader:()=>KI});g();y();var ZH=require("module");g();y();var AH=require("module");g();y();var fF=require("module");g();y();var CR=require("module"),Dl=globalThis.require??(0,CR.createRequire)(L),Pq=Object.create,jg=Object.defineProperty,Dq=Object.getOwnPropertyDescriptor,Bq=Object.getOwnPropertyNames,Lq=Object.getPrototypeOf,Oq=Object.prototype.hasOwnProperty,kv=(t=>typeof Dl<"u"?Dl:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof Dl<"u"?Dl:e)[r]}):t)(function(t){if(typeof Dl<"u")return Dl.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')}),TR=(t,e,r)=>()=>{if(r)throw r[0];try{return t&&(e=t(t=0)),e}catch(s){throw r=[s],s}},nt=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(r){throw e=0,r}},kR=(t,e)=>{for(var r in e)jg(t,r,{get:e[r],enumerable:!0})},AR=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Bq(e))!Oq.call(t,n)&&n!==r&&jg(t,n,{get:()=>e[n],enumerable:!(s=Dq(e,n))||s.enumerable});return t},Av=(t,e,r)=>(r=t!=null?Pq(Lq(t)):{},AR(e||!t||!t.__esModule?jg(r,"default",{value:t,enumerable:!0}):r,t)),IR=t=>AR(jg({},"__esModule",{value:!0}),t);var j1=Le(require("process"),1),gF=Le(require("os"),1),qA=Le(require("tty"),1);g();y();var pde=Le(ru(),1);g();y();lf();Hg();e_();Vv();var B6=new Map,N_=class{constructor(e){this.room=e,this.onmessage=null,this._onChange=r=>r.key===e&&this.onmessage!==null&&this.onmessage({data:m3(r.newValue||"")}),e3(this._onChange)}postMessage(e){ey.setItem(this.room,p3(f3(e)))}close(){t3(this._onChange)}},tW=typeof BroadcastChannel>"u"?N_:BroadcastChannel,U_=t=>Br(B6,t,()=>{let e=ri(),r=new tW(t);return r.onmessage=s=>e.forEach(n=>n(s.data,"broadcastchannel")),{bc:r,subs:e}}),L6=(t,e)=>(U_(t).subs.add(e),e),O6=(t,e)=>{let r=U_(t),s=r.subs.delete(e);return s&&r.subs.size===0&&(r.bc.close(),B6.delete(t)),s},Vc=(t,e,r=null)=>{let s=U_(t);s.bc.postMessage(e),s.subs.forEach(n=>n(e,r))};wf();gf();Kl();g();y();gf();Kl();var su=Le(ru(),1),N6=0,Ay=1,U6=2,Iy=(t,e)=>{De(t,N6);let r=su.encodeStateVector(e);er(t,r)},M_=(t,e,r)=>{De(t,Ay),er(t,su.encodeStateAsUpdate(e,r))},sW=(t,e,r)=>M_(e,r,Ar(t)),M6=(t,e,r,s)=>{try{su.applyUpdate(e,Ar(t),r)}catch(n){s?.(n),E.error("Caught error while handling a Yjs update",n)}},j6=(t,e)=>{De(t,U6),er(t,e)},nW=M6,$6=(t,e,r,s,n)=>{let i=st(t);switch(i){case N6:sW(t,e,r);break;case Ay:M6(t,r,s,n);break;case U6:nW(t,r,s,n);break;default:throw new Error("Unknown message type")}return i};g();y();var ide=Le(ru(),1);Kl();var oW=0;var F6=(t,e,r)=>{st(t)===oW&&r(e,en(t))};g();y();gf();Kl();wf();Tc();Wg();Sf();var dde=Le(ru(),1),j_=3e4,nu=class extends zg{constructor(e){super(),this.doc=e,this.clientID=e.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{let r=Ms();this.getLocalState()!==null&&j_/2<=r-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());let s=[];this.meta.forEach((n,i)=>{i!==this.clientID&&j_<=r-n.lastUpdated&&this.states.has(i)&&s.push(i)}),s.length>0&&Ry(this,s,"timeout")},ws(j_/10)),e.on("destroy",()=>{this.destroy()}),this.setLocalState({})}destroy(){this.emit("destroy",[this]),this.setLocalState(null),super.destroy(),clearInterval(this._checkInterval)}getLocalState(){return this.states.get(this.clientID)||null}setLocalState(e){let r=this.clientID,s=this.meta.get(r),n=s===void 0?0:s.clock+1,i=this.states.get(r);e===null?this.states.delete(r):this.states.set(r,e),this.meta.set(r,{clock:n,lastUpdated:Ms()});let o=[],a=[],c=[],d=[];e===null?d.push(r):i==null?e!=null&&o.push(r):(a.push(r),Gl(i,e)||c.push(r)),(o.length>0||c.length>0||d.length>0)&&this.emit("change",[{added:o,updated:c,removed:d},"local"]),this.emit("update",[{added:o,updated:a,removed:d},"local"])}setLocalStateField(e,r){let s=this.getLocalState();s!==null&&this.setLocalState({...s,[e]:r})}getStates(){return this.states}},Ry=(t,e,r)=>{let s=[];for(let n=0;n<e.length;n++){let i=e[n];if(t.states.has(i)){if(t.states.delete(i),i===t.clientID){let o=t.meta.get(i);t.meta.set(i,{clock:o.clock+1,lastUpdated:Ms()})}s.push(i)}}s.length>0&&(t.emit("change",[{added:[],updated:[],removed:s},r]),t.emit("update",[{added:[],updated:[],removed:s},r]))},iu=(t,e,r=t.states)=>{let s=e.length,n=pr();De(n,s);for(let i=0;i<s;i++){let o=e[i],a=r.get(o)||null,c=t.meta.get(o).clock;De(n,o),De(n,c),si(n,JSON.stringify(a))}return Ft(n)};var H6=(t,e,r)=>{let s=mr(e),n=Ms(),i=[],o=[],a=[],c=[],d=st(s);for(let u=0;u<d;u++){let l=st(s),h=st(s),p=JSON.parse(en(s)),m=t.meta.get(l),_=t.states.get(l),f=m===void 0?0:m.clock;(f<h||f===h&&p===null&&t.states.has(l))&&(p===null?l===t.clientID&&t.getLocalState()!=null?h++:t.states.delete(l):t.states.set(l,p),t.meta.set(l,{clock:h,lastUpdated:n}),m===void 0&&p!==null?i.push(l):m!==void 0&&p===null?c.push(l):p!==null&&(Gl(p,_)||a.push(l),o.push(l)))}(i.length>0||a.length>0||c.length>0)&&t.emit("change",[{added:i,updated:a,removed:c},r]),(i.length>0||o.length>0||c.length>0)&&t.emit("update",[{added:i,updated:o,removed:c},r])};Wg();Tc();g();y();ry();var q6=t=>a3(t,(e,r)=>`${encodeURIComponent(r)}=${encodeURIComponent(e)}`).join("&");Cf();var zc=0,z6=3,ou=1,lW=2,Hf=[];Hf[zc]=(t,e,r,s,n)=>{De(t,zc);let i=$6(e,t,r.doc,r);s&&i===Ay&&!r.synced&&(r.synced=!0)};Hf[z6]=(t,e,r,s,n)=>{De(t,ou),er(t,iu(r.awareness,Array.from(r.awareness.getStates().keys())))};Hf[ou]=(t,e,r,s,n)=>{H6(r.awareness,Ar(e),r)};Hf[lW]=(t,e,r,s,n)=>{F6(e,r.doc,(i,o)=>uW(r,o))};var V6=3e4,uW=(t,e)=>E.warn(`Permission denied to access ${t.url}.
|
|
141
141
|
${e}`),W6=(t,e,r)=>{let s=mr(e),n=pr(),i=st(s),o=t.messageHandlers[i];return o?o(n,s,t,r,i):E.error("Unable to compute message"),n},F_=(t,e,r)=>{e===t.ws&&(t.emit("connection-close",[r,t]),t.ws=null,e.close(),t.wsconnecting=!1,t.wsconnected?(t.wsconnected=!1,t.synced=!1,Ry(t.awareness,Array.from(t.awareness.getStates().keys()).filter(s=>s!==t.doc.clientID),t),t.emit("status",[{status:"disconnected"}])):t.wsUnsuccessfulReconnects++,setTimeout(K6,Ll(LR(2,t.wsUnsuccessfulReconnects)*100,t.maxBackoffTime),t))},K6=t=>{if(t.shouldConnect&&t.ws===null){let e=new t._WS(t.url,t.protocols);e.binaryType="arraybuffer",t.ws=e,t.wsconnecting=!0,t.wsconnected=!1,t.synced=!1,e.onmessage=r=>{t.wsLastMessageReceived=Ms();let s=W6(t,new Uint8Array(r.data),!0);Xg(s)>1&&e.send(Ft(s))},e.onerror=r=>{t.emit("connection-error",[r,t])},e.onclose=r=>{F_(t,e,r)},e.onopen=()=>{t.wsLastMessageReceived=Ms(),t.wsconnecting=!1,t.wsconnected=!0,t.wsUnsuccessfulReconnects=0,t.emit("status",[{status:"connected"}]);let r=pr();if(De(r,zc),Iy(r,t.doc),e.send(Ft(r)),t.awareness.getLocalState()!==null){let s=pr();De(s,ou),er(s,iu(t.awareness,[t.doc.clientID])),e.send(Ft(s))}},t.emit("status",[{status:"connecting"}])}},$_=(t,e)=>{let r=t.ws;t.wsconnected&&r&&r.readyState===r.OPEN&&r.send(e),t.bcconnected&&Vc(t.bcChannel,e,t)},Py=class extends na{constructor(e,r,s,{connect:n=!0,awareness:i=new nu(s),params:o={},protocols:a=[],WebSocketPolyfill:c=WebSocket,resyncInterval:d=-1,maxBackoffTime:u=2500,disableBc:l=!1}={}){for(super();e[e.length-1]==="/";)e=e.slice(0,e.length-1);this.serverUrl=e,this.bcChannel=e+"/"+r,this.maxBackoffTime=u,this.params=o,this.protocols=a,this.roomname=r,this.doc=s,this._WS=c,this.awareness=i,this.wsconnected=!1,this.wsconnecting=!1,this.bcconnected=!1,this.disableBc=l,this.wsUnsuccessfulReconnects=0,this.messageHandlers=Hf.slice(),this._synced=!1,this.ws=null,this.wsLastMessageReceived=0,this.shouldConnect=n,this._resyncInterval=0,d>0&&(this._resyncInterval=setInterval(()=>{if(this.ws&&this.ws.readyState===WebSocket.OPEN){let h=pr();De(h,zc),Iy(h,s),this.ws.send(Ft(h))}},d)),this._bcSubscriber=(h,p)=>{if(p!==this){let m=W6(this,new Uint8Array(h),!1);Xg(m)>1&&Vc(this.bcChannel,Ft(m),this)}},this._updateHandler=(h,p)=>{if(p!==this){let m=pr();De(m,zc),j6(m,h),$_(this,Ft(m))}},this.doc.on("update",this._updateHandler),this._awarenessUpdateHandler=({added:h,updated:p,removed:m},_)=>{let f=h.concat(p).concat(m),b=pr();De(b,ou),er(b,iu(i,f)),$_(this,Ft(b))},this._exitHandler=()=>{Ry(this.awareness,[s.clientID],"app closed")},Qi&&typeof process<"u"&&process.on("exit",this._exitHandler),i.on("update",this._awarenessUpdateHandler),this._checkInterval=setInterval(()=>{this.wsconnected&&V6<Ms()-this.wsLastMessageReceived&&F_(this,this.ws,null)},V6/10),n&&this.connect()}get url(){let e=q6(this.params);return this.serverUrl+"/"+this.roomname+(e.length===0?"":"?"+e)}get synced(){return this._synced}set synced(e){this._synced!==e&&(this._synced=e,this.emit("synced",[e]),this.emit("sync",[e]))}destroy(){this._resyncInterval!==0&&clearInterval(this._resyncInterval),clearInterval(this._checkInterval),this.disconnect(),Qi&&typeof process<"u"&&process.off("exit",this._exitHandler),this.awareness.off("update",this._awarenessUpdateHandler),this.doc.off("update",this._updateHandler),super.destroy()}connectBc(){if(this.disableBc)return;this.bcconnected||(L6(this.bcChannel,this._bcSubscriber),this.bcconnected=!0);let e=pr();De(e,zc),Iy(e,this.doc),Vc(this.bcChannel,Ft(e),this);let r=pr();De(r,zc),M_(r,this.doc),Vc(this.bcChannel,Ft(r),this);let s=pr();De(s,z6),Vc(this.bcChannel,Ft(s),this);let n=pr();De(n,ou),er(n,iu(this.awareness,[this.doc.clientID])),Vc(this.bcChannel,Ft(n),this)}disconnectBc(){let e=pr();De(e,ou),er(e,iu(this.awareness,[this.doc.clientID],new Map)),$_(this,Ft(e)),this.bcconnected&&(O6(this.bcChannel,this._bcSubscriber),this.bcconnected=!1)}disconnect(){this.shouldConnect=!1,this.disconnectBc(),this.ws!==null&&F_(this,this.ws,null)}connect(){this.shouldConnect=!0,!this.wsconnected&&this.ws===null&&(K6(this),this.connectBc())}};var pg=Le(ru(),1),r9e=globalThis.require??(0,fF.createRequire)(L),_re=nt((t,e)=>{"use strict";var r=1e3,s=r*60,n=s*60,i=n*24,o=i*7,a=i*365.25;e.exports=function(h,p){p=p||{};var m=typeof h;if(m==="string"&&h.length>0)return c(h);if(m==="number"&&isFinite(h))return p.long?u(h):d(h);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(h))};function c(h){if(h=String(h),!(h.length>100)){var p=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(h);if(p){var m=parseFloat(p[1]),_=(p[2]||"ms").toLowerCase();switch(_){case"years":case"year":case"yrs":case"yr":case"y":return m*a;case"weeks":case"week":case"w":return m*o;case"days":case"day":case"d":return m*i;case"hours":case"hour":case"hrs":case"hr":case"h":return m*n;case"minutes":case"minute":case"mins":case"min":case"m":return m*s;case"seconds":case"second":case"secs":case"sec":case"s":return m*r;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return m;default:return}}}}function d(h){var p=Math.abs(h);return p>=i?Math.round(h/i)+"d":p>=n?Math.round(h/n)+"h":p>=s?Math.round(h/s)+"m":p>=r?Math.round(h/r)+"s":h+"ms"}function u(h){var p=Math.abs(h);return p>=i?l(h,p,i,"day"):p>=n?l(h,p,n,"hour"):p>=s?l(h,p,s,"minute"):p>=r?l(h,p,r,"second"):h+" ms"}function l(h,p,m,_){var f=p>=m*1.5;return Math.round(h/m)+" "+_+(f?"s":"")}}),pF=nt((t,e)=>{"use strict";function r(s){i.debug=i,i.default=i,i.coerce=l,i.disable=d,i.enable=a,i.enabled=u,i.humanize=_re(),i.destroy=h,Object.keys(s).forEach(p=>{i[p]=s[p]}),i.names=[],i.skips=[],i.formatters={};function n(p){let m=0;for(let _=0;_<p.length;_++)m=(m<<5)-m+p.charCodeAt(_),m|=0;return i.colors[Math.abs(m)%i.colors.length]}i.selectColor=n;function i(p){let m,_=null,f,b;function w(...S){if(!w.enabled)return;let O=w,j=Number(new Date),P=j-(m||j);O.diff=P,O.prev=m,O.curr=j,m=j,S[0]=i.coerce(S[0]),typeof S[0]!="string"&&S.unshift("%O");let k=0;S[0]=S[0].replace(/%([a-zA-Z%])/g,(C,D)=>{if(C==="%%")return"%";k++;let H=i.formatters[D];if(typeof H=="function"){let W=S[k];C=H.call(O,W),S.splice(k,1),k--}return C}),i.formatArgs.call(O,S),(O.log||i.log).apply(O,S)}return w.namespace=p,w.useColors=i.useColors(),w.color=i.selectColor(p),w.extend=o,w.destroy=i.destroy,Object.defineProperty(w,"enabled",{enumerable:!0,configurable:!1,get:()=>_!==null?_:(f!==i.namespaces&&(f=i.namespaces,b=i.enabled(p)),b),set:S=>{_=S}}),typeof i.init=="function"&&i.init(w),w}function o(p,m){let _=i(this.namespace+(typeof m>"u"?":":m)+p);return _.log=this.log,_}function a(p){i.save(p),i.namespaces=p,i.names=[],i.skips=[];let m=(typeof p=="string"?p:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let _ of m)_[0]==="-"?i.skips.push(_.slice(1)):i.names.push(_)}function c(p,m){let _=0,f=0,b=-1,w=0;for(;_<p.length;)if(f<m.length&&(m[f]===p[_]||m[f]==="*"))m[f]==="*"?(b=f,w=_,f++):(_++,f++);else if(b!==-1)f=b+1,w++,_=w;else return!1;for(;f<m.length&&m[f]==="*";)f++;return f===m.length}function d(){let p=[...i.names,...i.skips.map(m=>"-"+m)].join(",");return i.enable(""),p}function u(p){for(let m of i.skips)if(c(p,m))return!1;for(let m of i.names)if(c(p,m))return!0;return!1}function l(p){return p instanceof Error?p.stack||p.message:p}function h(){E.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return i.enable(i.load()),i}e.exports=r}),Sre=nt((t,e)=>{"use strict";t.formatArgs=s,t.save=n,t.load=i,t.useColors=r,t.storage=o(),t.destroy=(()=>{let c=!1;return()=>{c||(c=!0,E.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function r(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let c;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(c=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(c[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function s(c){if(c[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+c[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;let d="color: "+this.color;c.splice(1,0,d,"color: inherit");let u=0,l=0;c[0].replace(/%[a-zA-Z%]/g,h=>{h!=="%%"&&(u++,h==="%c"&&(l=u))}),c.splice(l,0,d)}t.log=E.debug||E.log||(()=>{});function n(c){try{c?t.storage.setItem("debug",c):t.storage.removeItem("debug")}catch{}}function i(){let c;try{c=t.storage.getItem("debug")||t.storage.getItem("DEBUG")}catch{}return!c&&typeof process<"u"&&"env"in process&&(c=process.env.DEBUG),c}function o(){try{return localStorage}catch{}}e.exports=pF()(t);var{formatters:a}=e.exports;a.j=function(c){try{return JSON.stringify(c)}catch(d){return"[UnexpectedJSONParseError]: "+d.message}}}),mF={};kR(mF,{createSupportsColor:()=>VA,default:()=>yF});function _n(t,e=globalThis.Deno?globalThis.Deno.args:j1.default.argv){let r=t.startsWith("-")?"":t.length===1?"-":"--",s=e.indexOf(r+t),n=e.indexOf("--");return s!==-1&&(n===-1||s<n)}function Ere(){if(!("FORCE_COLOR"in Zt))return;if(Zt.FORCE_COLOR==="true")return 1;if(Zt.FORCE_COLOR==="false")return 0;if(Zt.FORCE_COLOR.length===0)return 1;let t=Math.min(Number.parseInt(Zt.FORCE_COLOR,10),3);if([0,1,2,3].includes(t))return t}function Cre(t){return t===0?!1:{level:t,hasBasic:!0,has256:t>=2,has16m:t>=3}}function Tre(t,{streamIsTTY:e,sniffFlags:r=!0}={}){let s=Ere();s!==void 0&&(D1=s);let n=r?D1:s;if(n===0)return 0;if(r){if(_n("color=16m")||_n("color=full")||_n("color=truecolor"))return 3;if(_n("color=256"))return 2}if("TF_BUILD"in Zt&&"AGENT_NAME"in Zt)return 1;if(t&&!e&&n===void 0)return 0;let i=n||0;if(Zt.TERM==="dumb")return i;if(j1.default.platform==="win32"){let o=gF.default.release().split(".");return Number(o[0])>=10&&Number(o[2])>=10586?Number(o[2])>=14931?3:2:1}if("CI"in Zt)return["GITHUB_ACTIONS","GITEA_ACTIONS","CIRCLECI"].some(o=>o in Zt)?3:["TRAVIS","APPVEYOR","GITLAB_CI","BUILDKITE","DRONE"].some(o=>o in Zt)||Zt.CI_NAME==="codeship"?1:i;if("TEAMCITY_VERSION"in Zt)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(Zt.TEAMCITY_VERSION)?1:0;if(Zt.COLORTERM==="truecolor"||Zt.TERM==="xterm-kitty"||Zt.TERM==="xterm-ghostty"||Zt.TERM==="wezterm")return 3;if("TERM_PROGRAM"in Zt){let o=Number.parseInt((Zt.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(Zt.TERM_PROGRAM){case"iTerm.app":return o>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(Zt.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(Zt.TERM)||"COLORTERM"in Zt?1:i}function VA(t,e={}){let r=Tre(t,{streamIsTTY:t&&t.isTTY,...e});return Cre(r)}var Zt,D1,j$,yF,kre=TR(()=>{"use strict";({env:Zt}=j1.default),_n("no-color")||_n("no-colors")||_n("color=false")||_n("color=never")?D1=0:(_n("color")||_n("colors")||_n("color=true")||_n("color=always"))&&(D1=1),j$={stdout:VA({isTTY:qA.default.isatty(1)}),stderr:VA({isTTY:qA.default.isatty(2)})},yF=j$}),Are=nt((t,e)=>{"use strict";var r=kv("tty"),s=kv("util");t.init=u,t.log=a,t.formatArgs=i,t.save=c,t.load=d,t.useColors=n,t.destroy=s.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."),t.colors=[6,2,3,4,5,1];try{let h=(kre(),IR(mF));h&&(h.stderr||h).level>=2&&(t.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}t.inspectOpts=Object.keys(process.env).filter(h=>/^debug_/i.test(h)).reduce((h,p)=>{let m=p.substring(6).toLowerCase().replace(/_([a-z])/g,(f,b)=>b.toUpperCase()),_=process.env[p];return/^(yes|on|true|enabled)$/i.test(_)?_=!0:/^(no|off|false|disabled)$/i.test(_)?_=!1:_==="null"?_=null:_=Number(_),h[m]=_,h},{});function n(){return"colors"in t.inspectOpts?!!t.inspectOpts.colors:r.isatty(process.stderr.fd)}function i(h){let{namespace:p,useColors:m}=this;if(m){let _=this.color,f="\x1B[3"+(_<8?_:"8;5;"+_),b=` ${f};1m${p} \x1B[0m`;h[0]=b+h[0].split(`
|
|
142
142
|
`).join(`
|
|
143
143
|
`+b),h.push(f+"m+"+e.exports.humanize(this.diff)+"\x1B[0m")}else h[0]=o()+p+" "+h[0]}function o(){return t.inspectOpts.hideDate?"":new Date().toISOString()+" "}function a(...h){return process.stderr.write(s.formatWithOptions(t.inspectOpts,...h)+`
|
|
144
144
|
`)}function c(h){h?process.env.DEBUG=h:delete process.env.DEBUG}function d(){return process.env.DEBUG}function u(h){h.inspectOpts={};let p=Object.keys(t.inspectOpts);for(let m=0;m<p.length;m++)h.inspectOpts[p[m]]=t.inspectOpts[p[m]]}e.exports=pF()(t);var{formatters:l}=e.exports;l.o=function(h){return this.inspectOpts.colors=this.useColors,s.inspect(h,this.inspectOpts).split(`
|
|
145
145
|
`).map(p=>p.trim()).join(" ")},l.O=function(h){return this.inspectOpts.colors=this.useColors,s.inspect(h,this.inspectOpts)}}),$1=nt((t,e)=>{"use strict";typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?e.exports=Sre():e.exports=Are()}),Ire=nt(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0})}),Os=nt(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Logger=void 0;var e=$1(),r="media-client",s=class{_debug;_warn;_error;constructor(n){n?(this._debug=(0,e.default)(`${r}:${n}`),this._warn=(0,e.default)(`${r}:WARN:${n}`),this._error=(0,e.default)(`${r}:ERROR:${n}`)):(this._debug=(0,e.default)(r),this._warn=(0,e.default)(`${r}:WARN`),this._error=(0,e.default)(`${r}:ERROR`)),this._debug.log=E.info.bind(E),this._warn.log=E.warn.bind(E),this._error.log=E.error.bind(E)}get debug(){return this._debug}get warn(){return this._warn}get error(){return this._error}};t.Logger=s}),Rre=nt((t,e)=>{"use strict";var r=typeof Reflect=="object"?Reflect:null,s=r&&typeof r.apply=="function"?r.apply:function(P,k,C){return Function.prototype.apply.call(P,k,C)},n;r&&typeof r.ownKeys=="function"?n=r.ownKeys:Object.getOwnPropertySymbols?n=function(P){return Object.getOwnPropertyNames(P).concat(Object.getOwnPropertySymbols(P))}:n=function(P){return Object.getOwnPropertyNames(P)};function i(P){E&&E.warn&&E.warn(P)}var o=Number.isNaN||function(P){return P!==P};function a(){a.init.call(this)}e.exports=a,e.exports.once=S,a.EventEmitter=a,a.prototype._events=void 0,a.prototype._eventsCount=0,a.prototype._maxListeners=void 0;var c=10;function d(P){if(typeof P!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof P)}Object.defineProperty(a,"defaultMaxListeners",{enumerable:!0,get:function(){return c},set:function(P){if(typeof P!="number"||P<0||o(P))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+P+".");c=P}}),a.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},a.prototype.setMaxListeners=function(P){if(typeof P!="number"||P<0||o(P))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+P+".");return this._maxListeners=P,this};function u(P){return P._maxListeners===void 0?a.defaultMaxListeners:P._maxListeners}a.prototype.getMaxListeners=function(){return u(this)},a.prototype.emit=function(P){for(var k=[],C=1;C<arguments.length;C++)k.push(arguments[C]);var D=P==="error",H=this._events;if(H!==void 0)D=D&&H.error===void 0;else if(!D)return!1;if(D){var W;if(k.length>0&&(W=k[0]),W instanceof Error)throw W;var J=new Error("Unhandled error."+(W?" ("+W.message+")":""));throw J.context=W,J}var F=H[P];if(F===void 0)return!1;if(typeof F=="function")s(F,this,k);else for(var q=F.length,Q=f(F,q),C=0;C<q;++C)s(Q[C],this,k);return!0};function l(P,k,C,D){var H,W,J;if(d(C),W=P._events,W===void 0?(W=P._events=Object.create(null),P._eventsCount=0):(W.newListener!==void 0&&(P.emit("newListener",k,C.listener?C.listener:C),W=P._events),J=W[k]),J===void 0)J=W[k]=C,++P._eventsCount;else if(typeof J=="function"?J=W[k]=D?[C,J]:[J,C]:D?J.unshift(C):J.push(C),H=u(P),H>0&&J.length>H&&!J.warned){J.warned=!0;var F=new Error("Possible EventEmitter memory leak detected. "+J.length+" "+String(k)+" listeners added. Use emitter.setMaxListeners() to increase limit");F.name="MaxListenersExceededWarning",F.emitter=P,F.type=k,F.count=J.length,i(F)}return P}a.prototype.addListener=function(P,k){return l(this,P,k,!1)},a.prototype.on=a.prototype.addListener,a.prototype.prependListener=function(P,k){return l(this,P,k,!0)};function h(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function p(P,k,C){var D={fired:!1,wrapFn:void 0,target:P,type:k,listener:C},H=h.bind(D);return H.listener=C,D.wrapFn=H,H}a.prototype.once=function(P,k){return d(k),this.on(P,p(this,P,k)),this},a.prototype.prependOnceListener=function(P,k){return d(k),this.prependListener(P,p(this,P,k)),this},a.prototype.removeListener=function(P,k){var C,D,H,W,J;if(d(k),D=this._events,D===void 0)return this;if(C=D[P],C===void 0)return this;if(C===k||C.listener===k)--this._eventsCount===0?this._events=Object.create(null):(delete D[P],D.removeListener&&this.emit("removeListener",P,C.listener||k));else if(typeof C!="function"){for(H=-1,W=C.length-1;W>=0;W--)if(C[W]===k||C[W].listener===k){J=C[W].listener,H=W;break}if(H<0)return this;H===0?C.shift():b(C,H),C.length===1&&(D[P]=C[0]),D.removeListener!==void 0&&this.emit("removeListener",P,J||k)}return this},a.prototype.off=a.prototype.removeListener,a.prototype.removeAllListeners=function(P){var k,C,D;if(C=this._events,C===void 0)return this;if(C.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):C[P]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete C[P]),this;if(arguments.length===0){var H=Object.keys(C),W;for(D=0;D<H.length;++D)W=H[D],W!=="removeListener"&&this.removeAllListeners(W);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(k=C[P],typeof k=="function")this.removeListener(P,k);else if(k!==void 0)for(D=k.length-1;D>=0;D--)this.removeListener(P,k[D]);return this};function m(P,k,C){var D=P._events;if(D===void 0)return[];var H=D[k];return H===void 0?[]:typeof H=="function"?C?[H.listener||H]:[H]:C?w(H):f(H,H.length)}a.prototype.listeners=function(P){return m(this,P,!0)},a.prototype.rawListeners=function(P){return m(this,P,!1)},a.listenerCount=function(P,k){return typeof P.listenerCount=="function"?P.listenerCount(k):_.call(P,k)},a.prototype.listenerCount=_;function _(P){var k=this._events;if(k!==void 0){var C=k[P];if(typeof C=="function")return 1;if(C!==void 0)return C.length}return 0}a.prototype.eventNames=function(){return this._eventsCount>0?n(this._events):[]};function f(P,k){for(var C=new Array(k),D=0;D<k;++D)C[D]=P[D];return C}function b(P,k){for(;k+1<P.length;k++)P[k]=P[k+1];P.pop()}function w(P){for(var k=new Array(P.length),C=0;C<k.length;++C)k[C]=P[C].listener||P[C];return k}function S(P,k){return new Promise(function(C,D){function H(J){P.removeListener(k,W),D(J)}function W(){typeof P.removeListener=="function"&&P.removeListener("error",H),C([].slice.call(arguments))}j(P,k,W,{once:!0}),k!=="error"&&O(P,H,{once:!0})})}function O(P,k,C){typeof P.on=="function"&&j(P,"error",k,C)}function j(P,k,C,D){if(typeof P.on=="function")D.once?P.once(k,C):P.on(k,C);else if(typeof P.addEventListener=="function")P.addEventListener(k,function H(W){D.once&&P.removeEventListener(k,H),C(W)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof P)}}),Xs=nt(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EnhancedEventEmitter=void 0;var e=Rre(),r=Os(),s=new r.Logger("EnhancedEventEmitter"),n=class extends e.EventEmitter{constructor(){super(),this.setMaxListeners(1/0)}close(){super.removeAllListeners()}emit(i,...o){return super.emit(i,...o)}safeEmit(i,...o){try{return super.emit(i,...o)}catch(a){s.error("safeEmit() | event listener threw an error [eventName:%s]:%o",i,a);try{super.emit("listenererror",i,a)}catch{}return!!super.listenerCount(i)}}on(i,o){return super.on(i,o),this}off(i,o){return super.off(i,o),this}addListener(i,o){return super.on(i,o),this}prependListener(i,o){return super.prependListener(i,o),this}once(i,o){return super.once(i,o),this}prependOnceListener(i,o){return super.prependOnceListener(i,o),this}removeListener(i,o){return super.off(i,o),this}removeAllListeners(i){return super.removeAllListeners(i),this}listenerCount(i){return super.listenerCount(i)}listeners(i){return super.listeners(i)}rawListeners(i){return super.rawListeners(i)}};t.EnhancedEventEmitter=n}),Zn=nt(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.InvalidStateError=t.UnsupportedError=void 0;var e=class bF extends Error{constructor(n){super(n),this.name="UnsupportedError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,bF):this.stack=new Error(n).stack}};t.UnsupportedError=e;var r=class xF extends Error{constructor(n){super(n),this.name="InvalidStateError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,xF):this.stack=new Error(n).stack}};t.InvalidStateError=r}),Yh=nt(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.clone=e,t.generateRandomNumber=r,t.deepFreeze=s;function e(n){if(n!==void 0)return Number.isNaN(n)?NaN:typeof structuredClone=="function"?structuredClone(n):JSON.parse(JSON.stringify(n))}function r(){return Math.round(Math.random()*1e7)}function s(n){let i=Reflect.ownKeys(n);for(let o of i){let a=n[o];(a&&typeof a=="object"||typeof a=="function")&&s(a)}return Object.freeze(n)}}),Pre=nt(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Logger=void 0;var e=$1(),r="h264-profile-level-id",s=class{_debug;_warn;_error;constructor(n){n?(this._debug=(0,e.default)(`${r}:${n}`),this._warn=(0,e.default)(`${r}:WARN:${n}`),this._error=(0,e.default)(`${r}:ERROR:${n}`)):(this._debug=(0,e.default)(r),this._warn=(0,e.default)(`${r}:WARN`),this._error=(0,e.default)(`${r}:ERROR`)),this._debug.log=E.info.bind(E),this._warn.log=E.warn.bind(E),this._error.log=E.error.bind(E)}get debug(){return this._debug}get warn(){return this._warn}get error(){return this._error}};t.Logger=s}),Dre=nt(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProfileLevelId=t.Level=t.Profile=void 0,t.parseProfileLevelId=l,t.profileLevelIdToString=h,t.profileToString=p,t.levelToString=m,t.parseSdpProfileLevelId=_,t.isSameProfile=f,t.isSameProfileAndLevel=b,t.generateProfileLevelIdStringForAnswer=w,t.supportedLevel=S;var e=Pre(),r=new e.Logger,s;(function(C){C[C.ConstrainedBaseline=1]="ConstrainedBaseline",C[C.Baseline=2]="Baseline",C[C.Main=3]="Main",C[C.ConstrainedHigh=4]="ConstrainedHigh",C[C.High=5]="High",C[C.PredictiveHigh444=6]="PredictiveHigh444"})(s||(t.Profile=s={}));var n;(function(C){C[C.L1_b=0]="L1_b",C[C.L1=10]="L1",C[C.L1_1=11]="L1_1",C[C.L1_2=12]="L1_2",C[C.L1_3=13]="L1_3",C[C.L2=20]="L2",C[C.L2_1=21]="L2_1",C[C.L2_2=22]="L2_2",C[C.L3=30]="L3",C[C.L3_1=31]="L3_1",C[C.L3_2=32]="L3_2",C[C.L4=40]="L4",C[C.L4_1=41]="L4_1",C[C.L4_2=42]="L4_2",C[C.L5=50]="L5",C[C.L5_1=51]="L5_1",C[C.L5_2=52]="L5_2"})(n||(t.Level=n={}));var i=class{profile;level;constructor(C,D){this.profile=C,this.level=D}};t.ProfileLevelId=i;var o=new i(s.ConstrainedBaseline,n.L3_1),a=class{mask;masked_value;constructor(C){this.mask=~O("x",C),this.masked_value=O("1",C)}isMatch(C){return this.masked_value===(C&this.mask)}},c=class{profile_idc;profile_iop;profile;constructor(C,D,H){this.profile_idc=C,this.profile_iop=D,this.profile=H}},d=[new c(66,new a("x1xx0000"),s.ConstrainedBaseline),new c(77,new a("1xxx0000"),s.ConstrainedBaseline),new c(88,new a("11xx0000"),s.ConstrainedBaseline),new c(66,new a("x0xx0000"),s.Baseline),new c(88,new a("10xx0000"),s.Baseline),new c(77,new a("0x0x0000"),s.Main),new c(100,new a("00000000"),s.High),new c(100,new a("00001100"),s.ConstrainedHigh),new c(244,new a("00000000"),s.PredictiveHigh444)],u=[{max_macroblocks_per_second:1485,max_macroblock_frame_size:99,level:n.L1},{max_macroblocks_per_second:1485,max_macroblock_frame_size:99,level:n.L1_b},{max_macroblocks_per_second:3e3,max_macroblock_frame_size:396,level:n.L1_1},{max_macroblocks_per_second:6e3,max_macroblock_frame_size:396,level:n.L1_2},{max_macroblocks_per_second:11880,max_macroblock_frame_size:396,level:n.L1_3},{max_macroblocks_per_second:11880,max_macroblock_frame_size:396,level:n.L2},{max_macroblocks_per_second:19800,max_macroblock_frame_size:792,level:n.L2_1},{max_macroblocks_per_second:20250,max_macroblock_frame_size:1620,level:n.L2_2},{max_macroblocks_per_second:40500,max_macroblock_frame_size:1620,level:n.L3},{max_macroblocks_per_second:108e3,max_macroblock_frame_size:3600,level:n.L3_1},{max_macroblocks_per_second:216e3,max_macroblock_frame_size:5120,level:n.L3_2},{max_macroblocks_per_second:245760,max_macroblock_frame_size:8192,level:n.L4},{max_macroblocks_per_second:245760,max_macroblock_frame_size:8192,level:n.L4_1},{max_macroblocks_per_second:522240,max_macroblock_frame_size:8704,level:n.L4_2},{max_macroblocks_per_second:589824,max_macroblock_frame_size:22080,level:n.L5},{max_macroblocks_per_second:983040,max_macroblock_frame_size:36864,level:n.L5_1},{max_macroblocks_per_second:2073600,max_macroblock_frame_size:36864,level:n.L5_2}];function l(C){if(typeof C!="string"||C.length!==6)return;let D=parseInt(C,16);if(D===0)return;let H=D&255,W=D>>8&255,J=D>>16&255,F;switch(H){case n.L1_1:{F=(W&16)!==0?n.L1_b:n.L1_1;break}case n.L1:case n.L1_2:case n.L1_3:case n.L2:case n.L2_1:case n.L2_2:case n.L3:case n.L3_1:case n.L3_2:case n.L4:case n.L4_1:case n.L4_2:case n.L5:case n.L5_1:case n.L5_2:{F=H;break}default:{r.warn(`parseProfileLevelId() | unrecognized level_idc [str:${C}, level_idc:${H}]`);return}}for(let q of d)if(J===q.profile_idc&&q.profile_iop.isMatch(W))return r.debug(`parseProfileLevelId() | result [str:${C}, profile:${q.profile}, level:${F}]`),new i(q.profile,F);r.warn(`parseProfileLevelId() | unrecognized profile_idc/profile_iop combination [str:${C}, profile_idc:${J}, profile_iop:${W}]`)}function h(C){if(C.level==n.L1_b)switch(C.profile){case s.ConstrainedBaseline:return"42f00b";case s.Baseline:return"42100b";case s.Main:return"4d100b";default:{r.warn(`profileLevelIdToString() | Level 1_b not is allowed for profile ${C.profile}`);return}}let D;switch(C.profile){case s.ConstrainedBaseline:{D="42e0";break}case s.Baseline:{D="4200";break}case s.Main:{D="4d00";break}case s.ConstrainedHigh:{D="640c";break}case s.High:{D="6400";break}case s.PredictiveHigh444:{D="f400";break}default:{r.warn(`profileLevelIdToString() | unrecognized profile ${C.profile}`);return}}let H=C.level.toString(16);return H.length===1&&(H=`0${H}`),`${D}${H}`}function p(C){switch(C){case s.ConstrainedBaseline:return"ConstrainedBaseline";case s.Baseline:return"Baseline";case s.Main:return"Main";case s.ConstrainedHigh:return"ConstrainedHigh";case s.High:return"High";case s.PredictiveHigh444:return"PredictiveHigh444";default:{r.warn(`profileToString() | unrecognized profile ${C}`);return}}}function m(C){switch(C){case n.L1_b:return"1b";case n.L1:return"1";case n.L1_1:return"1.1";case n.L1_2:return"1.2";case n.L1_3:return"1.3";case n.L2:return"2";case n.L2_1:return"2.1";case n.L2_2:return"2.2";case n.L3:return"3";case n.L3_1:return"3.1";case n.L3_2:return"3.2";case n.L4:return"4";case n.L4_1:return"4.1";case n.L4_2:return"4.2";case n.L5:return"5";case n.L5_1:return"5.1";case n.L5_2:return"5.2";default:{r.warn(`levelToString() | unrecognized level ${C}`);return}}}function _(C={}){let D=C["profile-level-id"];return D?l(D):o}function f(C={},D={}){let H=_(C),W=_(D);return!!(H&&W&&H.profile===W.profile)}function b(C={},D={}){let H=_(C),W=_(D);return!!(H&&W&&H.profile===W.profile&&H.level==W.level)}function w(C={},D={}){if(!C["profile-level-id"]&&!D["profile-level-id"]){r.warn("generateProfileLevelIdStringForAnswer() | profile-level-id missing in local and remote params");return}let H=_(C),W=_(D);if(!H)throw new TypeError("invalid local_profile_level_id");if(!W)throw new TypeError("invalid remote_profile_level_id");if(H.profile!==W.profile)throw new TypeError("H264 Profile mismatch");let J=k(C)&&k(D),F=H.level,q=W.level,Q=P(F,q),R=J?F:Q;return r.debug(`generateProfileLevelIdStringForAnswer() | result [profile:${H.profile}, level:${R}]`),h(new i(H.profile,R))}function S(C,D){for(let H=u.length-1;H>=0;--H){let W=u[H];if(W.max_macroblock_frame_size*256<=C&&W.max_macroblocks_per_second<=D*W.max_macroblock_frame_size)return r.debug(`supportedLevel() | result [max_frame_pixel_count:${C}, max_fps:${D}, level:${W.level}]`),W.level}r.warn(`supportedLevel() | no level supported [max_frame_pixel_count:${C}, max_fps:${D}]`)}function O(C,D){return+(D[0]===C)<<7|+(D[1]===C)<<6|+(D[2]===C)<<5|+(D[3]===C)<<4|+(D[4]===C)<<3|+(D[5]===C)<<2|+(D[6]===C)<<1|+(D[7]===C)<<0}function j(C,D){return C===n.L1_b?D!==n.L1&&D!==n.L1_b:D===n.L1_b?C!==n.L1:C<D}function P(C,D){return j(C,D)?C:D}function k(C={}){let D=C["level-asymmetry-allowed"];return D===!0||D===1||D==="1"}}),ea=nt(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validateAndNormalizeRtpCapabilities=o,t.validateAndNormalizeRtpParameters=a,t.validateAndNormalizeSctpStreamParameters=c,t.validateSctpCapabilities=d,t.getExtendedRtpCapabilities=u,t.getRecvRtpCapabilities=l,t.getSendRtpCapabilities=h,t.getSendingRtpParameters=p,t.getSendingRemoteRtpParameters=m,t.reduceCodecs=_,t.generateProbatorRtpParameters=f,t.canSend=b,t.canReceive=w;var e=Dre(),r=Yh(),s="probator",n=1234,i=127;function o(R){if(typeof R!="object")throw new TypeError("caps is not an object");if(R.codecs&&!Array.isArray(R.codecs))throw new TypeError("caps.codecs is not an array");R.codecs||(R.codecs=[]);for(let Y of R.codecs)S(Y);if(R.headerExtensions&&!Array.isArray(R.headerExtensions))throw new TypeError("caps.headerExtensions is not an array");R.headerExtensions||(R.headerExtensions=[]);for(let Y of R.headerExtensions)j(Y)}function a(R){if(typeof R!="object")throw new TypeError("params is not an object");if(R.mid&&typeof R.mid!="string")throw new TypeError("params.mid is not a string");if(!Array.isArray(R.codecs))throw new TypeError("missing params.codecs");for(let Y of R.codecs)P(Y);if(R.headerExtensions&&!Array.isArray(R.headerExtensions))throw new TypeError("params.headerExtensions is not an array");R.headerExtensions||(R.headerExtensions=[]);for(let Y of R.headerExtensions)k(Y);if(R.encodings&&!Array.isArray(R.encodings))throw new TypeError("params.encodings is not an array");R.encodings||(R.encodings=[]);for(let Y of R.encodings)C(Y);if(R.rtcp&&typeof R.rtcp!="object")throw new TypeError("params.rtcp is not an object");R.rtcp||(R.rtcp={}),D(R.rtcp)}function c(R){if(typeof R!="object")throw new TypeError("params is not an object");if(typeof R.streamId!="number")throw new TypeError("missing params.streamId");let Y=!1;if(typeof R.ordered=="boolean"?Y=!0:R.ordered=!0,R.maxPacketLifeTime&&typeof R.maxPacketLifeTime!="number")throw new TypeError("invalid params.maxPacketLifeTime");if(R.maxRetransmits&&typeof R.maxRetransmits!="number")throw new TypeError("invalid params.maxRetransmits");if(R.maxPacketLifeTime&&R.maxRetransmits)throw new TypeError("cannot provide both maxPacketLifeTime and maxRetransmits");if(Y&&R.ordered&&(R.maxPacketLifeTime||R.maxRetransmits))throw new TypeError("cannot be ordered with maxPacketLifeTime or maxRetransmits");if(!Y&&(R.maxPacketLifeTime||R.maxRetransmits)&&(R.ordered=!1),R.label&&typeof R.label!="string")throw new TypeError("invalid params.label");if(R.protocol&&typeof R.protocol!="string")throw new TypeError("invalid params.protocol")}function d(R){if(typeof R!="object")throw new TypeError("caps is not an object");if(!R.numStreams||typeof R.numStreams!="object")throw new TypeError("missing caps.numStreams");H(R.numStreams)}function u(R,Y,Z){let I={codecs:[],headerExtensions:[]};if(Z)for(let U of R.codecs??[]){if(J(U))continue;let K=(Y.codecs??[]).find(G=>F(G,U,{strict:!0,modify:!0}));if(!K)continue;let z={kind:U.kind,mimeType:U.mimeType,clockRate:U.clockRate,channels:U.channels,localPayloadType:U.preferredPayloadType,localRtxPayloadType:void 0,remotePayloadType:K.preferredPayloadType,remoteRtxPayloadType:void 0,localParameters:U.parameters??{},remoteParameters:K.parameters??{},rtcpFeedback:Q(U,K)};I.codecs.push(z)}else for(let U of Y.codecs??[]){if(J(U))continue;let K=(R.codecs??[]).find(G=>F(G,U,{strict:!0,modify:!0}));if(!K)continue;let z={kind:K.kind,mimeType:K.mimeType,clockRate:K.clockRate,channels:K.channels,localPayloadType:K.preferredPayloadType,localRtxPayloadType:void 0,remotePayloadType:U.preferredPayloadType,remoteRtxPayloadType:void 0,localParameters:K.parameters??{},remoteParameters:U.parameters??{},rtcpFeedback:Q(K,U)};I.codecs.push(z)}for(let U of I.codecs){let K=R.codecs.find(G=>J(G)&&G.parameters?.apt===U.localPayloadType),z=Y.codecs.find(G=>J(G)&&G.parameters?.apt===U.remotePayloadType);K&&z&&(U.localRtxPayloadType=K.preferredPayloadType,U.remoteRtxPayloadType=z.preferredPayloadType)}for(let U of Y.headerExtensions){let K=R.headerExtensions.find(G=>q(G,U));if(!K)continue;let z={kind:U.kind,uri:U.uri,sendId:K.preferredId,recvId:U.preferredId,encrypt:K.preferredEncrypt??!1,direction:"sendrecv"};switch(U.direction){case"sendrecv":{z.direction="sendrecv";break}case"recvonly":{z.direction="sendonly";break}case"sendonly":{z.direction="recvonly";break}case"inactive":{z.direction="inactive";break}}I.headerExtensions.push(z)}return I}function l(R){return W({direction:"recvonly",extendedRtpCapabilities:R})}function h(R){return W({direction:"sendonly",extendedRtpCapabilities:R})}function p(R,Y){let Z={mid:void 0,codecs:[],headerExtensions:[],encodings:[],rtcp:{}};for(let I of Y.codecs){if(I.kind!==R)continue;let U={mimeType:I.mimeType,payloadType:I.localPayloadType,clockRate:I.clockRate,channels:I.channels,parameters:I.localParameters,rtcpFeedback:I.rtcpFeedback};if(Z.codecs.push(U),I.localRtxPayloadType){let K={mimeType:`${I.kind}/rtx`,payloadType:I.localRtxPayloadType,clockRate:I.clockRate,parameters:{apt:I.localPayloadType},rtcpFeedback:[]};Z.codecs.push(K)}}for(let I of Y.headerExtensions){if(I.kind&&I.kind!==R||I.direction!=="sendrecv"&&I.direction!=="sendonly")continue;let U={uri:I.uri,id:I.sendId,encrypt:I.encrypt,parameters:{}};Z.headerExtensions.push(U)}return Z}function m(R,Y){let Z={mid:void 0,codecs:[],headerExtensions:[],encodings:[],rtcp:{}};for(let I of Y.codecs){if(I.kind!==R)continue;let U={mimeType:I.mimeType,payloadType:I.localPayloadType,clockRate:I.clockRate,channels:I.channels,parameters:I.remoteParameters,rtcpFeedback:I.rtcpFeedback};if(Z.codecs.push(U),I.localRtxPayloadType){let K={mimeType:`${I.kind}/rtx`,payloadType:I.localRtxPayloadType,clockRate:I.clockRate,parameters:{apt:I.localPayloadType},rtcpFeedback:[]};Z.codecs.push(K)}}for(let I of Y.headerExtensions){if(I.kind&&I.kind!==R||I.direction!=="sendrecv"&&I.direction!=="sendonly")continue;let U={uri:I.uri,id:I.sendId,encrypt:I.encrypt,parameters:{}};Z.headerExtensions.push(U)}if(Z.headerExtensions.some(I=>I.uri==="http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01"))for(let I of Z.codecs)I.rtcpFeedback=(I.rtcpFeedback??[]).filter(U=>U.type!=="goog-remb");else if(Z.headerExtensions.some(I=>I.uri==="http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time"))for(let I of Z.codecs)I.rtcpFeedback=(I.rtcpFeedback??[]).filter(U=>U.type!=="transport-cc");else for(let I of Z.codecs)I.rtcpFeedback=(I.rtcpFeedback??[]).filter(U=>U.type!=="transport-cc"&&U.type!=="goog-remb");return Z}function _(R,Y){let Z=[];if(!Y)Z.push(R[0]),J(R[1])&&Z.push(R[1]);else{for(let I=0;I<R.length;++I)if(F(R[I],Y,{strict:!0})){Z.push(R[I]),J(R[I+1])&&Z.push(R[I+1]);break}if(Z.length===0)throw new TypeError("no matching codec found")}return Z}function f(R){R=r.clone(R),a(R);let Y={mid:s,codecs:[],headerExtensions:[],encodings:[{ssrc:n}],rtcp:{cname:"probator"}};return Y.codecs.push(R.codecs[0]),Y.codecs[0].payloadType=i,Y.headerExtensions=R.headerExtensions,Y}function b(R,Y){return(Y.codecs??[]).some(Z=>Z.kind===R)}function w(R,Y){if(a(R),R.codecs.length===0)return!1;let Z=R.codecs[0];return(Y.codecs??[]).some(I=>I.preferredPayloadType===Z.payloadType)}function S(R){let Y=new RegExp("^(audio|video)/(.+)","i");if(typeof R!="object")throw new TypeError("codec is not an object");if(!R.mimeType||typeof R.mimeType!="string")throw new TypeError("missing codec.mimeType");let Z=Y.exec(R.mimeType);if(!Z)throw new TypeError("invalid codec.mimeType");if(R.kind=Z[1].toLowerCase(),typeof R.preferredPayloadType!="number")throw new TypeError("missing codec.preferredPayloadType");if(typeof R.clockRate!="number")throw new TypeError("missing codec.clockRate");R.kind==="audio"?typeof R.channels!="number"&&(R.channels=1):delete R.channels,(!R.parameters||typeof R.parameters!="object")&&(R.parameters={});for(let I of Object.keys(R.parameters)){let U=R.parameters[I];if(U===void 0&&(R.parameters[I]="",U=""),typeof U!="string"&&typeof U!="number")throw new TypeError(`invalid codec parameter [key:${I}s, value:${U}]`);if(I==="apt"&&typeof U!="number")throw new TypeError("invalid codec apt parameter")}(!R.rtcpFeedback||!Array.isArray(R.rtcpFeedback))&&(R.rtcpFeedback=[]);for(let I of R.rtcpFeedback)O(I)}function O(R){if(typeof R!="object")throw new TypeError("fb is not an object");if(!R.type||typeof R.type!="string")throw new TypeError("missing fb.type");(!R.parameter||typeof R.parameter!="string")&&(R.parameter="")}function j(R){if(typeof R!="object")throw new TypeError("ext is not an object");if(R.kind!=="audio"&&R.kind!=="video")throw new TypeError("invalid ext.kind");if(!R.uri||typeof R.uri!="string")throw new TypeError("missing ext.uri");if(typeof R.preferredId!="number")throw new TypeError("missing ext.preferredId");if(R.preferredEncrypt&&typeof R.preferredEncrypt!="boolean")throw new TypeError("invalid ext.preferredEncrypt");if(R.preferredEncrypt||(R.preferredEncrypt=!1),R.direction&&typeof R.direction!="string")throw new TypeError("invalid ext.direction");R.direction||(R.direction="sendrecv")}function P(R){let Y=new RegExp("^(audio|video)/(.+)","i");if(typeof R!="object")throw new TypeError("codec is not an object");if(!R.mimeType||typeof R.mimeType!="string")throw new TypeError("missing codec.mimeType");let Z=Y.exec(R.mimeType);if(!Z)throw new TypeError("invalid codec.mimeType");if(typeof R.payloadType!="number")throw new TypeError("missing codec.payloadType");if(typeof R.clockRate!="number")throw new TypeError("missing codec.clockRate");Z[1].toLowerCase()==="audio"?typeof R.channels!="number"&&(R.channels=1):delete R.channels,(!R.parameters||typeof R.parameters!="object")&&(R.parameters={});for(let I of Object.keys(R.parameters)){let U=R.parameters[I];if(U===void 0&&(R.parameters[I]="",U=""),typeof U!="string"&&typeof U!="number")throw new TypeError(`invalid codec parameter [key:${I}s, value:${U}]`);if(I==="apt"&&typeof U!="number")throw new TypeError("invalid codec apt parameter")}(!R.rtcpFeedback||!Array.isArray(R.rtcpFeedback))&&(R.rtcpFeedback=[]);for(let I of R.rtcpFeedback)O(I)}function k(R){if(typeof R!="object")throw new TypeError("ext is not an object");if(!R.uri||typeof R.uri!="string")throw new TypeError("missing ext.uri");if(typeof R.id!="number")throw new TypeError("missing ext.id");if(R.encrypt&&typeof R.encrypt!="boolean")throw new TypeError("invalid ext.encrypt");R.encrypt||(R.encrypt=!1),(!R.parameters||typeof R.parameters!="object")&&(R.parameters={});for(let Y of Object.keys(R.parameters)){let Z=R.parameters[Y];if(Z===void 0&&(R.parameters[Y]="",Z=""),typeof Z!="string"&&typeof Z!="number")throw new TypeError("invalid header extension parameter")}}function C(R){if(typeof R!="object")throw new TypeError("encoding is not an object");if(R.ssrc&&typeof R.ssrc!="number")throw new TypeError("invalid encoding.ssrc");if(R.rid&&typeof R.rid!="string")throw new TypeError("invalid encoding.rid");if(R.rtx&&typeof R.rtx!="object")throw new TypeError("invalid encoding.rtx");if(R.rtx&&typeof R.rtx.ssrc!="number")throw new TypeError("missing encoding.rtx.ssrc");if((!R.dtx||typeof R.dtx!="boolean")&&(R.dtx=!1),R.scalabilityMode&&typeof R.scalabilityMode!="string")throw new TypeError("invalid encoding.scalabilityMode")}function D(R){if(typeof R!="object")throw new TypeError("rtcp is not an object");if(R.cname&&typeof R.cname!="string")throw new TypeError("invalid rtcp.cname");(!R.reducedSize||typeof R.reducedSize!="boolean")&&(R.reducedSize=!0)}function H(R){if(typeof R!="object")throw new TypeError("numStreams is not an object");if(typeof R.OS!="number")throw new TypeError("missing numStreams.OS");if(typeof R.MIS!="number")throw new TypeError("missing numStreams.MIS")}function W({direction:R,extendedRtpCapabilities:Y}){let Z={codecs:[],headerExtensions:[]};for(let I of Y.codecs){let U={kind:I.kind,mimeType:I.mimeType,preferredPayloadType:I.remotePayloadType,clockRate:I.clockRate,channels:I.channels,parameters:I.localParameters,rtcpFeedback:I.rtcpFeedback};if(Z.codecs.push(U),!I.remoteRtxPayloadType)continue;let K={kind:I.kind,mimeType:`${I.kind}/rtx`,preferredPayloadType:I.remoteRtxPayloadType,clockRate:I.clockRate,parameters:{apt:I.remotePayloadType},rtcpFeedback:[]};Z.codecs.push(K)}for(let I of Y.headerExtensions){if(I.direction!=="sendrecv"&&I.direction!==R)continue;let U={kind:I.kind,uri:I.uri,preferredId:I.recvId,preferredEncrypt:I.encrypt??!1,direction:I.direction};Z.headerExtensions.push(U)}return Z}function J(R){return R?/.+\/rtx$/i.test(R.mimeType):!1}function F(R,Y,{strict:Z=!1,modify:I=!1}={}){let U=R.mimeType.toLowerCase(),K=Y.mimeType.toLowerCase();if(U!==K||R.clockRate!==Y.clockRate||R.channels!==Y.channels)return!1;switch(U){case"video/h264":{if(Z){let z=R.parameters["packetization-mode"]??0,G=Y.parameters["packetization-mode"]??0;if(z!==G||!e.isSameProfile(R.parameters,Y.parameters))return!1;let de;try{de=e.generateProfileLevelIdStringForAnswer(R.parameters,Y.parameters)}catch{return!1}I&&(de?(R.parameters["profile-level-id"]=de,Y.parameters["profile-level-id"]=de):(delete R.parameters["profile-level-id"],delete Y.parameters["profile-level-id"]))}break}case"video/vp9":{if(Z){let z=R.parameters["profile-id"]??0,G=Y.parameters["profile-id"]??0;if(z!==G)return!1}break}}return!0}function q(R,Y){return!(R.kind&&Y.kind&&R.kind!==Y.kind||R.uri!==Y.uri)}function Q(R,Y){let Z=[];for(let I of R.rtcpFeedback??[]){let U=(Y.rtcpFeedback??[]).find(K=>K.type===I.type&&(K.parameter===I.parameter||!K.parameter&&!I.parameter));U&&Z.push(U)}return Z}}),Bre=nt(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Logger=void 0;var e=$1(),r="awaitqueue",s=class{_debug;_warn;_error;constructor(n){n?(this._debug=e(`${r}:${n}`),this._warn=e(`${r}:WARN:${n}`),this._error=e(`${r}:ERROR:${n}`)):(this._debug=e(r),this._warn=e(`${r}:WARN`),this._error=e(`${r}:ERROR`)),this._debug.log=E.info.bind(E),this._warn.log=E.warn.bind(E),this._error.log=E.error.bind(E)}get debug(){return this._debug}get warn(){return this._warn}get error(){return this._error}};t.Logger=s}),wF=nt(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AwaitQueueRemovedTaskError=t.AwaitQueueStoppedError=void 0;var e=class vF extends Error{constructor(n){super(n??"queue stopped"),this.name="AwaitQueueStoppedError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,vF)}};t.AwaitQueueStoppedError=e;var r=class _F extends Error{constructor(n){super(n??"queue task removed"),this.name="AwaitQueueRemovedTaskError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,_F)}};t.AwaitQueueRemovedTaskError=r}),Lre=nt(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AwaitQueue=void 0;var e=Bre(),r=wF(),s=new e.Logger("AwaitQueue"),n=class{pendingTasks=new Map;nextTaskId=0;constructor(){s.debug("constructor()")}get size(){return this.pendingTasks.size}async push(i,o,a){if(o=o??i.name,s.debug(`push() [name:${o}, options:%o]`,a),typeof i!="function")throw new TypeError("given task is not a function");if(o)try{Object.defineProperty(i,"name",{value:o})}catch{}return new Promise((c,d)=>{if(o&&a?.removeOngoingTasksWithSameName)for(let l of this.pendingTasks.values())l.name===o&&l.reject(new r.AwaitQueueRemovedTaskError,{canExecuteNextTask:!1});let u={id:this.nextTaskId++,task:i,name:o,enqueuedAt:Date.now(),executedAt:void 0,completed:!1,resolve:l=>{if(u.completed)return;u.completed=!0,this.pendingTasks.delete(u.id),s.debug(`resolving task [name:${u.name}]`),c(l);let[h]=this.pendingTasks.values();h&&!h.executedAt&&this.execute(h)},reject:(l,{canExecuteNextTask:h})=>{if(!u.completed&&(u.completed=!0,this.pendingTasks.delete(u.id),s.debug(`rejecting task [name:${u.name}]: %s`,String(l)),d(l),h)){let[p]=this.pendingTasks.values();p&&!p.executedAt&&this.execute(p)}}};this.pendingTasks.set(u.id,u),this.pendingTasks.size===1&&this.execute(u)})}stop(){s.debug("stop()");for(let i of this.pendingTasks.values())s.debug(`stop() | stopping task [name:${i.name}]`),i.reject(new r.AwaitQueueStoppedError,{canExecuteNextTask:!1})}remove(i){s.debug(`remove() [taskIdx:${i}]`);let o=Array.from(this.pendingTasks.values())[i];if(!o){s.debug(`stop() | no task with given idx [taskIdx:${i}]`);return}o.reject(new r.AwaitQueueRemovedTaskError,{canExecuteNextTask:!0})}dump(){let i=Date.now(),o=0;return Array.from(this.pendingTasks.values()).map(a=>({idx:o++,task:a.task,name:a.name,enqueuedTime:a.executedAt?a.executedAt-a.enqueuedAt:i-a.enqueuedAt,executionTime:a.executedAt?i-a.executedAt:0}))}async execute(i){if(s.debug(`execute() [name:${i.name}]`),i.executedAt)throw new Error("task already being executed");i.executedAt=Date.now();try{let o=await i.task();i.resolve(o)}catch(o){i.reject(o,{canExecuteNextTask:!0})}}};t.AwaitQueue=n}),Ore=nt(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AwaitQueueRemovedTaskError=t.AwaitQueueStoppedError=t.AwaitQueue=void 0;var e=Lre();Object.defineProperty(t,"AwaitQueue",{enumerable:!0,get:function(){return e.AwaitQueue}});var r=wF();Object.defineProperty(t,"AwaitQueueStoppedError",{enumerable:!0,get:function(){return r.AwaitQueueStoppedError}}),Object.defineProperty(t,"AwaitQueueRemovedTaskError",{enumerable:!0,get:function(){return r.AwaitQueueRemovedTaskError}})}),Nre=nt(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Producer=void 0;var e=Os(),r=Xs(),s=Zn(),n=new e.Logger("Producer"),i=class extends r.EnhancedEventEmitter{_id;_localId;_closed=!1;_rtpSender;_track;_kind;_rtpParameters;_paused;_maxSpatialLayer;_stopTracks;_disableTrackOnPause;_zeroRtpOnPause;_appData;_observer=new r.EnhancedEventEmitter;constructor({id:o,localId:a,rtpSender:c,track:d,rtpParameters:u,stopTracks:l,disableTrackOnPause:h,zeroRtpOnPause:p,appData:m}){super(),n.debug("constructor()"),this._id=o,this._localId=a,this._rtpSender=c,this._track=d,this._kind=d.kind,this._rtpParameters=u,this._paused=h?!d.enabled:!1,this._maxSpatialLayer=void 0,this._stopTracks=l,this._disableTrackOnPause=h,this._zeroRtpOnPause=p,this._appData=m??{},this.onTrackEnded=this.onTrackEnded.bind(this),this.handleTrack()}get id(){return this._id}get localId(){return this._localId}get closed(){return this._closed}get kind(){return this._kind}get rtpSender(){return this._rtpSender}get track(){return this._track}get rtpParameters(){return this._rtpParameters}get paused(){return this._paused}get maxSpatialLayer(){return this._maxSpatialLayer}get appData(){return this._appData}set appData(o){this._appData=o}get observer(){return this._observer}close(){this._closed||(n.debug("close()"),this._closed=!0,this.destroyTrack(),this.emit("@close"),this._observer.safeEmit("close"),super.close(),this._observer.close())}transportClosed(){this._closed||(n.debug("transportClosed()"),this._closed=!0,this.destroyTrack(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}async getStats(){if(this._closed)throw new s.InvalidStateError("closed");return new Promise((o,a)=>{this.safeEmit("@getstats",o,a)})}pause(){if(n.debug("pause()"),this._closed){n.error("pause() | Producer closed");return}this._paused=!0,this._track&&this._disableTrackOnPause&&(this._track.enabled=!1),this._zeroRtpOnPause&&new Promise((o,a)=>{this.safeEmit("@pause",o,a)}).catch(()=>{}),this._observer.safeEmit("pause")}resume(){if(n.debug("resume()"),this._closed){n.error("resume() | Producer closed");return}this._paused=!1,this._track&&this._disableTrackOnPause&&(this._track.enabled=!0),this._zeroRtpOnPause&&new Promise((o,a)=>{this.safeEmit("@resume",o,a)}).catch(()=>{}),this._observer.safeEmit("resume")}async replaceTrack({track:o}){if(n.debug("replaceTrack() [track:%o]",o),this._closed){if(o&&this._stopTracks)try{o.stop()}catch{}throw new s.InvalidStateError("closed")}else if(o?.readyState==="ended")throw new s.InvalidStateError("track ended");if(o===this._track){n.debug("replaceTrack() | same track, ignored");return}await new Promise((a,c)=>{this.safeEmit("@replacetrack",o,a,c)}),this.destroyTrack(),this._track=o,this._track&&this._disableTrackOnPause&&(this._paused?this._paused&&(this._track.enabled=!1):this._track.enabled=!0),this.handleTrack()}async setMaxSpatialLayer(o){if(this._closed)throw new s.InvalidStateError("closed");if(this._kind!=="video")throw new s.UnsupportedError("not a video Producer");if(typeof o!="number")throw new TypeError("invalid spatialLayer");o!==this._maxSpatialLayer&&(await new Promise((a,c)=>{this.safeEmit("@setmaxspatiallayer",o,a,c)}).catch(()=>{}),this._maxSpatialLayer=o)}async setRtpEncodingParameters(o){if(this._closed)throw new s.InvalidStateError("closed");if(typeof o!="object")throw new TypeError("invalid params");await new Promise((a,c)=>{this.safeEmit("@setrtpencodingparameters",o,a,c)})}onTrackEnded(){n.debug('track "ended" event'),this.safeEmit("trackended"),this._observer.safeEmit("trackended")}handleTrack(){this._track&&this._track.addEventListener("ended",this.onTrackEnded)}destroyTrack(){if(this._track)try{this._track.removeEventListener("ended",this.onTrackEnded),this._stopTracks&&this._track.stop()}catch{}}};t.Producer=i}),Ure=nt(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Consumer=void 0;var e=Os(),r=Xs(),s=Zn(),n=new e.Logger("Consumer"),i=class extends r.EnhancedEventEmitter{_id;_localId;_producerId;_closed=!1;_rtpReceiver;_track;_rtpParameters;_paused;_appData;_observer=new r.EnhancedEventEmitter;constructor({id:o,localId:a,producerId:c,rtpReceiver:d,track:u,rtpParameters:l,appData:h}){super(),n.debug("constructor()"),this._id=o,this._localId=a,this._producerId=c,this._rtpReceiver=d,this._track=u,this._rtpParameters=l,this._paused=!u.enabled,this._appData=h??{},this.onTrackEnded=this.onTrackEnded.bind(this),this.handleTrack()}get id(){return this._id}get localId(){return this._localId}get producerId(){return this._producerId}get closed(){return this._closed}get kind(){return this._track.kind}get rtpReceiver(){return this._rtpReceiver}get track(){return this._track}get rtpParameters(){return this._rtpParameters}get paused(){return this._paused}get appData(){return this._appData}set appData(o){this._appData=o}get observer(){return this._observer}close(){this._closed||(n.debug("close()"),this._closed=!0,this.destroyTrack(),this.emit("@close"),this._observer.safeEmit("close"),super.close(),this._observer.close())}transportClosed(){this._closed||(n.debug("transportClosed()"),this._closed=!0,this.destroyTrack(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}async getStats(){if(this._closed)throw new s.InvalidStateError("closed");return new Promise((o,a)=>{this.safeEmit("@getstats",o,a)})}pause(){if(n.debug("pause()"),this._closed){n.error("pause() | Consumer closed");return}if(this._paused){n.debug("pause() | Consumer is already paused");return}this._paused=!0,this._track.enabled=!1,this.emit("@pause"),this._observer.safeEmit("pause")}resume(){if(n.debug("resume()"),this._closed){n.error("resume() | Consumer closed");return}if(!this._paused){n.debug("resume() | Consumer is already resumed");return}this._paused=!1,this._track.enabled=!0,this.emit("@resume"),this._observer.safeEmit("resume")}onTrackEnded(){n.debug('track "ended" event'),this.safeEmit("trackended"),this._observer.safeEmit("trackended")}handleTrack(){this._track.addEventListener("ended",this.onTrackEnded)}destroyTrack(){try{this._track.removeEventListener("ended",this.onTrackEnded),this._track.stop()}catch{}}};t.Consumer=i}),Mre=nt(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DataProducer=void 0;var e=Os(),r=Xs(),s=Zn(),n=new e.Logger("DataProducer"),i=class extends r.EnhancedEventEmitter{_id;_dataChannel;_closed=!1;_sctpStreamParameters;_appData;_observer=new r.EnhancedEventEmitter;constructor({id:o,dataChannel:a,sctpStreamParameters:c,appData:d}){super(),n.debug("constructor()"),this._id=o,this._dataChannel=a,this._sctpStreamParameters=c,this._appData=d??{},this.handleDataChannel()}get id(){return this._id}get closed(){return this._closed}get sctpStreamParameters(){return this._sctpStreamParameters}get readyState(){return this._dataChannel.readyState}get label(){return this._dataChannel.label}get protocol(){return this._dataChannel.protocol}get bufferedAmount(){return this._dataChannel.bufferedAmount}get bufferedAmountLowThreshold(){return this._dataChannel.bufferedAmountLowThreshold}set bufferedAmountLowThreshold(o){this._dataChannel.bufferedAmountLowThreshold=o}get appData(){return this._appData}set appData(o){this._appData=o}get observer(){return this._observer}close(){this._closed||(n.debug("close()"),this._closed=!0,this._dataChannel.close(),this.emit("@close"),this._observer.safeEmit("close"),super.close(),this._observer.close())}transportClosed(){this._closed||(n.debug("transportClosed()"),this._closed=!0,this._dataChannel.close(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}send(o){if(n.debug("send()"),this._closed)throw new s.InvalidStateError("closed");this._dataChannel.send(o)}handleDataChannel(){this._dataChannel.addEventListener("open",()=>{this._closed||(n.debug('DataChannel "open" event'),this.safeEmit("open"))}),this._dataChannel.addEventListener("error",o=>{if(this._closed)return;let a=o.error??new Error("unknown DataChannel error");o.error?.errorDetail==="sctp-failure"?n.error("DataChannel SCTP error [sctpCauseCode:%s]: %s",o.error?.sctpCauseCode,o.error.message):n.error('DataChannel "error" event: %o',a),this.safeEmit("error",a)}),this._dataChannel.addEventListener("close",()=>{this._closed||(n.warn('DataChannel "close" event'),this._closed=!0,this.emit("@close"),this.safeEmit("close"),this._observer.safeEmit("close"))}),this._dataChannel.addEventListener("message",()=>{this._closed||n.warn('DataChannel "message" event in a DataProducer, message discarded')}),this._dataChannel.addEventListener("bufferedamountlow",()=>{this._closed||this.safeEmit("bufferedamountlow")})}};t.DataProducer=i}),jre=nt(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DataConsumer=void 0;var e=Os(),r=Xs(),s=new e.Logger("DataConsumer"),n=class extends r.EnhancedEventEmitter{_id;_dataProducerId;_dataChannel;_closed=!1;_sctpStreamParameters;_appData;_observer=new r.EnhancedEventEmitter;constructor({id:i,dataProducerId:o,dataChannel:a,sctpStreamParameters:c,appData:d}){super(),s.debug("constructor()"),this._id=i,this._dataProducerId=o,this._dataChannel=a,this._sctpStreamParameters=c,this._appData=d??{},this.handleDataChannel()}get id(){return this._id}get dataProducerId(){return this._dataProducerId}get closed(){return this._closed}get sctpStreamParameters(){return this._sctpStreamParameters}get readyState(){return this._dataChannel.readyState}get label(){return this._dataChannel.label}get protocol(){return this._dataChannel.protocol}get binaryType(){return this._dataChannel.binaryType}set binaryType(i){this._dataChannel.binaryType=i}get appData(){return this._appData}set appData(i){this._appData=i}get observer(){return this._observer}close(){this._closed||(s.debug("close()"),this._closed=!0,this._dataChannel.close(),this.emit("@close"),this._observer.safeEmit("close"),super.close(),this._observer.close())}transportClosed(){this._closed||(s.debug("transportClosed()"),this._closed=!0,this._dataChannel.close(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}handleDataChannel(){this._dataChannel.addEventListener("open",()=>{this._closed||(s.debug('DataChannel "open" event'),this.safeEmit("open"))}),this._dataChannel.addEventListener("error",i=>{if(this._closed)return;let o=i.error??new Error("unknown DataChannel error");i.error?.errorDetail==="sctp-failure"?s.error("DataChannel SCTP error [sctpCauseCode:%s]: %s",i.error?.sctpCauseCode,i.error.message):s.error('DataChannel "error" event: %o',o),this.safeEmit("error",o)}),this._dataChannel.addEventListener("close",()=>{this._closed||(s.warn('DataChannel "close" event'),this._closed=!0,this.emit("@close"),this.safeEmit("close"),this._observer.safeEmit("close"))}),this._dataChannel.addEventListener("message",i=>{this._closed||this.safeEmit("message",i.data)})}};t.DataConsumer=n}),$re=nt(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Transport=void 0;var e=Ore(),r=Os(),s=Xs(),n=Zn(),i=Yh(),o=ea(),a=Nre(),c=Ure(),d=Mre(),u=jre(),l=new r.Logger("Transport"),h=class{consumerOptions;promise;resolve;reject;constructor(m){this.consumerOptions=m,this.promise=new Promise((_,f)=>{this.resolve=_,this.reject=f})}},p=class extends s.EnhancedEventEmitter{_id;_closed=!1;_direction;_getSendExtendedRtpCapabilities;_recvRtpCapabilities;_canProduceByKind;_maxSctpMessageSize;_handler;_iceGatheringState="new";_connectionState="new";_appData;_producers=new Map;_consumers=new Map;_dataProducers=new Map;_dataConsumers=new Map;_probatorConsumerCreated=!1;_awaitQueue=new e.AwaitQueue;_pendingConsumerTasks=[];_consumerCreationInProgress=!1;_pendingPauseConsumers=new Map;_consumerPauseInProgress=!1;_pendingResumeConsumers=new Map;_consumerResumeInProgress=!1;_pendingCloseConsumers=new Map;_consumerCloseInProgress=!1;_observer=new s.EnhancedEventEmitter;constructor({direction:m,id:_,iceParameters:f,iceCandidates:b,dtlsParameters:w,sctpParameters:S,iceServers:O,iceTransportPolicy:j,additionalSettings:P,appData:k,handlerFactory:C,getSendExtendedRtpCapabilities:D,recvRtpCapabilities:H,canProduceByKind:W}){super(),l.debug("constructor() [id:%s, direction:%s]",_,m),this._id=_,this._direction=m,this._getSendExtendedRtpCapabilities=D,this._recvRtpCapabilities=H,this._canProduceByKind=W,this._maxSctpMessageSize=S?.maxMessageSize;let J=i.clone(P)??{};delete J.iceServers,delete J.iceTransportPolicy,delete J.bundlePolicy,delete J.rtcpMuxPolicy,this._handler=C.factory({direction:m,iceParameters:f,iceCandidates:b,dtlsParameters:w,sctpParameters:S,iceServers:O,iceTransportPolicy:j,additionalSettings:J,getSendExtendedRtpCapabilities:this._getSendExtendedRtpCapabilities}),this._appData=k??{},this.handleHandler()}get id(){return this._id}get closed(){return this._closed}get direction(){return this._direction}get handler(){return this._handler}get iceGatheringState(){return this._iceGatheringState}get connectionState(){return this._connectionState}get appData(){return this._appData}set appData(m){this._appData=m}get observer(){return this._observer}close(){if(!this._closed){l.debug("close()"),this._closed=!0,this._awaitQueue.stop(),this._handler.close(),this._connectionState="closed";for(let m of this._producers.values())m.transportClosed();this._producers.clear();for(let m of this._consumers.values())m.transportClosed();this._consumers.clear();for(let m of this._dataProducers.values())m.transportClosed();this._dataProducers.clear();for(let m of this._dataConsumers.values())m.transportClosed();this._dataConsumers.clear(),this._observer.safeEmit("close"),super.close(),this._observer.close()}}async getStats(){if(this._closed)throw new n.InvalidStateError("closed");return this._handler.getTransportStats()}async restartIce({iceParameters:m}){if(l.debug("restartIce()"),this._closed)throw new n.InvalidStateError("closed");if(!m)throw new TypeError("missing iceParameters");return this._awaitQueue.push(async()=>await this._handler.restartIce(m),"transport.restartIce()")}async updateIceServers({iceServers:m}={}){if(l.debug("updateIceServers()"),this._closed)throw new n.InvalidStateError("closed");if(!Array.isArray(m))throw new TypeError("missing iceServers");return this._awaitQueue.push(async()=>this._handler.updateIceServers(m),"transport.updateIceServers()")}async produce({track:m,streamId:_,encodings:f,codecOptions:b,headerExtensionOptions:w,codec:S,stopTracks:O=!0,disableTrackOnPause:j=!0,zeroRtpOnPause:P=!1,onRtpSender:k,appData:C={}}={}){if(l.debug("produce() [track:%o]",m),this._closed)throw new n.InvalidStateError("closed");if(m){if(this._direction!=="send")throw new n.UnsupportedError("not a sending Transport");if(this._canProduceByKind[m.kind]){if(m.readyState==="ended")throw new n.InvalidStateError("track ended");if(this.listenerCount("connect")===0&&this._connectionState==="new")throw new TypeError('no "connect" listener set into this transport');if(this.listenerCount("produce")===0)throw new TypeError('no "produce" listener set into this transport');if(C&&typeof C!="object")throw new TypeError("if given, appData must be an object")}else throw new n.UnsupportedError(`cannot produce ${m.kind}`)}else throw new TypeError("missing track");return this._awaitQueue.push(async()=>{let D;if(f&&!Array.isArray(f))throw TypeError("encodings must be an array");f?.length===0?D=void 0:f&&(D=f.map(F=>{let q={active:!0};return F.active===!1&&(q.active=!1),typeof F.dtx=="boolean"&&(q.dtx=F.dtx),typeof F.scalabilityMode=="string"&&(q.scalabilityMode=F.scalabilityMode),typeof F.scaleResolutionDownBy=="number"&&(q.scaleResolutionDownBy=F.scaleResolutionDownBy),typeof F.maxBitrate=="number"&&(q.maxBitrate=F.maxBitrate),typeof F.maxFramerate=="number"&&(q.maxFramerate=F.maxFramerate),typeof F.adaptivePtime=="boolean"&&(q.adaptivePtime=F.adaptivePtime),typeof F.priority=="string"&&(q.priority=F.priority),typeof F.networkPriority=="string"&&(q.networkPriority=F.networkPriority),q}));let{localId:H,rtpParameters:W,rtpSender:J}=await this._handler.send({track:m,streamId:_,encodings:D,codecOptions:b,headerExtensionOptions:w,codec:S,onRtpSender:k});try{o.validateAndNormalizeRtpParameters(W);let{id:F}=await new Promise((Q,R)=>{this.safeEmit("produce",{kind:m.kind,rtpParameters:W,appData:C},Q,R)}),q=new a.Producer({id:F,localId:H,rtpSender:J,track:m,rtpParameters:W,stopTracks:O,disableTrackOnPause:j,zeroRtpOnPause:P,appData:C});return this._producers.set(q.id,q),this.handleProducer(q),this._observer.safeEmit("newproducer",q),q}catch(F){throw this._handler.stopSending(H).catch(()=>{}),F}},"transport.produce()").catch(D=>{if(O)try{m.stop()}catch{}throw D})}async consume({id:m,producerId:_,kind:f,rtpParameters:b,streamId:w,onRtpReceiver:S,appData:O={}}){if(l.debug("consume()"),this._closed)throw new n.InvalidStateError("closed");if(this._direction!=="recv")throw new n.UnsupportedError("not a receiving Transport");if(typeof m!="string")throw new TypeError("missing id");if(typeof _!="string")throw new TypeError("missing producerId");if(f!=="audio"&&f!=="video")throw new TypeError(`invalid kind '${f}'`);if(this.listenerCount("connect")===0&&this._connectionState==="new")throw new TypeError('no "connect" listener set into this transport');if(O&&typeof O!="object")throw new TypeError("if given, appData must be an object");let j=i.clone(b);if(!o.canReceive(j,this._recvRtpCapabilities))throw new n.UnsupportedError("cannot consume this Producer");let P=new h({id:m,producerId:_,kind:f,rtpParameters:j,streamId:w,onRtpReceiver:S,appData:O});return this._pendingConsumerTasks.push(P),queueMicrotask(()=>{this._closed||this._consumerCreationInProgress===!1&&this.createPendingConsumers()}),P.promise}async produceData({ordered:m=!0,maxPacketLifeTime:_,maxRetransmits:f,label:b="",protocol:w="",appData:S={}}={}){if(l.debug("produceData()"),this._closed)throw new n.InvalidStateError("closed");if(this._direction!=="send")throw new n.UnsupportedError("not a sending Transport");if(this._maxSctpMessageSize){if(this.listenerCount("connect")===0&&this._connectionState==="new")throw new TypeError('no "connect" listener set into this transport');if(this.listenerCount("producedata")===0)throw new TypeError('no "producedata" listener set into this transport');if(S&&typeof S!="object")throw new TypeError("if given, appData must be an object")}else throw new n.UnsupportedError("SCTP not enabled by remote Transport");return(_||f)&&(m=!1),this._awaitQueue.push(async()=>{let{dataChannel:O,sctpStreamParameters:j}=await this._handler.sendDataChannel({sctpStreamParameters:{ordered:m,maxPacketLifeTime:_,maxRetransmits:f,label:b,protocol:w}});o.validateAndNormalizeSctpStreamParameters(j);let{id:P}=await new Promise((C,D)=>{this.safeEmit("producedata",{sctpStreamParameters:j,label:b,protocol:w,appData:S},C,D)}),k=new d.DataProducer({id:P,dataChannel:O,sctpStreamParameters:j,appData:S});return this._dataProducers.set(k.id,k),this.handleDataProducer(k),this._observer.safeEmit("newdataproducer",k),k},"transport.produceData()")}async consumeData({id:m,dataProducerId:_,sctpStreamParameters:f,label:b="",protocol:w="",appData:S={}}){if(l.debug("consumeData()"),this._closed)throw new n.InvalidStateError("closed");if(this._direction!=="recv")throw new n.UnsupportedError("not a receiving Transport");if(this._maxSctpMessageSize){if(typeof m!="string")throw new TypeError("missing id");if(typeof _!="string")throw new TypeError("missing dataProducerId");if(this.listenerCount("connect")===0&&this._connectionState==="new")throw new TypeError('no "connect" listener set into this transport');if(S&&typeof S!="object")throw new TypeError("if given, appData must be an object")}else throw new n.UnsupportedError("SCTP not enabled by remote Transport");let O=i.clone(f);return o.validateAndNormalizeSctpStreamParameters(O),this._awaitQueue.push(async()=>{let{dataChannel:j}=await this._handler.receiveDataChannel({maxMessageSize:this._maxSctpMessageSize,sctpStreamParameters:O,label:b,protocol:w}),P=new u.DataConsumer({id:m,dataProducerId:_,dataChannel:j,sctpStreamParameters:O,appData:S});return this._dataConsumers.set(P.id,P),this.handleDataConsumer(P),this._observer.safeEmit("newdataconsumer",P),P},"transport.consumeData()")}getDataChannelMaxMessageSize(){return this._handler.getDataChannelMaxMessageSize()}createPendingConsumers(){this._consumerCreationInProgress=!0,this._awaitQueue.push(async()=>{if(this._pendingConsumerTasks.length===0){l.debug("createPendingConsumers() | there is no Consumer to be created");return}let m=[...this._pendingConsumerTasks];this._pendingConsumerTasks=[];let _,f=[];for(let b of m){let{id:w,kind:S,rtpParameters:O,streamId:j,onRtpReceiver:P}=b.consumerOptions;f.push({trackId:w,kind:S,rtpParameters:O,streamId:j,onRtpReceiver:P})}try{let b=await this._handler.receive(f);for(let w=0;w<b.length;++w){let S=m[w],O=b[w],{id:j,producerId:P,kind:k,rtpParameters:C,appData:D}=S.consumerOptions,{localId:H,rtpReceiver:W,track:J}=O,F=new c.Consumer({id:j,localId:H,producerId:P,rtpReceiver:W,track:J,rtpParameters:C,appData:D});this._consumers.set(F.id,F),this.handleConsumer(F),!this._probatorConsumerCreated&&!_&&k==="video"&&(_=F),this._observer.safeEmit("newconsumer",F),S.resolve(F)}}catch(b){for(let w of m)w.reject(b)}if(_)try{let b=o.generateProbatorRtpParameters(_.rtpParameters);await this._handler.receive([{trackId:"probator",kind:"video",rtpParameters:b}]),l.debug("createPendingConsumers() | Consumer for RTP probation created"),this._probatorConsumerCreated=!0}catch(b){l.error("createPendingConsumers() | failed to create Consumer for RTP probation:%o",b)}},"transport.createPendingConsumers()").then(()=>{this._consumerCreationInProgress=!1,this._pendingConsumerTasks.length>0&&this.createPendingConsumers()}).catch(()=>{})}pausePendingConsumers(){this._consumerPauseInProgress=!0,this._awaitQueue.push(async()=>{if(this._pendingPauseConsumers.size===0){l.debug("pausePendingConsumers() | there is no Consumer to be paused");return}let m=Array.from(this._pendingPauseConsumers.values());this._pendingPauseConsumers.clear();try{let _=m.map(f=>f.localId);await this._handler.pauseReceiving(_)}catch(_){l.error("pausePendingConsumers() | failed to pause Consumers:",_)}},"transport.pausePendingConsumers()").then(()=>{this._consumerPauseInProgress=!1,this._pendingPauseConsumers.size>0&&this.pausePendingConsumers()}).catch(()=>{})}resumePendingConsumers(){this._consumerResumeInProgress=!0,this._awaitQueue.push(async()=>{if(this._pendingResumeConsumers.size===0){l.debug("resumePendingConsumers() | there is no Consumer to be resumed");return}let m=Array.from(this._pendingResumeConsumers.values());this._pendingResumeConsumers.clear();try{let _=m.map(f=>f.localId);await this._handler.resumeReceiving(_)}catch(_){l.error("resumePendingConsumers() | failed to resume Consumers:",_)}},"transport.resumePendingConsumers()").then(()=>{this._consumerResumeInProgress=!1,this._pendingResumeConsumers.size>0&&this.resumePendingConsumers()}).catch(()=>{})}closePendingConsumers(){this._consumerCloseInProgress=!0,this._awaitQueue.push(async()=>{if(this._pendingCloseConsumers.size===0){l.debug("closePendingConsumers() | there is no Consumer to be closed");return}let m=Array.from(this._pendingCloseConsumers.values());this._pendingCloseConsumers.clear();try{await this._handler.stopReceiving(m.map(_=>_.localId))}catch(_){l.error("closePendingConsumers() | failed to close Consumers:",_)}},"transport.closePendingConsumers()").then(()=>{this._consumerCloseInProgress=!1,this._pendingCloseConsumers.size>0&&this.closePendingConsumers()}).catch(()=>{})}handleHandler(){let m=this._handler;m.on("@connect",({dtlsParameters:_},f,b)=>{if(this._closed){b(new n.InvalidStateError("closed"));return}this.safeEmit("connect",{dtlsParameters:_},f,b)}),m.on("@icegatheringstatechange",_=>{_!==this._iceGatheringState&&(l.debug("ICE gathering state changed to %s",_),this._iceGatheringState=_,this._closed||this.safeEmit("icegatheringstatechange",_))}),m.on("@icecandidateerror",_=>{l.warn(`ICE candidate error [url:${_.url}, localAddress:${_.address}, localPort:${_.port}]: ${_.errorCode} "${_.errorText}"`),this.safeEmit("icecandidateerror",_)}),m.on("@connectionstatechange",_=>{_!==this._connectionState&&(l.debug("connection state changed to %s",_),this._connectionState=_,this._closed||this.safeEmit("connectionstatechange",_))})}handleProducer(m){m.on("@close",()=>{this._producers.delete(m.id),!this._closed&&this._awaitQueue.push(async()=>await this._handler.stopSending(m.localId),"producer @close event").catch(_=>l.warn("producer.close() failed:%o",_))}),m.on("@pause",(_,f)=>{this._awaitQueue.push(async()=>await this._handler.pauseSending(m.localId),"producer @pause event").then(_).catch(f)}),m.on("@resume",(_,f)=>{this._awaitQueue.push(async()=>await this._handler.resumeSending(m.localId),"producer @resume event").then(_).catch(f)}),m.on("@replacetrack",(_,f,b)=>{this._awaitQueue.push(async()=>await this._handler.replaceTrack(m.localId,_),"producer @replacetrack event").then(f).catch(b)}),m.on("@setmaxspatiallayer",(_,f,b)=>{this._awaitQueue.push(async()=>await this._handler.setMaxSpatialLayer(m.localId,_),"producer @setmaxspatiallayer event").then(f).catch(b)}),m.on("@setrtpencodingparameters",(_,f,b)=>{this._awaitQueue.push(async()=>await this._handler.setRtpEncodingParameters(m.localId,_),"producer @setrtpencodingparameters event").then(f).catch(b)}),m.on("@getstats",(_,f)=>{if(this._closed)return f(new n.InvalidStateError("closed"));this._handler.getSenderStats(m.localId).then(_).catch(f)})}handleConsumer(m){m.on("@close",()=>{this._consumers.delete(m.id),this._pendingPauseConsumers.delete(m.id),this._pendingResumeConsumers.delete(m.id),!this._closed&&(this._pendingCloseConsumers.set(m.id,m),this._consumerCloseInProgress===!1&&this.closePendingConsumers())}),m.on("@pause",()=>{this._pendingResumeConsumers.has(m.id)&&this._pendingResumeConsumers.delete(m.id),this._pendingPauseConsumers.set(m.id,m),queueMicrotask(()=>{this._closed||this._consumerPauseInProgress===!1&&this.pausePendingConsumers()})}),m.on("@resume",()=>{this._pendingPauseConsumers.has(m.id)&&this._pendingPauseConsumers.delete(m.id),this._pendingResumeConsumers.set(m.id,m),queueMicrotask(()=>{this._closed||this._consumerResumeInProgress===!1&&this.resumePendingConsumers()})}),m.on("@getstats",(_,f)=>{if(this._closed)return f(new n.InvalidStateError("closed"));this._handler.getReceiverStats(m.localId).then(_).catch(f)})}handleDataProducer(m){m.on("@close",()=>{this._dataProducers.delete(m.id)})}handleDataConsumer(m){m.on("@close",()=>{this._dataConsumers.delete(m.id)})}};t.Transport=p}),GA=nt((t,e)=>{"use strict";var r=e.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(s){return s.encoding?"rtpmap:%d %s/%s/%s":s.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(s){return s.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(s){return s.subtype!=null?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(s){return"extmap:%d"+(s.direction?"/%s":"%v")+(s["encrypt-uri"]?" %s":"%v")+" %s"+(s.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(s){return s.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{push:"msid",reg:/^msid:([\w-]+)(?: ([\w-]+))?/,names:["id","appdata"],format:"msid:%s %s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(s){var n="candidate:%s %d %s %d %s %d typ %s";return n+=s.raddr!=null?" raddr %s rport %d":"%v%v",n+=s.tcptype!=null?" tcptype %s":"%v",s.generation!=null&&(n+=" generation %d"),n+=s["network-id"]!=null?" network-id %d":"%v",n+=s["network-cost"]!=null?" network-cost %d":"%v",n}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(s){var n="ssrc:%d";return s.attribute!=null&&(n+=" %s",s.value!=null&&(n+=":%s")),n}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(s){return s.maxMessageSize!=null?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(s){return s.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(s){return"imageattr:%s %s %s"+(s.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(s){return"simulcast:%s %s"+(s.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(s){return"ts-refclk:%s"+(s.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(s){var n="mediaclk:";return n+=s.id!=null?"id=%s %s":"%v%s",n+=s.mediaClockValue!=null?"=%s":"",n+=s.rateNumerator!=null?" rate=%s":"",n+=s.rateDenominator!=null?"/%s":"",n}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(r).forEach(function(s){var n=r[s];n.forEach(function(i){i.reg||(i.reg=/(.*)/),i.format||(i.format="%s")})})}),Fre=nt(t=>{"use strict";var e=function(a){return String(Number(a))===a?Number(a):a},r=function(a,c,d,u){if(u&&!d)c[u]=e(a[1]);else for(var l=0;l<d.length;l+=1)a[l+1]!=null&&(c[d[l]]=e(a[l+1]))},s=function(a,c,d){var u=a.name&&a.names;a.push&&!c[a.push]?c[a.push]=[]:u&&!c[a.name]&&(c[a.name]={});var l=a.push?{}:u?c[a.name]:c;r(d.match(a.reg),l,a.names,a.name),a.push&&c[a.push].push(l)},n=GA(),i=RegExp.prototype.test.bind(/^([a-z])=(.*)/);t.parse=function(a){var c={},d=[],u=c;return a.split(/(\r\n|\r|\n)/).filter(i).forEach(function(l){var h=l[0],p=l.slice(2);h==="m"&&(d.push({rtp:[],fmtp:[]}),u=d[d.length-1]);for(var m=0;m<(n[h]||[]).length;m+=1){var _=n[h][m];if(_.reg.test(p))return s(_,u,p)}}),c.media=d,c};var o=function(a,c){var d=c.split(/=(.+)/,2);return d.length===2?a[d[0]]=e(d[1]):d.length===1&&c.length>1&&(a[d[0]]=void 0),a};t.parseParams=function(a){return a.split(/;\s?/).reduce(o,{})},t.parseFmtpConfig=t.parseParams,t.parsePayloads=function(a){return a.toString().split(" ").map(Number)},t.parseRemoteCandidates=function(a){for(var c=[],d=a.split(" ").map(e),u=0;u<d.length;u+=3)c.push({component:d[u],ip:d[u+1],port:d[u+2]});return c},t.parseImageAttributes=function(a){return a.split(" ").map(function(c){return c.substring(1,c.length-1).split(",").reduce(o,{})})},t.parseSimulcastStreamList=function(a){return a.split(";").map(function(c){return c.split(",").map(function(d){var u,l=!1;return d[0]!=="~"?u=e(d):(u=e(d.substring(1,d.length)),l=!0),{scid:u,paused:l}})})}}),Hre=nt((t,e)=>{"use strict";var r=GA(),s=/%[sdv%]/g,n=function(c){var d=1,u=arguments,l=u.length;return c.replace(s,function(h){if(d>=l)return h;var p=u[d];switch(d+=1,h){case"%%":return"%";case"%s":return String(p);case"%d":return Number(p);case"%v":return""}})},i=function(c,d,u){var l=d.format instanceof Function?d.format(d.push?u:u[d.name]):d.format,h=[c+"="+l];if(d.names)for(var p=0;p<d.names.length;p+=1){var m=d.names[p];d.name?h.push(u[d.name][m]):h.push(u[d.names[p]])}else h.push(u[d.name]);return n.apply(null,h)},o=["v","o","s","i","u","e","p","c","b","t","r","z","a"],a=["i","c","b","a"];e.exports=function(c,d){d=d||{},c.version==null&&(c.version=0),c.name==null&&(c.name=" "),c.media.forEach(function(p){p.payloads==null&&(p.payloads="")});var u=d.outerOrder||o,l=d.innerOrder||a,h=[];return u.forEach(function(p){r[p].forEach(function(m){m.name in c&&c[m.name]!=null?h.push(i(p,m,c)):m.push in c&&c[m.push]!=null&&c[m.push].forEach(function(_){h.push(i(p,m,_))})})}),c.media.forEach(function(p){h.push(i("m",r.m[0],p)),l.forEach(function(m){r[m].forEach(function(_){_.name in p&&p[_.name]!=null?h.push(i(m,_,p)):_.push in p&&p[_.push]!=null&&p[_.push].forEach(function(f){h.push(i(m,_,f))})})})}),h.join(`\r
|
|
146
146
|
`)+`\r
|
|
147
|
-
`}}),wc=nt(t=>{"use strict";var e=Fre(),r=Hre(),s=GA();t.grammar=s,t.write=r,t.parse=e.parse,t.parseParams=e.parseParams,t.parseFmtpConfig=e.parseFmtpConfig,t.parsePayloads=e.parsePayloads,t.parseRemoteCandidates=e.parseRemoteCandidates,t.parseImageAttributes=e.parseImageAttributes,t.parseSimulcastStreamList=e.parseSimulcastStreamList}),Jh=nt(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parse=r;var e=new RegExp("^[LS]([1-9]\\d{0,1})T([1-9]\\d{0,1})");function r(s){let n=e.exec(s??"");return n?{spatialLayers:Number(n[1]),temporalLayers:Number(n[2])}:{spatialLayers:1,temporalLayers:1}}}),qre=nt(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OfferMediaSection=t.AnswerMediaSection=t.MediaSection=void 0;var e=wc(),r=Yh(),s=class{_mediaObject;constructor({iceParameters:a,iceCandidates:c,dtlsParameters:d}){if(this._mediaObject={type:"",port:0,protocol:"",payloads:"",rtp:[],fmtp:[]},a&&this.setIceParameters(a),c){this._mediaObject.candidates=[];for(let u of c){let l={foundation:u.foundation,component:1,ip:u.address??u.ip,port:u.port,priority:u.priority,transport:u.protocol,type:u.type};u.tcpType&&(l.tcptype=u.tcpType),this._mediaObject.candidates.push(l)}this._mediaObject.endOfCandidates="end-of-candidates",this._mediaObject.iceOptions="renomination"}d&&this.setDtlsRole(d.role)}get mid(){return String(this._mediaObject.mid)}get closed(){return this._mediaObject.port===0}getObject(){return this._mediaObject}setIceParameters(a){this._mediaObject.iceUfrag=a.usernameFragment,this._mediaObject.icePwd=a.password}pause(){this._mediaObject.direction="inactive"}disable(){this.pause()}close(){this.disable(),this._mediaObject.port=0,delete this._mediaObject.candidates,delete this._mediaObject.endOfCandidates,delete this._mediaObject.iceUfrag,delete this._mediaObject.icePwd,delete this._mediaObject.iceOptions,this._mediaObject.rtp=[],this._mediaObject.fmtp=[],delete this._mediaObject.rtcp,delete this._mediaObject.rtcpFb,delete this._mediaObject.ssrcs,delete this._mediaObject.ssrcGroups,delete this._mediaObject.simulcast,delete this._mediaObject.simulcast_03,delete this._mediaObject.rids,delete this._mediaObject.extmapAllowMixed}};t.MediaSection=s;var n=class extends s{constructor({iceParameters:a,iceCandidates:c,dtlsParameters:d,sctpParameters:u,plainRtpParameters:l,offerMediaObject:h,offerRtpParameters:p,answerRtpParameters:m,codecOptions:_}){switch(super({iceParameters:a,iceCandidates:c,dtlsParameters:d}),this._mediaObject.mid=String(h.mid),this._mediaObject.type=h.type,this._mediaObject.protocol=h.protocol,l?(this._mediaObject.connection={ip:l.ip,version:l.ipVersion},this._mediaObject.port=l.port):(this._mediaObject.connection={ip:"127.0.0.1",version:4},this._mediaObject.port=7),h.type){case"audio":case"video":{this._mediaObject.direction="recvonly",this._mediaObject.rtp=[],this._mediaObject.rtcpFb=[],this._mediaObject.fmtp=[];for(let f of m.codecs){let b={payload:f.payloadType,codec:o(f),rate:f.clockRate};f.channels>1&&(b.encoding=f.channels),this._mediaObject.rtp.push(b);let w=r.clone(f.parameters)??{},S=r.clone(f.rtcpFeedback)??[];if(_){let{opusStereo:j,opusFec:P,opusDtx:k,opusMaxPlaybackRate:C,opusMaxAverageBitrate:D,opusPtime:H,opusNack:W,videoGoogleStartBitrate:J,videoGoogleMaxBitrate:F,videoGoogleMinBitrate:q}=_,Q=p.codecs.find(R=>R.payloadType===f.payloadType);switch(f.mimeType.toLowerCase()){case"audio/opus":case"audio/multiopus":{j!==void 0&&(Q.parameters["sprop-stereo"]=j?1:0,w.stereo=j?1:0),P!==void 0&&(Q.parameters.useinbandfec=P?1:0,w.useinbandfec=P?1:0),k!==void 0&&(Q.parameters.usedtx=k?1:0,w.usedtx=k?1:0),C!==void 0&&(w.maxplaybackrate=C),D!==void 0&&(w.maxaveragebitrate=D),H!==void 0&&(Q.parameters.ptime=H,w.ptime=H),W||(Q.rtcpFeedback=Q.rtcpFeedback.filter(R=>R.type!=="nack"||R.parameter),S=S.filter(R=>R.type!=="nack"||R.parameter));break}case"video/vp8":case"video/vp9":case"video/h264":case"video/h265":case"video/av1":{J!==void 0&&(w["x-google-start-bitrate"]=J),F!==void 0&&(w["x-google-max-bitrate"]=F),q!==void 0&&(w["x-google-min-bitrate"]=q);break}}}let O={payload:f.payloadType,config:""};for(let j of Object.keys(w))O.config&&(O.config+=";"),O.config+=`${j}=${w[j]}`;O.config&&this._mediaObject.fmtp.push(O);for(let j of S)this._mediaObject.rtcpFb.push({payload:f.payloadType,type:j.type,subtype:j.parameter})}this._mediaObject.payloads=m.codecs.map(f=>f.payloadType).join(" "),this._mediaObject.ext=[];for(let f of m.headerExtensions)(h.ext??[]).some(b=>b.uri===f.uri)&&this._mediaObject.ext.push({uri:f.uri,value:f.id});if(h.extmapAllowMixed==="extmap-allow-mixed"&&(this._mediaObject.extmapAllowMixed="extmap-allow-mixed"),h.simulcast){this._mediaObject.simulcast={dir1:"recv",list1:h.simulcast.list1},this._mediaObject.rids=[];for(let f of h.rids??[])f.direction==="send"&&this._mediaObject.rids.push({id:f.id,direction:"recv"})}else if(h.simulcast_03){this._mediaObject.simulcast_03={value:h.simulcast_03.value.replace(/send/g,"recv")},this._mediaObject.rids=[];for(let f of h.rids??[])f.direction==="send"&&this._mediaObject.rids.push({id:f.id,direction:"recv"})}this._mediaObject.rtcpMux="rtcp-mux",this._mediaObject.rtcpRsize="rtcp-rsize";break}case"application":{typeof h.sctpPort=="number"?(this._mediaObject.payloads="webrtc-datachannel",this._mediaObject.sctpPort=u.port,this._mediaObject.maxMessageSize=u.maxMessageSize):h.sctpmap&&(this._mediaObject.payloads=String(u.port),this._mediaObject.sctpmap={app:"webrtc-datachannel",sctpmapNumber:u.port,maxMessageSize:u.maxMessageSize});break}}}setDtlsRole(a){switch(a){case"client":{this._mediaObject.setup="active";break}case"server":{this._mediaObject.setup="passive";break}case"auto":{this._mediaObject.setup="actpass";break}}}resume(){this._mediaObject.direction="recvonly"}muxSimulcastStreams(a){if(!this._mediaObject.simulcast?.list1)return;let c={};for(let l of a)l.rid&&(c[l.rid]=l);let d=this._mediaObject.simulcast.list1,u=e.parseSimulcastStreamList(d);for(let l of u)for(let h of l)h.paused=!c[h.scid]?.active;this._mediaObject.simulcast.list1=u.map(l=>l.map(h=>`${h.paused?"~":""}${h.scid}`).join(",")).join(";")}};t.AnswerMediaSection=n;var i=class extends s{constructor({iceParameters:a,iceCandidates:c,dtlsParameters:d,sctpParameters:u,plainRtpParameters:l,mid:h,kind:p,offerRtpParameters:m,streamId:_,trackId:f}){switch(super({iceParameters:a,iceCandidates:c,dtlsParameters:d}),this._mediaObject.mid=String(h),this._mediaObject.type=p,l?(this._mediaObject.connection={ip:l.ip,version:l.ipVersion},this._mediaObject.protocol="RTP/AVP",this._mediaObject.port=l.port):(this._mediaObject.connection={ip:"127.0.0.1",version:4},u?this._mediaObject.protocol="UDP/DTLS/SCTP":this._mediaObject.protocol="UDP/TLS/RTP/SAVPF",this._mediaObject.port=7),this._mediaObject.extmapAllowMixed="extmap-allow-mixed",p){case"audio":case"video":{this._mediaObject.direction="sendonly",this._mediaObject.rtp=[],this._mediaObject.rtcpFb=[],this._mediaObject.fmtp=[],this._mediaObject.msid=[{id:_,appdata:f}];for(let O of m.codecs){let j={payload:O.payloadType,codec:o(O),rate:O.clockRate};O.channels>1&&(j.encoding=O.channels),this._mediaObject.rtp.push(j);let P={payload:O.payloadType,config:""};for(let k of Object.keys(O.parameters??{}))P.config&&(P.config+=";"),P.config+=`${k}=${O.parameters[k]}`;P.config&&this._mediaObject.fmtp.push(P);for(let k of O.rtcpFeedback)this._mediaObject.rtcpFb.push({payload:O.payloadType,type:k.type,subtype:k.parameter})}this._mediaObject.payloads=m.codecs.map(O=>O.payloadType).join(" "),this._mediaObject.ext=[];for(let O of m.headerExtensions)this._mediaObject.ext.push({uri:O.uri,value:O.id});this._mediaObject.rtcpMux="rtcp-mux",this._mediaObject.rtcpRsize="rtcp-rsize";let b=m.encodings[0],w=b.ssrc,S=b.rtx?.ssrc;this._mediaObject.ssrcs=[],this._mediaObject.ssrcGroups=[],w&&m.rtcp.cname&&this._mediaObject.ssrcs.push({id:w,attribute:"cname",value:m.rtcp.cname}),S&&(m.rtcp.cname&&this._mediaObject.ssrcs.push({id:S,attribute:"cname",value:m.rtcp.cname}),w&&this._mediaObject.ssrcGroups.push({semantics:"FID",ssrcs:`${w} ${S}`}));break}case"application":{this._mediaObject.payloads="webrtc-datachannel",this._mediaObject.sctpPort=u.port,this._mediaObject.maxMessageSize=u.maxMessageSize;break}}}setDtlsRole(a){this._mediaObject.setup="actpass"}resume(){this._mediaObject.direction="sendonly"}};t.OfferMediaSection=i;function o(a){let c=new RegExp("^(audio|video)/(.+)","i").exec(a.mimeType);if(!c)throw new TypeError("invalid codec.mimeType");return c[2]}}),gg=nt(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RemoteSdp=void 0;var e=wc(),r=Os(),s=qre(),n=CF(),i=["av1","h264"],o=new r.Logger("RemoteSdp"),a=class{_iceParameters;_iceCandidates;_dtlsParameters;_sctpParameters;_plainRtpParameters;_mediaSections=[];_midToIndex=new Map;_firstMid;_sdpObject;constructor({iceParameters:c,iceCandidates:d,dtlsParameters:u,sctpParameters:l,plainRtpParameters:h}){if(this._iceParameters=c,this._iceCandidates=d,this._dtlsParameters=u,this._sctpParameters=l,this._plainRtpParameters=h,this._sdpObject={version:0,origin:{address:"0.0.0.0",ipVer:4,netType:"IN",sessionId:"10000",sessionVersion:0,username:`media-client-v${n.version}`},name:"-",timing:{start:0,stop:0},media:[]},this._sdpObject.iceOptions="ice2",c?.iceLite&&(this._sdpObject.icelite="ice-lite"),u){this._sdpObject.msidSemantic={semantic:"WMS",token:"*"};let p=this._dtlsParameters.fingerprints.length;this._sdpObject.fingerprint={type:u.fingerprints[p-1].algorithm,hash:u.fingerprints[p-1].value},this._sdpObject.groups=[{type:"BUNDLE",mids:""}]}h&&(this._sdpObject.origin.address=h.ip,this._sdpObject.origin.ipVer=h.ipVersion)}updateIceParameters(c){o.debug("updateIceParameters() [iceParameters:%o]",c),this._iceParameters=c,this._sdpObject.icelite=c.iceLite?"ice-lite":void 0;for(let d of this._mediaSections)d.setIceParameters(c)}updateDtlsRole(c){o.debug("updateDtlsRole() [role:%s]",c),this._dtlsParameters.role=c;for(let d of this._mediaSections)d.setDtlsRole(c)}setSessionExtmapAllowMixed(){o.debug("setSessionExtmapAllowMixed()"),this._sdpObject.extmapAllowMixed="extmap-allow-mixed"}getNextMediaSectionIdx(){for(let c=0;c<this._mediaSections.length;++c){let d=this._mediaSections[c];if(d.closed)return{idx:c,reuseMid:d.mid}}return{idx:this._mediaSections.length}}send({offerMediaObject:c,reuseMid:d,offerRtpParameters:u,answerRtpParameters:l,codecOptions:h}){let p=new s.AnswerMediaSection({iceParameters:this._iceParameters,iceCandidates:this._iceCandidates,dtlsParameters:this._dtlsParameters,plainRtpParameters:this._plainRtpParameters,offerMediaObject:c,offerRtpParameters:u,answerRtpParameters:l,codecOptions:h}),m=p.getObject();m.rtp.find(_=>i.includes(_.codec.toLowerCase()))||(m.ext=m.ext?.filter(_=>_.uri!=="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension")),d?this.replaceMediaSection(p,d):this._midToIndex.has(p.mid)?this.replaceMediaSection(p):this.addMediaSection(p)}receive({mid:c,kind:d,offerRtpParameters:u,streamId:l,trackId:h}){this.setSessionExtmapAllowMixed();let p=new s.OfferMediaSection({iceParameters:this._iceParameters,iceCandidates:this._iceCandidates,dtlsParameters:this._dtlsParameters,plainRtpParameters:this._plainRtpParameters,mid:c,kind:d,offerRtpParameters:u,streamId:l,trackId:h}),m=this._mediaSections.find(_=>_.closed&&_.getObject().type===d);m?this.replaceMediaSection(p,m.mid):this.addMediaSection(p)}pauseMediaSection(c){this.findMediaSection(c).pause()}resumeSendingMediaSection(c){this.findMediaSection(c).resume()}resumeReceivingMediaSection(c){this.findMediaSection(c).resume()}disableMediaSection(c){this.findMediaSection(c).disable()}closeMediaSection(c){let d=this.findMediaSection(c);return c===this._firstMid?(o.debug("closeMediaSection() | cannot close first media section, disabling it instead [mid:%s]",c),this.disableMediaSection(c),!1):(d.close(),this.regenerateBundleMids(),!0)}muxMediaSectionSimulcast(c,d){let u=this.findMediaSection(c);u.muxSimulcastStreams(d),this.replaceMediaSection(u)}sendSctpAssociation({offerMediaObject:c}){let d=new s.AnswerMediaSection({iceParameters:this._iceParameters,iceCandidates:this._iceCandidates,dtlsParameters:this._dtlsParameters,sctpParameters:this._sctpParameters,plainRtpParameters:this._plainRtpParameters,offerMediaObject:c});this.addMediaSection(d)}receiveSctpAssociation(){let c=new s.OfferMediaSection({iceParameters:this._iceParameters,iceCandidates:this._iceCandidates,dtlsParameters:this._dtlsParameters,sctpParameters:this._sctpParameters,plainRtpParameters:this._plainRtpParameters,mid:"datachannel",kind:"application"});this.addMediaSection(c)}getSdp(){return this._sdpObject.origin.sessionVersion++,e.write(this._sdpObject)}addMediaSection(c){this._firstMid||(this._firstMid=c.mid),this._mediaSections.push(c),this._midToIndex.set(c.mid,this._mediaSections.length-1),this._sdpObject.media.push(c.getObject()),this.regenerateBundleMids()}replaceMediaSection(c,d){if(typeof d=="string"){let u=this._midToIndex.get(d);if(u===void 0)throw new Error(`no media section found for reuseMid '${d}'`);let l=this._mediaSections[u];this._mediaSections[u]=c,this._midToIndex.delete(l.mid),this._midToIndex.set(c.mid,u),this._sdpObject.media[u]=c.getObject(),this.regenerateBundleMids()}else{let u=this._midToIndex.get(c.mid);if(u===void 0)throw new Error(`no media section found with mid '${c.mid}'`);this._mediaSections[u]=c,this._sdpObject.media[u]=c.getObject()}}findMediaSection(c){let d=this._midToIndex.get(c);if(d===void 0)throw new Error(`no media section found with mid '${c}'`);return this._mediaSections[d]}regenerateBundleMids(){this._dtlsParameters&&(this._sdpObject.groups[0].mids=this._mediaSections.filter(c=>!c.closed).map(c=>c.mid).join(" "))}};t.RemoteSdp=a}),yg=nt(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractRtpCapabilities=r,t.extractDtlsParameters=s,t.getCname=n,t.applyCodecParameters=i,t.addHeaderExtension=o;var e=wc();function r({sdpObject:a}){let c=new Map,d=new Map;for(let u of a.media){let l=u.type;switch(l){case"audio":case"video":break;default:continue}for(let h of u.rtp){let p={kind:l,mimeType:`${l}/${h.codec}`,preferredPayloadType:h.payload,clockRate:h.rate,channels:h.encoding,parameters:{},rtcpFeedback:[]};c.set(p.preferredPayloadType,p)}for(let h of u.fmtp??[]){let p=e.parseParams(h.config),m=c.get(h.payload);m&&(p?.hasOwnProperty("profile-level-id")&&(p["profile-level-id"]=String(p["profile-level-id"])),m.parameters=p)}for(let h of u.rtcpFb??[]){let p={type:h.type,parameter:h.subtype};if(p.parameter||delete p.parameter,h.payload!=="*"){let m=c.get(Number(h.payload));if(!m)continue;m.rtcpFeedback.push(p)}else for(let m of c.values())m.kind===l&&!/.+\/rtx$/i.test(m.mimeType)&&m.rtcpFeedback.push(p)}for(let h of u.ext??[]){if(h["encrypt-uri"])continue;let p={kind:l,uri:h.uri,preferredId:h.value};d.set(p.preferredId,p)}}return{codecs:Array.from(c.values()),headerExtensions:Array.from(d.values())}}function s({sdpObject:a}){let c=a.setup,d=a.fingerprint;if(!c||!d){let l=(a.media??[]).find(h=>h.port!==0);l&&(c=c??l.setup,d=d??l.fingerprint)}if(c){if(!d)throw new Error("no a=fingerprint found at SDP session or media level")}else throw new Error("no a=setup found at SDP session or media level");let u;switch(c){case"active":{u="client";break}case"passive":{u="server";break}case"actpass":{u="auto";break}}return{role:u,fingerprints:[{algorithm:d.type,value:d.hash}]}}function n({offerMediaObject:a}){let c=(a.ssrcs??[]).find(d=>d.attribute==="cname");return c?c.value:""}function i({offerRtpParameters:a,answerMediaObject:c}){for(let d of a.codecs){let u=d.mimeType.toLowerCase();if(u!=="audio/opus"||!(c.rtp??[]).find(p=>p.payload===d.payloadType))continue;c.fmtp=c.fmtp??[];let l=c.fmtp.find(p=>p.payload===d.payloadType);l||(l={payload:d.payloadType,config:""},c.fmtp.push(l));let h=e.parseParams(l.config);if(u==="audio/opus"){let p=d.parameters?.["sprop-stereo"];p!==void 0&&(h.stereo=Number(p)?1:0)}l.config="";for(let p of Object.keys(h))l.config&&(l.config+=";"),l.config+=`${p}=${h[p]}`}}function o({offerMediaObject:a,headerExtensionUri:c,headerExtensionId:d}){a.ext||(a.ext=[]),a.ext.push({uri:c,value:d})}}),bg=nt(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getRtpEncodings=e,t.addLegacySimulcast=r;function e({offerMediaObject:s,codecs:n}){let i=new Set;for(let c of s.ssrcs??[]){let d=c.id;d&&i.add(d)}if(i.size===0)throw new Error("no a=ssrc lines found");let o=new Map;for(let c of s.ssrcGroups??[]){if(c.semantics!=="FID")continue;let d=c.ssrcs.split(/\s+/),u=Number(d[0]),l=Number(d[1]);i.has(u)&&(i.delete(u),i.delete(l),o.set(u,l))}for(let c of i)o.set(c,void 0);let a=[];for(let[c,d]of o){let u={ssrc:c};d&&n.length>1&&(u.rtx={ssrc:d}),a.push(u)}return a}function r({offerMediaObject:s,numStreams:n}){if(n<=1)throw new TypeError("numStreams must be greater than 1");let i=(s.ssrcs??[]).find(m=>m.attribute==="msid");if(!i)throw new Error("a=ssrc line with msid information not found");let[o,a]=i.value.split(" "),c=Number(i.id),d;(s.ssrcGroups??[]).some(m=>{if(m.semantics!=="FID")return!1;let _=m.ssrcs.split(/\s+/);return Number(_[0])===c?(d=Number(_[1]),!0):!1});let u=(s.ssrcs??[]).find(m=>m.attribute==="cname");if(!u)throw new Error("a=ssrc line with cname information not found");let l=u.value,h=[],p=[];for(let m=0;m<n;++m)h.push(c+m),d&&p.push(d+m);s.ssrcGroups=[],s.ssrcs=[],s.ssrcGroups.push({semantics:"SIM",ssrcs:h.join(" ")});for(let m of h)s.ssrcs.push({id:m,attribute:"cname",value:l}),s.ssrcs.push({id:m,attribute:"msid",value:`${o} ${a}`});for(let m=0;m<p.length;++m){let _=h[m],f=p[m];s.ssrcs.push({id:f,attribute:"cname",value:l}),s.ssrcs.push({id:f,attribute:"msid",value:`${o} ${a}`}),s.ssrcGroups.push({semantics:"FID",ssrcs:`${_} ${f}`})}}}),xg=nt(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addNackSupportForOpus=e,t.addHeaderExtensionSupport=r,t.getMsidStreamIdAndTrackId=s;function e(n){for(let i of n.codecs??[])(i.mimeType.toLowerCase()==="audio/opus"||i.mimeType.toLowerCase()==="audio/multiopus")&&!i.rtcpFeedback?.some(o=>o.type==="nack"&&!o.parameter)&&(i.rtcpFeedback||(i.rtcpFeedback=[]),i.rtcpFeedback.push({type:"nack"}))}function r(n,i){let o,a=n.headerExtensions?.find(d=>d.uri===i.uri);if(a){if(a.kind===i.kind)return;o=a.preferredId}if(n.headerExtensions||(n.headerExtensions=[]),o===void 0){o=1;let d=new Set(n.headerExtensions.map(u=>u.preferredId));for(;d.has(o);)++o}let c={kind:i.kind,uri:i.uri,preferredId:o,preferredEncrypt:!1,direction:i.direction};n.headerExtensions.push(c)}function s(n){if(!n||typeof n!="string")return{msidStreamId:void 0,msidTrackId:void 0};let[i,o]=n.trim().split(/\s+/);return i?{msidStreamId:i,msidTrackId:o}:{msidStreamId:void 0,msidTrackId:void 0}}}),Vre=nt(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Chrome111=void 0;var e=wc(),r=Xs(),s=Os(),n=ea(),i=Zn(),o=Jh(),a=gg(),c=yg(),d=bg(),u=xg(),l=new s.Logger("Chrome111"),h="Chrome111",p={OS:65535,MIS:65535},m=class E1 extends r.EnhancedEventEmitter{_closed=!1;_direction;_remoteSdp;_getSendExtendedRtpCapabilities;_forcedLocalDtlsRole;_pc;_mapMidTransceiver=new Map;_sendStream=new MediaStream;_hasDataChannelMediaSection=!1;_nextSendSctpStreamId=0;_transportReady=!1;static createFactory(){return{name:h,factory:f=>new E1(f),getNativeRtpCapabilities:async({direction:f})=>{l.debug("getNativeRtpCapabilities() [direction:%o]",f);let b=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{b.addTransceiver("audio",{direction:f}),b.addTransceiver("video",{direction:f,sendEncodings:[{scalabilityMode:"L3T3"}]});let w=await b.createOffer();try{b.close()}catch{}b=void 0;let S=e.parse(w.sdp);return E1.getLocalRtpCapabilities(S)}catch(w){try{b?.close()}catch{}throw b=void 0,w}},getNativeSctpCapabilities:async()=>(l.debug("getNativeSctpCapabilities()"),{numStreams:p})}}static getLocalRtpCapabilities(f,b=[]){let w=c.extractRtpCapabilities({sdpObject:f});n.validateAndNormalizeRtpCapabilities(w),u.addNackSupportForOpus(w);for(let S of b)u.addHeaderExtensionSupport(w,S);return w}constructor({direction:f,iceParameters:b,iceCandidates:w,dtlsParameters:S,sctpParameters:O,iceServers:j,iceTransportPolicy:P,additionalSettings:k,getSendExtendedRtpCapabilities:C}){super(),l.debug("constructor()"),this._direction=f,this._remoteSdp=new a.RemoteSdp({iceParameters:b,iceCandidates:w,dtlsParameters:S,sctpParameters:O}),this._getSendExtendedRtpCapabilities=C,S.role&&S.role!=="auto"&&(this._forcedLocalDtlsRole=S.role==="server"?"client":"server"),this._pc=new RTCPeerConnection({iceServers:j??[],iceTransportPolicy:P??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...k}),this._pc.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.addEventListener("icecandidateerror",this.onIceCandidateError),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",this.onConnectionStateChange):(l.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return h}close(){if(l.debug("close()"),!this._closed){this._closed=!0;try{this._pc.close()}catch{}this._pc.removeEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.removeEventListener("icecandidateerror",this.onIceCandidateError),this._pc.removeEventListener("connectionstatechange",this.onConnectionStateChange),this._pc.removeEventListener("iceconnectionstatechange",this.onIceConnectionStateChange),this.emit("@close"),super.close()}}async updateIceServers(f){this.assertNotClosed(),l.debug("updateIceServers()");let b=this._pc.getConfiguration();b.iceServers=f,this._pc.setConfiguration(b)}async restartIce(f){if(this.assertNotClosed(),l.debug("restartIce()"),this._remoteSdp.updateIceParameters(f),!!this._transportReady)if(this._direction==="send"){let b=await this._pc.createOffer({iceRestart:!0});l.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",b),await this._pc.setLocalDescription(b);let w={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",w),await this._pc.setRemoteDescription(w)}else{let b={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",b),await this._pc.setRemoteDescription(b);let w=await this._pc.createAnswer();l.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",w),await this._pc.setLocalDescription(w)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:f,streamId:b,encodings:w,codecOptions:S,headerExtensionOptions:O,codec:j,onRtpSender:P}){if(this.assertNotClosed(),this.assertSendDirection(),l.debug("send() [kind:%s, track.id:%s, streamId:%s]",f.kind,f.id,b),w&&w.length>1){let I=1;for(let U of w){let K=U.scalabilityMode?(0,o.parse)(U.scalabilityMode).temporalLayers:3;K>I&&(I=K)}w.forEach((U,K)=>{U.rid=`r${K}`,U.scalabilityMode=`L1T${I}`})}let k=this._remoteSdp.getNextMediaSectionIdx(),C=this._pc.addTransceiver(f,{direction:"sendonly",streams:[this._sendStream],sendEncodings:w});P&&P(C.sender);let D=await this._pc.createOffer(),H=e.parse(D.sdp);H.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();let W=[];W.push({uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",kind:f.kind,direction:"sendonly"});let J=E1.getLocalRtpCapabilities(H,W),F=this._getSendExtendedRtpCapabilities(J),q=n.getSendingRtpParameters(f.kind,F);q.codecs=n.reduceCodecs(q.codecs,j);let Q=n.getSendingRemoteRtpParameters(f.kind,F);if(Q.codecs=n.reduceCodecs(Q.codecs,j),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:H}),O?.absCaptureTime){let I=H.media[k.idx];c.addHeaderExtension({offerMediaObject:I,headerExtensionUri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",headerExtensionId:Q.headerExtensions.find(U=>U.uri==="http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time").id}),D={type:"offer",sdp:e.write(H)}}l.debug("send() | calling pc.setLocalDescription() [offer:%o]",D),await this._pc.setLocalDescription(D);let R=C.mid;q.mid=R,H=e.parse(this._pc.localDescription.sdp);let Y=H.media[k.idx];if(q.rtcp.cname=c.getCname({offerMediaObject:Y}),q.msid=`${b??this._sendStream.id} ${f.id}`,!w)q.encodings=d.getRtpEncodings({offerMediaObject:Y,codecs:q.codecs});else if(w.length===1){let I=d.getRtpEncodings({offerMediaObject:Y,codecs:q.codecs});Object.assign(I[0],w[0]),q.encodings=I}else q.encodings=w;this._remoteSdp.send({offerMediaObject:Y,reuseMid:k.reuseMid,offerRtpParameters:q,answerRtpParameters:Q,codecOptions:S});let Z={type:"answer",sdp:this._remoteSdp.getSdp()};return l.debug("send() | calling pc.setRemoteDescription() [answer:%o]",Z),await this._pc.setRemoteDescription(Z),this._mapMidTransceiver.set(R,C),{localId:R,rtpParameters:q,rtpSender:C.sender}}async stopSending(f){if(this.assertSendDirection(),l.debug("stopSending() [localId:%s]",f),this._closed)return;let b=this._mapMidTransceiver.get(f);if(!b)throw new Error("associated RTCRtpTransceiver not found");if(b.sender.replaceTrack(null),this._pc.removeTrack(b.sender),this._remoteSdp.closeMediaSection(b.mid))try{b.stop()}catch{}let w=await this._pc.createOffer();l.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",w),await this._pc.setLocalDescription(w);let S={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",S),await this._pc.setRemoteDescription(S),this._mapMidTransceiver.delete(f)}async pauseSending(f){this.assertNotClosed(),this.assertSendDirection(),l.debug("pauseSending() [localId:%s]",f);let b=this._mapMidTransceiver.get(f);if(!b)throw new Error("associated RTCRtpTransceiver not found");b.direction="inactive",this._remoteSdp.pauseMediaSection(f);let w=await this._pc.createOffer();l.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",w),await this._pc.setLocalDescription(w);let S={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",S),await this._pc.setRemoteDescription(S)}async resumeSending(f){this.assertNotClosed(),this.assertSendDirection(),l.debug("resumeSending() [localId:%s]",f);let b=this._mapMidTransceiver.get(f);if(this._remoteSdp.resumeSendingMediaSection(f),!b)throw new Error("associated RTCRtpTransceiver not found");b.direction="sendonly";let w=await this._pc.createOffer();l.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",w),await this._pc.setLocalDescription(w);let S={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",S),await this._pc.setRemoteDescription(S)}async replaceTrack(f,b){this.assertNotClosed(),this.assertSendDirection(),b?l.debug("replaceTrack() [localId:%s, track.id:%s]",f,b.id):l.debug("replaceTrack() [localId:%s, no track]",f);let w=this._mapMidTransceiver.get(f);if(!w)throw new Error("associated RTCRtpTransceiver not found");await w.sender.replaceTrack(b)}async setMaxSpatialLayer(f,b){this.assertNotClosed(),this.assertSendDirection(),l.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",f,b);let w=this._mapMidTransceiver.get(f);if(!w)throw new Error("associated RTCRtpTransceiver not found");let S=w.sender.getParameters();S.encodings.forEach((P,k)=>{k<=b?P.active=!0:P.active=!1}),await w.sender.setParameters(S),this._remoteSdp.muxMediaSectionSimulcast(f,S.encodings);let O=await this._pc.createOffer();l.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",O),await this._pc.setLocalDescription(O);let j={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",j),await this._pc.setRemoteDescription(j)}async setRtpEncodingParameters(f,b){this.assertNotClosed(),this.assertSendDirection(),l.debug("setRtpEncodingParameters() [localId:%s, params:%o]",f,b);let w=this._mapMidTransceiver.get(f);if(!w)throw new Error("associated RTCRtpTransceiver not found");let S=w.sender.getParameters();S.encodings.forEach((P,k)=>{S.encodings[k]={...P,...b}}),await w.sender.setParameters(S),this._remoteSdp.muxMediaSectionSimulcast(f,S.encodings);let O=await this._pc.createOffer();l.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",O),await this._pc.setLocalDescription(O);let j={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",j),await this._pc.setRemoteDescription(j)}async getSenderStats(f){this.assertNotClosed(),this.assertSendDirection();let b=this._mapMidTransceiver.get(f);if(!b)throw new Error("associated RTCRtpTransceiver not found");return b.sender.getStats()}async sendDataChannel({sctpStreamParameters:f}){this.assertNotClosed(),this.assertSendDirection();let b={negotiated:!0,id:this._nextSendSctpStreamId,ordered:f.ordered,maxPacketLifeTime:f.maxPacketLifeTime,maxRetransmits:f.maxRetransmits,protocol:f.protocol};l.debug("sendDataChannel() [options:%o]",b);let w=this._pc.createDataChannel(f.label,b);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%p.MIS,!this._hasDataChannelMediaSection){let O=await this._pc.createOffer(),j=e.parse(O.sdp),P=j.media.find(C=>C.type==="application");this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:j}),l.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",O),await this._pc.setLocalDescription(O),this._remoteSdp.sendSctpAssociation({offerMediaObject:P});let k={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",k),await this._pc.setRemoteDescription(k),this._hasDataChannelMediaSection=!0}let S={streamId:b.id,ordered:b.ordered,maxPacketLifeTime:b.maxPacketLifeTime,maxRetransmits:b.maxRetransmits};return{dataChannel:w,sctpStreamParameters:S}}async receive(f){this.assertNotClosed(),this.assertRecvDirection();let b=[],w=new Map;for(let P of f){let{trackId:k,kind:C,rtpParameters:D,streamId:H}=P;l.debug("receive() [trackId:%s, kind:%s]",k,C);let W=D.mid??String(this._mapMidTransceiver.size);w.set(k,W);let{msidStreamId:J}=u.getMsidStreamIdAndTrackId(D.msid);this._remoteSdp.receive({mid:W,kind:C,offerRtpParameters:D,streamId:H??J??D.rtcp?.cname??"-",trackId:k})}let S={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",S),await this._pc.setRemoteDescription(S);for(let P of f){let{trackId:k,onRtpReceiver:C}=P;if(C){let D=w.get(k),H=this._pc.getTransceivers().find(W=>W.mid===D);if(!H)throw new Error("transceiver not found");C(H.receiver)}}let O=await this._pc.createAnswer(),j=e.parse(O.sdp);for(let P of f){let{trackId:k,rtpParameters:C}=P,D=w.get(k),H=j.media.find(W=>String(W.mid)===D);c.applyCodecParameters({offerRtpParameters:C,answerMediaObject:H})}O={type:"answer",sdp:e.write(j)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:j}),l.debug("receive() | calling pc.setLocalDescription() [answer:%o]",O),await this._pc.setLocalDescription(O);for(let P of f){let{trackId:k}=P,C=w.get(k),D=this._pc.getTransceivers().find(H=>H.mid===C);if(D)this._mapMidTransceiver.set(C,D),b.push({localId:C,track:D.receiver.track,rtpReceiver:D.receiver});else throw new Error("new RTCRtpTransceiver not found")}return b}async stopReceiving(f){if(this.assertRecvDirection(),this._closed)return;for(let S of f){l.debug("stopReceiving() [localId:%s]",S);let O=this._mapMidTransceiver.get(S);if(!O)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(O.mid)}let b={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",b),await this._pc.setRemoteDescription(b);let w=await this._pc.createAnswer();l.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",w),await this._pc.setLocalDescription(w);for(let S of f)this._mapMidTransceiver.delete(S)}async pauseReceiving(f){this.assertNotClosed(),this.assertRecvDirection();for(let S of f){l.debug("pauseReceiving() [localId:%s]",S);let O=this._mapMidTransceiver.get(S);if(!O)throw new Error("associated RTCRtpTransceiver not found");O.direction="inactive",this._remoteSdp.pauseMediaSection(S)}let b={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",b),await this._pc.setRemoteDescription(b);let w=await this._pc.createAnswer();l.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",w),await this._pc.setLocalDescription(w)}async resumeReceiving(f){this.assertNotClosed(),this.assertRecvDirection();for(let S of f){l.debug("resumeReceiving() [localId:%s]",S);let O=this._mapMidTransceiver.get(S);if(!O)throw new Error("associated RTCRtpTransceiver not found");O.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(S)}let b={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",b),await this._pc.setRemoteDescription(b);let w=await this._pc.createAnswer();l.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",w),await this._pc.setLocalDescription(w)}async getReceiverStats(f){this.assertNotClosed(),this.assertRecvDirection();let b=this._mapMidTransceiver.get(f);if(!b)throw new Error("associated RTCRtpTransceiver not found");return b.receiver.getStats()}async receiveDataChannel({maxMessageSize:f,sctpStreamParameters:b,label:w,protocol:S}){this.assertNotClosed(),this.assertRecvDirection();let{streamId:O,ordered:j,maxPacketLifeTime:P,maxRetransmits:k}=b,C={negotiated:!0,id:O,ordered:j,maxPacketLifeTime:P,maxRetransmits:k,protocol:S};l.debug("receiveDataChannel() [options:%o]",C);let D=this._pc.createDataChannel(w,C);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();let H={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",H),await this._pc.setRemoteDescription(H);let W=await this._pc.createAnswer(),J=e.parse(W.sdp),F=J.media.find(q=>q.type==="application");F.maxMessageSize=f,this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:J}),W={type:"answer",sdp:e.write(J)},l.debug("receiveDataChannel() | calling pc.setLocalDescription() [answer:%o]",W),await this._pc.setLocalDescription(W),this._hasDataChannelMediaSection=!0}return{dataChannel:D}}getDataChannelMaxMessageSize(){return this._pc.sctp?.maxMessageSize}async setupTransport({localDtlsRole:f,localSdpObject:b}){b||(b=e.parse(this._pc.localDescription.sdp));let w=c.extractDtlsParameters({sdpObject:b});w.role=f,this._remoteSdp.updateDtlsRole(f==="client"?"server":"client"),await new Promise((S,O)=>{this.safeEmit("@connect",{dtlsParameters:w},S,O)}),this._transportReady=!0}onIceGatheringStateChange=()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)};onIceCandidateError=f=>{this.emit("@icecandidateerror",f)};onConnectionStateChange=()=>{this.emit("@connectionstatechange",this._pc.connectionState)};onIceConnectionStateChange=()=>{switch(this._pc.iceConnectionState){case"checking":{this.emit("@connectionstatechange","connecting");break}case"connected":case"completed":{this.emit("@connectionstatechange","connected");break}case"failed":{this.emit("@connectionstatechange","failed");break}case"disconnected":{this.emit("@connectionstatechange","disconnected");break}case"closed":{this.emit("@connectionstatechange","closed");break}}};assertNotClosed(){if(this._closed)throw new i.InvalidStateError("method called in a closed handler")}assertSendDirection(){if(this._direction!=="send")throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if(this._direction!=="recv")throw new Error('method can just be called for handlers with "recv" direction')}};t.Chrome111=m}),zre=nt(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Chrome74=void 0;var e=wc(),r=Os(),s=Xs(),n=ea(),i=Zn(),o=Jh(),a=gg(),c=yg(),d=bg(),u=xg(),l=new r.Logger("Chrome74"),h="Chrome74",p={OS:1024,MIS:1024},m=class C1 extends s.EnhancedEventEmitter{_closed=!1;_direction;_remoteSdp;_getSendExtendedRtpCapabilities;_forcedLocalDtlsRole;_pc;_mapMidTransceiver=new Map;_sendStream=new MediaStream;_hasDataChannelMediaSection=!1;_nextSendSctpStreamId=0;_transportReady=!1;static createFactory(){return{name:h,factory:f=>new C1(f),getNativeRtpCapabilities:async({direction:f})=>{l.debug("getNativeRtpCapabilities() [direction:%o]",f);let b=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{b.addTransceiver("audio",{direction:f}),b.addTransceiver("video",{direction:f});let w=await b.createOffer();try{b.close()}catch{}b=void 0;let S=e.parse(w.sdp);return C1.getLocalRtpCapabilities(S)}catch(w){try{b?.close()}catch{}throw b=void 0,w}},getNativeSctpCapabilities:async()=>(l.debug("getNativeSctpCapabilities()"),{numStreams:p})}}static getLocalRtpCapabilities(f,b=[]){let w=c.extractRtpCapabilities({sdpObject:f});n.validateAndNormalizeRtpCapabilities(w),u.addNackSupportForOpus(w);for(let S of b)u.addHeaderExtensionSupport(w,S);return w}constructor({direction:f,iceParameters:b,iceCandidates:w,dtlsParameters:S,sctpParameters:O,iceServers:j,iceTransportPolicy:P,additionalSettings:k,getSendExtendedRtpCapabilities:C}){super(),l.debug("constructor()"),this._direction=f,this._remoteSdp=new a.RemoteSdp({iceParameters:b,iceCandidates:w,dtlsParameters:S,sctpParameters:O}),this._getSendExtendedRtpCapabilities=C,S.role&&S.role!=="auto"&&(this._forcedLocalDtlsRole=S.role==="server"?"client":"server"),this._pc=new RTCPeerConnection({iceServers:j??[],iceTransportPolicy:P??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...k}),this._pc.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.addEventListener("icecandidateerror",this.onIceCandidateError),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",this.onConnectionStateChange):(l.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return h}close(){if(l.debug("close()"),!this._closed){this._closed=!0;try{this._pc.close()}catch{}this._pc.removeEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.removeEventListener("icecandidateerror",this.onIceCandidateError),this._pc.removeEventListener("connectionstatechange",this.onConnectionStateChange),this._pc.removeEventListener("iceconnectionstatechange",this.onIceConnectionStateChange),this.emit("@close"),super.close()}}async updateIceServers(f){this.assertNotClosed(),l.debug("updateIceServers()");let b=this._pc.getConfiguration();b.iceServers=f,this._pc.setConfiguration(b)}async restartIce(f){if(this.assertNotClosed(),l.debug("restartIce()"),this._remoteSdp.updateIceParameters(f),!!this._transportReady)if(this._direction==="send"){let b=await this._pc.createOffer({iceRestart:!0});l.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",b),await this._pc.setLocalDescription(b);let w={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",w),await this._pc.setRemoteDescription(w)}else{let b={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",b),await this._pc.setRemoteDescription(b);let w=await this._pc.createAnswer();l.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",w),await this._pc.setLocalDescription(w)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:f,streamId:b,encodings:w,codecOptions:S,headerExtensionOptions:O,codec:j}){this.assertNotClosed(),this.assertSendDirection(),l.debug("send() [kind:%s, track.id:%s, streamId:%s]",f.kind,f.id,b),w&&w.length>1&&w.forEach((U,K)=>{U.rid=`r${K}`});let P=this._remoteSdp.getNextMediaSectionIdx(),k=this._pc.addTransceiver(f,{direction:"sendonly",streams:[this._sendStream],sendEncodings:w}),C=await this._pc.createOffer(),D=e.parse(C.sdp);D.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();let H=[];H.push({uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",kind:f.kind,direction:"sendonly"});let W=C1.getLocalRtpCapabilities(D,H),J=this._getSendExtendedRtpCapabilities(W),F=n.getSendingRtpParameters(f.kind,J);F.codecs=n.reduceCodecs(F.codecs,j);let q=n.getSendingRemoteRtpParameters(f.kind,J);q.codecs=n.reduceCodecs(q.codecs,j),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:D});let Q=!1,R=(0,o.parse)((w??[{}])[0].scalabilityMode),Y;w?.length===1&&R.spatialLayers>1&&F.codecs[0].mimeType.toLowerCase()==="video/vp9"&&(l.debug("send() | enabling legacy simulcast for VP9 SVC"),Q=!0,D=e.parse(C.sdp),Y=D.media[P.idx],d.addLegacySimulcast({offerMediaObject:Y,numStreams:R.spatialLayers}),C={type:"offer",sdp:e.write(D)}),l.debug("send() | calling pc.setLocalDescription() [offer:%o]",C),O?.absCaptureTime&&(Y=D.media[P.idx],c.addHeaderExtension({offerMediaObject:Y,headerExtensionUri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",headerExtensionId:q.headerExtensions.find(U=>U.uri==="http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time").id}),C={type:"offer",sdp:e.write(D)}),await this._pc.setLocalDescription(C);let Z=k.mid;if(F.mid=Z,D=e.parse(this._pc.localDescription.sdp),Y=D.media[P.idx],F.rtcp.cname=c.getCname({offerMediaObject:Y}),F.msid=`${b??this._sendStream.id} ${f.id}`,!w)F.encodings=d.getRtpEncodings({offerMediaObject:Y,codecs:F.codecs});else if(w.length===1){let U=d.getRtpEncodings({offerMediaObject:Y,codecs:F.codecs});Object.assign(U[0],w[0]),Q&&(U=[U[0]]),F.encodings=U}else F.encodings=w;if(F.encodings.length>1&&(F.codecs[0].mimeType.toLowerCase()==="video/vp8"||F.codecs[0].mimeType.toLowerCase()==="video/h264"))for(let U of F.encodings)U.scalabilityMode?U.scalabilityMode=`L1T${R.temporalLayers}`:U.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:Y,reuseMid:P.reuseMid,offerRtpParameters:F,answerRtpParameters:q,codecOptions:S});let I={type:"answer",sdp:this._remoteSdp.getSdp()};return l.debug("send() | calling pc.setRemoteDescription() [answer:%o]",I),await this._pc.setRemoteDescription(I),this._mapMidTransceiver.set(Z,k),{localId:Z,rtpParameters:F,rtpSender:k.sender}}async stopSending(f){if(this.assertSendDirection(),l.debug("stopSending() [localId:%s]",f),this._closed)return;let b=this._mapMidTransceiver.get(f);if(!b)throw new Error("associated RTCRtpTransceiver not found");if(b.sender.replaceTrack(null),this._pc.removeTrack(b.sender),this._remoteSdp.closeMediaSection(b.mid))try{b.stop()}catch{}let w=await this._pc.createOffer();l.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",w),await this._pc.setLocalDescription(w);let S={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",S),await this._pc.setRemoteDescription(S),this._mapMidTransceiver.delete(f)}async pauseSending(f){this.assertNotClosed(),this.assertSendDirection(),l.debug("pauseSending() [localId:%s]",f);let b=this._mapMidTransceiver.get(f);if(!b)throw new Error("associated RTCRtpTransceiver not found");b.direction="inactive",this._remoteSdp.pauseMediaSection(f);let w=await this._pc.createOffer();l.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",w),await this._pc.setLocalDescription(w);let S={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",S),await this._pc.setRemoteDescription(S)}async resumeSending(f){this.assertNotClosed(),this.assertSendDirection(),l.debug("resumeSending() [localId:%s]",f);let b=this._mapMidTransceiver.get(f);if(this._remoteSdp.resumeSendingMediaSection(f),!b)throw new Error("associated RTCRtpTransceiver not found");b.direction="sendonly";let w=await this._pc.createOffer();l.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",w),await this._pc.setLocalDescription(w);let S={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",S),await this._pc.setRemoteDescription(S)}async replaceTrack(f,b){this.assertNotClosed(),this.assertSendDirection(),b?l.debug("replaceTrack() [localId:%s, track.id:%s]",f,b.id):l.debug("replaceTrack() [localId:%s, no track]",f);let w=this._mapMidTransceiver.get(f);if(!w)throw new Error("associated RTCRtpTransceiver not found");await w.sender.replaceTrack(b)}async setMaxSpatialLayer(f,b){this.assertNotClosed(),this.assertSendDirection(),l.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",f,b);let w=this._mapMidTransceiver.get(f);if(!w)throw new Error("associated RTCRtpTransceiver not found");let S=w.sender.getParameters();S.encodings.forEach((P,k)=>{k<=b?P.active=!0:P.active=!1}),await w.sender.setParameters(S),this._remoteSdp.muxMediaSectionSimulcast(f,S.encodings);let O=await this._pc.createOffer();l.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",O),await this._pc.setLocalDescription(O);let j={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",j),await this._pc.setRemoteDescription(j)}async setRtpEncodingParameters(f,b){this.assertNotClosed(),this.assertSendDirection(),l.debug("setRtpEncodingParameters() [localId:%s, params:%o]",f,b);let w=this._mapMidTransceiver.get(f);if(!w)throw new Error("associated RTCRtpTransceiver not found");let S=w.sender.getParameters();S.encodings.forEach((P,k)=>{S.encodings[k]={...P,...b}}),await w.sender.setParameters(S),this._remoteSdp.muxMediaSectionSimulcast(f,S.encodings);let O=await this._pc.createOffer();l.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",O),await this._pc.setLocalDescription(O);let j={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",j),await this._pc.setRemoteDescription(j)}async getSenderStats(f){this.assertNotClosed(),this.assertSendDirection();let b=this._mapMidTransceiver.get(f);if(!b)throw new Error("associated RTCRtpTransceiver not found");return b.sender.getStats()}async sendDataChannel({sctpStreamParameters:f}){this.assertNotClosed(),this.assertSendDirection();let b={negotiated:!0,id:this._nextSendSctpStreamId,ordered:f.ordered,maxPacketLifeTime:f.maxPacketLifeTime,maxRetransmits:f.maxRetransmits,protocol:f.protocol};l.debug("sendDataChannel() [options:%o]",b);let w=this._pc.createDataChannel(f.label,b);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%p.MIS,!this._hasDataChannelMediaSection){let O=await this._pc.createOffer(),j=e.parse(O.sdp),P=j.media.find(C=>C.type==="application");this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:j}),l.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",O),await this._pc.setLocalDescription(O),this._remoteSdp.sendSctpAssociation({offerMediaObject:P});let k={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",k),await this._pc.setRemoteDescription(k),this._hasDataChannelMediaSection=!0}let S={streamId:b.id,ordered:b.ordered,maxPacketLifeTime:b.maxPacketLifeTime,maxRetransmits:b.maxRetransmits};return{dataChannel:w,sctpStreamParameters:S}}async receive(f){this.assertNotClosed(),this.assertRecvDirection();let b=[],w=new Map;for(let P of f){let{trackId:k,kind:C,rtpParameters:D,streamId:H}=P;l.debug("receive() [trackId:%s, kind:%s]",k,C);let W=D.mid??String(this._mapMidTransceiver.size);w.set(k,W);let{msidStreamId:J}=u.getMsidStreamIdAndTrackId(D.msid);this._remoteSdp.receive({mid:W,kind:C,offerRtpParameters:D,streamId:H??J??D.rtcp?.cname??"-",trackId:k})}let S={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",S),await this._pc.setRemoteDescription(S);let O=await this._pc.createAnswer(),j=e.parse(O.sdp);for(let P of f){let{trackId:k,rtpParameters:C}=P,D=w.get(k),H=j.media.find(W=>String(W.mid)===D);c.applyCodecParameters({offerRtpParameters:C,answerMediaObject:H})}O={type:"answer",sdp:e.write(j)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:j}),l.debug("receive() | calling pc.setLocalDescription() [answer:%o]",O),await this._pc.setLocalDescription(O);for(let P of f){let{trackId:k}=P,C=w.get(k),D=this._pc.getTransceivers().find(H=>H.mid===C);if(D)this._mapMidTransceiver.set(C,D),b.push({localId:C,track:D.receiver.track,rtpReceiver:D.receiver});else throw new Error("new RTCRtpTransceiver not found")}return b}async stopReceiving(f){if(this.assertRecvDirection(),this._closed)return;for(let S of f){l.debug("stopReceiving() [localId:%s]",S);let O=this._mapMidTransceiver.get(S);if(!O)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(O.mid)}let b={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",b),await this._pc.setRemoteDescription(b);let w=await this._pc.createAnswer();l.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",w),await this._pc.setLocalDescription(w);for(let S of f)this._mapMidTransceiver.delete(S)}async pauseReceiving(f){this.assertNotClosed(),this.assertRecvDirection();for(let S of f){l.debug("pauseReceiving() [localId:%s]",S);let O=this._mapMidTransceiver.get(S);if(!O)throw new Error("associated RTCRtpTransceiver not found");O.direction="inactive",this._remoteSdp.pauseMediaSection(S)}let b={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",b),await this._pc.setRemoteDescription(b);let w=await this._pc.createAnswer();l.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",w),await this._pc.setLocalDescription(w)}async resumeReceiving(f){this.assertNotClosed(),this.assertRecvDirection();for(let S of f){l.debug("resumeReceiving() [localId:%s]",S);let O=this._mapMidTransceiver.get(S);if(!O)throw new Error("associated RTCRtpTransceiver not found");O.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(S)}let b={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",b),await this._pc.setRemoteDescription(b);let w=await this._pc.createAnswer();l.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",w),await this._pc.setLocalDescription(w)}async getReceiverStats(f){this.assertNotClosed(),this.assertRecvDirection();let b=this._mapMidTransceiver.get(f);if(!b)throw new Error("associated RTCRtpTransceiver not found");return b.receiver.getStats()}async receiveDataChannel({maxMessageSize:f,sctpStreamParameters:b,label:w,protocol:S}){this.assertNotClosed(),this.assertRecvDirection();let{streamId:O,ordered:j,maxPacketLifeTime:P,maxRetransmits:k}=b,C={negotiated:!0,id:O,ordered:j,maxPacketLifeTime:P,maxRetransmits:k,protocol:S};l.debug("receiveDataChannel() [options:%o]",C);let D=this._pc.createDataChannel(w,C);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();let H={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",H),await this._pc.setRemoteDescription(H);let W=await this._pc.createAnswer(),J=e.parse(W.sdp),F=J.media.find(q=>q.type==="application");F.maxMessageSize=f,this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:J}),W={type:"answer",sdp:e.write(J)},l.debug("receiveDataChannel() | calling pc.setLocalDescription() [answer:%o]",W),await this._pc.setLocalDescription(W),this._hasDataChannelMediaSection=!0}return{dataChannel:D}}getDataChannelMaxMessageSize(){return this._pc.sctp?.maxMessageSize}async setupTransport({localDtlsRole:f,localSdpObject:b}){b||(b=e.parse(this._pc.localDescription.sdp));let w=c.extractDtlsParameters({sdpObject:b});w.role=f,this._remoteSdp.updateDtlsRole(f==="client"?"server":"client"),await new Promise((S,O)=>{this.safeEmit("@connect",{dtlsParameters:w},S,O)}),this._transportReady=!0}onIceGatheringStateChange=()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)};onIceCandidateError=f=>{this.emit("@icecandidateerror",f)};onConnectionStateChange=()=>{this.emit("@connectionstatechange",this._pc.connectionState)};onIceConnectionStateChange=()=>{switch(this._pc.iceConnectionState){case"checking":{this.emit("@connectionstatechange","connecting");break}case"connected":case"completed":{this.emit("@connectionstatechange","connected");break}case"failed":{this.emit("@connectionstatechange","failed");break}case"disconnected":{this.emit("@connectionstatechange","disconnected");break}case"closed":{this.emit("@connectionstatechange","closed");break}}};assertNotClosed(){if(this._closed)throw new i.InvalidStateError("method called in a closed handler")}assertSendDirection(){if(this._direction!=="send")throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if(this._direction!=="recv")throw new Error('method can just be called for handlers with "recv" direction')}};t.Chrome74=m}),Wre=nt(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Firefox120=void 0;var e=wc(),r=Xs(),s=Os(),n=Zn(),i=ea(),o=Jh(),a=gg(),c=yg(),d=bg(),u=xg(),l=new s.Logger("Firefox120"),h="Firefox120",p={OS:16,MIS:2048},m=class T1 extends r.EnhancedEventEmitter{_closed=!1;_direction;_remoteSdp;_getSendExtendedRtpCapabilities;_pc;_mapMidTransceiver=new Map;_sendStream=new MediaStream;_hasDataChannelMediaSection=!1;_nextSendSctpStreamId=0;_transportReady=!1;static createFactory(){return{name:h,factory:f=>new T1(f),getNativeRtpCapabilities:async({direction:f})=>{l.debug("getNativeRtpCapabilities() [direction:%o]",f);let b=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"}),w=document.createElement("canvas");w.getContext("2d");let S=w.captureStream().getVideoTracks()[0];try{b.addTransceiver("audio",{direction:f}),b.addTransceiver(S,{direction:f,sendEncodings:[{rid:"r0",maxBitrate:1e5},{rid:"r1",maxBitrate:5e5}]});let O=await b.createOffer();try{w.remove()}catch{}try{S.stop()}catch{}try{b.close()}catch{}b=void 0;let j=e.parse(O.sdp);return T1.getLocalRtpCapabilities(j)}catch(O){try{w.remove()}catch{}try{S.stop()}catch{}try{b?.close()}catch{}throw b=void 0,O}},getNativeSctpCapabilities:async()=>(l.debug("getNativeSctpCapabilities()"),{numStreams:p})}}static getLocalRtpCapabilities(f){let b=c.extractRtpCapabilities({sdpObject:f});return i.validateAndNormalizeRtpCapabilities(b),b}constructor({direction:f,iceParameters:b,iceCandidates:w,dtlsParameters:S,sctpParameters:O,iceServers:j,iceTransportPolicy:P,additionalSettings:k,getSendExtendedRtpCapabilities:C}){super(),l.debug("constructor()"),this._direction=f,this._remoteSdp=new a.RemoteSdp({iceParameters:b,iceCandidates:w,dtlsParameters:S,sctpParameters:O}),this._getSendExtendedRtpCapabilities=C,this._pc=new RTCPeerConnection({iceServers:j??[],iceTransportPolicy:P??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...k}),this._pc.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.addEventListener("icecandidateerror",this.onIceCandidateError),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",this.onConnectionStateChange):(l.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return h}close(){if(l.debug("close()"),!this._closed){this._closed=!0;try{this._pc.close()}catch{}this._pc.removeEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.removeEventListener("icecandidateerror",this.onIceCandidateError),this._pc.removeEventListener("connectionstatechange",this.onConnectionStateChange),this._pc.removeEventListener("iceconnectionstatechange",this.onIceConnectionStateChange),this.emit("@close"),super.close()}}async updateIceServers(f){throw this.assertNotClosed(),new n.UnsupportedError("not supported")}async restartIce(f){if(this.assertNotClosed(),l.debug("restartIce()"),this._remoteSdp.updateIceParameters(f),!!this._transportReady)if(this._direction==="send"){let b=await this._pc.createOffer({iceRestart:!0});l.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",b),await this._pc.setLocalDescription(b);let w={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",w),await this._pc.setRemoteDescription(w)}else{let b={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",b),await this._pc.setRemoteDescription(b);let w=await this._pc.createAnswer();l.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",w),await this._pc.setLocalDescription(w)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:f,streamId:b,encodings:w,codecOptions:S,codec:O,onRtpSender:j}){this.assertNotClosed(),this.assertSendDirection(),l.debug("send() [kind:%s, track.id:%s, streamId:%s]",f.kind,f.id,b),w&&w.length>1&&w.forEach((Y,Z)=>{Y.rid=`r${Z}`});let P=this._pc.addTransceiver(f,{direction:"sendonly",streams:[this._sendStream],sendEncodings:w});j&&j(P.sender);let k=await this._pc.createOffer(),C=e.parse(k.sdp);C.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();let D=T1.getLocalRtpCapabilities(C),H=this._getSendExtendedRtpCapabilities(D),W=i.getSendingRtpParameters(f.kind,H);W.codecs=i.reduceCodecs(W.codecs,O);let J=i.getSendingRemoteRtpParameters(f.kind,H);J.codecs=i.reduceCodecs(J.codecs,O),this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:C});let F=(0,o.parse)((w??[{}])[0].scalabilityMode);l.debug("send() | calling pc.setLocalDescription() [offer:%o]",k),await this._pc.setLocalDescription(k);let q=P.mid;W.mid=q,C=e.parse(this._pc.localDescription.sdp);let Q=C.media[C.media.length-1];if(W.rtcp.cname=c.getCname({offerMediaObject:Q}),W.msid=`${b??this._sendStream.id} ${f.id}`,!w)W.encodings=d.getRtpEncodings({offerMediaObject:Q,codecs:W.codecs});else if(w.length===1){let Y=d.getRtpEncodings({offerMediaObject:Q,codecs:W.codecs});Object.assign(Y[0],w[0]),W.encodings=Y}else W.encodings=w;if(W.encodings.length>1&&(W.codecs[0].mimeType.toLowerCase()==="video/vp8"||W.codecs[0].mimeType.toLowerCase()==="video/h264"))for(let Y of W.encodings)Y.scalabilityMode?Y.scalabilityMode=`L1T${F.temporalLayers}`:Y.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:Q,offerRtpParameters:W,answerRtpParameters:J,codecOptions:S});let R={type:"answer",sdp:this._remoteSdp.getSdp()};return l.debug("send() | calling pc.setRemoteDescription() [answer:%o]",R),await this._pc.setRemoteDescription(R),this._mapMidTransceiver.set(q,P),{localId:q,rtpParameters:W,rtpSender:P.sender}}async stopSending(f){if(this.assertSendDirection(),l.debug("stopSending() [localId:%s]",f),this._closed)return;let b=this._mapMidTransceiver.get(f);if(!b)throw new Error("associated transceiver not found");b.sender.replaceTrack(null),this._pc.removeTrack(b.sender),this._remoteSdp.disableMediaSection(b.mid);let w=await this._pc.createOffer();l.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",w),await this._pc.setLocalDescription(w);let S={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",S),await this._pc.setRemoteDescription(S),this._mapMidTransceiver.delete(f)}async pauseSending(f){this.assertNotClosed(),this.assertSendDirection(),l.debug("pauseSending() [localId:%s]",f);let b=this._mapMidTransceiver.get(f);if(!b)throw new Error("associated RTCRtpTransceiver not found");b.direction="inactive",this._remoteSdp.pauseMediaSection(f);let w=await this._pc.createOffer();l.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",w),await this._pc.setLocalDescription(w);let S={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",S),await this._pc.setRemoteDescription(S)}async resumeSending(f){this.assertNotClosed(),this.assertSendDirection(),l.debug("resumeSending() [localId:%s]",f);let b=this._mapMidTransceiver.get(f);if(!b)throw new Error("associated RTCRtpTransceiver not found");b.direction="sendonly",this._remoteSdp.resumeSendingMediaSection(f);let w=await this._pc.createOffer();l.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",w),await this._pc.setLocalDescription(w);let S={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",S),await this._pc.setRemoteDescription(S)}async replaceTrack(f,b){this.assertNotClosed(),this.assertSendDirection(),b?l.debug("replaceTrack() [localId:%s, track.id:%s]",f,b.id):l.debug("replaceTrack() [localId:%s, no track]",f);let w=this._mapMidTransceiver.get(f);if(!w)throw new Error("associated RTCRtpTransceiver not found");await w.sender.replaceTrack(b)}async setMaxSpatialLayer(f,b){this.assertNotClosed(),this.assertSendDirection(),l.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",f,b);let w=this._mapMidTransceiver.get(f);if(!w)throw new Error("associated transceiver not found");let S=w.sender.getParameters();S.encodings.forEach((P,k)=>{k<=b?P.active=!0:P.active=!1}),await w.sender.setParameters(S),this._remoteSdp.muxMediaSectionSimulcast(f,S.encodings);let O=await this._pc.createOffer();l.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",O),await this._pc.setLocalDescription(O);let j={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",j),await this._pc.setRemoteDescription(j)}async setRtpEncodingParameters(f,b){this.assertNotClosed(),this.assertSendDirection(),l.debug("setRtpEncodingParameters() [localId:%s, params:%o]",f,b);let w=this._mapMidTransceiver.get(f);if(!w)throw new Error("associated RTCRtpTransceiver not found");let S=w.sender.getParameters();S.encodings.forEach((P,k)=>{S.encodings[k]={...P,...b}}),await w.sender.setParameters(S),this._remoteSdp.muxMediaSectionSimulcast(f,S.encodings);let O=await this._pc.createOffer();l.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",O),await this._pc.setLocalDescription(O);let j={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",j),await this._pc.setRemoteDescription(j)}async getSenderStats(f){this.assertNotClosed(),this.assertSendDirection();let b=this._mapMidTransceiver.get(f);if(!b)throw new Error("associated RTCRtpTransceiver not found");return b.sender.getStats()}async sendDataChannel({sctpStreamParameters:f}){this.assertNotClosed(),this.assertSendDirection();let b={negotiated:!0,id:this._nextSendSctpStreamId,ordered:f.ordered,maxPacketLifeTime:f.maxPacketLifeTime,maxRetransmits:f.maxRetransmits,protocol:f.protocol};l.debug("sendDataChannel() [options:%o]",b);let w=this._pc.createDataChannel(f.label,b);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%p.MIS,!this._hasDataChannelMediaSection){let O=await this._pc.createOffer(),j=e.parse(O.sdp),P=j.media.find(C=>C.type==="application");this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:j}),l.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",O),await this._pc.setLocalDescription(O),this._remoteSdp.sendSctpAssociation({offerMediaObject:P});let k={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",k),await this._pc.setRemoteDescription(k),this._hasDataChannelMediaSection=!0}let S={streamId:b.id,ordered:b.ordered,maxPacketLifeTime:b.maxPacketLifeTime,maxRetransmits:b.maxRetransmits};return{dataChannel:w,sctpStreamParameters:S}}async receive(f){this.assertNotClosed(),this.assertRecvDirection();let b=[],w=new Map;for(let P of f){let{trackId:k,kind:C,rtpParameters:D,streamId:H}=P;l.debug("receive() [trackId:%s, kind:%s]",k,C);let W=D.mid??String(this._mapMidTransceiver.size);w.set(k,W);let{msidStreamId:J}=u.getMsidStreamIdAndTrackId(D.msid);this._remoteSdp.receive({mid:W,kind:C,offerRtpParameters:D,streamId:H??J??D.rtcp?.cname??"-",trackId:k})}let S={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",S),await this._pc.setRemoteDescription(S);for(let P of f){let{trackId:k,onRtpReceiver:C}=P;if(C){let D=w.get(k),H=this._pc.getTransceivers().find(W=>W.mid===D);if(!H)throw new Error("transceiver not found");C(H.receiver)}}let O=await this._pc.createAnswer(),j=e.parse(O.sdp);for(let P of f){let{trackId:k,rtpParameters:C}=P,D=w.get(k),H=j.media.find(W=>String(W.mid)===D);c.applyCodecParameters({offerRtpParameters:C,answerMediaObject:H}),O={type:"answer",sdp:e.write(j)}}this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:j}),l.debug("receive() | calling pc.setLocalDescription() [answer:%o]",O),await this._pc.setLocalDescription(O);for(let P of f){let{trackId:k}=P,C=w.get(k),D=this._pc.getTransceivers().find(H=>H.mid===C);if(!D)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(C,D),b.push({localId:C,track:D.receiver.track,rtpReceiver:D.receiver})}return b}async stopReceiving(f){if(this.assertRecvDirection(),this._closed)return;for(let S of f){l.debug("stopReceiving() [localId:%s]",S);let O=this._mapMidTransceiver.get(S);if(!O)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(O.mid)}let b={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",b),await this._pc.setRemoteDescription(b);let w=await this._pc.createAnswer();l.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",w),await this._pc.setLocalDescription(w);for(let S of f)this._mapMidTransceiver.delete(S)}async pauseReceiving(f){this.assertNotClosed(),this.assertRecvDirection();for(let S of f){l.debug("pauseReceiving() [localId:%s]",S);let O=this._mapMidTransceiver.get(S);if(!O)throw new Error("associated RTCRtpTransceiver not found");O.direction="inactive",this._remoteSdp.pauseMediaSection(S)}let b={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",b),await this._pc.setRemoteDescription(b);let w=await this._pc.createAnswer();l.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",w),await this._pc.setLocalDescription(w)}async resumeReceiving(f){this.assertNotClosed(),this.assertRecvDirection();for(let S of f){l.debug("resumeReceiving() [localId:%s]",S);let O=this._mapMidTransceiver.get(S);if(!O)throw new Error("associated RTCRtpTransceiver not found");O.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(S)}let b={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",b),await this._pc.setRemoteDescription(b);let w=await this._pc.createAnswer();l.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",w),await this._pc.setLocalDescription(w)}async getReceiverStats(f){this.assertRecvDirection();let b=this._mapMidTransceiver.get(f);if(!b)throw new Error("associated RTCRtpTransceiver not found");return b.receiver.getStats()}async receiveDataChannel({maxMessageSize:f,sctpStreamParameters:b,label:w,protocol:S}){this.assertNotClosed(),this.assertRecvDirection();let{streamId:O,ordered:j,maxPacketLifeTime:P,maxRetransmits:k}=b,C={negotiated:!0,id:O,ordered:j,maxPacketLifeTime:P,maxRetransmits:k,protocol:S};l.debug("receiveDataChannel() [options:%o]",C);let D=this._pc.createDataChannel(w,C);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();let H={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",H),await this._pc.setRemoteDescription(H);let W=await this._pc.createAnswer(),J=e.parse(W.sdp),F=J.media.find(q=>q.type==="application");F.maxMessageSize=f,this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:J}),W={type:"answer",sdp:e.write(J)},l.debug("receiveDataChannel() | calling pc.setLocalDescription() [answer:%o]",W),await this._pc.setLocalDescription(W),this._hasDataChannelMediaSection=!0}return{dataChannel:D}}getDataChannelMaxMessageSize(){return this._pc.sctp?.maxMessageSize}async setupTransport({localDtlsRole:f,localSdpObject:b}){b||(b=e.parse(this._pc.localDescription.sdp));let w=c.extractDtlsParameters({sdpObject:b});w.role=f,this._remoteSdp.updateDtlsRole(f==="client"?"server":"client"),await new Promise((S,O)=>{this.safeEmit("@connect",{dtlsParameters:w},S,O)}),this._transportReady=!0}onIceGatheringStateChange=()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)};onIceCandidateError=f=>{this.emit("@icecandidateerror",f)};onConnectionStateChange=()=>{this.emit("@connectionstatechange",this._pc.connectionState)};onIceConnectionStateChange=()=>{switch(this._pc.iceConnectionState){case"checking":{this.emit("@connectionstatechange","connecting");break}case"connected":case"completed":{this.emit("@connectionstatechange","connected");break}case"failed":{this.emit("@connectionstatechange","failed");break}case"disconnected":{this.emit("@connectionstatechange","disconnected");break}case"closed":{this.emit("@connectionstatechange","closed");break}}};assertNotClosed(){if(this._closed)throw new n.InvalidStateError("method called in a closed handler")}assertSendDirection(){if(this._direction!=="send")throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if(this._direction!=="recv")throw new Error('method can just be called for handlers with "recv" direction')}};t.Firefox120=m}),Kre=nt(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Safari12=void 0;var e=wc(),r=Xs(),s=Os(),n=ea(),i=Zn(),o=Jh(),a=gg(),c=yg(),d=bg(),u=xg(),l=new s.Logger("Safari12"),h="Safari12",p={OS:65535,MIS:65535},m=class k1 extends r.EnhancedEventEmitter{_closed=!1;_direction;_remoteSdp;_getSendExtendedRtpCapabilities;_forcedLocalDtlsRole;_pc;_mapMidTransceiver=new Map;_sendStream=new MediaStream;_hasDataChannelMediaSection=!1;_nextSendSctpStreamId=0;_transportReady=!1;static createFactory(){return{name:h,factory:f=>new k1(f),getNativeRtpCapabilities:async({direction:f})=>{l.debug("getNativeRtpCapabilities() [direction:%o]",f);let b=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{b.addTransceiver("audio",{direction:f}),b.addTransceiver("video",{direction:f});let w=await b.createOffer();try{b.close()}catch{}b=void 0;let S=e.parse(w.sdp);return k1.getLocalRtpCapabilities(S)}catch(w){try{b?.close()}catch{}throw b=void 0,w}},getNativeSctpCapabilities:async()=>(l.debug("getNativeSctpCapabilities()"),{numStreams:p})}}static getLocalRtpCapabilities(f,b=[]){let w=c.extractRtpCapabilities({sdpObject:f});n.validateAndNormalizeRtpCapabilities(w),u.addNackSupportForOpus(w);for(let S of b)u.addHeaderExtensionSupport(w,S);return w}constructor({direction:f,iceParameters:b,iceCandidates:w,dtlsParameters:S,sctpParameters:O,iceServers:j,iceTransportPolicy:P,additionalSettings:k,getSendExtendedRtpCapabilities:C}){super(),l.debug("constructor()"),this._direction=f,this._remoteSdp=new a.RemoteSdp({iceParameters:b,iceCandidates:w,dtlsParameters:S,sctpParameters:O}),this._getSendExtendedRtpCapabilities=C,S.role&&S.role!=="auto"&&(this._forcedLocalDtlsRole=S.role==="server"?"client":"server"),this._pc=new RTCPeerConnection({iceServers:j??[],iceTransportPolicy:P??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...k}),this._pc.addEventListener("icegatheringstatechange",()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)}),this._pc.addEventListener("icecandidateerror",D=>{this.emit("@icecandidateerror",D)}),this._pc.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.addEventListener("icecandidateerror",this.onIceCandidateError),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",this.onConnectionStateChange):(l.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return h}close(){if(l.debug("close()"),!this._closed){this._closed=!0;try{this._pc.close()}catch{}this._pc.removeEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.removeEventListener("icecandidateerror",this.onIceCandidateError),this._pc.removeEventListener("connectionstatechange",this.onConnectionStateChange),this._pc.removeEventListener("iceconnectionstatechange",this.onIceConnectionStateChange),this.emit("@close"),super.close()}}async updateIceServers(f){this.assertNotClosed(),l.debug("updateIceServers()");let b=this._pc.getConfiguration();b.iceServers=f,this._pc.setConfiguration(b)}async restartIce(f){if(this.assertNotClosed(),l.debug("restartIce()"),this._remoteSdp.updateIceParameters(f),!!this._transportReady)if(this._direction==="send"){let b=await this._pc.createOffer({iceRestart:!0});l.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",b),await this._pc.setLocalDescription(b);let w={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",w),await this._pc.setRemoteDescription(w)}else{let b={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",b),await this._pc.setRemoteDescription(b);let w=await this._pc.createAnswer();l.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",w),await this._pc.setLocalDescription(w)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:f,streamId:b,encodings:w,codecOptions:S,headerExtensionOptions:O,codec:j,onRtpSender:P}){this.assertNotClosed(),this.assertSendDirection(),l.debug("send() [kind:%s, track.id:%s, streamId:%s]",f.kind,f.id,b);let k=this._remoteSdp.getNextMediaSectionIdx(),C=this._pc.addTransceiver(f,{direction:"sendonly",streams:[this._sendStream]});P&&P(C.sender);let D=await this._pc.createOffer(),H=e.parse(D.sdp);H.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();let W=[];W.push({uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",kind:f.kind,direction:"sendonly"});let J=k1.getLocalRtpCapabilities(H,W),F=this._getSendExtendedRtpCapabilities(J),q=n.getSendingRtpParameters(f.kind,F);q.codecs=n.reduceCodecs(q.codecs,j);let Q=n.getSendingRemoteRtpParameters(f.kind,F);Q.codecs=n.reduceCodecs(Q.codecs,j);let R;this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:H});let Y=(0,o.parse)((w??[{}])[0].scalabilityMode);w&&w.length>1&&(l.debug("send() | enabling legacy simulcast"),H=e.parse(D.sdp),R=H.media[k.idx],d.addLegacySimulcast({offerMediaObject:R,numStreams:w.length}),D={type:"offer",sdp:e.write(H)}),O?.absCaptureTime&&(R=H.media[k.idx],c.addHeaderExtension({offerMediaObject:R,headerExtensionUri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",headerExtensionId:Q.headerExtensions.find(U=>U.uri==="http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time").id}),D={type:"offer",sdp:e.write(H)}),l.debug("send() | calling pc.setLocalDescription() [offer:%o]",D),await this._pc.setLocalDescription(D);let Z=C.mid;if(q.mid=Z,H=e.parse(this._pc.localDescription.sdp),R=H.media[k.idx],q.rtcp.cname=c.getCname({offerMediaObject:R}),q.msid=`${b??this._sendStream.id} ${f.id}`,q.encodings=d.getRtpEncodings({offerMediaObject:R,codecs:q.codecs}),w)for(let U=0;U<q.encodings.length;++U)w[U]&&Object.assign(q.encodings[U],w[U]);if(q.encodings.length>1&&(q.codecs[0].mimeType.toLowerCase()==="video/vp8"||q.codecs[0].mimeType.toLowerCase()==="video/h264"))for(let U of q.encodings)U.scalabilityMode?U.scalabilityMode=`L1T${Y.temporalLayers}`:U.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:R,reuseMid:k.reuseMid,offerRtpParameters:q,answerRtpParameters:Q,codecOptions:S});let I={type:"answer",sdp:this._remoteSdp.getSdp()};return l.debug("send() | calling pc.setRemoteDescription() [answer:%o]",I),await this._pc.setRemoteDescription(I),this._mapMidTransceiver.set(Z,C),{localId:Z,rtpParameters:q,rtpSender:C.sender}}async stopSending(f){if(this.assertSendDirection(),this._closed)return;l.debug("stopSending() [localId:%s]",f);let b=this._mapMidTransceiver.get(f);if(!b)throw new Error("associated RTCRtpTransceiver not found");if(b.sender.replaceTrack(null),this._pc.removeTrack(b.sender),this._remoteSdp.closeMediaSection(b.mid))try{b.stop()}catch{}let w=await this._pc.createOffer();l.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",w),await this._pc.setLocalDescription(w);let S={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",S),await this._pc.setRemoteDescription(S),this._mapMidTransceiver.delete(f)}async pauseSending(f){this.assertNotClosed(),this.assertSendDirection(),l.debug("pauseSending() [localId:%s]",f);let b=this._mapMidTransceiver.get(f);if(!b)throw new Error("associated RTCRtpTransceiver not found");b.direction="inactive",this._remoteSdp.pauseMediaSection(f);let w=await this._pc.createOffer();l.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",w),await this._pc.setLocalDescription(w);let S={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",S),await this._pc.setRemoteDescription(S)}async resumeSending(f){this.assertNotClosed(),this.assertSendDirection(),l.debug("resumeSending() [localId:%s]",f);let b=this._mapMidTransceiver.get(f);if(!b)throw new Error("associated RTCRtpTransceiver not found");b.direction="sendonly",this._remoteSdp.resumeSendingMediaSection(f);let w=await this._pc.createOffer();l.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",w),await this._pc.setLocalDescription(w);let S={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",S),await this._pc.setRemoteDescription(S)}async replaceTrack(f,b){this.assertNotClosed(),this.assertSendDirection(),b?l.debug("replaceTrack() [localId:%s, track.id:%s]",f,b.id):l.debug("replaceTrack() [localId:%s, no track]",f);let w=this._mapMidTransceiver.get(f);if(!w)throw new Error("associated RTCRtpTransceiver not found");await w.sender.replaceTrack(b)}async setMaxSpatialLayer(f,b){this.assertNotClosed(),this.assertSendDirection(),l.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",f,b);let w=this._mapMidTransceiver.get(f);if(!w)throw new Error("associated RTCRtpTransceiver not found");let S=w.sender.getParameters();S.encodings.forEach((P,k)=>{k<=b?P.active=!0:P.active=!1}),await w.sender.setParameters(S),this._remoteSdp.muxMediaSectionSimulcast(f,S.encodings);let O=await this._pc.createOffer();l.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",O),await this._pc.setLocalDescription(O);let j={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",j),await this._pc.setRemoteDescription(j)}async setRtpEncodingParameters(f,b){this.assertNotClosed(),this.assertSendDirection(),l.debug("setRtpEncodingParameters() [localId:%s, params:%o]",f,b);let w=this._mapMidTransceiver.get(f);if(!w)throw new Error("associated RTCRtpTransceiver not found");let S=w.sender.getParameters();S.encodings.forEach((P,k)=>{S.encodings[k]={...P,...b}}),await w.sender.setParameters(S),this._remoteSdp.muxMediaSectionSimulcast(f,S.encodings);let O=await this._pc.createOffer();l.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",O),await this._pc.setLocalDescription(O);let j={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",j),await this._pc.setRemoteDescription(j)}async getSenderStats(f){this.assertNotClosed(),this.assertSendDirection();let b=this._mapMidTransceiver.get(f);if(!b)throw new Error("associated RTCRtpTransceiver not found");return b.sender.getStats()}async sendDataChannel({sctpStreamParameters:f}){this.assertNotClosed(),this.assertSendDirection();let b={negotiated:!0,id:this._nextSendSctpStreamId,ordered:f.ordered,maxPacketLifeTime:f.maxPacketLifeTime,maxRetransmits:f.maxRetransmits,protocol:f.protocol};l.debug("sendDataChannel() [options:%o]",b);let w=this._pc.createDataChannel(f.label,b);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%p.MIS,!this._hasDataChannelMediaSection){let O=await this._pc.createOffer(),j=e.parse(O.sdp),P=j.media.find(C=>C.type==="application");this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:j}),l.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",O),await this._pc.setLocalDescription(O),this._remoteSdp.sendSctpAssociation({offerMediaObject:P});let k={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",k),await this._pc.setRemoteDescription(k),this._hasDataChannelMediaSection=!0}let S={streamId:b.id,ordered:b.ordered,maxPacketLifeTime:b.maxPacketLifeTime,maxRetransmits:b.maxRetransmits};return{dataChannel:w,sctpStreamParameters:S}}async receive(f){this.assertNotClosed(),this.assertRecvDirection();let b=[],w=new Map;for(let P of f){let{trackId:k,kind:C,rtpParameters:D,streamId:H}=P;l.debug("receive() [trackId:%s, kind:%s]",k,C);let W=D.mid??String(this._mapMidTransceiver.size);w.set(k,W);let{msidStreamId:J}=u.getMsidStreamIdAndTrackId(D.msid);this._remoteSdp.receive({mid:W,kind:C,offerRtpParameters:D,streamId:H??J??D.rtcp?.cname??"-",trackId:k})}let S={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",S),await this._pc.setRemoteDescription(S);for(let P of f){let{trackId:k,onRtpReceiver:C}=P;if(C){let D=w.get(k),H=this._pc.getTransceivers().find(W=>W.mid===D);if(!H)throw new Error("transceiver not found");C(H.receiver)}}let O=await this._pc.createAnswer(),j=e.parse(O.sdp);for(let P of f){let{trackId:k,rtpParameters:C}=P,D=w.get(k),H=j.media.find(W=>String(W.mid)===D);c.applyCodecParameters({offerRtpParameters:C,answerMediaObject:H})}O={type:"answer",sdp:e.write(j)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:j}),l.debug("receive() | calling pc.setLocalDescription() [answer:%o]",O),await this._pc.setLocalDescription(O);for(let P of f){let{trackId:k}=P,C=w.get(k),D=this._pc.getTransceivers().find(H=>H.mid===C);if(!D)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(C,D),b.push({localId:C,track:D.receiver.track,rtpReceiver:D.receiver})}return b}async stopReceiving(f){if(this.assertRecvDirection(),this._closed)return;for(let S of f){l.debug("stopReceiving() [localId:%s]",S);let O=this._mapMidTransceiver.get(S);if(!O)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(O.mid)}let b={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",b),await this._pc.setRemoteDescription(b);let w=await this._pc.createAnswer();l.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",w),await this._pc.setLocalDescription(w);for(let S of f)this._mapMidTransceiver.delete(S)}async pauseReceiving(f){this.assertNotClosed(),this.assertRecvDirection();for(let S of f){l.debug("pauseReceiving() [localId:%s]",S);let O=this._mapMidTransceiver.get(S);if(!O)throw new Error("associated RTCRtpTransceiver not found");O.direction="inactive",this._remoteSdp.pauseMediaSection(S)}let b={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",b),await this._pc.setRemoteDescription(b);let w=await this._pc.createAnswer();l.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",w),await this._pc.setLocalDescription(w)}async resumeReceiving(f){this.assertNotClosed(),this.assertRecvDirection();for(let S of f){l.debug("resumeReceiving() [localId:%s]",S);let O=this._mapMidTransceiver.get(S);if(!O)throw new Error("associated RTCRtpTransceiver not found");O.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(S)}let b={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",b),await this._pc.setRemoteDescription(b);let w=await this._pc.createAnswer();l.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",w),await this._pc.setLocalDescription(w)}async getReceiverStats(f){this.assertNotClosed(),this.assertRecvDirection();let b=this._mapMidTransceiver.get(f);if(!b)throw new Error("associated RTCRtpTransceiver not found");return b.receiver.getStats()}async receiveDataChannel({maxMessageSize:f,sctpStreamParameters:b,label:w,protocol:S}){this.assertNotClosed(),this.assertRecvDirection();let{streamId:O,ordered:j,maxPacketLifeTime:P,maxRetransmits:k}=b,C={negotiated:!0,id:O,ordered:j,maxPacketLifeTime:P,maxRetransmits:k,protocol:S};l.debug("receiveDataChannel() [options:%o]",C);let D=this._pc.createDataChannel(w,C);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();let H={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",H),await this._pc.setRemoteDescription(H);let W=await this._pc.createAnswer(),J=e.parse(W.sdp),F=J.media.find(q=>q.type==="application");F.maxMessageSize=f,this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:J}),W={type:"answer",sdp:e.write(J)},l.debug("receiveDataChannel() | calling pc.setLocalDescription() [answer:%o]",W),await this._pc.setLocalDescription(W),this._hasDataChannelMediaSection=!0}return{dataChannel:D}}getDataChannelMaxMessageSize(){return this._pc.sctp?.maxMessageSize}async setupTransport({localDtlsRole:f,localSdpObject:b}){b||(b=e.parse(this._pc.localDescription.sdp));let w=c.extractDtlsParameters({sdpObject:b});w.role=f,this._remoteSdp.updateDtlsRole(f==="client"?"server":"client"),await new Promise((S,O)=>{this.safeEmit("@connect",{dtlsParameters:w},S,O)}),this._transportReady=!0}onIceGatheringStateChange=()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)};onIceCandidateError=f=>{this.emit("@icecandidateerror",f)};onConnectionStateChange=()=>{this.emit("@connectionstatechange",this._pc.connectionState)};onIceConnectionStateChange=()=>{switch(this._pc.iceConnectionState){case"checking":{this.emit("@connectionstatechange","connecting");break}case"connected":case"completed":{this.emit("@connectionstatechange","connected");break}case"failed":{this.emit("@connectionstatechange","failed");break}case"disconnected":{this.emit("@connectionstatechange","disconnected");break}case"closed":{this.emit("@connectionstatechange","closed");break}}};assertNotClosed(){if(this._closed)throw new i.InvalidStateError("method called in a closed handler")}assertSendDirection(){if(this._direction!=="send")throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if(this._direction!=="recv")throw new Error('method can just be called for handlers with "recv" direction')}};t.Safari12=m}),Gre=nt(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ReactNative106=void 0;var e=wc(),r=Xs(),s=Os(),n=ea(),i=Zn(),o=Jh(),a=gg(),c=yg(),d=bg(),u=xg(),l=new s.Logger("ReactNative106"),h="ReactNative106",p={OS:65535,MIS:65535},m=class A1 extends r.EnhancedEventEmitter{_closed=!1;_direction;_remoteSdp;_getSendExtendedRtpCapabilities;_forcedLocalDtlsRole;_pc;_mapMidTransceiver=new Map;_sendStream=new MediaStream;_hasDataChannelMediaSection=!1;_nextSendSctpStreamId=0;_transportReady=!1;static createFactory(){return{name:h,factory:f=>new A1(f),getNativeRtpCapabilities:async({direction:f})=>{l.debug("getNativeRtpCapabilities() [direction:%o]",f);let b=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{b.addTransceiver("audio",{direction:f}),b.addTransceiver("video",{direction:f});let w=await b.createOffer();try{b.close()}catch{}b=void 0;let S=e.parse(w.sdp);return A1.getLocalRtpCapabilities(S)}catch(w){try{b?.close()}catch{}throw b=void 0,w}},getNativeSctpCapabilities:async()=>(l.debug("getNativeSctpCapabilities()"),{numStreams:p})}}static getLocalRtpCapabilities(f,b=[]){let w=c.extractRtpCapabilities({sdpObject:f});n.validateAndNormalizeRtpCapabilities(w),u.addNackSupportForOpus(w);for(let S of b)u.addHeaderExtensionSupport(w,S);return w}constructor({direction:f,iceParameters:b,iceCandidates:w,dtlsParameters:S,sctpParameters:O,iceServers:j,iceTransportPolicy:P,additionalSettings:k,getSendExtendedRtpCapabilities:C}){super(),l.debug("constructor()"),this._direction=f,this._remoteSdp=new a.RemoteSdp({iceParameters:b,iceCandidates:w,dtlsParameters:S,sctpParameters:O}),this._getSendExtendedRtpCapabilities=C,S.role&&S.role!=="auto"&&(this._forcedLocalDtlsRole=S.role==="server"?"client":"server"),this._pc=new RTCPeerConnection({iceServers:j??[],iceTransportPolicy:P??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...k}),this._pc.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.addEventListener("icecandidateerror",this.onIceCandidateError),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",this.onConnectionStateChange):(l.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return h}close(){if(l.debug("close()"),!this._closed){this._closed=!0,this._sendStream.release(!1);try{this._pc.close()}catch{}this._pc.removeEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.removeEventListener("icecandidateerror",this.onIceCandidateError),this._pc.removeEventListener("connectionstatechange",this.onConnectionStateChange),this._pc.removeEventListener("iceconnectionstatechange",this.onIceConnectionStateChange),this.emit("@close"),super.close()}}async updateIceServers(f){this.assertNotClosed(),l.debug("updateIceServers()");let b=this._pc.getConfiguration();b.iceServers=f,this._pc.setConfiguration(b)}async restartIce(f){if(this.assertNotClosed(),l.debug("restartIce()"),this._remoteSdp.updateIceParameters(f),!!this._transportReady)if(this._direction==="send"){let b=await this._pc.createOffer({iceRestart:!0});l.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",b),await this._pc.setLocalDescription(b);let w={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",w),await this._pc.setRemoteDescription(w)}else{let b={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",b),await this._pc.setRemoteDescription(b);let w=await this._pc.createAnswer();l.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",w),await this._pc.setLocalDescription(w)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:f,streamId:b,encodings:w,codecOptions:S,headerExtensionOptions:O,codec:j,onRtpSender:P}){this.assertNotClosed(),this.assertSendDirection(),l.debug("send() [kind:%s, track.id:%s, streamId:%s]",f.kind,f.id,b),w&&w.length>1&&w.forEach((K,z)=>{K.rid=`r${z}`});let k=this._remoteSdp.getNextMediaSectionIdx(),C=this._pc.addTransceiver(f,{direction:"sendonly",streams:[this._sendStream],sendEncodings:w});P&&P(C.sender);let D=await this._pc.createOffer(),H=e.parse(D.sdp);H.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();let W=[];W.push({uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",kind:f.kind,direction:"sendonly"});let J=A1.getLocalRtpCapabilities(H,W),F=this._getSendExtendedRtpCapabilities(J),q=n.getSendingRtpParameters(f.kind,F);q.codecs=n.reduceCodecs(q.codecs,j);let Q=n.getSendingRemoteRtpParameters(f.kind,F);Q.codecs=n.reduceCodecs(Q.codecs,j),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:H});let R=!1,Y=(0,o.parse)((w??[{}])[0].scalabilityMode),Z;w?.length===1&&Y.spatialLayers>1&&q.codecs[0].mimeType.toLowerCase()==="video/vp9"&&(l.debug("send() | enabling legacy simulcast for VP9 SVC"),R=!0,H=e.parse(D.sdp),Z=H.media[k.idx],d.addLegacySimulcast({offerMediaObject:Z,numStreams:Y.spatialLayers}),D={type:"offer",sdp:e.write(H)}),O?.absCaptureTime&&(Z=H.media[k.idx],c.addHeaderExtension({offerMediaObject:Z,headerExtensionUri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",headerExtensionId:Q.headerExtensions.find(K=>K.uri==="http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time").id}),D={type:"offer",sdp:e.write(H)}),l.debug("send() | calling pc.setLocalDescription() [offer:%o]",D),await this._pc.setLocalDescription(D);let I=C.mid??void 0;if(I||l.warn("send() | missing transceiver.mid (bug in react-native-webrtc, using a workaround"),q.mid=I,H=e.parse(this._pc.localDescription.sdp),Z=H.media[k.idx],q.rtcp.cname=c.getCname({offerMediaObject:Z}),q.msid=`${b??this._sendStream.id} ${f.id}`,!w)q.encodings=d.getRtpEncodings({offerMediaObject:Z,codecs:q.codecs});else if(w.length===1){let K=d.getRtpEncodings({offerMediaObject:Z,codecs:q.codecs});Object.assign(K[0],w[0]),R&&(K=[K[0]]),q.encodings=K}else q.encodings=w;if(q.encodings.length>1&&(q.codecs[0].mimeType.toLowerCase()==="video/vp8"||q.codecs[0].mimeType.toLowerCase()==="video/h264"))for(let K of q.encodings)K.scalabilityMode?K.scalabilityMode=`L1T${Y.temporalLayers}`:K.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:Z,reuseMid:k.reuseMid,offerRtpParameters:q,answerRtpParameters:Q,codecOptions:S});let U={type:"answer",sdp:this._remoteSdp.getSdp()};return l.debug("send() | calling pc.setRemoteDescription() [answer:%o]",U),await this._pc.setRemoteDescription(U),I||(I=C.mid,q.mid=I),this._mapMidTransceiver.set(I,C),{localId:I,rtpParameters:q,rtpSender:C.sender}}async stopSending(f){if(this.assertSendDirection(),this._closed)return;l.debug("stopSending() [localId:%s]",f);let b=this._mapMidTransceiver.get(f);if(!b)throw new Error("associated RTCRtpTransceiver not found");if(b.sender.replaceTrack(null),this._pc.removeTrack(b.sender),this._remoteSdp.closeMediaSection(b.mid))try{b.stop()}catch{}let w=await this._pc.createOffer();l.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",w),await this._pc.setLocalDescription(w);let S={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",S),await this._pc.setRemoteDescription(S),this._mapMidTransceiver.delete(f)}async pauseSending(f){this.assertNotClosed(),this.assertSendDirection(),l.debug("pauseSending() [localId:%s]",f);let b=this._mapMidTransceiver.get(f);if(!b)throw new Error("associated RTCRtpTransceiver not found");b.direction="inactive",this._remoteSdp.pauseMediaSection(f);let w=await this._pc.createOffer();l.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",w),await this._pc.setLocalDescription(w);let S={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",S),await this._pc.setRemoteDescription(S)}async resumeSending(f){this.assertNotClosed(),this.assertSendDirection(),l.debug("resumeSending() [localId:%s]",f);let b=this._mapMidTransceiver.get(f);if(this._remoteSdp.resumeSendingMediaSection(f),!b)throw new Error("associated RTCRtpTransceiver not found");b.direction="sendonly";let w=await this._pc.createOffer();l.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",w),await this._pc.setLocalDescription(w);let S={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",S),await this._pc.setRemoteDescription(S)}async replaceTrack(f,b){this.assertNotClosed(),this.assertSendDirection(),b?l.debug("replaceTrack() [localId:%s, track.id:%s]",f,b.id):l.debug("replaceTrack() [localId:%s, no track]",f);let w=this._mapMidTransceiver.get(f);if(!w)throw new Error("associated RTCRtpTransceiver not found");await w.sender.replaceTrack(b)}async setMaxSpatialLayer(f,b){this.assertNotClosed(),this.assertSendDirection(),l.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",f,b);let w=this._mapMidTransceiver.get(f);if(!w)throw new Error("associated RTCRtpTransceiver not found");let S=w.sender.getParameters();S.encodings.forEach((P,k)=>{k<=b?P.active=!0:P.active=!1}),await w.sender.setParameters(S),this._remoteSdp.muxMediaSectionSimulcast(f,S.encodings);let O=await this._pc.createOffer();l.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",O),await this._pc.setLocalDescription(O);let j={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",j),await this._pc.setRemoteDescription(j)}async setRtpEncodingParameters(f,b){this.assertNotClosed(),this.assertSendDirection(),l.debug("setRtpEncodingParameters() [localId:%s, params:%o]",f,b);let w=this._mapMidTransceiver.get(f);if(!w)throw new Error("associated RTCRtpTransceiver not found");let S=w.sender.getParameters();S.encodings.forEach((P,k)=>{S.encodings[k]={...P,...b}}),await w.sender.setParameters(S),this._remoteSdp.muxMediaSectionSimulcast(f,S.encodings);let O=await this._pc.createOffer();l.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",O),await this._pc.setLocalDescription(O);let j={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",j),await this._pc.setRemoteDescription(j)}async getSenderStats(f){this.assertNotClosed(),this.assertSendDirection();let b=this._mapMidTransceiver.get(f);if(!b)throw new Error("associated RTCRtpTransceiver not found");return b.sender.getStats()}async sendDataChannel({sctpStreamParameters:f}){this.assertNotClosed(),this.assertSendDirection();let b={negotiated:!0,id:this._nextSendSctpStreamId,ordered:f.ordered,maxPacketLifeTime:f.maxPacketLifeTime,maxRetransmits:f.maxRetransmits,protocol:f.protocol};l.debug("sendDataChannel() [options:%o]",b);let w=this._pc.createDataChannel(f.label,b);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%p.MIS,!this._hasDataChannelMediaSection){let O=await this._pc.createOffer(),j=e.parse(O.sdp),P=j.media.find(C=>C.type==="application");this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:j}),l.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",O),await this._pc.setLocalDescription(O),this._remoteSdp.sendSctpAssociation({offerMediaObject:P});let k={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",k),await this._pc.setRemoteDescription(k),this._hasDataChannelMediaSection=!0}let S={streamId:b.id,ordered:b.ordered,maxPacketLifeTime:b.maxPacketLifeTime,maxRetransmits:b.maxRetransmits};return{dataChannel:w,sctpStreamParameters:S}}async receive(f){this.assertNotClosed(),this.assertRecvDirection();let b=[],w=new Map;for(let P of f){let{trackId:k,kind:C,rtpParameters:D,streamId:H}=P;l.debug("receive() [trackId:%s, kind:%s]",k,C);let W=D.mid??String(this._mapMidTransceiver.size);w.set(k,W);let{msidStreamId:J}=u.getMsidStreamIdAndTrackId(D.msid);this._remoteSdp.receive({mid:W,kind:C,offerRtpParameters:D,streamId:H??J??D.rtcp?.cname??"-",trackId:k})}let S={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",S),await this._pc.setRemoteDescription(S);for(let P of f){let{trackId:k,onRtpReceiver:C}=P;if(C){let D=w.get(k),H=this._pc.getTransceivers().find(W=>W.mid===D);if(!H)throw new Error("transceiver not found");C(H.receiver)}}let O=await this._pc.createAnswer(),j=e.parse(O.sdp);for(let P of f){let{trackId:k,rtpParameters:C}=P,D=w.get(k),H=j.media.find(W=>String(W.mid)===D);c.applyCodecParameters({offerRtpParameters:C,answerMediaObject:H})}O={type:"answer",sdp:e.write(j)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:j}),l.debug("receive() | calling pc.setLocalDescription() [answer:%o]",O),await this._pc.setLocalDescription(O);for(let P of f){let{trackId:k}=P,C=w.get(k),D=this._pc.getTransceivers().find(H=>H.mid===C);if(D)this._mapMidTransceiver.set(C,D),b.push({localId:C,track:D.receiver.track,rtpReceiver:D.receiver});else throw new Error("new RTCRtpTransceiver not found")}return b}async stopReceiving(f){if(this.assertRecvDirection(),this._closed)return;for(let S of f){l.debug("stopReceiving() [localId:%s]",S);let O=this._mapMidTransceiver.get(S);if(!O)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(O.mid)}let b={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",b),await this._pc.setRemoteDescription(b);let w=await this._pc.createAnswer();l.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",w),await this._pc.setLocalDescription(w);for(let S of f)this._mapMidTransceiver.delete(S)}async pauseReceiving(f){this.assertNotClosed(),this.assertRecvDirection();for(let S of f){l.debug("pauseReceiving() [localId:%s]",S);let O=this._mapMidTransceiver.get(S);if(!O)throw new Error("associated RTCRtpTransceiver not found");O.direction="inactive",this._remoteSdp.pauseMediaSection(S)}let b={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",b),await this._pc.setRemoteDescription(b);let w=await this._pc.createAnswer();l.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",w),await this._pc.setLocalDescription(w)}async resumeReceiving(f){this.assertNotClosed(),this.assertRecvDirection();for(let S of f){l.debug("resumeReceiving() [localId:%s]",S);let O=this._mapMidTransceiver.get(S);if(!O)throw new Error("associated RTCRtpTransceiver not found");O.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(S)}let b={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",b),await this._pc.setRemoteDescription(b);let w=await this._pc.createAnswer();l.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",w),await this._pc.setLocalDescription(w)}async getReceiverStats(f){this.assertNotClosed(),this.assertRecvDirection();let b=this._mapMidTransceiver.get(f);if(!b)throw new Error("associated RTCRtpTransceiver not found");return b.receiver.getStats()}async receiveDataChannel({maxMessageSize:f,sctpStreamParameters:b,label:w,protocol:S}){this.assertNotClosed(),this.assertRecvDirection();let{streamId:O,ordered:j,maxPacketLifeTime:P,maxRetransmits:k}=b,C={negotiated:!0,id:O,ordered:j,maxPacketLifeTime:P,maxRetransmits:k,protocol:S};l.debug("receiveDataChannel() [options:%o]",C);let D=this._pc.createDataChannel(w,C);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();let H={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",H),await this._pc.setRemoteDescription(H);let W=await this._pc.createAnswer(),J=e.parse(W.sdp),F=J.media.find(q=>q.type==="application");F.maxMessageSize=f,this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:J}),W={type:"answer",sdp:e.write(J)},l.debug("receiveDataChannel() | calling pc.setLocalDescription() [answer:%o]",W),await this._pc.setLocalDescription(W),this._hasDataChannelMediaSection=!0}return{dataChannel:D}}getDataChannelMaxMessageSize(){return this._pc.sctp?.maxMessageSize}async setupTransport({localDtlsRole:f,localSdpObject:b}){b||(b=e.parse(this._pc.localDescription.sdp));let w=c.extractDtlsParameters({sdpObject:b});w.role=f,this._remoteSdp.updateDtlsRole(f==="client"?"server":"client"),await new Promise((S,O)=>{this.safeEmit("@connect",{dtlsParameters:w},S,O)}),this._transportReady=!0}onIceGatheringStateChange=()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)};onIceCandidateError=f=>{this.emit("@icecandidateerror",f)};onConnectionStateChange=()=>{this.emit("@connectionstatechange",this._pc.connectionState)};onIceConnectionStateChange=()=>{switch(this._pc.iceConnectionState){case"checking":{this.emit("@connectionstatechange","connecting");break}case"connected":case"completed":{this.emit("@connectionstatechange","connected");break}case"failed":{this.emit("@connectionstatechange","failed");break}case"disconnected":{this.emit("@connectionstatechange","disconnected");break}case"closed":{this.emit("@connectionstatechange","closed");break}}};assertNotClosed(){if(this._closed)throw new i.InvalidStateError("method called in a closed handler")}assertSendDirection(){if(this._direction!=="send")throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if(this._direction!=="recv")throw new Error('method can just be called for handlers with "recv" direction')}};t.ReactNative106=m}),Xre=nt(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Device=void 0,t.detectDevice=p,t.detectDeviceAsync=m;var e=Os(),r=Xs(),s=Zn(),n=Yh(),i=ea(),o=$re(),a=Vre(),c=zre(),d=Wre(),u=Kre(),l=Gre(),h=new e.Logger("Device");function p(k,C){return h.debug("detectDevice()"),!k&&typeof navigator=="object"&&(k=navigator.userAgent),!C&&typeof navigator=="object"&&(C=navigator.userAgentData),f(k,C)}async function m(k,C){return h.debug("detectDeviceAsync()"),!k&&typeof navigator=="object"&&(k=navigator.userAgent),!C&&typeof navigator=="object"&&(C=navigator.userAgentData),f(k,C)}var _=class SF{_handlerFactory;_handlerName;_loaded=!1;_getSendExtendedRtpCapabilities;_recvRtpCapabilities;_sendRtpCapabilities;_canProduceByKind={audio:!1,video:!1};_sctpCapabilities;_observer=new r.EnhancedEventEmitter;static async factory({handlerName:C,handlerFactory:D}={}){if(h.debug("factory()"),C&&D)throw new TypeError("just one of handlerName or handlerInterface can be given");if(!C&&!D&&(C=await m(),!C))throw new s.UnsupportedError("device not supported");return new SF({handlerName:C,handlerFactory:D})}constructor({handlerName:C,handlerFactory:D}={}){if(h.debug("constructor()"),C&&D)throw new TypeError("just one of handlerName or handlerInterface can be given");if(D)this._handlerFactory=D;else{if(C)h.debug("constructor() | handler given: %s",C);else if(C=p(),C)h.debug("constructor() | detected handler: %s",C);else throw new s.UnsupportedError("device not supported");switch(C){case"Chrome111":{this._handlerFactory=a.Chrome111.createFactory();break}case"Chrome74":{this._handlerFactory=c.Chrome74.createFactory();break}case"Firefox120":{this._handlerFactory=d.Firefox120.createFactory();break}case"Safari12":{this._handlerFactory=u.Safari12.createFactory();break}case"ReactNative106":{this._handlerFactory=l.ReactNative106.createFactory();break}default:throw new TypeError(`unknown handlerName "${C}"`)}}this._handlerName=this._handlerFactory.name}get handlerName(){return this._handlerName}get loaded(){return this._loaded}get rtpCapabilities(){return this.recvRtpCapabilities}get recvRtpCapabilities(){if(!this._loaded)throw new s.InvalidStateError("not loaded");return this._recvRtpCapabilities}get sendRtpCapabilities(){if(!this._loaded)throw new s.InvalidStateError("not loaded");return this._sendRtpCapabilities}get sctpCapabilities(){if(!this._loaded)throw new s.InvalidStateError("not loaded");return this._sctpCapabilities}get observer(){return this._observer}async load({routerRtpCapabilities:C,preferLocalCodecsOrder:D=!1}){if(h.debug("load() [routerRtpCapabilities:%o]",C),this._loaded)throw new s.InvalidStateError("already loaded");let H=n.clone(C);i.validateAndNormalizeRtpCapabilities(H);let{getNativeRtpCapabilities:W,getNativeSctpCapabilities:J}=this._handlerFactory,F=n.clone(await W({direction:"recvonly"}));h.debug("load() | got native receiving RTP capabilities:%o",F),i.validateAndNormalizeRtpCapabilities(F);let q=n.clone(await W({direction:"sendonly"}));h.debug("load() | got native sending RTP capabilities:%o",q),i.validateAndNormalizeRtpCapabilities(q),this._getSendExtendedRtpCapabilities=Y=>n.clone(i.getExtendedRtpCapabilities(Y,H,D));let Q=i.getExtendedRtpCapabilities(F,H,!1);this._recvRtpCapabilities=i.getRecvRtpCapabilities(Q),h.debug("load() | got receiving RTP capabilities:%o",this._recvRtpCapabilities),i.validateAndNormalizeRtpCapabilities(this._recvRtpCapabilities);let R=i.getExtendedRtpCapabilities(q,H,D);this._sendRtpCapabilities=i.getSendRtpCapabilities(R),h.debug("load() | got sending RTP capabilities:%o",this._sendRtpCapabilities),i.validateAndNormalizeRtpCapabilities(this._sendRtpCapabilities),this._canProduceByKind.audio=i.canSend("audio",this._sendRtpCapabilities),this._canProduceByKind.video=i.canSend("video",this._sendRtpCapabilities),this._sctpCapabilities=await J(),i.validateSctpCapabilities(this._sctpCapabilities),h.debug("load() | got native SCTP capabilities:%o",this._sctpCapabilities),h.debug("load() succeeded"),this._loaded=!0}canProduce(C){if(this._loaded){if(C!=="audio"&&C!=="video")throw new TypeError(`invalid kind "${C}"`)}else throw new s.InvalidStateError("not loaded");return this._canProduceByKind[C]}createSendTransport({id:C,iceParameters:D,iceCandidates:H,dtlsParameters:W,sctpParameters:J,iceServers:F,iceTransportPolicy:q,additionalSettings:Q,appData:R}){return h.debug("createSendTransport()"),this.createTransport({direction:"send",id:C,iceParameters:D,iceCandidates:H,dtlsParameters:W,sctpParameters:J,iceServers:F,iceTransportPolicy:q,additionalSettings:Q,appData:R})}createRecvTransport({id:C,iceParameters:D,iceCandidates:H,dtlsParameters:W,sctpParameters:J,iceServers:F,iceTransportPolicy:q,additionalSettings:Q,appData:R}){return h.debug("createRecvTransport()"),this.createTransport({direction:"recv",id:C,iceParameters:D,iceCandidates:H,dtlsParameters:W,sctpParameters:J,iceServers:F,iceTransportPolicy:q,additionalSettings:Q,appData:R})}createTransport({direction:C,id:D,iceParameters:H,iceCandidates:W,dtlsParameters:J,sctpParameters:F,iceServers:q,iceTransportPolicy:Q,additionalSettings:R,appData:Y}){if(this._loaded){if(typeof D!="string")throw new TypeError("missing id");if(typeof H!="object")throw new TypeError("missing iceParameters");if(Array.isArray(W)){if(typeof J!="object")throw new TypeError("missing dtlsParameters");if(F&&typeof F!="object")throw new TypeError("wrong sctpParameters");if(Y&&typeof Y!="object")throw new TypeError("if given, appData must be an object")}else throw new TypeError("missing iceCandidates")}else throw new s.InvalidStateError("not loaded");let Z=new o.Transport({direction:C,id:D,iceParameters:H,iceCandidates:W,dtlsParameters:J,sctpParameters:F,iceServers:q,iceTransportPolicy:Q,additionalSettings:R,appData:Y,handlerFactory:this._handlerFactory,getSendExtendedRtpCapabilities:this._getSendExtendedRtpCapabilities,recvRtpCapabilities:this._recvRtpCapabilities,canProduceByKind:this._canProduceByKind});return this._observer.safeEmit("newtransport",Z),Z}};t.Device=_;function f(k,C){h.debug('detectDeviceImpl() [userAgent:"%s", userAgentData:%o]',k,C);let D=b(k,C);if(D){if(D>=111)return h.debug("detectDeviceImpl() | using Chrome111 handler"),"Chrome111";if(D>=74)return h.debug("detectDeviceImpl() | using Chrome74 handler"),"Chrome74";h.warn("detectDeviceImpl() | unsupported Chromium based browser/version");return}let H=w(k);if(H){if(H>=120)return h.debug("detectDeviceImpl() | using Firefox120 handler"),"Firefox120";h.warn("detectDeviceImpl() | unsupported Firefox browser/version");return}let W=S(k);if(W){if(W>=605)return h.debug("detectDeviceImpl() | using Safari12 handler"),"Safari12";h.warn("detectDeviceImpl() | unsupported desktop Safari browser/version");return}let J=O(k);if(J){if(J>=605)return h.debug("detectDeviceImpl() | using Safari12 handler"),"Safari12";h.warn("detectDeviceImpl() | unsupported iOS Safari based browser/version");return}if(P()){if(typeof RTCPeerConnection<"u"&&typeof RTCRtpTransceiver<"u")return h.debug("detectDeviceImpl() | using ReactNative106 handler"),"ReactNative106";h.warn("detectDeviceImpl() | unsupported react-native-webrtc version without RTCPeerConnection or RTCRtpTransceiver, forgot to call registerGlobals() on it?");return}h.warn('detectDeviceImpl() | device not supported [userAgent:"%s", userAgentData:%o]',k,C)}function b(k,C){if(h.debug("getChromiumMajorVersion()"),j(k,C)){h.debug("getChromiumMajorVersion() | this is iOS => undefined");return}if(P()){h.debug("getChromiumMajorVersion() | this is React-Native => undefined");return}if(C){let H=(Array.isArray(C.brands)?C.brands:[]).find(W=>W.brand==="Chromium");if(H){let W=Number(H.version);return h.debug(`getChromiumMajorVersion() | Chromium major version based on NavigatorUAData => ${W}`),W}}let D=k?.match(/\b(?:Chrome|Chromium)\/(\w+)/i);if(D?.[1]){let H=Number(D[1]);return h.debug(`getChromiumMajorVersion() | Chromium major version based on User-Agent => ${H}`),H}h.debug("getChromiumMajorVersion() | this is not Chromium => undefined")}function w(k){if(h.debug("getFirefoxMajorVersion()"),j(k)){h.debug("getFirefoxMajorVersion() | this is iOS => undefined");return}if(P()){h.debug("getFirefoxMajorVersion() | this is React-Native => undefined");return}let C=k?.match(/\bFirefox\/(\w+)/i);if(C?.[1]){let D=Number(C[1]);return h.debug(`getFirefoxMajorVersion() | Firefox major version based on User-Agent => ${D}`),D}h.debug("getFirefoxMajorVersion() | this is not Firefox => undefined")}function S(k){if(h.debug("getMacOSWebKitMajorVersion()"),j(k)){h.debug("getMacOSWebKitMajorVersion() | this is iOS => undefined");return}if(P()){h.debug("getMacOSWebKitMajorVersion() | this is React-Native => undefined");return}if(!(k&&/\bSafari\b/i.test(k)&&!/\bChrome\b/i.test(k)&&!/\bChromium\b/i.test(k)&&!/\bFirefox\b/i.test(k))){h.debug("getMacOSWebKitMajorVersion() | this is not Safari => undefined");return}let C=k.match(/AppleWebKit\/(\w+)/i);if(C?.[1]){let D=Number(C[1]);return h.debug(`getMacOSWebKitMajorVersion() | WebKit major version based on User-Agent => ${D}`),D}h.debug("getMacOSWebKitMajorVersion() | this is not WebKit => undefined")}function O(k){if(h.debug("getIOSWebKitMajorVersion()"),!j(k)){h.debug("getIOSWebKitMajorVersion() | this is not iOS => undefined");return}if(P()){h.debug("getIOSWebKitMajorVersion() | this is React-Native => undefined");return}let C=k?.match(/AppleWebKit\/(\w+)/i);if(C?.[1]){let D=Number(C[1]);return h.debug(`getIOSWebKitMajorVersion() | WebKit major version based on User-Agent => ${D}`),D}h.debug("getIOSWebKitMajorVersion() | this is not WebKit => undefined")}function j(k,C){return h.debug("isIOS()"),C?.platform==="iOS"?(h.debug("isIOS() | this is iOS based on NavigatorUAData.platform => true"),!0):C?.platform?(h.debug("isIOS() | this is not iOS based on NavigatorUAData.platform => false"),!1):k&&/iPad|iPhone|iPod/.test(k)?(h.debug("isIOS() | this is iOS based on User-Agent => true"),!0):typeof navigator=="object"&&navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1?(h.debug("isIOS() | this is iPadOS 13+ based on User-Agent => true"),!0):(h.debug("isIOS() | this is not iOS => false"),!1)}function P(){return h.debug("isReactNative()"),typeof navigator=="object"&&navigator.product==="ReactNative"?(h.debug("isReactNative() | this is React-Native based on navigator.product"),!0):(h.debug("isReactNative() | this is not React-Native => false"),!1)}}),Yre=nt(t=>{"use strict";for(var e=256,r=[],s;e--;)r[e]=(e+256).toString(16).substring(1);function n(){var i=0,o,a="";if(!s||e+16>256){for(s=Array(i=256);i--;)s[i]=256*Math.random()|0;i=e=0}for(;i<16;i++)o=s[e+i],i==6?a+=r[o&15|64]:i==8?a+=r[o&63|128]:a+=r[o],i&1&&i>1&&i<11&&(a+="-");return e++,a}t.v4=n}),Jre=nt(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.FakeEventTarget=void 0;var e=class{listeners={};addEventListener(r,s,n){s&&(this.listeners[r]=this.listeners[r]??[],this.listeners[r].push({callback:typeof s=="function"?s:s.handleEvent,once:typeof n=="object"&&n.once===!0}))}removeEventListener(r,s,n){this.listeners[r]&&s&&(this.listeners[r]=this.listeners[r].filter(i=>i.callback!==(typeof s=="function"?s:s.handleEvent)))}dispatchEvent(r){if(!r||typeof r.type!="string")throw new Error("invalid event object");let s=this.listeners[r.type];if(!s)return!0;for(let n of[...s]){try{n.callback.call(this,r)}catch(i){setTimeout(()=>{throw i},0)}n.once&&this.removeEventListener(r.type,n.callback)}return!r.defaultPrevented}};t.FakeEventTarget=e}),Qre=nt(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.FakeEvent=void 0;var e=class{NONE=0;CAPTURING_PHASE=1;AT_TARGET=2;BUBBLING_PHASE=3;type;bubbles;cancelable;defaultPrevented=!1;composed=!1;currentTarget=null;eventPhase=this.NONE;isTrusted=!0;target=null;timeStamp=0;cancelBubble=!1;returnValue=!0;srcElement=null;constructor(r,s={}){this.type=r,this.bubbles=s.bubbles??!1,this.cancelable=s.cancelable??!1}preventDefault(){this.cancelable&&(this.defaultPrevented=!0)}stopPropagation(){}stopImmediatePropagation(){}composedPath(){return[]}initEvent(r,s,n){}};t.FakeEvent=e}),Zre=nt(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.clone=e;function e(r){if(r!==void 0)return Number.isNaN(r)?NaN:typeof structuredClone=="function"?structuredClone(r):JSON.parse(JSON.stringify(r))}}),ese=nt(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.FakeMediaStreamTrack=void 0;var e=Yre(),r=Jre(),s=Qre(),n=Zre(),i=class EF extends r.FakeEventTarget{#m;#u;#h;#e;#r;#t;#s;#f;#n;#p;#i;#o=null;#a=null;#c=null;#d=null;#l=null;constructor({kind:a,id:c,label:d,contentHint:u,enabled:l,muted:h,readyState:p,capabilities:m,constraints:_,settings:f,data:b}){super(),this.#m=c??(0,e.v4)(),this.#u=a,this.#h=d??"",this.#s=u??"",this.#r=l??!0,this.#t=h??!1,this.#e=p??"live",this.#f=m??{},this.#n=_??{},this.#p=f??{},this.#i=b??{}}get id(){return this.#m}get kind(){return this.#u}get label(){return this.#h}get contentHint(){return this.#s}set contentHint(a){this.#s=a}get enabled(){return this.#r}set enabled(a){let c=this.#r!==a;this.#r=a,c&&this.dispatchEvent(new s.FakeEvent("enabledchange"))}get muted(){return this.#t}get readyState(){return this.#e}get data(){return this.#i}set data(a){this.#i=a}get onmute(){return this.#o}set onmute(a){this.#o&&this.removeEventListener("mute",this.#o),this.#o=a,a&&this.addEventListener("mute",a)}get onunmute(){return this.#a}set onunmute(a){this.#a&&this.removeEventListener("unmute",this.#a),this.#a=a,a&&this.addEventListener("unmute",a)}get onended(){return this.#c}set onended(a){this.#c&&this.removeEventListener("ended",this.#c),this.#c=a,a&&this.addEventListener("ended",a)}get onenabledchange(){return this.#d}set onenabledchange(a){this.#d&&this.removeEventListener("enabledchange",this.#d),this.#d=a,a&&this.addEventListener("enabledchange",a)}get onstopped(){return this.#l}set onstopped(a){this.#l&&this.removeEventListener("stopped",this.#l),this.#l=a,a&&this.addEventListener("stopped",a)}addEventListener(a,c,d){super.addEventListener(a,c,d)}removeEventListener(a,c,d){super.removeEventListener(a,c,d)}stop(){this.#e!=="ended"&&(this.#e="ended",this.dispatchEvent(new s.FakeEvent("stopped")))}clone({id:a,data:c}={}){return new EF({id:a??(0,e.v4)(),kind:this.#u,label:this.#h,contentHint:this.#s,enabled:this.#r,muted:this.#t,readyState:this.#e,capabilities:(0,n.clone)(this.#f),constraints:(0,n.clone)(this.#n),settings:(0,n.clone)(this.#p),data:c??(0,n.clone)(this.#i)})}getCapabilities(){return this.#f}getConstraints(){return this.#n}async applyConstraints(a={}){return this.#n=a,Promise.resolve()}getSettings(){return this.#p}remoteStop(){this.#e!=="ended"&&(this.#e="ended",this.dispatchEvent(new s.FakeEvent("stopped")),this.dispatchEvent(new s.FakeEvent("ended")))}remoteMute(){this.#t||(this.#t=!0,this.dispatchEvent(new s.FakeEvent("mute")))}remoteUnmute(){this.#t&&(this.#t=!1,this.dispatchEvent(new s.FakeEvent("unmute")))}};t.FakeMediaStreamTrack=i}),tse=nt(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.FakeEventTarget=void 0;var e=class{listeners={};addEventListener(r,s,n){s&&(this.listeners[r]=this.listeners[r]??[],this.listeners[r].push({callback:typeof s=="function"?s:s.handleEvent,once:typeof n=="object"&&n.once===!0}))}removeEventListener(r,s,n){this.listeners[r]&&s&&(this.listeners[r]=this.listeners[r].filter(i=>i.callback!==(typeof s=="function"?s:s.handleEvent)))}dispatchEvent(r){if(!r||typeof r.type!="string")throw new Error("invalid event object");let s=this.listeners[r.type];if(!s)return!0;for(let n of[...s]){try{n.callback.call(this,r)}catch(i){setTimeout(()=>{throw i},0)}n.once&&this.removeEventListener(r.type,n.callback)}return!r.defaultPrevented}};t.FakeEventTarget=e}),rse=nt(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.FakeHandler=void 0;var e=ese(),r=Xs(),s=Os(),n=Yh(),i=ea(),o=Zn(),a=tse(),c=new s.Logger("FakeHandler"),d="FakeHandler",u=class I1 extends r.EnhancedEventEmitter{_closed=!1;_fakeParameters;_getSendExtendedRtpCapabilities;_cname=`CNAME-${n.generateRandomNumber()}`;_defaultSendStreamId=`${n.generateRandomNumber()}`;_transportReady=!1;_nextLocalId=1;_tracks=new Map;_nextSctpStreamId=0;static createFactory(p){return{name:d,factory:m=>new I1(m,p),getNativeRtpCapabilities:async({direction:m})=>(c.debug("getNativeRtpCapabilities() [direction:%o]",m),I1.getLocalRtpCapabilities(p)),getNativeSctpCapabilities:async()=>(c.debug("getNativeSctpCapabilities()"),p.generateNativeSctpCapabilities())}}static getLocalRtpCapabilities(p){let m=p.generateNativeRtpCapabilities();return i.validateAndNormalizeRtpCapabilities(m),m}constructor({getSendExtendedRtpCapabilities:p},m){super(),c.debug("constructor()"),this._getSendExtendedRtpCapabilities=p,this._fakeParameters=m}get name(){return d}close(){c.debug("close()"),!this._closed&&(this._closed=!0,super.close())}setIceGatheringState(p){this.emit("@icegatheringstatechange",p)}setConnectionState(p){this.emit("@connectionstatechange",p)}async updateIceServers(p){this.assertNotClosed(),c.debug("updateIceServers()")}async restartIce(p){this.assertNotClosed(),c.debug("restartIce()")}async getTransportStats(){return this.assertNotClosed(),new Map}async send({track:p,streamId:m,encodings:_,codecOptions:f,codec:b}){this.assertNotClosed(),c.debug("send() [kind:%s, track.id:%s]",p.kind,p.id),this._transportReady||await this.setupTransport({localDtlsRole:"server"});let w=I1.getLocalRtpCapabilities(this._fakeParameters),S=this._getSendExtendedRtpCapabilities(w),O=i.getSendingRtpParameters(p.kind,S);O.codecs=i.reduceCodecs(O.codecs,b);let j=O.codecs.some(k=>/.+\/rtx$/i.test(k.mimeType));O.mid=`mid-${n.generateRandomNumber()}`,O.msid=`${m??"-"} ${p.id}`,_||(_=[{}]);for(let k of _)k.ssrc=n.generateRandomNumber(),j&&(k.rtx={ssrc:n.generateRandomNumber()});O.encodings=_,O.rtcp={cname:this._cname,reducedSize:!0,mux:!0},O.msid=`${m??this._defaultSendStreamId} ${p.id}`;let P=this._nextLocalId++;return this._tracks.set(P,p),{localId:String(P),rtpParameters:O}}async stopSending(p){if(c.debug("stopSending() [localId:%s]",p),!this._closed){if(!this._tracks.has(Number(p)))throw new Error("local track not found");this._tracks.delete(Number(p))}}async pauseSending(p){this.assertNotClosed()}async resumeSending(p){this.assertNotClosed()}async replaceTrack(p,m){this.assertNotClosed(),m?c.debug("replaceTrack() [localId:%s, track.id:%s]",p,m.id):c.debug("replaceTrack() [localId:%s, no track]",p),this._tracks.delete(Number(p)),this._tracks.set(Number(p),m)}async setMaxSpatialLayer(p,m){this.assertNotClosed(),c.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",p,m)}async setRtpEncodingParameters(p,m){this.assertNotClosed(),c.debug("setRtpEncodingParameters() [localId:%s, params:%o]",p,m)}async getSenderStats(p){return this.assertNotClosed(),new Map}async sendDataChannel({sctpStreamParameters:p}){this.assertNotClosed(),this._transportReady||await this.setupTransport({localDtlsRole:"server"}),c.debug("sendDataChannel()");let m=new l({id:this._nextSctpStreamId++,ordered:p.ordered,maxPacketLifeTime:p.maxPacketLifeTime,maxRetransmits:p.maxRetransmits,label:p.label,protocol:p.protocol}),_={streamId:this._nextSctpStreamId,ordered:p.ordered,maxPacketLifeTime:p.maxPacketLifeTime,maxRetransmits:p.maxRetransmits};return{dataChannel:m,sctpStreamParameters:_}}async receive(p){this.assertNotClosed();let m=[];for(let _ of p){let{trackId:f,kind:b}=_;this._transportReady||await this.setupTransport({localDtlsRole:"client"}),c.debug("receive() [trackId:%s, kind:%s]",f,b);let w=this._nextLocalId++,S=new e.FakeMediaStreamTrack({kind:b});this._tracks.set(w,S),m.push({localId:String(w),track:S})}return m}async stopReceiving(p){if(!this._closed)for(let m of p)c.debug("stopReceiving() [localId:%s]",m),this._tracks.delete(Number(m))}async pauseReceiving(p){this.assertNotClosed()}async resumeReceiving(p){this.assertNotClosed()}async getReceiverStats(p){return this.assertNotClosed(),new Map}async receiveDataChannel({sctpStreamParameters:p,label:m,protocol:_}){return this.assertNotClosed(),this._transportReady||await this.setupTransport({localDtlsRole:"client"}),c.debug("receiveDataChannel()"),{dataChannel:new l({id:p.streamId,ordered:p.ordered,maxPacketLifeTime:p.maxPacketLifeTime,maxRetransmits:p.maxRetransmits,label:m,protocol:_})}}getDataChannelMaxMessageSize(){return 5e5}async setupTransport({localDtlsRole:p,localSdpObject:m}){let _=n.clone(this._fakeParameters.generateLocalDtlsParameters());p&&(_.role=p),this.emit("@connectionstatechange","connecting"),await new Promise((f,b)=>this.emit("@connect",{dtlsParameters:_},f,b)),this._transportReady=!0}assertNotClosed(){if(this._closed)throw new o.InvalidStateError("method called in a closed handler")}};t.FakeHandler=u;var l=class extends a.FakeEventTarget{_id;_negotiated=!0;_ordered;_maxPacketLifeTime;_maxRetransmits;_label;_protocol;_readyState="connecting";_bufferedAmount=0;_bufferedAmountLowThreshold=0;_binaryType="arraybuffer";_onopen=null;_onclosing=null;_onclose=null;_onmessage=null;_onbufferedamountlow=null;_onerror=null;constructor({id:h,ordered:p=!0,maxPacketLifeTime:m=null,maxRetransmits:_=null,label:f="",protocol:b=""}){super(),c.debug(`constructor() [id:${h}, ordered:${p}, maxPacketLifeTime:${m}, maxRetransmits:${_}, label:${f}, protocol:${b}`),this._id=h,this._ordered=p,this._maxPacketLifeTime=m,this._maxRetransmits=_,this._label=f,this._protocol=b}get id(){return this._id}get negotiated(){return this._negotiated}get ordered(){return this._ordered}get maxPacketLifeTime(){return this._maxPacketLifeTime}get maxRetransmits(){return this._maxRetransmits}get label(){return this._label}get protocol(){return this._protocol}get readyState(){return this._readyState}get bufferedAmount(){return this._bufferedAmount}get bufferedAmountLowThreshold(){return this._bufferedAmountLowThreshold}set bufferedAmountLowThreshold(h){this._bufferedAmountLowThreshold=h}get binaryType(){return this._binaryType}set binaryType(h){this._binaryType=h}get onopen(){return this._onopen}set onopen(h){this._onopen&&this.removeEventListener("open",this._onopen),this._onopen=h,h&&this.addEventListener("open",h)}get onclosing(){return this._onclosing}set onclosing(h){this._onclosing&&this.removeEventListener("closing",this._onclosing),this._onclosing=h,h&&this.addEventListener("closing",h)}get onclose(){return this._onclose}set onclose(h){this._onclose&&this.removeEventListener("close",this._onclose),this._onclose=h,h&&this.addEventListener("close",h)}get onmessage(){return this._onmessage}set onmessage(h){this._onmessage&&this.removeEventListener("message",this._onmessage),this._onmessage=h,h&&this.addEventListener("message",h)}get onbufferedamountlow(){return this._onbufferedamountlow}set onbufferedamountlow(h){this._onbufferedamountlow&&this.removeEventListener("bufferedamountlow",this._onbufferedamountlow),this._onbufferedamountlow=h,h&&this.addEventListener("bufferedamountlow",h)}get onerror(){return this._onerror}set onerror(h){this._onerror&&this.removeEventListener("error",this._onerror),this._onerror=h,h&&this.addEventListener("error",h)}addEventListener(h,p,m){super.addEventListener(h,p,m)}removeEventListener(h,p,m){super.removeEventListener(h,p,m)}close(){["closing","closed"].includes(this._readyState)||(this._readyState="closed")}send(h){if(this._readyState!=="open")throw new o.InvalidStateError("not open")}}}),sse=nt(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.generateRouterRtpCapabilities=s,t.generateNativeRtpCapabilities=n,t.generateNativeSctpCapabilities=i,t.generateLocalDtlsParameters=o,t.generateTransportRemoteParameters=a,t.generateProducerRemoteParameters=c,t.generateConsumerRemoteParameters=d,t.generateDataProducerRemoteParameters=u,t.generateDataConsumerRemoteParameters=l;var e=Yh();function r(){return String(e.generateRandomNumber())}function s(){return e.deepFreeze({codecs:[{mimeType:"audio/opus",kind:"audio",preferredPayloadType:100,clockRate:48e3,channels:2,rtcpFeedback:[{type:"transport-cc"}],parameters:{useinbandfec:1,foo:"bar"}},{mimeType:"video/VP8",kind:"video",preferredPayloadType:101,clockRate:9e4,rtcpFeedback:[{type:"nack"},{type:"nack",parameter:"pli"},{type:"ccm",parameter:"fir"},{type:"goog-remb"},{type:"transport-cc"}],parameters:{"x-google-start-bitrate":1500}},{mimeType:"video/rtx",kind:"video",preferredPayloadType:102,clockRate:9e4,rtcpFeedback:[],parameters:{apt:101}},{mimeType:"video/H264",kind:"video",preferredPayloadType:103,clockRate:9e4,rtcpFeedback:[{type:"nack"},{type:"nack",parameter:"pli"},{type:"ccm",parameter:"fir"},{type:"goog-remb"},{type:"transport-cc"}],parameters:{"level-asymmetry-allowed":1,"packetization-mode":1,"profile-level-id":"42e01f"}},{mimeType:"video/rtx",kind:"video",preferredPayloadType:104,clockRate:9e4,rtcpFeedback:[],parameters:{apt:103}},{mimeType:"video/VP9",kind:"video",preferredPayloadType:105,clockRate:9e4,rtcpFeedback:[{type:"nack"},{type:"nack",parameter:"pli"},{type:"ccm",parameter:"fir"},{type:"goog-remb"},{type:"transport-cc"}],parameters:{"profile-id":0,"x-google-start-bitrate":1500}},{mimeType:"video/rtx",kind:"video",preferredPayloadType:106,clockRate:9e4,rtcpFeedback:[],parameters:{apt:105}}],headerExtensions:[{kind:"audio",uri:"urn:ietf:params:rtp-hdrext:sdes:mid",preferredId:1,preferredEncrypt:!1,direction:"sendrecv"},{kind:"video",uri:"urn:ietf:params:rtp-hdrext:sdes:mid",preferredId:1,preferredEncrypt:!1,direction:"sendrecv"},{kind:"video",uri:"urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id",preferredId:2,preferredEncrypt:!1,direction:"recvonly"},{kind:"video",uri:"urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id",preferredId:3,preferredEncrypt:!1,direction:"recvonly"},{kind:"audio",uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time",preferredId:4,preferredEncrypt:!1,direction:"sendrecv"},{kind:"video",uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time",preferredId:4,preferredEncrypt:!1,direction:"sendrecv"},{kind:"audio",uri:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",preferredId:5,preferredEncrypt:!1,direction:"recvonly"},{kind:"video",uri:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",preferredId:5,preferredEncrypt:!1,direction:"sendrecv"},{kind:"audio",uri:"urn:ietf:params:rtp-hdrext:ssrc-audio-level",preferredId:10,preferredEncrypt:!1,direction:"sendrecv"},{kind:"video",uri:"urn:3gpp:video-orientation",preferredId:11,preferredEncrypt:!1,direction:"sendrecv"},{kind:"video",uri:"urn:ietf:params:rtp-hdrext:toffset",preferredId:12,preferredEncrypt:!1,direction:"sendrecv"}]})}function n(){return{codecs:[{mimeType:"audio/opus",kind:"audio",preferredPayloadType:111,clockRate:48e3,channels:2,rtcpFeedback:[{type:"transport-cc"}],parameters:{minptime:10,useinbandfec:1}},{mimeType:"audio/ISAC",kind:"audio",preferredPayloadType:103,clockRate:16e3,channels:1,rtcpFeedback:[{type:"transport-cc"}],parameters:{}},{mimeType:"audio/CN",kind:"audio",preferredPayloadType:106,clockRate:32e3,channels:1,rtcpFeedback:[{type:"transport-cc"}],parameters:{}},{mimeType:"audio/foo",kind:"audio",preferredPayloadType:107,clockRate:9e4,channels:4,rtcpFeedback:[{type:"foo-qwe-qwe"}],parameters:{foo:"lalala"}},{mimeType:"video/BAZCODEC",kind:"video",preferredPayloadType:100,clockRate:9e4,rtcpFeedback:[{type:"foo"},{type:"transport-cc"},{type:"ccm",parameter:"fir"},{type:"nack"},{type:"nack",parameter:"pli"}],parameters:{baz:"1234abcd"}},{mimeType:"video/rtx",kind:"video",preferredPayloadType:101,clockRate:9e4,rtcpFeedback:[],parameters:{apt:100}},{mimeType:"video/VP8",kind:"video",preferredPayloadType:96,clockRate:9e4,rtcpFeedback:[{type:"goog-remb"},{type:"transport-cc"},{type:"ccm",parameter:"fir"},{type:"nack"},{type:"nack",parameter:"pli"}],parameters:{baz:"1234abcd"}},{mimeType:"video/rtx",kind:"video",preferredPayloadType:97,clockRate:9e4,rtcpFeedback:[],parameters:{apt:96}},{mimeType:"video/VP9",kind:"video",preferredPayloadType:98,clockRate:9e4,rtcpFeedback:[{type:"goog-remb"},{type:"transport-cc"},{type:"ccm",parameter:"fir"},{type:"nack"},{type:"nack",parameter:"pli"}],parameters:{"profile-id":0}},{mimeType:"video/rtx",kind:"video",preferredPayloadType:99,clockRate:9e4,rtcpFeedback:[],parameters:{apt:98}}],headerExtensions:[{kind:"audio",uri:"urn:ietf:params:rtp-hdrext:sdes:mid",preferredId:1},{kind:"video",uri:"urn:ietf:params:rtp-hdrext:sdes:mid",preferredId:1},{kind:"video",uri:"urn:ietf:params:rtp-hdrext:toffset",preferredId:2},{kind:"video",uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time",preferredId:3},{kind:"video",uri:"urn:3gpp:video-orientation",preferredId:4},{kind:"video",uri:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",preferredId:5},{kind:"video",uri:"http://www.webrtc.org/experiments/rtp-hdrext/playout-delay",preferredId:6},{kind:"video",uri:"http://www.webrtc.org/experiments/rtp-hdrext/video-content-type",preferredId:7},{kind:"video",uri:"http://www.webrtc.org/experiments/rtp-hdrext/video-timing",preferredId:8},{kind:"audio",uri:"urn:ietf:params:rtp-hdrext:ssrc-audio-level",preferredId:10}]}}function i(){return e.deepFreeze({numStreams:{OS:2048,MIS:2048}})}function o(){return e.deepFreeze({fingerprints:[{algorithm:"sha-256",value:"82:5A:68:3D:36:C3:0A:DE:AF:E7:32:43:D2:88:83:57:AC:2D:65:E5:80:C4:B6:FB:AF:1A:A0:21:9F:6D:0C:AD"}],role:"auto"})}function a(){return{id:r(),iceParameters:e.deepFreeze({iceLite:!0,password:"yku5ej8nvfaor28lvtrabcx0wkrpkztz",usernameFragment:"h3hk1iz6qqlnqlne"}),iceCandidates:e.deepFreeze([{foundation:"udpcandidate",address:"9.9.9.9",ip:"9.9.9.9",port:40533,priority:1078862079,protocol:"udp",type:"host",tcpType:"passive"},{foundation:"udpcandidate",address:"9.9.9.9",ip:"9:9:9:9:9:9",port:41333,priority:1078862089,protocol:"udp",type:"host",tcpType:"passive"}]),dtlsParameters:e.deepFreeze({fingerprints:[{algorithm:"sha-256",value:"A9:F4:E0:D2:74:D3:0F:D9:CA:A5:2F:9F:7F:47:FA:F0:C4:72:DD:73:49:D0:3B:14:90:20:51:30:1B:90:8E:71"},{algorithm:"sha-384",value:"03:D9:0B:87:13:98:F6:6D:BC:FC:92:2E:39:D4:E1:97:32:61:30:56:84:70:81:6E:D1:82:97:EA:D9:C1:21:0F:6B:C5:E7:7F:E1:97:0C:17:97:6E:CF:B3:EF:2E:74:B0"},{algorithm:"sha-512",value:"84:27:A4:28:A4:73:AF:43:02:2A:44:68:FF:2F:29:5C:3B:11:9A:60:F4:A8:F0:F5:AC:A0:E3:49:3E:B1:34:53:A9:85:CE:51:9B:ED:87:5E:B8:F4:8E:3D:FA:20:51:B8:96:EE:DA:56:DC:2F:5C:62:79:15:23:E0:21:82:2B:2C"}],role:"auto"}),sctpParameters:e.deepFreeze({port:5e3,OS:2048,MIS:2048,maxMessageSize:2e6})}}function c(){return e.deepFreeze({id:r()})}function d({id:h,codecMimeType:p}={}){switch(p){case"audio/opus":return{id:h??r(),producerId:r(),kind:"audio",rtpParameters:e.deepFreeze({codecs:[{mimeType:"audio/opus",payloadType:100,clockRate:48e3,channels:2,rtcpFeedback:[{type:"transport-cc"}],parameters:{useinbandfec:1,foo:"bar"}}],encodings:[{ssrc:46687003}],headerExtensions:[{uri:"urn:ietf:params:rtp-hdrext:sdes:mid",id:1},{uri:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",id:5},{uri:"urn:ietf:params:rtp-hdrext:ssrc-audio-level",id:10}],rtcp:{cname:"wB4Ql4lrsxYLjzuN",reducedSize:!0,mux:!0}})};case"audio/ISAC":return{id:h??r(),producerId:r(),kind:"audio",rtpParameters:e.deepFreeze({codecs:[{mimeType:"audio/ISAC",payloadType:111,clockRate:16e3,channels:1,rtcpFeedback:[{type:"transport-cc"}],parameters:{}}],encodings:[{ssrc:46687004}],headerExtensions:[{uri:"urn:ietf:params:rtp-hdrext:sdes:mid",id:1},{uri:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",id:5}],rtcp:{cname:"wB4Ql4lrsxYLjzuN",reducedSize:!0,mux:!0}})};case"video/VP8":return{id:h??r(),producerId:r(),kind:"video",rtpParameters:e.deepFreeze({codecs:[{mimeType:"video/VP8",payloadType:101,clockRate:9e4,rtcpFeedback:[{type:"nack"},{type:"nack",parameter:"pli"},{type:"ccm",parameter:"fir"},{type:"goog-remb"},{type:"transport-cc"}],parameters:{"x-google-start-bitrate":1500}},{mimeType:"video/rtx",payloadType:102,clockRate:9e4,rtcpFeedback:[],parameters:{apt:101}}],encodings:[{ssrc:99991111,rtx:{ssrc:99991112}}],headerExtensions:[{uri:"urn:ietf:params:rtp-hdrext:sdes:mid",id:1},{uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time",id:4},{uri:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",id:5},{uri:"urn:3gpp:video-orientation",id:11},{uri:"urn:ietf:params:rtp-hdrext:toffset",id:12}],rtcp:{cname:"wB4Ql4lrsxYLjzuN",reducedSize:!0,mux:!0}})};case"video/H264":return{id:h??r(),producerId:r(),kind:"video",rtpParameters:e.deepFreeze({codecs:[{mimeType:"video/H264",payloadType:103,clockRate:9e4,rtcpFeedback:[{type:"nack"},{type:"nack",parameter:"pli"},{type:"ccm",parameter:"fir"},{type:"goog-remb"},{type:"transport-cc"}],parameters:{"level-asymmetry-allowed":1,"packetization-mode":1,"profile-level-id":"42e01f"}},{mimeType:"video/rtx",payloadType:104,clockRate:9e4,rtcpFeedback:[],parameters:{apt:103}}],encodings:[{ssrc:99991113,rtx:{ssrc:99991114}}],headerExtensions:[{uri:"urn:ietf:params:rtp-hdrext:sdes:mid",id:1},{uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time",id:4},{uri:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",id:5},{uri:"urn:3gpp:video-orientation",id:11},{uri:"urn:ietf:params:rtp-hdrext:toffset",id:12}],rtcp:{cname:"wB4Ql4lrsxYLjzuN",reducedSize:!0,mux:!0}})};default:throw new TypeError(`unknown codecMimeType '${p}'`)}}function u(){return e.deepFreeze({id:r()})}function l({id:h}={}){return{id:h??r(),dataProducerId:r(),sctpStreamParameters:e.deepFreeze({streamId:666,maxPacketLifeTime:5e3,maxRetransmits:void 0})}}}),CF=nt(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.debug=t.testFakeParameters=t.FakeHandler=t.enhancedEvents=t.ortc=t.parseScalabilityMode=t.detectDeviceAsync=t.detectDevice=t.Device=t.version=t.types=void 0;var e=$1();t.debug=e.default,t.types=Ire(),t.version="3.20.0";var r=Xre();Object.defineProperty(t,"Device",{enumerable:!0,get:function(){return r.Device}}),Object.defineProperty(t,"detectDevice",{enumerable:!0,get:function(){return r.detectDevice}}),Object.defineProperty(t,"detectDeviceAsync",{enumerable:!0,get:function(){return r.detectDeviceAsync}});var s=Jh();Object.defineProperty(t,"parseScalabilityMode",{enumerable:!0,get:function(){return s.parse}}),t.ortc=ea(),t.enhancedEvents=Xs();var n=rse();Object.defineProperty(t,"FakeHandler",{enumerable:!0,get:function(){return n.FakeHandler}}),t.testFakeParameters=sse()}),nse=nt((t,e)=>{"use strict";var r=Object.prototype.hasOwnProperty,s="~";function n(){}Object.create&&(n.prototype=Object.create(null),new n().__proto__||(s=!1));function i(d,u,l){this.fn=d,this.context=u,this.once=l||!1}function o(d,u,l,h,p){if(typeof l!="function")throw new TypeError("The listener must be a function");var m=new i(l,h||d,p),_=s?s+u:u;return d._events[_]?d._events[_].fn?d._events[_]=[d._events[_],m]:d._events[_].push(m):(d._events[_]=m,d._eventsCount++),d}function a(d,u){--d._eventsCount===0?d._events=new n:delete d._events[u]}function c(){this._events=new n,this._eventsCount=0}c.prototype.eventNames=function(){var d=[],u,l;if(this._eventsCount===0)return d;for(l in u=this._events)r.call(u,l)&&d.push(s?l.slice(1):l);return Object.getOwnPropertySymbols?d.concat(Object.getOwnPropertySymbols(u)):d},c.prototype.listeners=function(d){var u=s?s+d:d,l=this._events[u];if(!l)return[];if(l.fn)return[l.fn];for(var h=0,p=l.length,m=new Array(p);h<p;h++)m[h]=l[h].fn;return m},c.prototype.listenerCount=function(d){var u=s?s+d:d,l=this._events[u];return l?l.fn?1:l.length:0},c.prototype.emit=function(d,u,l,h,p,m){var _=s?s+d:d;if(!this._events[_])return!1;var f=this._events[_],b=arguments.length,w,S;if(f.fn){switch(f.once&&this.removeListener(d,f.fn,void 0,!0),b){case 1:return f.fn.call(f.context),!0;case 2:return f.fn.call(f.context,u),!0;case 3:return f.fn.call(f.context,u,l),!0;case 4:return f.fn.call(f.context,u,l,h),!0;case 5:return f.fn.call(f.context,u,l,h,p),!0;case 6:return f.fn.call(f.context,u,l,h,p,m),!0}for(S=1,w=new Array(b-1);S<b;S++)w[S-1]=arguments[S];f.fn.apply(f.context,w)}else{var O=f.length,j;for(S=0;S<O;S++)switch(f[S].once&&this.removeListener(d,f[S].fn,void 0,!0),b){case 1:f[S].fn.call(f[S].context);break;case 2:f[S].fn.call(f[S].context,u);break;case 3:f[S].fn.call(f[S].context,u,l);break;case 4:f[S].fn.call(f[S].context,u,l,h);break;default:if(!w)for(j=1,w=new Array(b-1);j<b;j++)w[j-1]=arguments[j];f[S].fn.apply(f[S].context,w)}}return!0},c.prototype.on=function(d,u,l){return o(this,d,u,l,!1)},c.prototype.once=function(d,u,l){return o(this,d,u,l,!0)},c.prototype.removeListener=function(d,u,l,h){var p=s?s+d:d;if(!this._events[p])return this;if(!u)return a(this,p),this;var m=this._events[p];if(m.fn)m.fn===u&&(!h||m.once)&&(!l||m.context===l)&&a(this,p);else{for(var _=0,f=[],b=m.length;_<b;_++)(m[_].fn!==u||h&&!m[_].once||l&&m[_].context!==l)&&f.push(m[_]);f.length?this._events[p]=f.length===1?f[0]:f:a(this,p)}return this},c.prototype.removeAllListeners=function(d){var u;return d?(u=s?s+d:d,this._events[u]&&a(this,u)):(this._events=new n,this._eventsCount=0),this},c.prototype.off=c.prototype.removeListener,c.prototype.addListener=c.prototype.on,c.prefixed=s,c.EventEmitter=c,typeof e<"u"&&(e.exports=c)}),XA=class{_handlers=new Map;_ws;_onMessage;_onOpen;_listeningForOpen=!1;_pendingSends=[];_disposed=!1;constructor(t){this._ws=t,this._onMessage=e=>{if(typeof e.data!="string")return;let r;try{r=JSON.parse(e.data)}catch{E.warn("[ChannelMultiplexer] Failed to parse WebSocket message as JSON");return}if(!r.channel)return;let s=this._handlers.get(r.channel);if(s)for(let n of s)n(r)},this._ws.addEventListener("message",this._onMessage),this._onOpen=()=>{this.flushPendingSends()}}on(t,e){let r=this._handlers.get(t);return r||(r=new Set,this._handlers.set(t,r)),r.add(e),()=>{r.delete(e),r.size===0&&this._handlers.delete(t)}}emit(t,e){if(this._disposed)return;let r=JSON.stringify({channel:t,...e});if(this._ws.readyState===WebSocket.OPEN){this._ws.send(r);return}this._ws.readyState===WebSocket.CONNECTING&&(this._pendingSends.push(r),this.listenForOpen())}dispose(){this._disposed=!0,this._pendingSends=[],this._handlers.clear(),this._ws.removeEventListener("message",this._onMessage),this._ws.removeEventListener("open",this._onOpen),this._listeningForOpen=!1}flushPendingSends(){if(this._disposed||this._ws.readyState!==WebSocket.OPEN)return;this._ws.removeEventListener("open",this._onOpen),this._listeningForOpen=!1;let t=this._pendingSends;this._pendingSends=[];for(let e of t)this._ws.send(e)}listenForOpen(){this._listeningForOpen||(this._listeningForOpen=!0,this._ws.addEventListener("open",this._onOpen))}},YA=class{_handlers=new Map;_pendingSends=[];_target=null;_targetUnsubscribes=[];_disposed=!1;setTarget(t){if(this._disposed)return;this.detachTarget(),this._target=t;for(let[r,s]of this._handlers)for(let n of s)this._targetUnsubscribes.push(t.on(r,n));let e=this._pendingSends;this._pendingSends=[];for(let r of e)t.emit(r.channel,r.data)}rewriteSessionChannels(t,e){if(t===e)return;let r=`session:${t}:`,s=`session:${e}:`,n=new Map;for(let[i,o]of this._handlers)n.set(i.startsWith(r)?s+i.slice(r.length):i,o);this._handlers=n,this._pendingSends=this._pendingSends.map(i=>({...i,channel:i.channel.startsWith(r)?s+i.channel.slice(r.length):i.channel}))}on(t,e){if(this._disposed)return()=>{};let r=this._handlers.get(t);r||(r=new Set,this._handlers.set(t,r)),r.add(e);let s=this._target?.on(t,e);return s&&this._targetUnsubscribes.push(s),()=>{r?.delete(e),r?.size===0&&this._handlers.delete(t),s?.(),s&&(this._targetUnsubscribes=this._targetUnsubscribes.filter(n=>n!==s))}}emit(t,e){if(!this._disposed){if(this._target){this._target.emit(t,e);return}this._pendingSends.push({channel:t,data:e})}}dispose(){this._disposed=!0,this._pendingSends=[],this._handlers.clear(),this.detachTarget()}detachTarget(){for(let t of this._targetUnsubscribes)t();this._targetUnsubscribes=[],this._target=null}},El=class extends Error{code="session_end_unavailable";constructor(t="[urun] this session handle cannot terminally end the session; disconnect the viewer instead",e){super(t),this.name="SessionEndUnavailableError",e?.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,new.target.prototype)}},Sn=class extends Error{code;httpStatus;requestId;sessionId;constructor(t,e){super(t),this.name="SessionEndError",this.code=e.code??"session_end_failed",this.httpStatus=e.httpStatus,this.requestId=e.requestId,this.sessionId=e.sessionId,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,new.target.prototype)}},Gi=class extends Error{code;httpStatus;constructor(t,e){super(t),this.name="SessionDirectoryError",this.code=e?.code??"session_directory_failed",this.httpStatus=e?.httpStatus,e?.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,new.target.prototype)}},ta=class extends Error{requestId;code;constructor(t,e){super(t),this.name="RequestError",this.requestId=e?.requestId,this.code=e?.code,e?.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,new.target.prototype)}},F1=class extends ta{timeoutMs;constructor(t,e){super(`[urun] request timed out after ${t}ms`,{requestId:e}),this.name="RequestTimeoutError",this.timeoutMs=t,Object.setPrototypeOf(this,new.target.prototype)}},H1=class extends ta{timeoutMs;constructor(t,e){super(`[urun] request doc-sync did not establish within ${t}ms \u2014 the request was never delivered to the runtime (the session doc never synced with the session-server; check the doc-sync transport / connection)`,{requestId:e}),this.name="RequestDocSyncError",this.timeoutMs=t,Object.setPrototypeOf(this,new.target.prototype)}},q1=class extends Error{stream;owner;attempted;constructor(t,e,r){super(`[urun] stream "${t}" is already produced by the ${e}; this (${r}) peer cannot also produce it \u2014 a named stream has exactly one producer (consume it instead, or use a distinct name for the reverse direction)`),this.name="StreamDirectionConflict",this.stream=t,this.owner=e,this.attempted=r,Object.setPrototypeOf(this,new.target.prototype)}},fg=15e3,JA=class extends Error{kind;stream;timeoutMs;constructor(t,e){let r=e?.timeoutMs??fg,s=e?.stream??t,n=s!==t?` "${s}"`:"";super(`[urun] SFU did not ack producer ${t}${n} within ${Math.round(r/1e3)}s \u2014 the server never replied to 'produce'. The runtime's inbound port for this stream is likely unadvertised (a cold or capacity-queued runtime), so the SFU has nothing to forward the track to; the published track never reached the runtime.`),this.name="ProduceAckTimeout",this.kind=t,this.stream=s,this.timeoutMs=r,Object.setPrototypeOf(this,new.target.prototype)}},wg=class extends ta{constructor(t){super("[urun] request aborted",{requestId:t}),this.name="RequestAbortError",Object.setPrototypeOf(this,new.target.prototype)}},V1=class extends ta{constructor(t){super("[urun] request cancelled: session disconnected",{requestId:t}),this.name="RequestCancelledError",Object.setPrototypeOf(this,new.target.prototype)}},ise=/^\[urun\] (?:timed out waiting for session allocation at|session allocation wait expired at|session allocation poll failed at|session allocation failed at|session allocation at|session create at) \S+(?::[ \t]+|[ \t]+|$)/;function ose(t){return t.replace(/\bhttps?:\/\/[^\s)]+/g,"the session gateway")}function $$(t){let e=t.replace(ise,"");return ose(e||t.replace(/^\[urun\] /,""))}function F$(t){let e=t.error?.httpStatus;if(e===401||e===403)return"The backend rejected this client \u2014 sign in again or check the auth token / org access.";if(t.error?.code==="session_archived")return"This session is archived \u2014 call directory.unarchive(sessionId) (the session directory's un-archive verb), then reconnect with the same id.";let r=t.error?.retryAfterSeconds,s=r!==void 0?` It asked for ${Math.round(r)}s.`:"";return e===429?`The backend is shedding load \u2014 its admission queue is full, so this is capacity, not your request.${s} The SDK already retried with backoff; try again in a moment.`:e===408?`The request timed out before the backend answered \u2014 that is a timeout, not a verdict on your request.${s} The SDK already retried with backoff; try again in a moment.`:e!==void 0&&e>=500?"The backend is having an outage (nothing is wrong with your request) \u2014 the SDK already retried with backoff, so try again shortly and report the status above if it persists.":"The backend could not create a session \u2014 check the app/function name and auth, then retry."}function z1(t,e){let r=e.error?.reason,s=e.elapsedMs!==void 0?Math.round(e.elapsedMs/1e3):void 0;switch(t){case"create-failed":{let n=e.error?.httpStatus!==void 0?` (HTTP ${e.error.httpStatus})`:"",i=e.error?.code;return i==="queue_ttl_expired"||i==="stale_poll_expired"?{message:`[urun] the queued session REQUEST timed out while waiting${n} (${i}) \u2014 the session itself is untouched`,hint:"Nothing was lost and nothing needs replacing: connect again with the same session and the control plane re-admits the request (a poll that arrives in time re-drives it on its own)."}:i==="session_archived"?{message:`[urun] this session is archived${n} \u2014 un-archive it before resuming`+(r?`: ${$$(r)}`:""),hint:F$(e)}:i==="client_release"?{message:`[urun] the session's admission request was closed (client_release)${n} \u2014 this dial cannot attach through it`,hint:"The request row is terminal; retrying the same dial only repeats the 410. Create a fresh session (a new dial). The SDK itself never closes a request \u2014 a whenLive timeout only rejects."}:{message:`[urun] session create failed${n}${r?`: ${$$(r)}`:""}`,hint:F$(e)}}case"never-live":{let n=s!==void 0?` after ${s}s`:"",i=` (last server status: ${e.lastServerStatus??"none"})`,o=e.lastServerStatus!==void 0&&["requested","queued","pending","allocating","provisioning","waking","waiting_for_capacity","unavailable","allocated","starting"].includes(e.lastServerStatus);return e.error?.code==="expired"?o?{message:`[urun] session${e.sessionId?` ${e.sessionId}`:""} expired before a runtime picked it up${n}${i} \u2014 the backend never dispatched the session (no runtime pulled it), so no media transport could ever connect`,hint:"Not a network problem \u2014 the session was still waiting for a runtime. Retry in a moment; if it persists, the backend dispatch lane is stuck."}:{message:`[urun] session${e.sessionId?` ${e.sessionId}`:""} expired before media connected${n} \u2014 the control plane reclaims sessions whose media transport never establishes (~80s after create)`,hint:"Retry to mint a fresh session, and connect promptly after start (a backgrounded tab or paused debugger can miss the window)."}:e.sessionId?o?{message:`[urun] session ${e.sessionId} was created but no runtime ever picked it up${n}${i} \u2014 the backend has not dispatched the session yet (a runtime pulls the demand, then the session server exists)`,hint:"Waiting for a runtime \u2014 not a network, VPN, or firewall problem. Retry in a moment; if it persists, the session id above is what to report."}:{message:`[urun] session ${e.sessionId} was created but never went live${n}${i} \u2014 the backend is busy or wedged (no runtime picked the session up)`,hint:"The backend is at capacity or stuck. Retry in a moment; if it persists, the session id above is what to report."}:{message:`[urun] no session went live${n} (phase=${e.phase}${e.lastServerStatus?`, last server status: ${e.lastServerStatus}`:""})`,hint:"The session never got past admission. Retry; if it persists, check the backend deployment."}}case"transport-failed":return e.error?.code==="transport-consumed"?{message:`[urun] the retry reused a session whose media transport was already connected${e.sessionId?` (id ${e.sessionId})`:""} \u2014 the session was consumed by an earlier attempt`,hint:"Start a fresh session (reload the page) \u2014 this session leg cannot be connected again."}:{message:`[urun] media/transport connection failed${r?`: ${r}`:""} (transport state: ${e.transportState})`,hint:"The network is likely blocking the media connection (WebRTC/WebSocket) \u2014 try a different network or disable VPN/proxy, then retry."};case"media-permission":return{message:`[urun] microphone/camera unavailable${r?`: ${r}`:""}`,hint:e.error?.code==="NotFoundError"||e.error?.code==="OverconstrainedError"?"No matching input device was found \u2014 connect or select a microphone/camera and retry.":"Allow microphone/camera access for this site (browser permission \u2014 or, when embedded, the parent page's permissions policy), then retry."};case"runtime-failed":return{message:`[urun] session${e.sessionId?` ${e.sessionId}`:""} failed at runtime${r?`: ${r}`:""}`,hint:"The session function crashed on the backend \u2014 check the app logs. The session itself is parked, not gone: attach to it again once the app is fixed."};case"produce-timeout":return{message:`[urun] publishing a track timed out${r?`: ${r}`:""} \u2014 the SFU never acked the produce (the runtime\u2019s inbound port for the stream was not advertised in time)`,hint:"The runtime was still cold or the backend was at capacity when the track was published. Retry in a moment; if it persists, the backend never opened the stream to receive it."};case"insufficient-credits":return{message:`[urun] session create refused${e.error?.httpStatus!==void 0?` (HTTP ${e.error.httpStatus})`:""} \u2014 the org has insufficient credits${r?`: ${r}`:""}`,hint:"Out of credits \u2014 add credits to keep running sessions."}}}var Sl=class extends Error{kind;status;hint;constructor(t,e,r){let{message:s,hint:n}=z1(t,e);super(s),this.name="SessionFailedError",this.kind=t,this.status=e,this.hint=n,r?.cause!==void 0&&(this.cause=r.cause),Object.setPrototypeOf(this,new.target.prototype)}};function TF(t,e){if(t instanceof Sl)return t;let r=t instanceof Error?t:new Error(String(t)),s={phase:e?.phase??"idle",transportState:e?.transportState??"disconnected",...e,error:{reason:r.message,code:r.name,kind:"media-permission"}};return new Sl("media-permission",s,{cause:t})}var B1=class extends Error{code="transport_session_mismatch";connectedSessionId;requestedSessionId;constructor(t,e){super(`[urun] cannot retarget a connected transport to a different session: this leg is live on ${t??"(unknown)"} but setConnection() asked for ${e} \u2014 disconnect() this leg first (or use a fresh session handle)`),this.name="TransportSessionMismatchError",this.connectedSessionId=t,this.requestedSessionId=e,Object.setPrototypeOf(this,new.target.prototype)}},Cr=class extends Error{httpStatus;code;balanceCredits;platformStatus;retryAfterSeconds;constructor(t,e){super(t),this.name="SessionAllocationError",this.httpStatus=e?.httpStatus,this.code=e?.code,this.balanceCredits=e?.balanceCredits,this.platformStatus=e?.platformStatus,this.retryAfterSeconds=e?.retryAfterSeconds,e?.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,new.target.prototype)}};function xc(t){if(!t)return!1;let e=typeof t=="string"?t:t.name;return e==="queued"||e==="unavailable"||e==="provisioning"||e==="waiting_for_capacity"}function kF(t){return t?(typeof t=="string"?t:t.name)==="paused":!1}var QA=45e3,L1=6e5;function W1(t,e={}){let{signal:r}=e;return new Promise((s,n)=>{if(r?.aborted){n(r.reason instanceof Error?r.reason:new Error("whenLive aborted"));return}if(t.phase?.name==="live"){s();return}if(t.phase?.name==="error"){let S=t.phase,O=t.status??{phase:S.name,transportState:"disconnected",sessionId:S.sessionId,requestId:S.requestId,queue:S.queue,error:S.error,region:S.region};n(new Sl(S.error?.kind??"transport-failed",O));return}let i,o,a=!1,c=S=>{a||(a=!0,o!==void 0&&clearTimeout(o),r?.removeEventListener("abort",d),i?.(),S?n(S):s())},d=()=>{c(r?.reason instanceof Error?r.reason:new Error("whenLive aborted"))};r?.addEventListener("abort",d,{once:!0});let u=()=>{let S=t.phase;return t.status??{phase:S?.name??"idle",transportState:"disconnected",sessionId:S?.sessionId,requestId:S?.requestId,queue:S?.queue,error:S?.error,region:S?.region}},l=S=>c(new Sl(S,u())),h=e.timeout!==void 0,p=Date.now(),m=h?e.timeout:QA,_=()=>{o!==void 0&&(clearTimeout(o),o=void 0)},f=()=>{if(a||m<=0)return;clearTimeout(o);let S=p+m-Date.now();o=setTimeout(()=>{if(!h&&xc(t.phase?.name)){o=void 0;return}let O=u();O.elapsedMs===void 0&&(O.elapsedMs=m),o=void 0,r?.removeEventListener("abort",d),i?.(),i=void 0,c(new Sl("never-live",O))},Math.max(0,S))},b=S=>{!h||a||m<=0||S?.runtime?.wake?.expectedWakePath==="cold-boot"&&(L1<=m||(m=L1,f()))},w=S=>{if(!a){if(!h&&xc(S?.name)){_();return}if(h){b(S),o===void 0&&m>0&&f();return}o===void 0&&(p=Date.now(),f())}};i=t.onPhase(S=>{S?.name==="live"?c():S?.name==="error"?l(S.error?.kind??"transport-failed"):w(S)}),a||w(t.phase),a&&i()})}function AF(t){switch(t.name){case"idle":return"Initializing\u2026";case"unavailable":return"Starting the app\u2026";case"queued":return t.queue?`Waiting in queue (position ${t.queue.position} of ${t.queue.depth})\u2026`:t.runtime?.state==="busy"?"All runtimes are busy \u2014 waiting for capacity\u2026":"Waiting for capacity\u2026";case"provisioning":return t.runtime?.state==="starting"?"Starting model\u2026":"Provisioning\u2026";case"waiting_for_capacity":return t.queue?`Waiting for GPU capacity (position ${t.queue.position} of ${t.queue.depth})\u2026`:"Waiting for GPU capacity";case"connecting":return"Connecting\u2026";case"live":return"Live";case"paused":return ase(t.reason);case"error":{if(t.error?.kind==="insufficient-credits")return"Out of credits \u2014 add credits to keep running sessions.";let e=t.error?.kind;if(e){let{message:r,hint:s}=z1(e,{phase:t.name,transportState:"disconnected",sessionId:t.sessionId,requestId:t.requestId,queue:t.queue,error:t.error});return`${r.replace(/^\[urun\] /,"")} \u2014 ${s}`}return t.error?.reason?`Session failed \u2014 ${t.error.reason}`:"Session failed"}case"unknown":return t.reason?`Session in an unrecognized state ("${t.reason}") \u2014 the client SDK may be out of date`:"Session in an unrecognized state \u2014 the client SDK may be out of date"}}function ase(t){switch(t){case"client_ended":return"Paused \u2014 you hung up. Resume any time.";case"client_paused":return"Paused \u2014 you paused it. Resume any time.";case"client_detached":return"Paused \u2014 this device let go. Resume any time.";case"client_gone":return"Paused \u2014 every device disconnected. Resume any time.";case"session_ended":case"ended":case"closed":return"Paused \u2014 the compute was released. Resume any time.";case"idle_timeout":return"Paused \u2014 idle. Resume any time.";case"max_session_age":return"Paused \u2014 reached its maximum length. Resume any time.";case"credits_exhausted":return"Paused \u2014 out of credits. Add credits, then resume.";case"capacity_pressure":return"Paused \u2014 the GPU was reclaimed while the platform was under load. Resume any time.";case"control_plane_release":return"Paused \u2014 the platform reclaimed the compute. Resume any time.";case"superseded":return"Paused \u2014 another client attached. Resume any time.";case"superseded_by_redial":return"Paused \u2014 a newer connection from this session took over. Resume any time.";case"connect_deadline":return"Paused \u2014 the runtime never finished connecting in time. Resume to try again.";case"adoption_expired":return"Paused \u2014 the runtime was assigned but never picked the session up. Resume to try again.";case"media_lane_bind_failed":return"Paused \u2014 the audio/video lane could not be set up. Resume to try again.";case"lease_lost":return"Paused \u2014 the runtime stopped renewing its lease. Resume any time.";case"presence_unconfirmed":return"Paused \u2014 the platform could not confirm anyone was still attached. Resume any time.";case"runtime_inert":case"assignment_unconfirmable":return"Paused \u2014 the runtime never acknowledged its assignment. Resume to try again.";case"runtime_unreachable":return"Paused \u2014 the platform could not reach the runtime. Resume to try again.";case"runtime_silent":return"Paused \u2014 the runtime stopped sending audio/video. Resume to try again.";case"assignment_undelivered":return"Paused \u2014 the assignment never reached a runtime. Resume to try again.";case"dispatch_released":return"Paused \u2014 the worker finished and gave its GPU seat back. Resume any time.";case"dispatch_parked":return"Paused \u2014 the worker finished and parked the session. Resume any time.";case"runtime_swap_exhausted":return"Paused \u2014 the platform ran out of runtimes to try. Resume any time.";case"dispatch_failed":return"Paused \u2014 handing the session to a worker did not succeed. Resume to try again.";default:return t?`Paused \u2014 ${t}. Resume any time.`:"Paused \u2014 resume any time."}}function lg(){return typeof process<"u"&&process.stdout!=null&&typeof process.stdout.write=="function"}function Qh(){return typeof window>"u"&&typeof process<"u"&&process.versions!=null&&process.versions.node!=null}function cse(){return Qh()?"Chrome111":void 0}var dse=["RTCSessionDescription","RTCIceCandidate","RTCRtpReceiver","RTCRtpSender","RTCRtpTransceiver","RTCDataChannel","MediaStream","MediaStreamTrack"],HA=null,IF=null;function lse(){return typeof globalThis.RTCPeerConnection<"u"?null:IF??"the WebRTC peer globals (RTCPeerConnection) are not installed in this runtime"}function K1(){return Qh()?HA||(HA=use(),HA):Promise.resolve()}async function use(){let t=globalThis;if(typeof t.WebSocket>"u")try{let e=await Promise.resolve().then(()=>(i8(),n8)),r=e.default??e;t.WebSocket=r}catch(e){H$("WebSocket",e)}if(typeof t.RTCPeerConnection>"u")try{let e=await Promise.resolve().then(()=>(M$(),U$));fse(t,e)}catch(e){IF=H$("werift",e)}}var hse=4;function fse(t,e){let{RTCPeerConnection:r,useH264:s,useVP8:n,useOPUS:i,useSdesMid:o,useSdesRTPStreamId:a,useAbsSendTime:c,useTransportWideCC:d,useVideoOrientation:u}=e,l=()=>({video:[s(),n()],audio:[i()]}),h=()=>({video:[o(),a(),c(),d(),u()],audio:[o(),c(),d()]});class p extends r{constructor(_){super({..._,codecs:_?.codecs??l(),headerExtensions:_?.headerExtensions??h()})}async setRemoteDescription(_){await super.setRemoteDescription(_);let f=this.sctpManager,b=f?.sctpTransport,w=f?.connectSctp;!b||typeof w!="function"||b.dtlsTransport?.state==="connected"&&b.sctp?.associationState!==hse&&await w.call(f)}}t.RTCPeerConnection=p;for(let m of dse)e[m]!=null&&typeof t[m]>"u"&&(t[m]=e[m])}function H$(t,e){let r=e instanceof Error?e.message:String(e),s=`optional dependency "${t}" unavailable (${r})`;return E.warn(`[urun-sh/core] Node WebRTC support: ${s}. Realtime media will not work in this Node process; install "${t}" to enable it. Doc/KV transport over WebSocket is unaffected.`),s}var G1=500,vg=15e3,Wh=6;function _g(t,e=Math.random){if(!Number.isFinite(t)||t<0)throw new Error(`[urun] computeBackoffDelay: attempt must be a non-negative number, got ${t}`);let r=Math.min(vg,G1*2**t);return Math.round(e()*r)}function X1(t){if(t instanceof Cr){let e=t.httpStatus;return e===408||e===429||e!==void 0&&e>=500}return t instanceof Error?t.name==="TypeError"||t.name==="TimeoutError"||t.name==="AbortError":!1}var RF=10,pse=.5,O1=RF;function PF(){return O1<1?!1:(O1-=1,!0)}function DF(){O1=Math.min(RF,O1+pse)}var mse="session-api.prod.cloud.urun.sh",gse=["https://session-api.use2.prod.cloud.urun.sh","https://session-api.usw2.prod.cloud.urun.sh"];function Tr(t){return t.trim().replace(/\/+$/,"")}function Sg(t,e){let r=[],s=n=>{if(!n)return;let i=Tr(n);i&&!r.includes(i)&&r.push(i)};s(t);for(let n of e??[])s(n);for(let n of zse(t))s(n);return r}function Eg(t){try{if(typeof fetch!="function")return;let e=Tr(t.baseUrl),r=t.sessionId?`${e}/api/sessions/${encodeURIComponent(t.sessionId)}/end`:`${e}/api/session-requests/${encodeURIComponent(t.requestId)}/cancel`;fetch(r,{method:"POST",headers:t.reason!==void 0?{...Qn(t,t.jwt),"Content-Type":"application/json"}:Qn(t,t.jwt),...t.reason!==void 0?{body:JSON.stringify({reason:t.reason})}:{},keepalive:!0}).catch(()=>{})}catch{}}async function ZA(t){try{let e=`${Tr(t.baseUrl)}/api/session-requests/${encodeURIComponent(t.requestId)}/cancel`,r=await Jn(t);if(t.getAccessToken&&!r)throw new Sn("[urun] session request cancel refused: getAccessToken resolved no token (an unauthenticated cancel is never sent)",{requestId:t.requestId,code:"no_access_token"});let s=await fetch(e,{method:"POST",headers:Qn(t,r),keepalive:!0});if((s.status===401||s.status===403)&&t.getAccessToken){let o=await Jn(t,{forceRefresh:!0,reason:"unauthorized"});o&&o!==r&&(s=await fetch(e,{method:"POST",headers:Qn(t,o),keepalive:!0}))}let n=await Kh(s);if(!s.ok)throw new Sn(`[urun] session request cancel failed: ${J1(n,s.status)}`,{requestId:t.requestId,code:n.error_code,httpStatus:s.status});let i=String(n.status??"");if(i==="cancelled"||i==="canceled"||i==="closed")return{status:"canceled",requestId:t.requestId};if(i==="failed"||i==="rejected"||i==="expired")return{status:"canceled",requestId:t.requestId,platformStatus:i};throw new Sn(`[urun] session request cancel returned an unrecognized request status ${JSON.stringify(i)} (recognized: cancelled/canceled, closed, failed, rejected, expired)`,{requestId:t.requestId,code:"invalid_release_response",httpStatus:s.status})}catch(e){throw e instanceof Sn?e:new Sn("[urun] session request cancel failed",{requestId:t.requestId,cause:e})}}async function eI(t){let e;try{e=await Y1(t,`/api/sessions/${encodeURIComponent(t.sessionId)}/end`,{method:"POST",keepalive:!0},"session end")}catch(n){if(n instanceof Sn)throw n;let i=n;throw new Sn(i?.message??"[urun] session end request failed",{sessionId:t.sessionId,...i?.code!==void 0?{code:i.code}:{},...i?.httpStatus!==void 0?{httpStatus:i.httpStatus}:{},cause:n})}let r=String(e.status??""),s=e.pause_reason;if(r==="paused")return{status:"paused",sessionId:String(e.logical_id??e.id??t.sessionId),reason:typeof s=="string"&&s.length>0?s:"client_ended"};throw new Sn(`[urun] session end returned ${JSON.stringify(r)} for session ${t.sessionId} \u2014 an end PARKS the session, so the only contract-valid answer is "paused" (a terminal word on this route would be a session-plane terminal write, which is forbidden)`,{sessionId:t.sessionId,code:"invalid_end_response"})}function BF(t){if(typeof t!="string"||t.length===0)return null;let e=new Date(t);return Number.isFinite(e.getTime())?e:null}var yse=120,bse=1e3,xse=20,wse=5,vse=5e3;function _se(t,e=Date.now()){if(!t)return null;let r=t.split(".")[1];if(!r)return null;try{let s=r.replace(/-/g,"+").replace(/_/g,"/"),n=s.padEnd(s.length+(4-s.length%4)%4,"="),i=JSON.parse(atob(n));return typeof i.exp!="number"||!Number.isFinite(i.exp)?null:i.exp*1e3-e}catch{return null}}var Sse=500,LF=1e4,Ese=new Set([502,503,504]),Cse=2,Tse=50,q$=1e4;async function V$(t,e){let r=Date.now()+q$;for(;;){await zh(Tse);let s=await Jn(t);if(s)return s;if(Date.now()>=r)throw new Cr(`[urun] session allocation at ${e} never got an access token: the wired getAccessToken resolved nothing within ${Math.round(q$/1e3)}s (no unauthenticated request was sent)`)}}function kse(t,e){if(!t)return null;try{let r=new URL(t),s=e?new URL(Tr(e)):null,n=r.pathname==="/api/sessions/create"||r.pathname==="/api/sessions/create/";return r.protocol!=="https:"||!n||!Pse(r,s)?null:Tr(r.origin)}catch{return null}}function Ase(t,e){if(!t||!t.trim())return{outcome:"absent"};if(!Ise(e))return{outcome:"bootstrap-only"};let r=t.includes("://")?t:`https://${t}`,s;try{s=new URL(r)}catch{return{outcome:"rejected",reason:"not a parseable URL or host"}}return s.protocol!=="https:"?{outcome:"rejected",reason:`scheme ${s.protocol} is not https:`}:s.pathname!=="/"&&s.pathname!==""?{outcome:"rejected",reason:`expected a bare origin, got path ${s.pathname}`}:N1(s.hostname)?{outcome:"pinned",base:Tr(s.origin)}:{outcome:"rejected",reason:`host ${s.hostname} is outside the urun.sh trust set`}}function Ise(t){if(!t)return!1;try{let e=new URL(Tr(t));return e.protocol==="https:"&&N1(e.hostname)}catch{return!1}}function Rse(t){let e=Tr(t);try{return Tr(new URL(e).origin)}catch{return e}}function Pse(t,e){return N1(t.hostname)&&(!e||N1(e.hostname))}function N1(t){let e=t.toLowerCase();return e==="urun.sh"||e.endsWith(".urun.sh")}function Dse(t){let e=t instanceof Cr?t.retryAfterSeconds:void 0;return e===void 0||!Number.isFinite(e)||e<=0?0:Math.min(e*1e3,vg)}function OF(t,e){let r=Dse(e);return r>0?Math.max(t,Date.now()+r):t}async function NF(t){let e=Sg(t.baseUrl,t.fallbackUrls),r=null,s=0,n=e.length>1;for(let i=0;i<Wh;i++){for(let o of e)try{let a=await Bse(o,t,{pollAttempts:yse,retryAfterLimitMs:n?bse:void 0});return DF(),a}catch(a){if(r=a instanceof Error?a:new Error(String(a)),s=OF(s,r),r instanceof Zo||r instanceof ug||Nse(r))throw r}if(!X1(r))break;if(i+1<Wh){if(!PF())break;await zh(Math.max(_g(i),s-Date.now()))}}throw r??new Error("[urun] session allocation failed")}async function Bse(t,e,r){let s,n,i,o,a=Rse(t),c=0,d=new Set,u=Date.now(),l=u+r.pollAttempts*LF,h=!1,p=12e4,m=10080*60,_=S=>{if(typeof S!="number"||!Number.isFinite(S)||S<=0||S>m)return;let O=u+S*1e3+p;O>l&&(l=O,h=!0)},f=()=>h?Number.POSITIVE_INFINITY:r.pollAttempts,b=8,w=0;for(let S=0;S<f();S++){if(h&&Date.now()>=l)throw dg(a,!!s,o);n=i??await Jn(e),i=void 0,e.getAccessToken&&!n&&(n=await V$(e,a));let O=!!s,j=Date.now(),P;if(s){let W=0,J=F=>{let q=Math.min(vg,G1*2**W),Q=Math.max(Math.ceil(q/2),_g(W));return W+=1,Math.min(Math.max(F,Q),Math.max(0,l-Date.now()))};for(;;){let F=l-Date.now();if(F<=0)throw dg(a,!0,o);let q=Math.max(1,Math.min(xse,Math.floor(F/1e3)));{let R=_se(n);if(R!==null&&R<q*1e3+vse)try{let Y=await Jn(e,{forceRefresh:!0});Y&&Y!==n&&(n=Y)}catch{}}j=Date.now();try{P=await fetch(`${a}/api/session-requests/${encodeURIComponent(s)}?wait_s=${q}`,{headers:Qn(e,n),redirect:"manual",signal:Hse((q+wse)*1e3)})}catch{let R=J(0);if(R<=0)throw dg(a,!0,o);await zh(R);continue}if(o=`HTTP ${P.status}`,!Ese.has(P.status))break;try{await P.body?.cancel()}catch(R){throw new ug(`[urun] session allocation poll response cleanup failed at ${a}`,{cause:R})}let Q=J(W$(P,{},r.retryAfterLimitMs));if(Q<=0)throw dg(a,!0,o);await zh(Q)}}else P=await fetch(`${a}/api/sessions/create`,{method:"POST",redirect:"manual",headers:{...Qn(e,n),"Content-Type":"application/json","Idempotency-Key":e.idempotencyKey},body:JSON.stringify(Lse(e))});if(P.type==="opaqueredirect"||P.status>=300&&P.status<400){try{await P.body?.cancel()}catch{}throw new Zo(`[urun] ${O?"session poll":"session create"} at ${a} answered an HTTP redirect (status ${P.status}) \u2014 browsers cannot follow a cross-origin redirect with credentials; the control plane must emit the JSON redirect envelope ({status:"redirect", location})`)}let k=await Kh(P);if(o=typeof k.status=="string"&&k.status?k.status:`HTTP ${P.status}`,P.status!==401&&P.status!==403&&(w=0),!s&&k.status==="redirect"){let W=kse(k.location,a);if(!W)throw new Cr(`[urun] session create at ${a} answered a redirect envelope without a usable location (${JSON.stringify(k.location??null)}) \u2014 refusing to re-issue an authenticated create to an untrusted target`);if(W===a)throw new Cr(`[urun] session create at ${a} redirected to ITSELF \u2014 control-plane region apex map misconfiguration`);if(c>=Cse)throw new Cr(`[urun] session create followed ${c} region redirects and was redirected AGAIN (${a} -> ${W}) \u2014 region forward loop, giving up loudly`);c+=1,a=W;continue}if(k.request_id)try{e.onRequest?.({requestId:k.request_id,baseUrl:a,...k.session_id?{sessionId:k.session_id}:{}})}catch{}if(P.ok&&(k.status==="allocated"||!k.status&&k.session_id)&&k.session_id){let W=k.session_id,J=Ase(k.session_api_base,a);if(J.outcome==="rejected")throw new Zo(`[urun] gateway allocated session ${k.session_id} with an unusable session_api_base (${JSON.stringify(k.session_api_base)}): ${J.reason} \u2014 refusing to pin the session to a region it may not belong to`);if(J.outcome==="pinned"&&J.base!==a&&(a=J.base,k.request_id))try{e.onRequest?.({requestId:k.request_id,baseUrl:a,...k.session_id?{sessionId:k.session_id}:{}})}catch{}let F=qF(k.ws_url,a,W,"gateway allocated session");return{baseUrl:a,sessionId:W,wsUrl:F,endsAt:BF(k.ends_at),response:k}}if(P.status===202||k.status==="pending"||k.status==="queued"||k.queued){if(s=k.request_id||s,!s)throw new Error("[urun] gateway queued session without request_id");if(_(k.effective_max_queue_time_s),e.onAdmission)try{e.onAdmission(Fse(k,s))}catch{}let W=Date.now()-j<Sse;O&&W&&await zh(W$(P,k,r.retryAfterLimitMs));continue}if((P.status===401||P.status===403)&&e.getAccessToken&&k.error_code!=="session_name_not_yours"){let W=n??"";if(d.add(W),h&&(w+=1,w>b))throw new ug(`[urun] session allocation failed at ${a}: authorization refused ${b} consecutive refreshes while the admission wait was extended (last server status: ${o??"none received"}) \u2014 the token provider keeps minting fresh tokens the control plane rejects`,{httpStatus:P.status,code:k.error_code,platformStatus:k.status});let J=await Jn(e,{forceRefresh:!0,reason:"unauthorized"});if(J&&!d.has(J)){i=J;continue}if(J===void 0){let F=await V$(e,a);if(!d.has(F)){i=F;continue}}}let C=J1(k,P.status),D=k.error_code??(P.status===402?"insufficient_credits":void 0),H=O?ug:Cr;throw new H(`[urun] session allocation failed at ${a}: ${C}`,{httpStatus:P.status,code:D,balanceCredits:typeof k.balance_credits=="number"?k.balance_credits:void 0,platformStatus:k.status,retryAfterSeconds:sI(P,k)})}throw dg(a,!!s,o)}function dg(t,e=!1,r){let s=e?ug:Cr;return new s(`[urun] session allocation wait expired at ${t} \u2014 the CLIENT-side wait budget elapsed (last server status: ${r??"none received"}; the gateway reported no failure)`)}function Qn(t,e){let r={"X-Tenant-Id":t.orgId,"X-Auth-Provider":t.authProvider||"default","X-User-Id":"anonymous"};return e&&(r.Authorization=`Bearer ${e}`),r}async function Jn(t,e){return t.getAccessToken?await t.getAccessToken(e)??void 0:t.jwt}function Lse(t){let e=t.priority==="preempt";return{app:t.app,function:t.functionName,gpus:1,idempotency_key:t.idempotencyKey,...t.sessionKey&&!e?{logical_id:t.sessionKey}:{},...t.concurrencyKey&&!e?{concurrency_key:t.concurrencyKey}:{},...t.label&&!t.sessionKey?{label:t.label}:{},...e?{priority:"preempt"}:{},...t.sharedApp?{shared_app:!0}:{}}}async function Y1(t,e,r,s){let n=await Jn(t);if(t.getAccessToken&&!n)throw new Gi(`[urun] ${s} refused: getAccessToken resolved no token (an unauthenticated request is never sent)`,{code:"no_access_token"});let i=Sg(t.baseUrl,t.fallbackUrls),o;for(let a of i){let c=`${Tr(a)}${e}`,d=h=>fetch(c,{method:r.method,headers:r.body!==void 0?{...Qn(t,h),"Content-Type":"application/json"}:Qn(t,h),...r.body!==void 0?{body:JSON.stringify(r.body)}:{},...r.keepalive?{keepalive:!0}:{}}),u;try{if(u=await d(n),(u.status===401||u.status===403)&&t.getAccessToken){let h=await Jn(t,{forceRefresh:!0,reason:"unauthorized"});h&&h!==n&&(u=await d(h))}}catch(h){o=h;continue}let l=await Kh(u);if(!u.ok)throw new Gi(`[urun] ${s} failed: ${J1(l,u.status)}`,{code:l.error_code,httpStatus:u.status});return l}throw new Gi(`[urun] ${s} request failed`,{cause:o})}async function UF(t){let e=new URLSearchParams;t.app&&e.set("app",t.app),t.functionName&&e.set("function",t.functionName),t.includeArchived&&e.set("include_archived","true"),t.limit!==void 0&&e.set("limit",String(t.limit)),t.cursor&&e.set("cursor",t.cursor);let r=e.toString(),s=await Y1(t,`/api/sessions${r?`?${r}`:""}`,{method:"GET"},"session list");if(!Array.isArray(s?.sessions))throw new Gi("[urun] session list returned no `sessions` array \u2014 the control plane and this SDK disagree on the response shape",{code:"invalid_list_response"});return{rows:s.sessions,nextCursor:s.next_cursor??null}}async function tI(t){let e=t.archived?"archive":"unarchive";await Y1(t,`/api/sessions/${encodeURIComponent(t.sessionId)}/${e}`,{method:"POST"},`session ${e}`)}async function MF(t){await eI(t)}async function jF(t){let e=t.name.trim();if(e.length===0)throw new Gi("[urun] session name refused: a name is required (an empty name is not a rename)",{code:"invalid_session_name"});await Y1(t,`/api/sessions/${encodeURIComponent(t.sessionId)}/name`,{method:"POST",body:{name:e,...t.source?{source:t.source}:{}}},"session name")}async function $F(t){let e=Sg(t.baseUrl,t.fallbackUrls),r=null,s=0;for(let n=0;n<Wh;n++){for(let i of e)try{let o={baseUrl:i,app:"",functionName:"",orgId:t.orgId,jwt:t.jwt,getAccessToken:t.getAccessToken,authProvider:t.authProvider,idempotencyKey:""},a=`${Tr(i)}/api/sessions/${encodeURIComponent(t.sessionId)}/viewer-connect`,c=await Jn(o);if(t.getAccessToken&&!c)throw new Cr(`[urun] viewer-connect for ${t.sessionId} refused: getAccessToken resolved no token (an unauthenticated viewer-connect is never sent)`);let d=await fetch(a,{headers:Qn(o,c)});if((d.status===401||d.status===403)&&t.getAccessToken){let h=await Jn(o,{forceRefresh:!0,reason:"unauthorized"});h&&h!==c&&(d=await fetch(a,{headers:Qn(o,h)}))}if(!d.ok){let h=await Kh(d);throw new Cr(`[urun] viewer-connect for ${t.sessionId} failed: `+J1(h,d.status),{httpStatus:d.status,retryAfterSeconds:sI(d,h)})}let u=await Kh(d),l=qF(u.ws_url,i,t.sessionId,"viewer-connect");return DF(),{baseUrl:Tr(i),sessionId:t.sessionId,wsUrl:l,endsAt:BF(u.ends_at),response:u}}catch(o){if(r=o instanceof Error?o:new Error(String(o)),s=OF(s,r),r instanceof Zo)throw r}if(!X1(r))break;if(n+1<Wh){if(!PF())break;await zh(Math.max(_g(n),s-Date.now()))}}throw r??new Error("[urun] viewer-connect failed")}async function FF(t){try{let e=Tr(t.baseUrl),r=await Jn(t);if(t.getAccessToken&&!r)return{status:"unavailable"};let s=await fetch(`${e}/api/sessions/prewake`,{method:"POST",headers:{...Qn(t,r),"Content-Type":"application/json"},body:JSON.stringify({app:t.app,function:t.functionName})});if(s.status===404)return{status:"unknown-app"};if(!s.ok)return{status:"unavailable"};let n=await Kh(s),i={status:n.status==="prebound"?"prebound":"warming"};return typeof n.expires_at=="string"&&(i.expiresAt=n.expires_at),typeof n.warm_capable=="boolean"&&(i.warmCapable=n.warm_capable),i}catch(e){return lg()?E.warn("[urun] prewake failed (advisory, ignored):",e):E.debug?.("[urun] prewake failed (advisory, ignored):",e),{status:"unavailable"}}}async function Kh(t){try{let e=await t.json();return e&&typeof e=="object"?e:{}}catch{return{}}}function J1(t,e){let r=t.error_code,s=t.error_message||t.message||t.error,n=r&&s&&s!==r?`${r}: ${s}`:s||r;return n?`${n} (HTTP ${e})`:`HTTP ${e}`}var Ose=new Set([400,402,409]);function Nse(t){return t instanceof Cr&&t.httpStatus!==void 0&&Ose.has(t.httpStatus)}var Use=new Set(["capture-attested","no-portable-golden","portable-golden-release-mismatch","portable-golden-attestation-invalid"]);function HF(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function zA(t){return typeof t=="string"&&t.trim().length>0}function z$(t){return typeof t=="number"&&Number.isSafeInteger(t)&&t>0}function Mse(t){return typeof t=="number"&&Number.isSafeInteger(t)&&t>=0}function jse(t){if(HF(t)&&!(!zA(t.snapshot_id)||!zA(t.snapshot_compat_key)||!z$(t.artifact_size_bytes)||!z$(t.durable_arena_bytes)||t.volatile_arena_bytes!==0||!Mse(t.uncovered_weight_bytes)))return{snapshotId:t.snapshot_id,snapshotCompatKey:t.snapshot_compat_key,artifactSizeBytes:t.artifact_size_bytes,durableArenaBytes:t.durable_arena_bytes,volatileArenaBytes:0,uncoveredWeightBytes:t.uncovered_weight_bytes}}function $se(t){if(!HF(t)||t.schema!=="urun.runtime.wake.v1"||t.portability!=="portable"&&t.portability!=="none"||t.expected_wake_path!=="portable-golden-restore"&&t.expected_wake_path!=="cold-boot"||typeof t.reason_code!="string"||!Use.has(t.reason_code)||t.expectation_basis!=="snapshot-registry"||t.restore_observation!=="not-observed")return;let e=t.reason_code;if(t.portability==="portable"&&t.expected_wake_path==="portable-golden-restore"&&e==="capture-attested"){let r=jse(t.golden);return r?{schema:"urun.runtime.wake.v1",portability:"portable",expectedWakePath:"portable-golden-restore",reasonCode:e,expectationBasis:"snapshot-registry",restoreObservation:"not-observed",golden:r}:void 0}if(t.portability==="none"&&t.expected_wake_path==="cold-boot"&&e!=="capture-attested"&&t.golden===void 0)return{schema:"urun.runtime.wake.v1",portability:"none",expectedWakePath:"cold-boot",reasonCode:e,expectationBasis:"snapshot-registry",restoreObservation:"not-observed"}}function rI(t){if("serving_region"in t)return typeof t.serving_region=="string"&&t.serving_region.length>0?t.serving_region:null}function Fse(t,e){let r={status:typeof t.status=="string"&&t.status.length>0?t.status:t.queued?"queued":"pending",requestId:e};zA(t.session_id)&&(r.sessionId=t.session_id);let s=rI(t);s!==void 0&&(r.region=s),typeof t.reason=="string"&&t.reason.length>0&&(r.reason=t.reason),typeof t.decision_reason=="string"&&t.decision_reason.length>0&&(r.decisionReason=t.decision_reason),typeof t.provisioning_refusal_source=="string"&&t.provisioning_refusal_source.length>0&&(r.refusalSource=t.provisioning_refusal_source),typeof t.provisioning_refusal_message=="string"&&t.provisioning_refusal_message.length>0&&(r.refusalMessage=t.provisioning_refusal_message),typeof t.queue_position=="number"&&typeof t.queue_depth=="number"&&(r.queue={position:t.queue_position,depth:t.queue_depth});let n=t.runtime_state;if(n==="unavailable"||n==="starting"||n==="busy"){r.runtime={state:n},typeof t.runtime_reason=="string"&&t.runtime_reason.length>0&&(r.runtime.reason=t.runtime_reason);let i=$se(t.runtime_wake);i&&(r.runtime.wake=i)}return r}function sI(t,e){let r=Number(t.headers.get("Retry-After")||""),s=Number(e.retry_after_seconds??r);return Number.isFinite(s)&&s>0?s:void 0}function W$(t,e,r){let s=sI(t,e),n=r??LF;return s!==void 0?Math.min(s*1e3,n):1e3}function zh(t){return new Promise(e=>setTimeout(e,t))}function Hse(t){let e=typeof AbortSignal<"u"?AbortSignal:void 0;return typeof e?.timeout=="function"?e.timeout(t):void 0}var Zo=class extends Error{},ug=class extends Cr{};function qF(t,e,r,s){if(!t)throw new Zo(`[urun] ${s} ${r} without ws_url`);let n,i;try{n=new URL(t)}catch{throw new Zo(s==="viewer-connect"?`[urun] viewer-connect returned no usable ws_url for ${r}`:`[urun] ${s} ${r} with non-absolute ws_url`)}try{i=new URL(Tr(e))}catch{throw new Zo(`[urun] ${s} ${r} has invalid gateway base URL`)}let o=qse(i.hostname)&&i.protocol==="http:";if(!(o&&n.protocol==="ws:"||n.protocol==="wss:"))throw new Zo(`[urun] ${s} ${r} with insecure ws_url`);if(!Vse(n,i,o))throw new Zo(`[urun] ${s} ${r} with cross-origin ws_url`);return n.toString()}function qse(t){return t==="localhost"||t==="127.0.0.1"||t==="::1"||t.endsWith(".localhost")}function Vse(t,e,r){return!!(r||t.hostname===e.hostname&&t.port===e.port||K$(t.hostname)&&K$(e.hostname))}function K$(t){return t==="urun.sh"||t.endsWith(".urun.sh")}function zse(t){try{return new URL(t).hostname!==mse?[]:gse}catch{return[]}}function Wse(t){return`stream:${t}`}var Kse="urun-stream-v1",nI=1,xs={BINARY:0,TEXT:1,JSON:2,END:3,CHUNK:4},Gh=2,G$=253952,Gse=[xs.BINARY,xs.TEXT,xs.JSON],Cl=Symbol("urun:stream:end");function Q1(t){if(t===Cl)return Uint8Array.from([nI,xs.END]);let{kind:e,body:r}=VF(t);return R1(e,r)}function VF(t){return t instanceof Uint8Array?{kind:xs.BINARY,body:t}:t instanceof ArrayBuffer?{kind:xs.BINARY,body:new Uint8Array(t)}:typeof t=="string"?{kind:xs.TEXT,body:new TextEncoder().encode(t)}:{kind:xs.JSON,body:new TextEncoder().encode(JSON.stringify(t))}}function R1(t,e){let r=new Uint8Array(Gh+e.length);return r[0]=nI,r[1]=t,r.set(e,Gh),r}function Xse(t){if(t===Cl)return[Q1(t)];let{kind:e,body:r}=VF(t);if(r.length+Gh<=G$)return[R1(e,r)];let s=G$-Gh,n=[],i=0;for(;r.length-i>s;)n.push(R1(xs.CHUNK,r.subarray(i,i+s))),i+=s;return n.push(R1(e,r.subarray(i))),n}function Z1(t){let{kind:e,body:r}=zF(t);if(e===xs.CHUNK)throw new Error("[urun] CHUNK envelope requires StreamFragmentReassembler (oversized payload)");return P1(e,r)}function zF(t){let e=t instanceof Uint8Array?t:new Uint8Array(t);if(e.length<Gh||e[0]!==nI)throw new Error(`[urun] bad stream envelope (version=${e[0]}, len=${e.length})`);return{kind:e[1],body:e.subarray(Gh)}}function P1(t,e){switch(t){case xs.BINARY:return e.slice();case xs.TEXT:return new TextDecoder().decode(e);case xs.JSON:return JSON.parse(new TextDecoder().decode(e));case xs.END:return Cl;default:throw new Error(`[urun] unknown stream envelope KIND 0x${t.toString(16)}`)}}var Yse=class{_chunks=[];_bufferedLength=0;feed(t){let{kind:e,body:r}=zF(t);if(e===xs.CHUNK){this._chunks.push(r.slice()),this._bufferedLength+=r.length;return}if(Gse.includes(e)){if(this._chunks.length===0)return P1(e,r);let s=new Uint8Array(this._bufferedLength+r.length),n=0;for(let i of this._chunks)s.set(i,n),n+=i.length;return s.set(r,n),this._chunks=[],this._bufferedLength=0,P1(e,s)}if(this._chunks.length>0)throw this._chunks=[],this._bufferedLength=0,new Error(`[urun] stream envelope KIND 0x${e.toString(16)} arrived mid-fragment-sequence; discarding partial payload`);return P1(e,r)}};function WF(t){return{get consumerId(){return t.consumerId},onData(e,r){return t.onStreamData(e,r)},sendData(e,r,s){return t.sendStreamData(e,r,s)}}}var Jse=Av(CF()),Qse=Av(nse(),1),X$="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function Zse(t){let e=globalThis.crypto,r=new Uint8Array(t);if(e?.getRandomValues)return e.getRandomValues(r),r;for(let s=0;s<t;s++)r[s]=Math.floor(Math.random()*256);return r}function ev(t=16){let e=Zse(t),r="";for(let s=0;s<t;s++)r+=X$[e[s]%X$.length];return r}var Y$=[1e3,2e3,4e3,8e3,3e4],J$=5,ene=15e3,Q$={closed:!0,released:!0,releasing:!0,reaped:!0,expired:!0,superseded:!0,cancelled:!0,canceled:!0,max_session_age:!0},tne=15e3,Z$=15e3,eF=15e3,rne=2e3,sne=6e3,nne=2e3,ine=300,tF=4e3,one=2,ane=750,cne=3,rF=[1e3,2e3,4e3],dne=15e3;var Xh="--",lne=["video","audio"];function U1(t){let e=t.lastIndexOf(Xh);if(e<=0)return;let r=t.slice(e+Xh.length);return lne.includes(r)?r:void 0}function KF(t,e){return`${t}${Xh}${e}`}var iI="v1";function une(t,e){return t.name!==e.name||t.reason!==e.reason||t.sessionId!==e.sessionId||t.requestId!==e.requestId||t.wakingSince!==e.wakingSince||t.region!==e.region||(t.endsAt?.getTime()??null)!==(e.endsAt?.getTime()??null)||t.queue?.position!==e.queue?.position||t.queue?.depth!==e.queue?.depth||t.runtime?.state!==e.runtime?.state||t.runtime?.reason!==e.runtime?.reason||t.runtime?.wake!==e.runtime?.wake?!1:t.error?.reason===e.error?.reason&&t.error?.code===e.error?.code&&t.error?.kind===e.error?.kind&&t.error?.httpStatus===e.error?.httpStatus&&t.error?.retryAfterSeconds===e.error?.retryAfterSeconds}var sF={requested:"provisioning",queued:"queued",pending:"provisioning",allocating:"provisioning",provisioning:"provisioning",waking:"provisioning",waiting_for_capacity:"waiting_for_capacity",allocated:"connecting",connecting:"connecting",establishing:"connecting",live:"live",running:"live",paused:"paused",error:"error",failed:"error",rejected:"error",expired:"paused",cancelled:"paused",canceled:"paused",closed:"paused",releasing:"paused",released:"paused",reaped:"paused",superseded:"paused"};function nF(t){return Object.prototype.hasOwnProperty.call(sF,t)?{phase:sF[t],unknown:!1}:{phase:"unknown",unknown:!0}}function hne(t){return t==="queued"||t==="pending"}function iF(t){return t==="credits_exhausted"}var oF=3,aF=4e3,cF=[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun1.l.google.com:19302"}];function dF(t){if(!t)return;let e=/\/(?:ws\/)?rtc\/([^/?#]+)/.exec(t);if(e)try{return decodeURIComponent(e[1])}catch{return e[1]}}var oI=class{_state="disconnected";_sessionId=null;_tracks=new Map;_tracksByName=new Map;_options;_emitter=new Qse.default;_ws=null;_connectedUrl=null;_device=null;_mediaUnavailableReason=null;_mediaVerdictResolve;_mediaVerdict=new Promise(t=>{this._mediaVerdictResolve=t});_recvTransport=null;_pendingConsumeData=[];_sendTransport=null;_consumers=new Map;_audioProducer=null;_videoProducer=null;_publishedAudio=null;_publishedVideo=null;_wtMicUplink=null;_wtCamUplink=null;_wtDataUpSender=null;_pendingProduce=null;_multiplexer=null;_reconnectAttempts=0;_reconnectExhaustedWarned=!1;_intentionalDisconnect=!1;_reconnectTimer=null;_cancelPendingDial=null;_stableResetTimer=null;_generation=0;_lastStartOptions;_resolveConnection=null;_recvIceRestartAttempts=0;_recvIceRestartTimer=null;_sendIceRestartAttempts=0;_sendIceRestartTimer=null;_phase={name:"idle"};_requestId;_liveReached=!1;_lastServerStatus;_endsAt=null;_forceResolveOnNextConnect=!1;_connectStartedAt;_wakingSince;_mediaProbeTimer=null;_statsTimer=null;_statsSampleInFlight=!1;_joinProbes=new Map;_decodeDeathHandled=!1;_selectedCandidatePair=XF();_reportedCandidatePairKey=null;_candidatePairRefreshSeq=0;_diagnosticSinkFailed=!1;_currentEpoch=0;_selfEpochAdoptUntil=0;_pausedIncarnation=null;_consumerId=null;_streamDataHandlers=new Map;_streamDataLane="sctp";_dataProducers=new Map;_dataProducerPromises=new Map;_dataConsumers=new Map;_pendingDataProduce=new Map;_sendTransportWaiters=[];get consumerId(){return this._consumerId===null&&(this._consumerId=fne()),this._consumerId}get state(){return this._state}get currentIncarnation(){return this._currentEpoch}get phase(){return this._phase}get isProducingMedia(){let t=r=>r!==null&&!r.closed&&!r.paused,e=(r,s)=>r!==null&&s!==null&&s.track.readyState!=="ended"&&r.deliveredDatagrams()>0;return t(this._audioProducer)||t(this._videoProducer)||e(this._wtMicUplink,this._publishedAudio)||e(this._wtCamUplink,this._publishedVideo)}get endsAt(){return this._endsAt}setEndsAt(t){this._endsAt=t}seedRegion(t){t!==void 0&&this._setPhase(this._phase.name,{reason:this._phase.reason,queue:this._phase.queue,runtime:this._phase.runtime,error:this._phase.error,region:t})}_pastDeadline(){return this._endsAt!==null&&Date.now()>=this._endsAt.getTime()}get status(){let t={phase:this._phase.name,transportState:this._state};return this._sessionId&&(t.sessionId=this._sessionId),this._requestId&&(t.requestId=this._requestId),this._lastServerStatus!==void 0&&(t.lastServerStatus=this._lastServerStatus),this._connectStartedAt!==void 0&&(t.elapsedMs=Date.now()-this._connectStartedAt),this._endsAt!==null&&(t.endsAt=this._endsAt),this._phase.queue&&(t.queue=this._phase.queue),this._phase.runtime&&(t.runtime=this._phase.runtime),this._phase.wakingSince!==void 0&&(t.wakingSince=this._phase.wakingSince),this._phase.error&&(t.error=this._phase.error),this._phase.region!==void 0&&(t.region=this._phase.region),t}get region(){return this._phase.region}get sessionId(){return this._sessionId}get tracks(){return this._tracks}get multiplexer(){return this._multiplexer}get isOpen(){return this._ws!==null&&this._ws.readyState===WebSocket.OPEN}signalingOpen(){return this.isOpen}onWtOnlyLegDeath(t){return this._wtOnlyLegDeath=t,()=>{this._wtOnlyLegDeath===t&&(this._wtOnlyLegDeath=null)}}_wtOnlyLegDeath=null;get connectedUrl(){return this._connectedUrl}get intentionalDisconnect(){return this._intentionalDisconnect}getTrackByName(t){if(U1(t)!==void 0)return;let e=this._tracksByName.get(t);if(e&&e.readyState!=="ended")return e;for(let r of this._tracks.values())if(!(r.kind!==t||r.readyState==="ended")&&this._streamNameOf(r)===void 0)return r;return e}_streamNameOf(t){for(let[e,r]of this._tracksByName)if(r===t)return e}setAuth(t){this._options={...this._options,...t},this.isOpen&&this._send({type:"auth",orgId:this._options.orgId,jwt:this._options.jwt,authProvider:this._options.authProvider})}constructor(t){this._options=t??{url:""},t?.sessionId&&(this._sessionId=t.sessionId)}setConnection(t){if(this.isOpen){let e=dF(t.url);if(t.sessionId!==void 0&&t.sessionId!==this._sessionId)throw new B1(this._sessionId,t.sessionId);if(e!==void 0&&e!==this._sessionId)throw new B1(this._sessionId,e);this._options={...this._options,...t};return}this._options={...this._options,...t},t.sessionId&&(this._sessionId=t.sessionId)}setConnectionResolver(t){this._resolveConnection=t}applyControlDocState(t){let e=t&&typeof t=="object"?t.session:void 0,r=xne(e);if(r!==void 0&&this.setIncarnation(r),!e||typeof e!="object")return;let s=e,n=typeof s.status=="string"?s.status:void 0;if(n&&!this.isStaleClosedMarker(s)){if(n==="error"){let i=s.error_reason??s.errorReason,o=typeof i=="string"&&i?i:"session failed";this._setPhase("error",{error:{reason:o,code:"runtime-failed",kind:"runtime-failed"}})}else if(n==="closed"||n==="ended"||n==="paused"){let i=s.close_reason??s.closeReason??s.pause_reason??s.pauseReason;if(iF(i)){this._setPhase("paused",{reason:"credits_exhausted"});return}if(this._pastDeadline()){this._setPhase("paused",{reason:"max_session_age"});return}this._setPhase("paused",{reason:typeof i=="string"&&i?i:n})}}}setIncarnation(t){if(!Number.isFinite(t)||t<=this._currentEpoch)return;let e=this._currentEpoch>0,r=this._state==="connected";this._currentEpoch=t;let s=this._selfEpochAdoptUntil>0&&Date.now()<=this._selfEpochAdoptUntil;this._selfEpochAdoptUntil=0,!s&&e&&r&&!this._intentionalDisconnect&&this._renegotiate()}isStaleIncarnation(t){return Number.isFinite(t)?t<this._currentEpoch:!1}isStaleClosedMarker(t){if(!t)return!1;let e=typeof t.status=="string"?t.status:void 0;if(e!=="closed"&&e!=="ended"&&e!=="paused"&&e!=="error")return!1;let r=t.status_epoch??t.statusEpoch,s=typeof r=="number"?r:Number(r);return Number.isFinite(s)?s<this._currentEpoch:!1}_isStaleLivenessEvidence(){return this._phase.name!=="paused"||this._pausedIncarnation===null?!1:this._currentEpoch<=this._pausedIncarnation}async connect(t){if(this.isOpen&&this._state==="connected"&&!this._intentionalDisconnect){t!==void 0&&(this._lastStartOptions=t);return}this._lastStartOptions=t,this._intentionalDisconnect=!1,this._pausedIncarnation=null,this._connectStartedAt??=Date.now(),this._cancelPendingDial?.(new Error("TransportSession: connect superseded by a newer connect()"));let e=++this._generation,r=this._state==="reconnecting"||this._state==="renegotiating";r||this._setState("connecting");let s=null,n=()=>e!==this._generation||this._intentionalDisconnect,i=()=>{if(n())throw new Error("TransportSession: connect cancelled")},o=async()=>{for(let u of this._connectUrls()){i();try{return await this._connectOnce(u,e,t),!0}catch(l){s=l instanceof Error?l:new Error(String(l)),n()||this._cleanupSocket()}}return!1},a=this._forceResolveOnNextConnect&&this._resolveConnection!==null;this._forceResolveOnNextConnect=!1;let c=a?0:this._resolveConnection?one:1;for(let u=0;u<c;u++)if(u>0&&(await lF(ane),i()),await o())return;if(this._resolveConnection)for(let u=0;u<cne;u++){this._setState("reconnecting"),await lF(rF[Math.min(u,rF.length-1)]),i();try{let l=await this._resolveConnection();i(),this.setAuth({jwt:l.jwt??this._options.jwt,authProvider:this._options.authProvider,orgId:this._options.orgId}),this.setConnection({url:l.url,sessionId:l.sessionId,iceServers:l.iceServers??this._options.iceServers}),l.endsAt!==void 0&&(this._endsAt=l.endsAt)}catch(l){if(n())throw new Error("TransportSession: connect cancelled");s=l instanceof Error?l:new Error(String(l));continue}if(await o())return}if(n())throw s??new Error("TransportSession: connect cancelled");this._setState("failed");let d=s??new Error("TransportSession: connect failed");throw r||this._emitError(d),d}leaveLeg(){if(!this.isOpen)return!1;this._intentionalDisconnect=!0,this._selfEpochAdoptUntil=0,this._stopMediaProbe(),this._stopStatsSampler(),this._clearRecvIceRestart(),this._clearSendIceRestart(),this._reconnectTimer&&(clearTimeout(this._reconnectTimer),this._reconnectTimer=null);try{this._send({type:"leave"})}catch{}try{this._ws?.close()}catch{}return!0}disconnect(t="client_detached"){this._generation+=1,this._intentionalDisconnect=!0,this._selfEpochAdoptUntil=0,this._cancelPendingDial?.(new Error("TransportSession: connect cancelled by disconnect()")),this._stopMediaProbe(),this._stopStatsSampler(),this._reconnectTimer&&(clearTimeout(this._reconnectTimer),this._reconnectTimer=null),this._clearReconnectBudgetReset(),this._reconnectAttempts=0;try{this._publishedAudio?.track.stop()}catch{}try{this._publishedVideo?.track.stop()}catch{}if(this._publishedAudio=null,this._publishedVideo=null,this._audioProducer){this._send({type:"stopAudio"});try{this._audioProducer.track?.stop()}catch{}try{this._audioProducer.close()}catch{}this._audioProducer=null}if(this._videoProducer){this._send({type:"stopVideo"});try{this._videoProducer.track?.stop()}catch{}try{this._videoProducer.close()}catch{}this._videoProducer=null}for(let e of this._consumers.values())try{e.close()}catch{}if(this._consumers.clear(),this._cleanupDataChannels(),this._settleSendTransportWaiters(null,new Error("[urun] sendStreamData: transport disconnected before the send transport arrived")),this._sendTransport){try{this._sendTransport.close()}catch{}this._sendTransport=null}if(this._recvTransport){try{this._recvTransport.close()}catch{}this._recvTransport=null}this._pendingConsumeData=[],this._pendingProduce&&(clearTimeout(this._pendingProduce.timeoutId),this._pendingProduce.reject(new Error("TransportSession: disconnected")),this._pendingProduce=null),this._device=null,this._multiplexer&&(this._multiplexer.dispose(),this._multiplexer=null),this._cleanupSocket(),this._tracks.clear(),this._tracksByName.clear(),this._setState("disconnected"),this._liveReached=!1,this._setPhase("paused",{reason:t}),this._emitter.emit("disconnected")}on(t,e){return this._emitter.on(t,e),()=>{this._emitter.off(t,e)}}_emitDiagnostic(t){let e=this._options.diagnosticSink;if(e)try{e(t)}catch(r){this._diagnosticSinkFailed||(this._diagnosticSinkFailed=!0,E.warn(`[urun] diagnosticSink threw (${String(r instanceof Error?r.message:r)}) \u2014 further diagnostics ride only the structured 'diagnostic' event`))}else t.level==="debug"?lg()?E.warn(`[urun] ${t.message}`,t.detail??{}):E.debug(`[urun] ${t.message}`,t.detail??{}):t.level==="error"?E.error(`[urun] ${t.message}`,t.detail??{}):E.warn(`[urun] ${t.message}`,t.detail??{});this._emitter.emit("diagnostic",t)}sendInput(t,e){this._send({type:"input",data:t,sequence:e})}sendSignal(t){return this._send(t)}onSignal(t){return this.on("signal",t)}emitDiagnostic(t){this._emitDiagnostic(t)}onStreamData(t,e){let r=this._streamDataHandlers.get(t);return r||(r=new Set,this._streamDataHandlers.set(t,r)),r.add(e),()=>{let s=this._streamDataHandlers.get(t);s?.delete(e),s&&s.size===0&&this._streamDataHandlers.delete(t)}}sendStreamData(t,e,r){try{this._requireMediaSupport("sendStreamData")}catch(s){return Promise.reject(s)}return this._wtDataUpSender?this._wtDataUpSender.send(t,Q1(e)):this._ensureDataProducer(t).then(s=>{for(let n of Xse(e))s.send(n)})}get wtDataUplinkSeam(){return{onUplink:t=>{this._wtDataUpSender=t},onUplinkLost:(t,e)=>{if(this._wtDataUpSender&&!(e&&this._wtDataUpSender!==e)){if(this._wtDataUpSender=null,!this._sendTransport){E.warn(`[urun-sh/core] WT data uplink lost (${t}) with NO WebRTC send transport \u2014 there is no SCTP to revert to; failing the WT leg so the re-dial ladder re-establishes it`),this._wtOnlyLegDeath?.(t);return}E.warn(`[urun-sh/core] WT data uplink lost (${t}) \u2014 data-up reverts to SCTP for this leg`)}}}}_awaitSendTransport(){return this._sendTransport?Promise.resolve(this._sendTransport):new Promise((t,e)=>{let r={resolve:n=>{clearTimeout(s),t(n)},reject:n=>{clearTimeout(s),e(n)}},s=setTimeout(()=>{let n=this._sendTransportWaiters.indexOf(r);n>=0&&this._sendTransportWaiters.splice(n,1),e(new Error(`[urun] no send transport after ${Z$}ms (the server never offered createSendTransport \u2014 media/data produce is impossible on this leg)`))},Z$);this._sendTransportWaiters.push(r)})}_settleSendTransportWaiters(t,e){let r=this._sendTransportWaiters;this._sendTransportWaiters=[];for(let s of r)t?s.resolve(t):s.reject(e??new Error("TransportSession: disconnected"))}_ensureDataProducer(t){let e=this._dataProducers.get(t);if(e&&!e.closed)return Promise.resolve(e);let r=this._dataProducerPromises.get(t);if(r)return r;let s=this._awaitSendTransport().then(n=>n.produceData({label:Wse(t),protocol:Kse,ordered:!0})).then(n=>this._awaitDataChannelOpen(n)).then(n=>(this._dataProducers.set(t,n),this._dataProducerPromises.delete(t),n)).catch(n=>{throw this._dataProducerPromises.delete(t),n});return this._dataProducerPromises.set(t,s),s}_awaitDataChannelOpen(t){if(t.closed)return Promise.reject(new Error("[urun] sendStreamData: DataProducer closed before its DataChannel opened"));let e=t.readyState;return e==="open"?Promise.resolve(t):e==="closing"||e==="closed"?Promise.reject(new Error(`[urun] sendStreamData: DataChannel is ${e} \u2014 cannot deliver data-up payloads`)):new Promise((r,s)=>{let n=()=>{c(),r(t)},i=u=>{d(new Error(`[urun] sendStreamData: DataChannel error before open: ${u.message}`))},o=()=>{c(),s(new Error("[urun] sendStreamData: DataProducer closed before its DataChannel opened"))},a=setTimeout(()=>{d(new Error(`[urun] sendStreamData: DataChannel not open after ${eF}ms (the SCTP handshake never completed \u2014 data-up produce is impossible on this channel)`))},eF),c=()=>{clearTimeout(a),t.off("open",n),t.off("error",i),t.observer.off("close",o)},d=u=>{c();try{t.close()}catch{}s(u)};t.on("open",n),t.on("error",i),t.observer.on("close",o)})}_dispatchStreamData(t,e){for(let r of this._streamDataHandlers.get(t)??[])r(e)}markStreamDataLaneQuic(){this._streamDataLane="quic"}noteQuicMediaFlowing(){this._intentionalDisconnect||this._phase.name==="error"&&this._isParkedPhase()||this._isStaleLivenessEvidence()||this._liveReached||this._setPhase("live")}dispatchQuicStreamData(t,e){this._dispatchStreamData(t,e)}raiseQuicStreamDataError(t){E.error(t.message),this._emitter.emit("error",t)}quicStreamDataLaneLost(t){if(this._streamDataLane!=="quic")return;this._streamDataLane="sctp";let e=[...this._streamDataHandlers.keys()];if(e.length===0)return;let r=new Error(`[urun] QUIC data lane lost mid-stream (${t}) \u2014 active named streams [${e.join(", ")}] resume over SCTP on the failover leg from now; envelopes in flight on the dead lane are gone (mid-stream-join semantics)`);E.error(r.message),this._emitter.emit("error",r)}_streamNameFromLabel(t){if(t)return t.startsWith("stream:")?t.slice(7):void 0}mediaUnavailableReason(){return this._mediaUnavailableReason}mediaAvailability(){return this._mediaVerdict}_requireMediaSupport(t){if(this._mediaUnavailableReason)throw new Error(`[urun-sh/core] ${t}: realtime media is unavailable in this process \u2014 ${this._mediaUnavailableReason}. This session joined in doc/KV-only mode (the media device was skipped); install the optional "werift" dependency to enable realtime media.`)}async addTrack(t,e){this._requireMediaSupport("addTrack"),await this._publishTrack(t,e)}async _publishTrack(t,e){let r=t.kind==="video";if(!r&&this._wtMicUplink){this._rememberPublishIntent(!1,t,e),this._wtMicUplink.setSource(t);return}if(r&&this._wtCamUplink){this._rememberPublishIntent(!0,t,e),this._wtCamUplink.setSource(t);return}let s=r?this._videoProducer:this._audioProducer;if(s&&!s.closed){if(s.track===t)return;await s.replaceTrack({track:t}),this._rememberPublishIntent(r,t,e);return}let n=await(await this._awaitSendTransport()).produce({track:t,...r?{}:{codecOptions:{opusStereo:!1,opusDtx:!1,opusFec:!1}},stopTracks:!1,...e?{appData:{name:e}}:{}});r?this._videoProducer=n:this._audioProducer=n,this._rememberPublishIntent(r,t,e)}_rememberPublishIntent(t,e,r){let s={track:e,...r!==void 0?{name:r}:{}};t?this._publishedVideo=s:this._publishedAudio=s}removeTrack(){let t=this._publishedAudio;if(this._publishedAudio=null,this._wtMicUplink){this._wtMicUplink.setSource(null);try{t?.track.stop()}catch{}}if(this._audioProducer){this._send({type:"stopAudio"});try{this._audioProducer.track?.stop()}catch{}this._audioProducer.close(),this._audioProducer=null}}async addVideoTrack(t,e){this._requireMediaSupport("addVideoTrack"),await this._publishTrack(t,e)}stopVideo(){let t=this._publishedVideo;if(this._publishedVideo=null,this._wtCamUplink){this._wtCamUplink.setSource(null);try{t?.track.stop()}catch{}}if(this._videoProducer){this._send({type:"stopVideo"});try{this._videoProducer.track?.stop()}catch{}this._videoProducer.close(),this._videoProducer=null}}requestDiagnostics(){this._send({type:"diagnostics"})}seekStream(t,e){this._send({type:"stream.seek",stream:t,target:e})}async _handleMessage(t){switch(t.type){case"routerRtpCapabilities":await this._onRouterCapabilities(t.rtpCapabilities);break;case"createWebRtcTransport":await this._onCreateRecvTransport(t);break;case"createSendTransport":await this._onCreateSendTransport(t);break;case"consume":await this._onConsume(t);break;case"consumerClosed":this._closeConsumer(t.consumerId);break;case"producerClosed":this._closeConsumersByProducer(t.producerId);break;case"consumerPaused":this._consumers.get(t.consumerId)?.pause();break;case"consumerResumed":this._consumers.get(t.consumerId)?.resume();break;case"iceRestarted":this._onIceRestarted(t);break;case"produced":if(this._pendingProduce){let e=this._pendingProduce;this._pendingProduce=null,clearTimeout(e.timeoutId),e.resolve(t.id)}break;case"dataProduced":{let e=t.label,r=e?this._pendingDataProduce.get(e):void 0;r&&e&&(this._pendingDataProduce.delete(e),r.resolve(t.id));break}case"consumeData":await this._onConsumeData(t);break;case"started":this._emitter.emit("started");break;case"status":this._onStatus(t);break;case"stream.seeked":this._onStreamSeeked(t);break;case"error":this._onServerError(t);break;default:this._emitter.emit("signal",t);break}}_onServerError(t){let e=typeof t.message=="string"?t.message:"signaling error",r=typeof t.code=="string"?t.code:void 0;if(/connect\(\) already called/i.test(e)){if(this._resolveConnection){this._generation++;let s=this._ws;this._ws=null;try{s?.close()}catch{}this._cleanupMedia(),this._forceResolveOnNextConnect=!0,this._renegotiate();return}this._setPhase("error",{error:{reason:e,code:"transport-consumed",kind:"transport-failed"}}),this._emitter.emit("error",new Error(e));return}if(r==="TRANSPORT_BIND_FAILED"){this._emitError(new Error(e),r);return}if(r==="PROTOCOL_VERSION_UNSUPPORTED"){this._setPhase("error",{error:{reason:e,code:r,kind:"create-failed"},reason:e}),this._emitter.emit("error",new Error(e));return}E.warn("[urun] signaling error from server:",e)}_onStreamSeeked(t){let e=typeof t.stream=="string"?t.stream:void 0;if(!e)return;let r=t.target,s=r==="live"?"live":typeof r=="number"?r:Number(r);this._emitter.emit("seeked",e,s)}_reportUnknownServerStatus(t,e,r="signaling",s){let n=`server reported unrecognized ${r==="admission"?"admission response":"session status"} status ${JSON.stringify(t)}`+(e?` (reason: ${JSON.stringify(e)})`:"")+' \u2014 this @urun-sh/core build does not know this word; refusing to render it as "provisioning". The SDK may be out of date for this server.';this._emitDiagnostic({level:"error",kind:"unknown-server-status",message:n,detail:{status:t,origin:r,...e?{reason:e}:{}}}),!this._liveReached&&(this._lastServerStatus=t,this._setPhase("unknown",{reason:t,region:s}))}_onStatus(t){let e=t.request_id??t.requestId;e&&(this._requestId=e);let r=typeof t.status=="string"?t.status:void 0,s=typeof t.reason=="string"&&t.reason?t.reason:void 0,n="region"in t?typeof t.region=="string"&&t.region.length>0?t.region:null:void 0,i=r!==void 0?nF(r):void 0;if(r!==void 0&&i?.unknown){this._reportUnknownServerStatus(r,s,"signaling",n);return}let o=i?.phase??"provisioning";if(this._liveReached&&o!=="paused"&&o!=="error"){o==="live"&&n!==void 0&&n!==this._phase.region&&this._setPhase("live",{reason:s,region:n});return}if(this._isStaleLivenessEvidence()&&o!=="live"&&o!=="paused"&&o!=="error")return;r!==void 0&&(this._lastServerStatus=r);let a=t.queue_position??t.queuePosition,c=t.queue_depth??t.queueDepth,d=typeof a=="number"&&typeof c=="number";if(o==="paused"){let u=t.reason??t.close_reason??t.closeReason??t.pause_reason??t.pauseReason,l=typeof u=="string"&&u?u:void 0,h=iF(u)?"credits_exhausted":this._pastDeadline()?"max_session_age":s??l??r??"paused";this._setPhase("paused",{reason:h,region:n??null}),this._stopMediaProbe();return}if(o==="error"){let u=s??r??"admission failed";this._setPhase("error",{error:{reason:u,code:r,kind:r==="error"?"runtime-failed":"create-failed"},reason:u,region:n});return}if(o==="queued"){this._setPhase("queued",{...d?{queue:{position:a,depth:c}}:{},reason:s,region:n});return}if(o==="waiting_for_capacity"){this._setPhase("waiting_for_capacity",{...d?{queue:{position:a,depth:c}}:{},reason:s,region:n});return}if(o==="connecting"){this._setPhase("connecting",{reason:s,region:n});return}if(o==="live"){this._setPhase("live",{reason:s,region:n});return}this._setPhase("provisioning",{reason:s,region:n})}_webRtcDialHeld=!1;_heldRouterCaps=null;holdWebRtcDial(){return this._webRtcDialHeld=!0,{proceed:t=>{if(!this._webRtcDialHeld)return;this._webRtcDialHeld=!1;let e=this._heldRouterCaps;this._heldRouterCaps=null,e&&(lg()?E.warn(`[urun-sh/core] running the deferred WebRTC dial (${t})`):E.info(`[urun-sh/core] running the deferred WebRTC dial (${t})`),this._onRouterCapabilities(e).catch(r=>{E.error("[urun-sh/core] deferred WebRTC dial failed:",r)}))},skip:t=>{lg()?E.warn(`[urun-sh/core] WebRTC dial SKIPPED (${t}) \u2014 WT-only leg, no RTCPeerConnection`):E.info(`[urun-sh/core] WebRTC dial SKIPPED (${t}) \u2014 WT-only leg, no RTCPeerConnection`)}}}async _onRouterCapabilities(t){if(this._webRtcDialHeld){this._heldRouterCaps=t;return}Qh()&&await K1();let e=lse();if(e){this._mediaUnavailableReason=e,this._mediaVerdictResolve(e);return}this._mediaVerdictResolve(null);let r=cse(),s=new Jse.Device(r?{handlerName:r}:void 0);await s.load({routerRtpCapabilities:t}),this._device=s,this._send({type:"rtpCapabilities",rtpCapabilities:s.rtpCapabilities})}async _onCreateRecvTransport(t){this._device&&this._buildRecvTransport(t)}_buildRecvTransport(t){if(!this._device)return;let e=t.iceCandidates,r=this._device.createRecvTransport({id:t.id,iceParameters:t.iceParameters,iceCandidates:e,dtlsParameters:t.dtlsParameters,...t.sctpParameters?{sctpParameters:t.sctpParameters}:{},iceServers:this._options.iceServers??cF});this._recvIceRestartAttempts=0,this._clearRecvIceRestart();let s=this._generation;r.on("connect",({dtlsParameters:i},o,a)=>{try{this._send({type:"connectTransport",transportId:r.id,dtlsParameters:i}),o()}catch(c){a(c)}}),r.on("connectionstatechange",i=>{if(s===this._generation){if(i==="connected"){this._clearRecvIceRestart(),this._recvIceRestartAttempts=0,this._reportSelectedCandidatePair(r);return}if(!(this._intentionalDisconnect&&i==="closed")&&(i==="failed"||i==="disconnected")){if(this._tryRestartRecvIce())return;i==="failed"&&this._emitError(new Error(`media transport ${i}`),i),this._renegotiate()}}}),this._recvTransport=r;let n=this._pendingConsumeData.splice(0,this._pendingConsumeData.length);for(let i of n)this._onConsumeData(i).catch(()=>{})}async _reportSelectedCandidatePair(t){let e=++this._candidatePairRefreshSeq,r=null;if(typeof t.getStats=="function")try{r=await t.getStats()}catch{}if(this._recvTransport!==t||e!==this._candidatePairRefreshSeq)return;let s=bne(r);if(s.localType===null&&s.remoteType===null&&s.protocol===null&&s.remoteAddress===null&&s.remotePort===null&&this._reportedCandidatePairKey!==null)return;this._selectedCandidatePair=s;let n=JSON.stringify(s);if(this._reportedCandidatePairKey===n)return;this._reportedCandidatePairKey=n;let i=Object.values(this._selectedCandidatePair).some(o=>o!==null);this._emitDiagnostic({level:i?"info":"debug",kind:"ice-candidate-pair",message:`selected ICE candidate pair: local=${this._selectedCandidatePair.localType??"unknown"} remote=${this._selectedCandidatePair.remoteType??"unknown"} protocol=${this._selectedCandidatePair.protocol??"unknown"} remote=${this._selectedCandidatePair.remoteAddress??"unknown"}:${this._selectedCandidatePair.remotePort??"unknown"}`,detail:{sessionId:this._options.sessionId,...this._selectedCandidatePair}})}_tryRestartRecvIce(){let t=this._recvTransport;return!t||t.closed?!1:this._recvIceRestartTimer?!0:this._recvIceRestartAttempts>=oF?!1:(this._recvIceRestartAttempts++,this._armRecvIceRestartWatchdog(),this._requestIceRestart(t.id),!0)}_trySendIceRestart(){let t=this._sendTransport;return!t||t.closed?!1:this._sendIceRestartTimer?!0:this._sendIceRestartAttempts>=oF?!1:(this._sendIceRestartAttempts++,this._armSendIceRestartWatchdog(),this._requestIceRestart(t.id),!0)}_requestIceRestart(t){this._send({type:"restartIce",transportId:t})}_onIceRestarted(t){let e=t.transportId??t.id,r=t.iceParameters;if(!r)return;let s=!!this._recvTransport&&this._recvTransport.id===e,n=!s&&!!this._sendTransport&&this._sendTransport.id===e,i=s?this._recvTransport:n?this._sendTransport:null;i&&(Promise.resolve(i.restartIce({iceParameters:r})).catch(o=>{this._emitter.emit("error",o instanceof Error?o:new Error(String(o)))}),s&&this._recvIceRestartTimer?this._armRecvIceRestartWatchdog():n&&this._sendIceRestartTimer&&this._armSendIceRestartWatchdog())}_armRecvIceRestartWatchdog(){this._clearRecvIceRestart();let t=this._generation;this._recvIceRestartTimer=setTimeout(()=>{this._recvIceRestartTimer=null,!(t!==this._generation||this._intentionalDisconnect)&&this._recvTransport?.connectionState!=="connected"&&(this._emitError(new Error("media transport failed (ice restart timeout)"),"failed"),this._renegotiate())},aF)}_armSendIceRestartWatchdog(){this._clearSendIceRestart();let t=this._generation;this._sendIceRestartTimer=setTimeout(()=>{this._sendIceRestartTimer=null,!(t!==this._generation||this._intentionalDisconnect)&&this._sendTransport?.connectionState!=="connected"&&this._emitError(new Error("media send transport failed (ice restart timeout)"),"failed")},aF)}_clearRecvIceRestart(){this._recvIceRestartTimer&&(clearTimeout(this._recvIceRestartTimer),this._recvIceRestartTimer=null)}_clearSendIceRestart(){this._sendIceRestartTimer&&(clearTimeout(this._sendIceRestartTimer),this._sendIceRestartTimer=null)}async _onCreateSendTransport(t){if(!this._device)return;let e=this._device.createSendTransport({id:t.id,iceParameters:t.iceParameters,iceCandidates:t.iceCandidates,dtlsParameters:t.dtlsParameters,...t.sctpParameters?{sctpParameters:t.sctpParameters}:{},iceServers:this._options.iceServers??cF});this._sendIceRestartAttempts=0,this._clearSendIceRestart();let r=this._generation;e.on("connect",({dtlsParameters:s},n,i)=>{try{this._send({type:"connectSendTransport",transportId:e.id,dtlsParameters:s}),n()}catch(o){i(o)}}),e.on("produce",({kind:s,rtpParameters:n,appData:i},o,a)=>{if(this._pendingProduce){a(new Error("produce already pending"));return}let c=i&&typeof i.name=="string"?i.name:void 0,d=setTimeout(()=>{let u=this._pendingProduce;if(!u||u.timeoutId!==d)return;this._pendingProduce=null;let l=new JA(s,{stream:c,timeoutMs:fg});this._setPhase("error",{error:{reason:l.message,code:"produce-ack-timeout",kind:"produce-timeout"}}),this._emitter.emit("error",l),u.reject(l)},fg);this._pendingProduce={timeoutId:d,resolve:u=>{o({id:u})},reject:a};try{this._send(c?{type:"produce",kind:s,name:c,rtpParameters:n}:{type:"produce",kind:s,rtpParameters:n})}catch(u){this._pendingProduce?.timeoutId===d&&(this._pendingProduce=null,clearTimeout(d)),a(u)}}),e.on("producedata",({sctpStreamParameters:s,label:n,protocol:i},o,a)=>{try{n&&this._pendingDataProduce.set(n,{resolve:c=>o({id:c}),reject:a}),this._send({type:"produceData",sctpStreamParameters:s,label:n,protocol:i})}catch(c){n&&this._pendingDataProduce.delete(n),a(c)}}),e.on("connectionstatechange",s=>{if(r===this._generation){if(s==="connected"){this._clearSendIceRestart(),this._sendIceRestartAttempts=0;return}this._intentionalDisconnect&&s==="closed"||(s==="failed"||s==="disconnected")&&this._trySendIceRestart()||(s==="failed"||s==="closed")&&this._emitError(new Error(`media send transport ${s}`),s)}}),this._sendTransport=e,this._settleSendTransportWaiters(e),this._emitter.emit("audioTransportReady"),this._republishPublishedTracks()}async _republishPublishedTracks(){let t=this._publishedAudio;if(t&&t.track.readyState!=="ended"&&(!this._audioProducer||this._audioProducer.closed))try{await this.addTrack(t.track,t.name)}catch(r){E.warn("[urun] republish: mic re-produce after reconnect failed",r)}else t&&t.track.readyState==="ended"&&E.warn("[urun] republish: published mic track is ended \u2014 not republishing (device re-acquisition is the app/page-recovery pass)");let e=this._publishedVideo;if(e&&e.track.readyState!=="ended"&&(!this._videoProducer||this._videoProducer.closed))try{await this.addVideoTrack(e.track,e.name)}catch(r){E.warn("[urun] republish: camera re-produce after reconnect failed",r)}else e&&e.track.readyState==="ended"&&E.warn("[urun] republish: published camera track is ended \u2014 not republishing (device re-acquisition is the app/page-recovery pass)")}async _onConsumeData(t){if(this._streamDataLane==="quic"){this.raiseQuicStreamDataError(new Error(`[urun] consumeData (label=${String(t.label)}) pushed on a leg whose data lane is QUIC \u2014 refusing (one canonical data path per leg, contract urun-infra#1605)`));return}let e=this._recvTransport;if(!e){this._pendingConsumeData.push(t);return}let r=t.label,s=this._streamNameFromLabel(r);if(!s){E.error(`[urun] consumeData pushed with an unparseable label ${JSON.stringify(r??null)} \u2014 no DataConsumer will be attached and no ack sent; the server egress will strand envelopes for this stream (expected label form: "stream:<name>")`),this._emitter.emit("error",new Error(`[urun] consumeData pushed with unparseable label ${JSON.stringify(r??null)}`));return}let n=this._generation,i;try{i=await e.consumeData({id:t.id,dataProducerId:t.dataProducerId,sctpStreamParameters:t.sctpStreamParameters,label:r,protocol:t.protocol})}catch(u){E.error(`[urun] consumeData for named stream "${s}" failed \u2014 no channel will open and no dataConsumerReady ack will be sent; the server egress will strand envelopes on this lane:`,u),this._emitter.emit("error",u instanceof Error?u:new Error(String(u)));return}if(n!==this._generation||this._recvTransport!==e||e.closed||this._intentionalDisconnect){try{i.close()}catch{}return}this._dataConsumers.set(s,i);let o=new Yse;i.on("message",u=>{try{let l=typeof u=="string"?new TextEncoder().encode(u):new Uint8Array(u),h=o.feed(l);h!==void 0&&this._dispatchStreamData(s,h)}catch(l){this._emitter.emit("error",l instanceof Error?l:new Error(String(l)))}});let a=!1,c=setTimeout(()=>{if(a||i.closed||i.readyState==="open")return;let u=new Error(`[urun] data channel for named stream "${s}" did not open within 10s (consumeData resolved at creation; the SCTP association never established) \u2014 no dataConsumerReady ack was sent and the server egress will strand envelopes on this lane`);E.error(u.message),this._emitter.emit("error",u)},1e4),d=()=>{a||i.closed||(a=!0,clearTimeout(c),this._send({type:"dataConsumerReady",id:t.id}))};i.readyState==="open"?d():i.on("open",d),i.once?.("close",()=>clearTimeout(c))}async _onConsume(t){let e=this._recvTransport;if(!e)return;let r=this._generation,s=await e.consume({id:t.id,producerId:t.producerId,kind:t.kind,rtpParameters:t.rtpParameters});if(r!==this._generation||this._recvTransport!==e||e.closed||this._intentionalDisconnect){try{s.close()}catch{}return}this._consumers.set(s.id,s),this._tracks.set(s.track.id,s.track),this._capJitterBuffer(s,s.kind==="video"?"video":"audio");let n=t.streamName??t.label;n&&this._tracksByName.set(n,s.track),s.track.addEventListener?.("unmute",()=>{r!==this._generation||this._intentionalDisconnect||this._phase.name==="error"&&this._isParkedPhase()||this._isStaleLivenessEvidence()||this._liveReached||this._setPhase("live")},{once:!0}),this._emitter.emit("track",s.track);let i=s.id;s.track.addEventListener("ended",()=>{r!==this._generation||this._intentionalDisconnect||this._closeConsumer(i)},{once:!0}),this._send({type:"resumeConsumer",consumerId:s.id}),this._startMediaProbe(),this._startStatsSampler()}get audioPlayoutOptions(){return this._options.audioPlayout}get wtMicUplinkSeam(){return{onUplink:t=>{this._wtMicUplink=t;let e=this._publishedAudio;if(this._audioProducer&&!this._audioProducer.closed){E.warn("[urun-sh/core] WT mic uplink engaged \u2014 moving the mic from WebRTC produce to the QUIC lane"),this._send({type:"stopAudio"});try{this._audioProducer.close()}catch{}this._audioProducer=null}e&&e.track.readyState!=="ended"&&t.setSource(e.track)},onUplinkLost:(t,e)=>{if(!this._wtMicUplink||e&&this._wtMicUplink!==e)return;this._wtMicUplink=null;let r=this._publishedAudio;if(!(!r||r.track.readyState==="ended")){if(E.warn(`[urun-sh/core] WT mic uplink lost (${t}) \u2014 republishing the mic over WebRTC`),!this._sendTransport){this._emitDiagnostic({level:"error",kind:"wt-mic-uplink-dead",message:`WT mic uplink lost (${t}) with NO WebRTC send transport \u2014 the republish above cannot run. If a reconnect is in flight this self-heals; on a WT-only leg (no RTCPeerConnection was dialled) the mic is now DEAD until the WT uplink re-engages.`,detail:{reason:t}});return}this._publishTrack(r.track,r.name).catch(s=>{E.error("[urun-sh/core] mic republish over WebRTC failed:",s)})}}}}get wtCamUplinkSeam(){return{onUplink:t=>{this._wtCamUplink=t;let e=this._publishedVideo;if(this._videoProducer&&!this._videoProducer.closed){E.warn("[urun-sh/core] WT video uplink engaged \u2014 moving the camera from WebRTC produce to the QUIC lane"),this._send({type:"stopVideo"});try{this._videoProducer.close()}catch{}this._videoProducer=null}e&&e.track.readyState!=="ended"&&t.setSource(e.track)},onUplinkLost:(t,e)=>{if(!this._wtCamUplink||e&&this._wtCamUplink!==e)return;this._wtCamUplink=null;let r=this._publishedVideo;if(!(!r||r.track.readyState==="ended")){if(E.warn(`[urun-sh/core] WT video uplink lost (${t}) \u2014 republishing the camera over WebRTC`),!this._sendTransport){this._emitDiagnostic({level:"error",kind:"wt-cam-uplink-dead",message:`WT camera uplink lost (${t}) with NO WebRTC send transport \u2014 the republish above cannot run. If a reconnect is in flight this self-heals; on a WT-only leg (no RTCPeerConnection was dialled) the camera is now DEAD until the WT uplink re-engages.`,detail:{reason:t}});return}this._publishTrack(r.track,r.name).catch(s=>{E.error("[urun-sh/core] camera republish over WebRTC failed:",s)})}}}}_jitterBufferTargetMs(t){if(t==="audio"){let e=this._options.audioPlayout?.jitterBufferTargetMs;return e===void 0?ine:e}return this._options.videoPlayout?.jitterBufferTargetMs}_capJitterBuffer(t,e){let r=this._jitterBufferTargetMs(e);if(r===void 0)return;let s=e==="video"?"videoPlayout":"audioPlayout",n={mediaKind:e,transportId:this._recvTransport?.id??null};if(!Number.isFinite(r)){this._emitDiagnostic({level:"warning",kind:`${e}-jitter-buffer-invalid`,message:`${s}.jitterBufferTargetMs must be a finite number of milliseconds; got ${String(r)}. No jitter-buffer cap applied.`,detail:{consumerId:t.id,targetMs:String(r),...n}});return}if(r<=0)return;if(r>tF){this._emitDiagnostic({level:"warning",kind:`${e}-jitter-buffer-invalid`,message:`${s}.jitterBufferTargetMs must be within the W3C jitterBufferTarget range 0-${tF}ms; got ${r}. No jitter-buffer cap applied.`,detail:{consumerId:t.id,targetMs:r,...n}});return}let i=t.rtpReceiver;if(!i){this._emitDiagnostic({level:"debug",kind:`${e}-jitter-buffer-unsupported`,message:`${e} consumer exposes no RTCRtpReceiver (node/werift leg); no jitter-buffer cap applied.`,detail:{consumerId:t.id,targetMs:r,reason:"no-receiver",...n}});return}let o=[];if("jitterBufferTarget"in i&&(i.jitterBufferTarget=r,o.push("jitterBufferTarget")),"playoutDelayHint"in i&&(i.playoutDelayHint=r/1e3,o.push("playoutDelayHint")),o.length===0){this._emitDiagnostic({level:"debug",kind:`${e}-jitter-buffer-unsupported`,message:`${e==="audio"?"Audio":"Video"} receiver exposes neither jitterBufferTarget nor playoutDelayHint; standing ${e} playout delay is unbounded on this engine.`,detail:{consumerId:t.id,targetMs:r,...n}});return}this._emitDiagnostic({level:"debug",kind:`${e}-jitter-buffer-capped`,message:`${e==="audio"?"Audio":"Video"} receiver jitter buffer capped at ${r}ms.`,detail:{consumerId:t.id,targetMs:r,applied:o,...n}})}_closeConsumer(t){let e=this._consumers.get(t);if(!e)return;this._consumers.delete(t);let r=e.track;try{e.close()}catch{}if(r){this._tracks.delete(r.id);for(let[s,n]of this._tracksByName)n===r&&this._tracksByName.delete(s)}}_closeConsumersByProducer(t){for(let[e,r]of this._consumers)r.producerId===t&&this._closeConsumer(e)}_mediaPollMs(){let t=this._options.mediaLiveness?.pollMs;return t===void 0?rne:t}_firstFrameWindowMs(){let t=this._options.mediaLiveness?.stallTimeoutMs;return t===void 0?sne:t}_startMediaProbe(){let t=this._mediaPollMs();if(t<=0||this._mediaProbeTimer)return;let e=this._generation;this._mediaProbeTimer=setInterval(()=>{e!==this._generation||this._intentionalDisconnect||this._phase.name==="error"&&this._isParkedPhase()||this._isStaleLivenessEvidence()||this._sampleMediaArrival(e)},t)}_stopMediaProbe(){this._mediaProbeTimer&&(clearInterval(this._mediaProbeTimer),this._mediaProbeTimer=null)}_statsPollMs(){let t=this._options.sessionStats;if(!t)return 0;let e=t.pollMs;return e===void 0?nne:Number.isFinite(e)&&e>0?e:0}_startStatsSampler(){let t=this._statsPollMs();if(t<=0||this._statsTimer)return;let e=this._generation;this._statsTimer=setInterval(()=>{e!==this._generation||this._intentionalDisconnect||this._isParkedPhase()||this._statsSampleInFlight||(this._statsSampleInFlight=!0,this._sampleSessionStats(e).catch(r=>{try{this._emitter.emit("error",r instanceof Error?r:new Error(String(r)))}catch{}}).finally(()=>{this._statsSampleInFlight=!1}))},t)}_stopStatsSampler(){this._statsTimer&&(clearInterval(this._statsTimer),this._statsTimer=null),this._statsSampleInFlight=!1}_lanePairKey(t){let e=t.track,r=e?this._streamNameOf(e):void 0;if(r===void 0)return null;let s=U1(r);return s===void 0?r:r.slice(0,r.length-Xh.length-s.length)}async _sampleSessionStats(t){if(this._consumers.size===0)return;let e=Array.from(this._consumers.values()),r=await Promise.all(e.map(async l=>({consumerId:l.id,kind:l.kind==="video"?"video":"audio",pairKey:this._lanePairKey(l),sample:await hF(l)})));if(t!==this._generation||this._intentionalDisconnect||this._isParkedPhase())return;let s=r.filter(l=>l.pairKey===null),n=r.filter(l=>l.pairKey!==null),i=null,o=r;if(n.length>0){let l=new Map;for(let m of n){let _=m.pairKey,f=l.get(_);f?f.push(m):l.set(_,[m])}let h=-1,p=-1;for(let[m,_]of l){let f=new Set(_.map(w=>w.kind)).size>=2?1:0,b=_.reduce((w,S)=>w+S.sample.total,0);(f>h||f===h&&b>p)&&(h=f,p=b,i=m,o=[..._,...s])}}let a=l=>{let h=null,p=-1;for(let{consumerId:m,kind:_,sample:f}of o)_===l&&f.total>p&&(p=f.total,h={consumerId:m,...f});return h},c=a("audio"),d=a("video"),u=d?.estimatedPlayoutTimestamp!=null&&c?.estimatedPlayoutTimestamp!=null?d.estimatedPlayoutTimestamp-c.estimatedPlayoutTimestamp:null;this._emitter.emit("stats",{timestamp:Date.now(),stream:i,avSyncMs:u,audio:c,video:d})}_resetJoinProbes(){this._joinProbes.clear(),this._decodeDeathHandled=!1}async _sampleMediaArrival(t){if(this._consumers.size===0)return;let e=Array.from(this._consumers.entries()),r=await Promise.all(e.map(async([o,a])=>[o,await hF(a)]));if(t!==this._generation||this._intentionalDisconnect||this._phase.name==="error"&&this._isParkedPhase()||this._isStaleLivenessEvidence())return;for(let o of this._joinProbes.keys())this._consumers.has(o)||this._joinProbes.delete(o);let s=Date.now();!this._liveReached&&r.some(([,o])=>o.total>0)&&this._setPhase("live");let n=null,i=!1;for(let[o,a]of r){if(a.total<=0){i=!0;continue}let c=this._joinProbes.get(o);if(c||(c={firstBytesAt:s,startSample:a,settled:!1},this._joinProbes.set(o,c)),!c.settled){if(a.framesDecoded===null){c.settled=!0;continue}if(a.framesDecoded>0){c.settled=!0;continue}if(s-c.firstBytesAt>=this._firstFrameWindowMs()){n??={id:o,probe:c,sample:a};continue}i=!0}}if(n&&!this._decodeDeathHandled){this._decodeDeathHandled=!0;let o=this._firstFrameWindowMs(),a=yne(n.probe.startSample,n.sample),c=a.lossPct!==null&&a.lossPct>=5?" \u2014 consistent with network packet loss between the SFU and this browser":"";this._emitDiagnostic({level:"warning",kind:"decode-wall",message:`video is arriving but the decoder never produced its first frame within ${o/1e3}s of join (framesDecoded still 0) \u2014 no keyframe to start from${c}; re-consuming the stream`,detail:{sessionId:this._options.sessionId,consumerId:n.id,firstFrameWindowMs:o,inboundTotal:n.sample.total,framesDecoded:n.sample.framesDecoded,...gne(n.sample),...a,likelyCause:a.lossPct!==null&&a.lossPct>=5?"network-packet-loss":null,...this._selectedCandidatePair}}),this._renegotiate();return}!i&&!n&&this._stopMediaProbe()}_renegotiate(){this._intentionalDisconnect||this._isExplicitEndPhase()||this._reconnectTimer||(this._stopMediaProbe(),this._stopStatsSampler(),this._setState("renegotiating"),this._attemptReconnect())}recover(){if(this._intentionalDisconnect||this._isExplicitEndPhase()||this._connectStartedAt===void 0||this._cancelPendingDial)return;if(!this.isOpen){this._reconnectTimer&&(clearTimeout(this._reconnectTimer),this._reconnectTimer=null),this._reconnectAttempts=0,this._attemptReconnect(void 0,!0);return}let t=this._recvTransport?.connectionState;(t==="disconnected"||t==="failed")&&(this._recvIceRestartTimer||(this._recvIceRestartAttempts=0),this._tryRestartRecvIce()||this._renegotiate());let e=this._sendTransport?.connectionState;(e==="disconnected"||e==="failed")&&(this._sendIceRestartTimer||(this._sendIceRestartAttempts=0),this._trySendIceRestart())}_attemptReconnect(t,e=!1){if(this._intentionalDisconnect||this._isExplicitEndPhase()||this._reconnectTimer)return;this._reconnectAttempts>=J$&&(this._reconnectExhaustedWarned||(this._reconnectExhaustedWarned=!0,this._emitDiagnostic({level:"warning",kind:"signaling-reconnect-forever",message:`signaling reconnect budget spent (${J$} attempts) \u2014 retrying forever with capped backoff while the session lives`})));let r=e?0:Y$[Math.min(this._reconnectAttempts,Y$.length-1)];this._reconnectAttempts++,this._state!=="renegotiating"&&this._setState("reconnecting"),this._reconnectTimer=setTimeout(async()=>{this._reconnectTimer=null,this._replaceCurrentLegForReconnect();try{await this.connect(t??this._lastStartOptions)}catch(s){if(s instanceof Error&&s.message==="TransportSession: connect cancelled")return;this._attemptReconnect(t)}},r)}_connectUrls(){let t=[],e=r=>{if(!r)return;let s=dF(r)!==void 0,n=this._sessionId&&!s?`${r}${r.includes("?")?"&":"?"}sessionId=${encodeURIComponent(this._sessionId)}`:r;t.includes(n)||t.push(n)};e(this._options.url);for(let r of this._options.fallbackUrls??[])e(r);return t}_connectOnce(t,e,r){return new Promise((s,n)=>{let i=!1,o=!1,a=null,c=new WebSocket(t);this._ws=c;let d=()=>this._ws!==c||e!==this._generation,u=h=>{o||(o=!0,a&&clearTimeout(a),this._cancelPendingDial===l&&(this._cancelPendingDial=null),n(h))},l=h=>{try{c.close()}catch{}u(h)};this._cancelPendingDial=l,a=setTimeout(()=>{try{c.close()}catch{}u(new Error("TransportSession: connect timed out"))},ene),c.onopen=()=>{if(!o){if(d()){try{c.close()}catch{}u(new Error("TransportSession: connect superseded during dial"));return}i=!0,a&&clearTimeout(a),this._connectedUrl=t,this._multiplexer=new XA(c),c.send(JSON.stringify(this._startMessage(r))),this._scheduleReconnectBudgetReset(),this._selfEpochAdoptUntil=Date.now()+tne,this._setState("connected"),this._liveReached||this._setPhase("connecting"),this._emitter.emit("connected"),o=!0,this._cancelPendingDial===l&&(this._cancelPendingDial=null),s()}},c.onerror=()=>{i||u(new Error("WebSocket connection error"))},c.onclose=()=>{if(!i){u(new Error("WebSocket closed before connecting"));return}if(!d()&&(this._clearReconnectBudgetReset(),a&&clearTimeout(a),this._setState("disconnected"),!this._intentionalDisconnect)){if(this._pastDeadline()&&this._phase.name!=="paused"){this._setPhase("paused",{reason:"max_session_age"}),this._emitter.emit("disconnected");return}this._emitter.emit("disconnected"),!this._isExplicitEndPhase()&&this._attemptReconnect(r)}},c.onmessage=h=>{if(!(this._ws!==c||e!==this._generation)&&typeof h.data=="string")try{this._handleMessage(JSON.parse(h.data)).catch(p=>{this._emitter.emit("error",p instanceof Error?p:new Error(String(p)))})}catch(p){this._emitter.emit("error",p instanceof Error?p:new Error(String(p)))}}})}_startMessage(t){let e={type:"start",version:iI,video:t?.video??{width:854,height:480,frameRate:16}};return t?.prompt&&(e.prompt=t.prompt),t?.cameraControl&&(e.camera_control=t.cameraControl),t?.args&&(e.args=t.args),t?.app&&(e.app=t.app),t?.functionName&&(e.function=t.functionName),t?.role&&(e.role=t.role),this._options.orgId&&(e.orgId=this._options.orgId),this._options.jwt&&(e.jwt=this._options.jwt),this._options.authProvider&&(e.authProvider=this._options.authProvider),e}_cleanupSocket(){if(this._clearReconnectBudgetReset(),!this._ws)return;let t=this._ws;this._ws=null,t.onopen=null,t.onmessage=null,t.onerror=null,t.onclose=null;try{t.close()}catch{}}_replaceCurrentLegForReconnect(){this._cleanupSocket(),this._cancelPendingDial?.(new Error("TransportSession: reconnect replacing current dial")),this._cleanupMedia()}_scheduleReconnectBudgetReset(){this._clearReconnectBudgetReset(),this._reconnectAttempts!==0&&(this._stableResetTimer=setTimeout(()=>{this._stableResetTimer=null,this._reconnectAttempts=0,this._reconnectExhaustedWarned=!1},dne))}_clearReconnectBudgetReset(){this._stableResetTimer&&(clearTimeout(this._stableResetTimer),this._stableResetTimer=null)}_cleanupDataChannels(){for(let t of this._dataProducers.values())try{t.close()}catch{}this._dataProducers.clear(),this._dataProducerPromises.clear();for(let t of this._dataConsumers.values())try{t.close()}catch{}this._dataConsumers.clear();for(let t of this._pendingDataProduce.values())try{t.reject(new Error("TransportSession: disconnected"))}catch{}this._pendingDataProduce.clear()}_cleanupMedia(){this._stopMediaProbe(),this._stopStatsSampler(),this._resetJoinProbes();for(let t of this._consumers.values())try{t.close()}catch{}if(this._consumers.clear(),this._cleanupDataChannels(),this._audioProducer){try{this._audioProducer.close()}catch{}this._audioProducer=null}if(this._videoProducer){try{this._videoProducer.close()}catch{}this._videoProducer=null}if(this._clearRecvIceRestart(),this._clearSendIceRestart(),this._recvTransport){try{this._recvTransport.close()}catch{}this._recvTransport=null}if(this._pendingConsumeData=[],this._sendTransport){try{this._sendTransport.close()}catch{}this._sendTransport=null}this._pendingProduce&&(clearTimeout(this._pendingProduce.timeoutId),this._pendingProduce=null),this._device=null,this._tracks.clear(),this._tracksByName.clear(),this._multiplexer&&(this._multiplexer.dispose(),this._multiplexer=null)}_send(t){return!this._ws||this._ws.readyState!==WebSocket.OPEN?!1:(this._ws.send(JSON.stringify(t)),!0)}_setState(t){this._state!==t&&(this._state=t,this._emitter.emit("stateChange",t))}_isParkedPhase(){return this._phase.name==="paused"?!0:this._phase.name!=="error"?!1:this._phase.error?.kind!=="transport-failed"}_isExplicitEndPhase(){if(this._phase.name==="paused"&&!this._isComputeReleasedPark())return!1;if(this._phase.name!=="error")return this._isComputeReleasedPark();let t=this._phase.error?.kind;return t!==void 0&&t!=="transport-failed"}_isComputeReleasedPark(){return this._phase.name!=="paused"?!1:Q$[this._phase.reason??""]===!0}_setPhase(t,e){let r=this._liveReached;t==="live"?this._liveReached=!0:(t==="paused"||t==="error")&&(this._liveReached=!1,t==="paused"&&!r&&Q$[e?.reason??""]!==!0&&(this._forceResolveOnNextConnect=!0,this._cancelPendingDial||this._attemptReconnect()));let s={name:t};e?.queue&&(s.queue=e.queue),e?.runtime&&(s.runtime=e.runtime),e?.reason&&(s.reason=e.reason),s.region=e?.region!==void 0?e.region:this._phase.region,xc(t)?(this._wakingSince??=Date.now(),s.wakingSince=this._wakingSince):this._wakingSince=void 0,this._requestId&&(s.requestId=this._requestId),this._sessionId&&(s.sessionId=this._sessionId),this._endsAt!==null&&(s.endsAt=this._endsAt),e?.error&&(s.error=e.error),!une(this._phase,s)&&(this._phase=s,this._pausedIncarnation=t==="paused"?this._currentEpoch:null,this._isParkedPhase()&&(this._stopMediaProbe(),this._stopStatsSampler(),this._clearRecvIceRestart(),this._clearSendIceRestart()),this._emitter.emit("phase",s))}reportAdmission(t){t.requestId&&(this._requestId=t.requestId),this._lastServerStatus=t.status;let e=nF(t.status);if(e.unknown){this._reportUnknownServerStatus(t.status,t.reason,"admission",t.region);return}if(this._liveReached)return;t.sessionId&&!this._sessionId&&(this._sessionId=t.sessionId);let{runtime:r,queue:s}=t,n=t.decisionReason==="provisioning_refused"?t.refusalMessage??t.decisionReason:t.reason,i={runtime:r,queue:s,...n?{reason:n}:{},...t.region!==void 0?{region:t.region}:{}};if(hne(t.status)){if(r?.state==="unavailable"){this._setPhase("unavailable",i);return}if(r?.state==="starting"){this._setPhase("provisioning",i);return}if(r?.state==="busy"||t.status==="queued"){this._setPhase("queued",i);return}this._setPhase("provisioning",i);return}this._setPhase(e.phase,e.phase==="paused"?{...i,region:i.region??null}:i)}_emitError(t,e){this._setPhase("error",{error:{reason:t.message,code:e,kind:"transport-failed"}}),this._emitter.emit("error",t)}reportAllocationFailure(t,e,r,s){r==="insufficient_credits"?this._setPhase("error",{error:{reason:t.message,code:r,kind:"insufficient-credits",httpStatus:e}}):this._setPhase("error",{error:{reason:t.message,code:r??"allocation-failed",kind:"create-failed",httpStatus:e,retryAfterSeconds:s}}),this._emitter.emit("error",t)}};function lF(t){return new Promise(e=>setTimeout(e,t))}function fne(){return ev()}var GF=["packetsReceived","packetsLost","nackCount","pliCount","firCount","keyFramesDecoded","framesReceived","framesDropped","retransmittedPacketsReceived","retransmittedBytesReceived","jitterBufferDelay","jitterBufferEmittedCount","estimatedPlayoutTimestamp","jitterBufferTargetDelay","jitterBufferMinimumDelay","concealedSamples","insertedSamplesForDeceleration"],pne=new Set(["estimatedPlayoutTimestamp"]);function mne(){return{total:0,framesDecoded:null,packetsReceived:null,packetsLost:null,nackCount:null,jitter:null,pliCount:null,firCount:null,keyFramesDecoded:null,framesReceived:null,framesDropped:null,retransmittedPacketsReceived:null,retransmittedBytesReceived:null,jitterBufferDelay:null,jitterBufferEmittedCount:null,estimatedPlayoutTimestamp:null,jitterBufferTargetDelay:null,jitterBufferMinimumDelay:null,concealedSamples:null,insertedSamplesForDeceleration:null}}function gne(t){return Object.fromEntries(GF.map(e=>[e,t[e]]))}function uF(t,e){return t===null||e===null||e<t?null:e-t}function yne(t,e){let r=t.packetsLost!==null&&e.packetsLost!==null?e.packetsLost-t.packetsLost:null,s=uF(t.packetsReceived,e.packetsReceived),n=uF(t.nackCount,e.nackCount),i=r===null?null:Math.max(0,r),o=i!==null&&s!==null?i+s:0;return{packetsLostWindow:r,packetsReceivedWindow:s,nackCountWindow:n,jitterSec:e.jitter,lossPct:o>0&&i!==null?i/o*100:null}}function XF(){return{localType:null,remoteType:null,protocol:null,remoteAddress:null,remotePort:null}}function bne(t){let e=new Map;YF(t,a=>{let c=typeof a.id=="string"?a.id:null;c&&e.set(c,a)});let r=Array.from(e.values()).find(a=>a.type==="transport"),s=typeof r?.selectedCandidatePairId=="string"?r.selectedCandidatePairId:null,n=(s?e.get(s):void 0)??Array.from(e.values()).find(a=>a.type==="candidate-pair"&&a.selected===!0)??Array.from(e.values()).find(a=>a.type==="candidate-pair"&&a.nominated===!0);if(!n)return XF();let i=typeof n.localCandidateId=="string"?e.get(n.localCandidateId):void 0,o=typeof n.remoteCandidateId=="string"?e.get(n.remoteCandidateId):void 0;return{localType:typeof i?.candidateType=="string"?i.candidateType:null,remoteType:typeof o?.candidateType=="string"?o.candidateType:null,protocol:typeof i?.protocol=="string"?i.protocol:typeof o?.protocol=="string"?o.protocol:null,remoteAddress:typeof o?.address=="string"?o.address:typeof o?.ip=="string"?o.ip:null,remotePort:typeof o?.port=="number"?o.port:null}}function YF(t,e){let r=s=>{s&&typeof s=="object"&&e(s)};if(t instanceof Map)for(let[s,n]of t.entries()){if(!n||typeof n!="object")continue;let i=n;e(typeof i.id=="string"?i:{...i,id:s})}else(Array.isArray(t)||t&&typeof t.forEach=="function")&&t.forEach(r)}async function hF(t){let e=mne();if(typeof t.getStats!="function")return e;let r;try{r=await t.getStats()}catch{return e}return YF(r,s=>{if(s.type==="inbound-rtp"){let n=typeof s.bytesReceived=="number"?s.bytesReceived:0,i=typeof s.packetsReceived=="number"?s.packetsReceived:0;e.total+=n+i,typeof s.framesDecoded=="number"&&(e.framesDecoded=(e.framesDecoded??0)+s.framesDecoded),typeof s.jitter=="number"&&(e.jitter=e.jitter===null?s.jitter:Math.max(e.jitter,s.jitter));for(let o of GF)typeof s[o]=="number"&&(e[o]=pne.has(o)?e[o]===null?s[o]:Math.max(e[o],s[o]):(e[o]??0)+s[o])}}),e}function xne(t){if(!t||typeof t!="object")return;let e=t.epoch,r=typeof e=="number"?e:Number(e);return Number.isFinite(r)?r:void 0}var wne=1;function aI(t){let e=new URL(t);return`${e.protocol}//${e.host}/doc`}var vne=2500,_ne=3e4,Sne=1e4,Ene=3;function JF(t){let e=t.WebSocketPolyfill??globalThis.WebSocket;if(!e)throw new Error("[urun] no WebSocket implementation available for the yjs doc provider (browser global missing and no WebSocketPolyfill passed)");return(r,s,n)=>{let i=`${t.sessionId}/${r}`,o=typeof t.token=="function"?t.token:null,a=typeof t.token=="string"?t.token:void 0,c=t.maxBackoffTimeMs??vne,d=t.dialTimeoutMs??_ne,u=new Py(t.serverUrl,i,s,{awareness:n,params:{dsv:String(wne),...a?{token:a}:{}},WebSocketPolyfill:e,disableBc:!0,maxBackoffTime:c,resyncInterval:Sne,connect:o===null}),l=!1,h,p=!1,m=I=>{p||(p=!0,E.error(`[urun] doc token refresh failed for room ${i} (redialing with previous token):`,I))},_=()=>{if(o){if(h)return h;try{let I=o();if(typeof I=="string"){u.params.token=I,p=!1;return}if(I&&typeof I.then=="function"){let U=I.then(K=>{typeof K=="string"&&(u.params.token=K,p=!1)},K=>{m(K)}).finally(()=>{h===U&&(h=void 0)});return h=U,U}}catch(I){m(I)}}},f=t.resolveServerUrl,b=0,w=!1,S=I=>{if(typeof I!="string"||I==="")return;let U=I.replace(/\/+$/,"");U!==u.serverUrl&&(u.serverUrl=U,w=!1)},O=()=>{if(!f)return;let I=++b,U=K=>{w||(w=!0,E.error(`[urun] doc endpoint re-resolve failed for room ${i} (redialing previous host):`,K))};try{let K=f();if(K&&typeof K.then=="function")return K.then(z=>{I===b&&S(z)},U);S(K)}catch(K){U(K)}},j={connected:!1,consecutiveFailures:0,lastCloseCode:null,lastCloseReason:null},P=new Set,k=!1,C=()=>{let I={...j};for(let U of[...P])U(I)},D=null,H=()=>{D!==null&&(clearTimeout(D),D=null)},W=()=>{H(),D=setTimeout(()=>{if(D=null,!l&&u.wsconnecting&&u.ws)try{u.ws.close()}catch{}},d)},J=null,F=()=>{J!==null&&(clearTimeout(J),J=null)},q=()=>{F(),J=setTimeout(()=>{if(J=null,!l&&u.shouldConnect&&!u.wsconnected&&!u.wsconnecting&&u.ws===null)try{u.connect()}catch(I){k||(k=!0,E.error(`[urun] doc connection redial threw for room ${i} (still retrying):`,I)),q()}},c+500)},Q=({status:I})=>{if(I==="connecting"){F(),W();return}if(I==="connected"){H(),F(),j={...j,connected:!0},C();return}j.connected&&(j={...j,connected:!1},C())},R=I=>{I&&(k&&(lg()?E.warn(`[urun] doc connection recovered for room ${i}`):E.info(`[urun] doc connection recovered for room ${i}`),k=!1),j.consecutiveFailures!==0&&(j={...j,consecutiveFailures:0},C()))},Y=I=>{H(),j={connected:!1,consecutiveFailures:j.consecutiveFailures+1,lastCloseCode:I?I.code:null,lastCloseReason:I&&I.reason?I.reason:null},!k&&j.consecutiveFailures>=Ene&&(k=!0,E.error(`[urun] doc connection failing for room ${i}: ${j.consecutiveFailures} consecutive failures (last close ${j.lastCloseCode===null?"by provider liveness reap":`code ${j.lastCloseCode}`}${j.lastCloseReason?`, reason "${j.lastCloseReason}"`:""}). Still retrying \u2014 the doc provider never gives up.`)),C(),_(),O(),q()};u.on("status",Q),u.on("sync",R),u.on("connection-close",Y),u.wsconnecting?W():u.wsconnected&&(j={...j,connected:!0});let Z=!1;return o!==null&&_(),Z||u.connect(),{get awareness(){return u.awareness},get synced(){return u.synced},onSync(I){let U=K=>I(K);return u.on("sync",U),()=>u.off("sync",U)},onConnectionState(I){return P.add(I),I({...j}),()=>P.delete(I)},ensureConnected(){Z=!1,u.wsconnected||u.connect()},disconnect(){Z=!0,u.disconnect()},destroy(){l=!0,H(),F(),u.off("status",Q),u.off("sync",R),u.off("connection-close",Y),P.clear(),u.destroy()}}}}var Cne=class{constructor(t,e,r){this._name=t,this._doc=e,this.awareness=r}_name;_doc;awareness;_inner=null;_innerUnsub=null;_innerStateUnsub=null;_syncHandlers=new Set;_stateHandlers=new Set;_lastState={connected:!1,consecutiveFailures:0,lastCloseCode:null,lastCloseReason:null};_destroyed=!1;_suspended=!1;get synced(){return this._inner?.synced??!1}get destroyed(){return this._destroyed}onSync(t){return this._syncHandlers.add(t),()=>this._syncHandlers.delete(t)}onConnectionState(t){return this._stateHandlers.add(t),t({...this._lastState}),()=>this._stateHandlers.delete(t)}attach(t){if(!this._destroyed){if(this._inner&&(this._innerUnsub?.(),this._innerUnsub=null,this._innerStateUnsub?.(),this._innerStateUnsub=null,this._inner.destroy(),this._inner=null),this._inner=t(this._name,this._doc,this.awareness),this._innerUnsub=this._inner.onSync(e=>{for(let r of[...this._syncHandlers])r(e)}),this._inner.onConnectionState)this._innerStateUnsub=this._inner.onConnectionState(e=>{this._lastState=e;for(let r of[...this._stateHandlers])r(e)});else{this._innerStateUnsub=null,this._lastState={connected:!0,consecutiveFailures:0,lastCloseCode:null,lastCloseReason:null};for(let e of[...this._stateHandlers])e({...this._lastState})}if(this._suspended&&this._inner.disconnect?.(),this._inner.synced)for(let e of[...this._syncHandlers])e(!0)}}ensureConnected(){this._suspended=!1,this._inner?.ensureConnected?.()}get disconnect(){return this._inner?.disconnect?()=>{this._suspended=!0,this._inner.disconnect()}:void 0}destroy(){this._destroyed=!0,this._innerUnsub?.(),this._innerUnsub=null,this._innerStateUnsub?.(),this._innerStateUnsub=null,this._inner?.destroy(),this._inner=null,this._syncHandlers.clear(),this._stateHandlers.clear()}},QF=class{_target=null;_bridges=[];connect=(t,e,r)=>{let s=new Cne(t,e,r);return this._bridges.push(s),this._target&&s.attach(this._target),s};get connected(){return this._target!==null}setTarget(t){if(this._target!==t){this._target=t,this._bridges=this._bridges.filter(e=>!e.destroyed);for(let e of this._bridges)e.attach(t)}}};function mg(t){if(t===null||typeof t!="object"||Array.isArray(t))return!1;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}var M1="$bytes";function Tne(t){return t instanceof Uint8Array||t instanceof ArrayBuffer}function kne(t){if(!mg(t))return!1;let e=Object.keys(t);return e.length===1&&e[0]===M1&&typeof t[M1]=="string"}function Ane(t){return t instanceof ArrayBuffer?new Uint8Array(t):t}function Ine(t){if(typeof Buffer<"u")return Buffer.from(t).toString("base64");let e="";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return btoa(e)}function Rne(t){if(typeof Buffer<"u")return new Uint8Array(Buffer.from(t,"base64"));let e=atob(t),r=new Uint8Array(e.length);for(let s=0;s<e.length;s++)r[s]=e.charCodeAt(s);return r}function WA(t){if(Tne(t))return{[M1]:Ine(Ane(t))};if(Array.isArray(t))return t.map(WA);if(mg(t)){let e={};for(let[r,s]of Object.entries(t))e[r]=WA(s);return e}return t}function hg(t){if(kne(t))return Rne(t[M1]);if(Array.isArray(t))return t.map(hg);if(mg(t)){let e={};for(let[r,s]of Object.entries(t))e[r]=hg(s);return e}return t}var ZF=Symbol("urun:doc:path-absent");function Pne(t,e){let r=e.split("."),s=t;for(let n of r){if(s===null||typeof s!="object"||!(n in s))return ZF;s=s[n]}return s}function Dne(t,e){return t===e?!0:JSON.stringify(t)===JSON.stringify(e)}function KA(t,e){for(let[r,s]of Object.entries(e))if(mg(s)){let n=t.get(r);if(!(n instanceof pg.Map)){let i=n;n=new pg.Map,t.set(r,n),mg(i)&&KA(n,i)}KA(n,s)}else{if(Dne(t.get(r),s))continue;t.set(r,s)}}var Bne=Symbol("urun:doc:local"),eH=class{_doc=new pg.Doc;_root=this._doc.getMap("session");_awareness=new nu(this._doc);_listeners=new Set;_key;_sessionId;_connection=null;_connUnsub=null;_synced;_syncWaiters=new Set;_texts=new Map;_observer=()=>this.notify();constructor(t,e,r){this._key=t,this._sessionId=e,this._root.observeDeep(this._observer),r?(this._connection=r(t,this._doc,this._awareness),this._synced=this._connection.synced,this._connUnsub=this._connection.onSync(s=>{s&&this._markSynced()}),this._synced&&this._markSynced()):this._synced=!0}get awareness(){return this._awareness}setSessionId(t){this._sessionId=t}get synced(){return this._synced}ensureConnected(){this._connection?.ensureConnected?.()}reconnect(){this.ensureConnected()}disconnect(){let t=this._connection;if(!t?.disconnect)throw new Error(`[urun-sh/core] doc('${this._key}').disconnect(): no disconnect-capable connection to sever (a local-only doc, or a connector with no live socket) \u2014 there is nothing to disconnect`);t.disconnect()}onConnectionState(t){return this._connection?.onConnectionState?this._connection.onConnectionState(t):(t({connected:!0,consecutiveFailures:0,lastCloseCode:null,lastCloseReason:null}),()=>{})}onSynced(t){return this._synced?(t(),()=>{}):(this._syncWaiters.add(t),()=>this._syncWaiters.delete(t))}set(t){t=WA(t),this.applyPatch(t)}get(t,e){let r=this.snapshot();if(!t)return hg(r);let s=Pne(r,t);return s===ZF?e:hg(s)}on(t,e){return this._listeners.add(e),()=>this._listeners.delete(e)}text(t){let e=this._texts.get(t);return e||(e=new Lne(this._doc.getText(`text:${t}`)),this._texts.set(t,e)),e}dispose(){this._root.unobserveDeep(this._observer),this._connUnsub?.(),this._connUnsub=null,this._connection?.destroy(),this._connection=null,this._listeners.clear(),this._syncWaiters.clear();for(let t of this._texts.values())t.dispose();this._texts.clear(),this._awareness.destroy(),this._doc.destroy()}_markSynced(){let t=[...this._syncWaiters];this._synced=!0,this._syncWaiters.clear();for(let e of t)e()}applyPatch(t){this._doc.transact(()=>{KA(this._root,t)},Bne)}snapshot(){return this._root.toJSON()}notify(){let t=hg(this.snapshot());for(let e of this._listeners)e(t)}},Lne=class{constructor(t){this._ytext=t,this._observer=e=>{for(let r of e.delta)if(typeof r.insert=="string"&&r.insert.length>0){let s=r.insert;for(let n of this._delta)n(s)}},this._ytext.observe(this._observer)}_ytext;_delta=new Set;_observer;append(t){t.length!==0&&this._ytext.insert(this._ytext.length,t)}toString(){return this._ytext.toString()}get length(){return this._ytext.length}on(t,e){return this._delta.add(e),()=>this._delta.delete(e)}dispose(){this._ytext.unobserve(this._observer),this._delta.clear()}};function tH(t){return{get clientId(){return t.clientID},set(e){t.setLocalState(e)},setField(e,r){t.setLocalStateField(e,r)},getLocal(){return t.getLocalState()??null},getStates(){return t.getStates()},on(e,r){let s=()=>r(t.getStates());return t.on("change",s),s(),()=>t.off("change",s)}}}g();y();g();y();g();y();g();y();function rH(t){let e=t.length,r=0,s=0;for(;s<e;){let n=t.charCodeAt(s++);if((n&4294967168)===0){r++;continue}else if((n&4294965248)===0)r+=2;else{if(n>=55296&&n<=56319&&s<e){let i=t.charCodeAt(s);(i&64512)===56320&&(++s,n=((n&1023)<<10)+(i&1023)+65536)}(n&4294901760)===0?r+=3:r+=4}}return r}function One(t,e,r){let s=t.length,n=r,i=0;for(;i<s;){let o=t.charCodeAt(i++);if((o&4294967168)===0){e[n++]=o;continue}else if((o&4294965248)===0)e[n++]=o>>6&31|192;else{if(o>=55296&&o<=56319&&i<s){let a=t.charCodeAt(i);(a&64512)===56320&&(++i,o=((o&1023)<<10)+(a&1023)+65536)}(o&4294901760)===0?(e[n++]=o>>12&15|224,e[n++]=o>>6&63|128):(e[n++]=o>>18&7|240,e[n++]=o>>12&63|128,e[n++]=o>>6&63|128)}e[n++]=o&63|128}}var Nne=new TextEncoder,Une=50;function Mne(t,e,r){Nne.encodeInto(t,e.subarray(r))}function sH(t,e,r){t.length>Une?Mne(t,e,r):One(t,e,r)}var jne=4096;function cI(t,e,r){let s=e,n=s+r,i=[],o="";for(;s<n;){let a=t[s++];if((a&128)===0)i.push(a);else if((a&224)===192){let c=t[s++]&63;i.push((a&31)<<6|c)}else if((a&240)===224){let c=t[s++]&63,d=t[s++]&63;i.push((a&31)<<12|c<<6|d)}else if((a&248)===240){let c=t[s++]&63,d=t[s++]&63,u=t[s++]&63,l=(a&7)<<18|c<<12|d<<6|u;l>65535&&(l-=65536,i.push(l>>>10&1023|55296),l=56320|l&1023),i.push(l)}else i.push(a);i.length>=jne&&(o+=String.fromCharCode(...i),i.length=0)}return i.length>0&&(o+=String.fromCharCode(...i)),o}var $ne=new TextDecoder,Fne=200;function Hne(t,e,r){let s=t.subarray(e,e+r);return $ne.decode(s)}function nH(t,e,r){return r>Fne?Hne(t,e,r):cI(t,e,r)}g();y();g();y();var Tl=class{type;data;constructor(e,r){this.type=e,this.data=r}};g();y();g();y();var Ns=class t extends Error{constructor(e){super(e);let r=Object.create(t.prototype);Object.setPrototypeOf(this,r),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:t.name})}};g();y();function iH(t,e,r){let s=r/4294967296,n=r;t.setUint32(e,s),t.setUint32(e+4,n)}function tv(t,e,r){let s=Math.floor(r/4294967296),n=r;t.setUint32(e,s),t.setUint32(e+4,n)}function rv(t,e){let r=t.getInt32(e),s=t.getUint32(e+4);return r*4294967296+s}function oH(t,e){let r=t.getUint32(e),s=t.getUint32(e+4);return r*4294967296+s}var qne=-1,Vne=4294967296-1,zne=17179869184-1;function Wne({sec:t,nsec:e}){if(t>=0&&e>=0&&t<=zne)if(e===0&&t<=Vne){let r=new Uint8Array(4);return new DataView(r.buffer).setUint32(0,t),r}else{let r=t/4294967296,s=t&4294967295,n=new Uint8Array(8),i=new DataView(n.buffer);return i.setUint32(0,e<<2|r&3),i.setUint32(4,s),n}else{let r=new Uint8Array(12),s=new DataView(r.buffer);return s.setUint32(0,e),tv(s,4,t),r}}function Kne(t){let e=t.getTime(),r=Math.floor(e/1e3),s=(e-r*1e3)*1e6,n=Math.floor(s/1e9);return{sec:r+n,nsec:s-n*1e9}}function Gne(t){if(t instanceof Date){let e=Kne(t);return Wne(e)}else return null}function Xne(t){let e=new DataView(t.buffer,t.byteOffset,t.byteLength);switch(t.byteLength){case 4:return{sec:e.getUint32(0),nsec:0};case 8:{let r=e.getUint32(0),s=e.getUint32(4),n=(r&3)*4294967296+s,i=r>>>2;return{sec:n,nsec:i}}case 12:{let r=rv(e,4),s=e.getUint32(0);return{sec:r,nsec:s}}default:throw new Ns(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${t.length}`)}}function Yne(t){let e=Xne(t);return new Date(e.sec*1e3+e.nsec/1e6)}var aH={type:qne,encode:Gne,decode:Yne};var Zh=class t{static defaultCodec=new t;__brand;builtInEncoders=[];builtInDecoders=[];encoders=[];decoders=[];constructor(){this.register(aH)}register({type:e,encode:r,decode:s}){if(e>=0)this.encoders[e]=r,this.decoders[e]=s;else{let n=-1-e;this.builtInEncoders[n]=r,this.builtInDecoders[n]=s}}tryToEncode(e,r){for(let s=0;s<this.builtInEncoders.length;s++){let n=this.builtInEncoders[s];if(n!=null){let i=n(e,r);if(i!=null){let o=-1-s;return new Tl(o,i)}}}for(let s=0;s<this.encoders.length;s++){let n=this.encoders[s];if(n!=null){let i=n(e,r);if(i!=null){let o=s;return new Tl(o,i)}}}return e instanceof Tl?e:null}decode(e,r,s){let n=r<0?this.builtInDecoders[-1-r]:this.decoders[r];return n?n(e,r,s):new Tl(r,e)}};g();y();function Jne(t){return t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer}function Cg(t){return t instanceof Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):Jne(t)?new Uint8Array(t):Uint8Array.from(t)}var Qne=100,Zne=2048,sv=class t{extensionCodec;context;useBigInt64;maxDepth;initialBufferSize;sortKeys;forceFloat32;ignoreUndefined;forceIntegerToFloat;pos;view;bytes;entered=!1;constructor(e){this.extensionCodec=e?.extensionCodec??Zh.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.maxDepth=e?.maxDepth??Qne,this.initialBufferSize=e?.initialBufferSize??Zne,this.sortKeys=e?.sortKeys??!1,this.forceFloat32=e?.forceFloat32??!1,this.ignoreUndefined=e?.ignoreUndefined??!1,this.forceIntegerToFloat=e?.forceIntegerToFloat??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new t({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(e){if(this.entered)return this.clone().encodeSharedRef(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(e){if(this.entered)return this.clone().encode(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(e,r){if(r>this.maxDepth)throw new Error(`Too deep objects in depth ${r}`);e==null?this.encodeNil():typeof e=="boolean"?this.encodeBoolean(e):typeof e=="number"?this.forceIntegerToFloat?this.encodeNumberAsFloat(e):this.encodeNumber(e):typeof e=="string"?this.encodeString(e):this.useBigInt64&&typeof e=="bigint"?this.encodeBigInt64(e):this.encodeObject(e,r)}ensureBufferSizeToWrite(e){let r=this.pos+e;this.view.byteLength<r&&this.resizeBuffer(r*2)}resizeBuffer(e){let r=new ArrayBuffer(e),s=new Uint8Array(r),n=new DataView(r);s.set(this.bytes),this.view=n,this.bytes=s}encodeNil(){this.writeU8(192)}encodeBoolean(e){e===!1?this.writeU8(194):this.writeU8(195)}encodeNumber(e){!this.forceIntegerToFloat&&Number.isSafeInteger(e)?e>=0?e<128?this.writeU8(e):e<256?(this.writeU8(204),this.writeU8(e)):e<65536?(this.writeU8(205),this.writeU16(e)):e<4294967296?(this.writeU8(206),this.writeU32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(207),this.writeU64(e)):e>=-32?this.writeU8(224|e+32):e>=-128?(this.writeU8(208),this.writeI8(e)):e>=-32768?(this.writeU8(209),this.writeI16(e)):e>=-2147483648?(this.writeU8(210),this.writeI32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(211),this.writeI64(e)):this.encodeNumberAsFloat(e)}encodeNumberAsFloat(e){this.forceFloat32?(this.writeU8(202),this.writeF32(e)):(this.writeU8(203),this.writeF64(e))}encodeBigInt64(e){e>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(e)):(this.writeU8(211),this.writeBigInt64(e))}writeStringHeader(e){if(e<32)this.writeU8(160+e);else if(e<256)this.writeU8(217),this.writeU8(e);else if(e<65536)this.writeU8(218),this.writeU16(e);else if(e<4294967296)this.writeU8(219),this.writeU32(e);else throw new Error(`Too long string: ${e} bytes in UTF-8`)}encodeString(e){let s=rH(e);this.ensureBufferSizeToWrite(5+s),this.writeStringHeader(s),sH(e,this.bytes,this.pos),this.pos+=s}encodeObject(e,r){let s=this.extensionCodec.tryToEncode(e,this.context);if(s!=null)this.encodeExtension(s);else if(Array.isArray(e))this.encodeArray(e,r);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else if(typeof e=="object")this.encodeMap(e,r);else throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(e)}`)}encodeBinary(e){let r=e.byteLength;if(r<256)this.writeU8(196),this.writeU8(r);else if(r<65536)this.writeU8(197),this.writeU16(r);else if(r<4294967296)this.writeU8(198),this.writeU32(r);else throw new Error(`Too large binary: ${r}`);let s=Cg(e);this.writeU8a(s)}encodeArray(e,r){let s=e.length;if(s<16)this.writeU8(144+s);else if(s<65536)this.writeU8(220),this.writeU16(s);else if(s<4294967296)this.writeU8(221),this.writeU32(s);else throw new Error(`Too large array: ${s}`);for(let n of e)this.doEncode(n,r+1)}countWithoutUndefined(e,r){let s=0;for(let n of r)e[n]!==void 0&&s++;return s}encodeMap(e,r){let s=Object.keys(e);this.sortKeys&&s.sort();let n=this.ignoreUndefined?this.countWithoutUndefined(e,s):s.length;if(n<16)this.writeU8(128+n);else if(n<65536)this.writeU8(222),this.writeU16(n);else if(n<4294967296)this.writeU8(223),this.writeU32(n);else throw new Error(`Too large map object: ${n}`);for(let i of s){let o=e[i];this.ignoreUndefined&&o===void 0||(this.encodeString(i),this.doEncode(o,r+1))}}encodeExtension(e){if(typeof e.data=="function"){let s=e.data(this.pos+6),n=s.length;if(n>=4294967296)throw new Error(`Too large extension object: ${n}`);this.writeU8(201),this.writeU32(n),this.writeI8(e.type),this.writeU8a(s);return}let r=e.data.length;if(r===1)this.writeU8(212);else if(r===2)this.writeU8(213);else if(r===4)this.writeU8(214);else if(r===8)this.writeU8(215);else if(r===16)this.writeU8(216);else if(r<256)this.writeU8(199),this.writeU8(r);else if(r<65536)this.writeU8(200),this.writeU16(r);else if(r<4294967296)this.writeU8(201),this.writeU32(r);else throw new Error(`Too large extension object: ${r}`);this.writeI8(e.type),this.writeU8a(e.data)}writeU8(e){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,e),this.pos++}writeU8a(e){let r=e.length;this.ensureBufferSizeToWrite(r),this.bytes.set(e,this.pos),this.pos+=r}writeI8(e){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,e),this.pos++}writeU16(e){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,e),this.pos+=2}writeI16(e){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,e),this.pos+=2}writeU32(e){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,e),this.pos+=4}writeI32(e){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,e),this.pos+=4}writeF32(e){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,e),this.pos+=4}writeF64(e){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,e),this.pos+=8}writeU64(e){this.ensureBufferSizeToWrite(8),iH(this.view,this.pos,e),this.pos+=8}writeI64(e){this.ensureBufferSizeToWrite(8),tv(this.view,this.pos,e),this.pos+=8}writeBigUint64(e){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,e),this.pos+=8}writeBigInt64(e){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,e),this.pos+=8}};function dI(t,e){return new sv(e).encodeSharedRef(t)}g();y();g();y();g();y();function nv(t){return`${t<0?"-":""}0x${Math.abs(t).toString(16).padStart(2,"0")}`}g();y();var eie=16,tie=16,iv=class{hit=0;miss=0;caches;maxKeyLength;maxLengthPerKey;constructor(e=eie,r=tie){this.maxKeyLength=e,this.maxLengthPerKey=r,this.caches=[];for(let s=0;s<this.maxKeyLength;s++)this.caches.push([])}canBeCached(e){return e>0&&e<=this.maxKeyLength}find(e,r,s){let n=this.caches[s-1];e:for(let i of n){let o=i.bytes;for(let a=0;a<s;a++)if(o[a]!==e[r+a])continue e;return i.str}return null}store(e,r){let s=this.caches[e.length-1],n={bytes:e,str:r};s.length>=this.maxLengthPerKey?s[Math.random()*s.length|0]=n:s.push(n)}decode(e,r,s){let n=this.find(e,r,s);if(n!=null)return this.hit++,n;this.miss++;let i=cI(e,r,s),o=Uint8Array.prototype.slice.call(e,r,r+s);return this.store(o,i),i}};var lI="array",Ag="map_key",dH="map_value",rie=t=>{if(typeof t=="string"||typeof t=="number")return t;throw new Ns("The type of key must be string or number but "+typeof t)},uI=class{stack=[];stackHeadPosition=-1;get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(e){let r=this.getUninitializedStateFromPool();r.type=lI,r.position=0,r.size=e,r.array=new Array(e)}pushMapState(e){let r=this.getUninitializedStateFromPool();r.type=Ag,r.readCount=0,r.size=e,r.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){let e={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(e)}return this.stack[this.stackHeadPosition]}release(e){if(this.stack[this.stackHeadPosition]!==e)throw new Error("Invalid stack state. Released state is not on top of the stack.");if(e.type===lI){let s=e;s.size=0,s.array=void 0,s.position=0,s.type=void 0}if(e.type===Ag||e.type===dH){let s=e;s.size=0,s.map=void 0,s.readCount=0,s.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}},kg=-1,hI=new DataView(new ArrayBuffer(0)),sie=new Uint8Array(hI.buffer);try{hI.getInt8(0)}catch(t){if(!(t instanceof RangeError))throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}var cH=new RangeError("Insufficient data"),nie=new iv,ov=class t{extensionCodec;context;useBigInt64;rawStrings;maxStrLength;maxBinLength;maxArrayLength;maxMapLength;maxExtLength;keyDecoder;mapKeyConverter;totalPos=0;pos=0;view=hI;bytes=sie;headByte=kg;stack=new uI;entered=!1;constructor(e){this.extensionCodec=e?.extensionCodec??Zh.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.rawStrings=e?.rawStrings??!1,this.maxStrLength=e?.maxStrLength??4294967295,this.maxBinLength=e?.maxBinLength??4294967295,this.maxArrayLength=e?.maxArrayLength??4294967295,this.maxMapLength=e?.maxMapLength??4294967295,this.maxExtLength=e?.maxExtLength??4294967295,this.keyDecoder=e?.keyDecoder!==void 0?e.keyDecoder:nie,this.mapKeyConverter=e?.mapKeyConverter??rie}clone(){return new t({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=kg,this.stack.reset()}setBuffer(e){let r=Cg(e);this.bytes=r,this.view=new DataView(r.buffer,r.byteOffset,r.byteLength),this.pos=0}appendBuffer(e){if(this.headByte===kg&&!this.hasRemaining(1))this.setBuffer(e);else{let r=this.bytes.subarray(this.pos),s=Cg(e),n=new Uint8Array(r.length+s.length);n.set(r),n.set(s,r.length),this.setBuffer(n)}}hasRemaining(e){return this.view.byteLength-this.pos>=e}createExtraByteError(e){let{view:r,pos:s}=this;return new RangeError(`Extra ${r.byteLength-s} of ${r.byteLength} byte(s) found at buffer[${e}]`)}decode(e){if(this.entered)return this.clone().decode(e);try{this.entered=!0,this.reinitializeState(),this.setBuffer(e);let r=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return r}finally{this.entered=!1}}*decodeMulti(e){if(this.entered){yield*this.clone().decodeMulti(e);return}try{for(this.entered=!0,this.reinitializeState(),this.setBuffer(e);this.hasRemaining(1);)yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(e){if(this.entered)return this.clone().decodeAsync(e);try{this.entered=!0;let r=!1,s;for await(let a of e){if(r)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(a);try{s=this.doDecodeSync(),r=!0}catch(c){if(!(c instanceof RangeError))throw c}this.totalPos+=this.pos}if(r){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return s}let{headByte:n,pos:i,totalPos:o}=this;throw new RangeError(`Insufficient data in parsing ${nv(n)} at ${o} (${i} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(e){return this.decodeMultiAsync(e,!0)}decodeStream(e){return this.decodeMultiAsync(e,!1)}async*decodeMultiAsync(e,r){if(this.entered){yield*this.clone().decodeMultiAsync(e,r);return}try{this.entered=!0;let s=r,n=-1;for await(let i of e){if(r&&n===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(i),s&&(n=this.readArraySize(),s=!1,this.complete());try{for(;yield this.doDecodeSync(),--n!==0;);}catch(o){if(!(o instanceof RangeError))throw o}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){e:for(;;){let e=this.readHeadByte(),r;if(e>=224)r=e-256;else if(e<192)if(e<128)r=e;else if(e<144){let n=e-128;if(n!==0){this.pushMapState(n),this.complete();continue e}else r={}}else if(e<160){let n=e-144;if(n!==0){this.pushArrayState(n),this.complete();continue e}else r=[]}else{let n=e-160;r=this.decodeString(n,0)}else if(e===192)r=null;else if(e===194)r=!1;else if(e===195)r=!0;else if(e===202)r=this.readF32();else if(e===203)r=this.readF64();else if(e===204)r=this.readU8();else if(e===205)r=this.readU16();else if(e===206)r=this.readU32();else if(e===207)this.useBigInt64?r=this.readU64AsBigInt():r=this.readU64();else if(e===208)r=this.readI8();else if(e===209)r=this.readI16();else if(e===210)r=this.readI32();else if(e===211)this.useBigInt64?r=this.readI64AsBigInt():r=this.readI64();else if(e===217){let n=this.lookU8();r=this.decodeString(n,1)}else if(e===218){let n=this.lookU16();r=this.decodeString(n,2)}else if(e===219){let n=this.lookU32();r=this.decodeString(n,4)}else if(e===220){let n=this.readU16();if(n!==0){this.pushArrayState(n),this.complete();continue e}else r=[]}else if(e===221){let n=this.readU32();if(n!==0){this.pushArrayState(n),this.complete();continue e}else r=[]}else if(e===222){let n=this.readU16();if(n!==0){this.pushMapState(n),this.complete();continue e}else r={}}else if(e===223){let n=this.readU32();if(n!==0){this.pushMapState(n),this.complete();continue e}else r={}}else if(e===196){let n=this.lookU8();r=this.decodeBinary(n,1)}else if(e===197){let n=this.lookU16();r=this.decodeBinary(n,2)}else if(e===198){let n=this.lookU32();r=this.decodeBinary(n,4)}else if(e===212)r=this.decodeExtension(1,0);else if(e===213)r=this.decodeExtension(2,0);else if(e===214)r=this.decodeExtension(4,0);else if(e===215)r=this.decodeExtension(8,0);else if(e===216)r=this.decodeExtension(16,0);else if(e===199){let n=this.lookU8();r=this.decodeExtension(n,1)}else if(e===200){let n=this.lookU16();r=this.decodeExtension(n,2)}else if(e===201){let n=this.lookU32();r=this.decodeExtension(n,4)}else throw new Ns(`Unrecognized type byte: ${nv(e)}`);this.complete();let s=this.stack;for(;s.length>0;){let n=s.top();if(n.type===lI)if(n.array[n.position]=r,n.position++,n.position===n.size)r=n.array,s.release(n);else continue e;else if(n.type===Ag){if(r==="__proto__")throw new Ns("The key __proto__ is not allowed");n.key=this.mapKeyConverter(r),n.type=dH;continue e}else if(n.map[n.key]=r,n.readCount++,n.readCount===n.size)r=n.map,s.release(n);else{n.key=null,n.type=Ag;continue e}}return r}}readHeadByte(){return this.headByte===kg&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=kg}readArraySize(){let e=this.readHeadByte();switch(e){case 220:return this.readU16();case 221:return this.readU32();default:{if(e<160)return e-144;throw new Ns(`Unrecognized array type byte: ${nv(e)}`)}}}pushMapState(e){if(e>this.maxMapLength)throw new Ns(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new Ns(`Max length exceeded: array length (${e}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(e)}decodeString(e,r){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(e,r):this.decodeBinary(e,r)}decodeUtf8String(e,r){if(e>this.maxStrLength)throw new Ns(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+r+e)throw cH;let s=this.pos+r,n;return this.stateIsMapKey()&&this.keyDecoder?.canBeCached(e)?n=this.keyDecoder.decode(this.bytes,s,e):n=nH(this.bytes,s,e),this.pos+=r+e,n}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===Ag:!1}decodeBinary(e,r){if(e>this.maxBinLength)throw new Ns(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+r))throw cH;let s=this.pos+r,n=this.bytes.subarray(s,s+e);return this.pos+=r+e,n}decodeExtension(e,r){if(e>this.maxExtLength)throw new Ns(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);let s=this.view.getInt8(this.pos+r),n=this.decodeBinary(e,r+1);return this.extensionCodec.decode(n,s,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){let e=this.view.getUint8(this.pos);return this.pos++,e}readI8(){let e=this.view.getInt8(this.pos);return this.pos++,e}readU16(){let e=this.view.getUint16(this.pos);return this.pos+=2,e}readI16(){let e=this.view.getInt16(this.pos);return this.pos+=2,e}readU32(){let e=this.view.getUint32(this.pos);return this.pos+=4,e}readI32(){let e=this.view.getInt32(this.pos);return this.pos+=4,e}readU64(){let e=oH(this.view,this.pos);return this.pos+=8,e}readI64(){let e=rv(this.view,this.pos);return this.pos+=8,e}readU64AsBigInt(){let e=this.view.getBigUint64(this.pos);return this.pos+=8,e}readI64AsBigInt(){let e=this.view.getBigInt64(this.pos);return this.pos+=8,e}readF32(){let e=this.view.getFloat32(this.pos);return this.pos+=4,e}readF64(){let e=this.view.getFloat64(this.pos);return this.pos+=8,e}};function fI(t,e){return new ov(e).decode(t)}var dOe=globalThis.require??(0,AH.createRequire)(L),IH=15e3,RH=45e3,PH=12e4,_I="platform",SI="activation",EI="desired.activation";function CI(t){if(typeof t=="string"&&t.length>0)return t;if(t&&typeof t=="object"){let e=t.note;if(typeof e=="string"&&e.length>0)return e}}var iie=[{state:"still-activating",afterMs:15e3},{state:"cold-boot",afterMs:45e3},{state:"degraded",afterMs:12e4}],TI=class{constructor(t){this._options=t,this._offPhase=t.onPhase(e=>{if(!this._stopped)if(e?.name==="live"){if(this._liveAt===null){this._liveAt=Date.now();for(let r of this._watches.values())this._arm(r)}}else(e?.name==="error"||e?.name==="paused")&&this._park()})}_options;_watches=new Map;_handlers=new Set;_liveAt=null;_stopped=!1;_offPhase=null;_park(){this._liveAt=null;for(let t of this._watches.values())if(!t.done){for(let e of t.timers)clearTimeout(e);t.timers=[],t.startedAt=null,t.lastEvent=null}}watch(t,e){if(this._stopped||this._watches.has(t))return;let r={name:t,stream:e,startedAt:null,done:!1,timers:[],cleanups:[],lastEvent:null};this._watches.set(t,r),this._hookFirstMediaSignals(r),!r.done&&this._liveAt!==null&&this._arm(r)}unwatch(t){let e=this._watches.get(t);!e||e.done||this._settle(e)}onActivation(t){for(let e of this._watches.values())!e.done&&e.lastEvent&&t(e.lastEvent);return this._handlers.add(t),()=>this._handlers.delete(t)}dispose(){if(!this._stopped){this._stopped=!0;for(let t of this._watches.values())t.done||this._settle(t);this._offPhase?.(),this._offPhase=null,this._handlers.clear()}}_hookFirstMediaSignals(t){let e=r=>{if(!(!r||t.done)){if(r.muted===!0&&typeof r.addEventListener=="function"){let s=()=>this._firstMedia(t);r.addEventListener("unmute",s,{once:!0}),t.cleanups.push(()=>r.removeEventListener?.("unmute",s));return}this._firstMedia(t)}};t.cleanups.push(t.stream.on("track",r=>e(r))),this._options.onData&&t.cleanups.push(this._options.onData(t.name,()=>this._firstMedia(t))),e(t.stream.track)}_arm(t){if(!(t.done||t.startedAt!==null||this._stopped)){t.startedAt=Date.now(),this._emit(t,"activating",0);for(let e of iie){let r=setTimeout(()=>{t.done||this._stopped||this._emit(t,e.state,Date.now()-t.startedAt)},e.afterMs);r.unref?.(),t.timers.push(r)}}}_firstMedia(t){if(t.done||this._stopped)return;let e=t.startedAt;this._settle(t),this._emit(t,"first-media",e===null?0:Date.now()-e)}_settle(t){t.done=!0;for(let e of t.timers)clearTimeout(e);t.timers=[];for(let e of t.cleanups.splice(0))e()}_emit(t,e,r){let s={state:e,elapsedMs:r,stream:t.name},n=CI(this._options.hint());n!==void 0&&(s.hint=n),t.lastEvent=s;for(let i of Array.from(this._handlers))i(s)}},Ys=class extends Error{status;code;constructor(t,e,r=e>0?`http_${e}`:"runtime_artifacts_error",s){super(t),this.name="RuntimeArtifactsError",this.status=e,this.code=r,s!==void 0&&(this.cause=s),Object.setPrototypeOf(this,new.target.prototype)}},kI=class extends Ys{constructor(t="[urun] runtime artifacts: unauthorized",e="unauthorized"){super(t,401,e),this.name="RuntimeArtifactsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},AI=class extends Ys{constructor(t="[urun] runtime artifacts: not found",e="not_found"){super(t,404,e),this.name="RuntimeArtifactNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}};function xI(t){return{baseUrl:t.baseUrl,fallbackUrls:t.fallbackUrls,orgId:t.orgId,jwt:t.jwt,getAccessToken:t.getAccessToken,authProvider:t.authProvider}}function DH(t){return new Rg(t)}var Rg=class{_options;constructor(t){this._options=t}async list(t){let e=uH(await this._request(t,"")).artifacts;if(!Array.isArray(e))throw new Ys("[urun] runtime artifacts: response missing `artifacts`",0,"bad_response");return e.map(lH)}async getDownloadUrl(t,e){let r=uH(await this._request(e,`/${encodeURIComponent(t)}/download`)),s=r.download_url;if(typeof s!="string"||!aie(s))throw new Ys("[urun] runtime artifacts: response missing HTTPS download_url",0,"bad_response");return{artifact:lH(r.artifact),downloadUrl:s}}async _request(t,e){let r=Sg(this._options.baseUrl,this._options.fallbackUrls),s=null;for(let n of r)try{return await this._requestFromBase(n,t,e)}catch(i){if(s=i instanceof Error?i:new Error(String(i)),s instanceof Ys&&cie(s.status))throw s}throw s??new Ys("[urun] runtime artifacts request failed",0)}async _requestFromBase(t,e,r){let s=`${Tr(t)}/api/sessions/${encodeURIComponent(e)}/artifacts${r}`,n=await this._resolveToken(),i=await fetch(s,{method:"GET",headers:this._headers(n)});if(i.status===401&&this._options.getAccessToken){let o=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});o&&o!==n&&(n=o,i=await fetch(s,{method:"GET",headers:this._headers(n)}))}if(!i.ok){let{code:o,message:a}=await this._readError(i,t);throw die(i.status,o,a)}try{return await i.json()}catch(o){throw new Ys(`[urun] runtime artifacts: invalid JSON response from ${Tr(t)}`,0,"bad_response",o)}}async _resolveToken(){return this._options.getAccessToken?await this._options.getAccessToken()??void 0:this._options.jwt}_headers(t){let e={Accept:"application/json","X-Tenant-Id":this._options.orgId,"X-Auth-Provider":this._options.authProvider||"default"};return t&&(e.Authorization=`Bearer ${t}`),e}async _readError(t,e){let r=Tr(e);try{let s=(await t.json()).error;if(s&&typeof s=="object"){let{code:n,message:i}=s;return{code:typeof n=="string"&&n.length>0?n:`http_${t.status}`,message:typeof i=="string"&&i.length>0?`[urun] runtime artifacts request failed at ${r}: ${i}`:`[urun] runtime artifacts request failed at ${r}: HTTP ${t.status}`}}}catch{}return{code:`http_${t.status}`,message:`[urun] runtime artifacts request failed at ${r}: HTTP ${t.status}`}}};function lH(t){if(!t||typeof t!="object")throw new Ys("[urun] runtime artifacts: malformed artifact",0,"malformed_artifact");let e=t,r=ra(e,"artifact_id")||ra(e,"id"),s=ra(e,"filename"),n=ra(e,"kind"),i=ra(e,"status")||"ready",o=oie(e,"size_bytes"),a=ra(e,"sha256");if(!r||!s||!n||o==null||!a)throw new Ys("[urun] runtime artifacts: malformed artifact metadata",0,"malformed_artifact");return{artifactId:r,kind:n,filename:s,contentType:ra(e,"content_type")||"application/octet-stream",sizeBytes:o,sha256:a,status:i,createdAt:ra(e,"created_at"),expiresAt:ra(e,"expires_at")}}function ra(t,e){let r=t[e];return typeof r=="string"&&r.length>0?r:void 0}function oie(t,e){let r=t[e];return typeof r=="number"&&Number.isFinite(r)&&Number.isInteger(r)&&r>=0?r:void 0}function aie(t){try{return new URL(t).protocol==="https:"}catch{return!1}}function cie(t){return t===401||t===403}function die(t,e,r){return t===401?new kI(r,e):t===404?new AI(r,e):new Ys(r,t,e)}function uH(t){if(!t||typeof t!="object"||Array.isArray(t))throw new Ys("[urun] runtime artifacts: malformed response",0,"bad_response");return t}var Xi=class extends Error{status;code;constructor(t,e){super(t),this.name="RecordingsError",this.status=e.status,this.code=e.code,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,new.target.prototype)}},cv=class extends Xi{constructor(t="[urun] recordings: unauthorized",e="unauthorized"){super(t,{status:401,code:e}),this.name="RecordingsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},II=class extends Xi{constructor(t="[urun] recordings: not found",e="not_found"){super(t,{status:404,code:e}),this.name="RecordingNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}},RI=class extends Xi{constructor(t="[urun] recordings: retain requires a temp recording",e="retain_not_temp"){super(t,{status:409,code:e}),this.name="RetainNotTempError",Object.setPrototypeOf(this,new.target.prototype)}},PI=class extends Xi{constructor(t="[urun] recordings: pin requires an active temp recording",e="pin_requires_active_temp"){super(t,{status:409,code:e}),this.name="PinRequiresActiveTempError",Object.setPrototypeOf(this,new.target.prototype)}},DI=class extends Xi{constructor(t="[urun] recordings: recording is permanent and locked",e="permanent_locked"){super(t,{status:409,code:e}),this.name="PermanentLockedError",Object.setPrototypeOf(this,new.target.prototype)}},Pg=class extends Xi{constructor(t="[urun] recordings: invalid retention duration",e="bad_duration",r=400){super(t,{status:r,code:e}),this.name="InvalidDurationError",Object.setPrototypeOf(this,new.target.prototype)}};function dv(t){return/^(\d+[smhdw])+$/.test(t)}function BH(t){if(t==="pin")return{action:"pin"};if(dv(t))return{action:"retain",duration:t};throw new Pg(`[urun] recordings: "${t}" is not a duration or "pin"`)}function lie(t,e,r){let s=r||e||`HTTP ${t}`;if(t===401)return new cv(s,e??"unauthorized");if(t===404)return new II(s,e??"not_found");if(t===400)return new Pg(s,e??"bad_request",400);if(t===409)switch(e){case"retain_not_temp":return new RI(s,e);case"pin_requires_active_temp":return new PI(s,e);case"permanent_locked":return new DI(s,e)}return new Xi(s,{status:t,code:e??`http_${t}`})}var lv=class{constructor(t){this._options=t,this._base=`${t.functionsUrl.replace(/\/+$/,"")}/recordings`}_options;_base;async list(t){let e=(await this._request("GET","",{params:t?{session_id:t}:void 0})).recordings;return Array.isArray(e)?e:[]}async get(t){return this._one(await this._request("GET",`/${encodeURIComponent(t)}`))}async retain(t,e){if(!dv(e))throw new Pg(`[urun] recordings: "${e}" is not a valid retention duration`);return this._one(await this._request("POST",`/${encodeURIComponent(t)}/retain`,{body:{duration:e}}))}async pin(t){return this._one(await this._request("POST",`/${encodeURIComponent(t)}/pin`))}async unpin(t){return this._one(await this._request("POST",`/${encodeURIComponent(t)}/unpin`))}async permanent(t){return this._one(await this._request("POST",`/${encodeURIComponent(t)}/permanent`))}async delete(t){return this._one(await this._request("POST",`/${encodeURIComponent(t)}/delete`))}_one(t){let e=t.recording;if(!e||typeof e!="object")throw new Xi("[urun] recordings: response missing `recording`",{status:0,code:"bad_response"});return e}async _request(t,e,r={}){let s=this._buildUrl(e,r.params),n=await this._resolveToken(),i=await this._fetch(s,t,n,r.body);if(i.status===401&&this._options.getAccessToken){let o=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});o&&o!==n&&(n=o,i=await this._fetch(s,t,n,r.body))}if(!i.ok){let{code:o,message:a}=await this._readError(i);throw lie(i.status,o,a)}return this._readJson(i)}_buildUrl(t,e){let r=`${this._base}${t}`,s=Object.entries(e??{}).filter(([,n])=>n!=null&&n!=="").map(([n,i])=>`${encodeURIComponent(n)}=${encodeURIComponent(i)}`).join("&");return s&&(r+=`?${s}`),r}_fetch(t,e,r,s){let n={Authorization:`Bearer ${r}`,apikey:r,Accept:"application/json","X-Tenant-Id":this._options.orgId};this._options.authProvider&&(n["X-Auth-Provider"]=this._options.authProvider);let i={method:e,headers:n};return s!==void 0&&(n["Content-Type"]="application/json",i.body=JSON.stringify(s)),fetch(t,i)}async _resolveToken(){if(this._options.getAccessToken){let e=await this._options.getAccessToken();if(e)return e}let t=this._options.jwt??this._options.apiKey;if(!t)throw new cv("[urun] recordings: no credential \u2014 provide one of apiKey, jwt, or getAccessToken");return t}async _readJson(t){try{return await t.json()}catch{return{}}}async _readError(t){try{let e=(await t.json()).error;if(e&&typeof e=="object"){let{code:r,message:s}=e;return{code:typeof r=="string"?r:void 0,message:typeof s=="string"?s:`HTTP ${t.status}`}}}catch{}return{message:`HTTP ${t.status}`}}};function LH(t){return new lv(t)}var OH=1e3,NH=12e3;function BI(t,e,r={}){let s=null,n=0,i=0,o=null,a=-1,c=()=>{let f=t.get("desired.billing.generationSeconds");if(typeof f!="number"||!Number.isFinite(f)||f<=0)return null;let b=t.get("desired.billing.epoch"),w=t.get("desired.billing.updatedAtMs");return{seconds:f,epoch:typeof b=="number"&&Number.isFinite(b)?b:0,updatedAtMs:typeof w=="number"&&Number.isFinite(w)?w:null}},d=()=>{if(s===null)return null;let f=Math.min(Math.max(0,Date.now()-n),i);return s+f/1e3},u=()=>{let f=r.creditsPerSecond;if(typeof f=="number"&&Number.isFinite(f)&&f>0)return f;let b=t.get("desired.billing.creditsPerSecond");return typeof b=="number"&&Number.isFinite(b)&&b>0?b:null},l=()=>{let f=d();if(f===null)return;let b=Math.floor(f);if(b<=a)return;a=b;let w={seconds:b},S=u();S!==null&&(w.estimatedCredits=b*S),e(w)},h=f=>{n=Date.now();let b=f===null?0:Math.max(0,n-f);i=Math.max(0,12e3-b)},p=()=>{let f=c();if(f!==null){if(o!==null&&f.epoch!==o){o=f.epoch,s=f.seconds,a=-1,h(f.updatedAtMs),l();return}s!==null&&f.seconds<=s||(o=f.epoch,s=f.seconds,h(f.updatedAtMs),l())}};p();let m=t.on("change",p),_=setInterval(l,1e3);return _.unref?.(),()=>{clearInterval(_),m()}}var LI="activity",OI="visibility",UH=15e3,av=["pointerdown","pointermove","keydown","wheel","touchstart"];function NI(t){let e=t.now??Date.now,r=t.mode==="explicit",s=r?null:t.windowTarget!==void 0?t.windowTarget:typeof window<"u"?window:null,n=r?null:t.documentTarget!==void 0?t.documentTarget:typeof document<"u"?document:null,i=!1,o,a=()=>{if(i)return;let h=e();if(!(o!==void 0&&h-o<15e3)){o=h;try{t.awareness.setLocalStateField(LI,{at:h})}catch{}}},c=()=>{if(!(i||!n||n.visibilityState===void 0))try{t.awareness.setLocalStateField(OI,n.visibilityState)}catch{}},d=()=>a(),u=()=>{c(),(!n||n.visibilityState===void 0||n.visibilityState==="visible")&&a()};if(s)for(let h of av)s.addEventListener(h,d,{passive:!0,capture:!0});n&&n.addEventListener("visibilitychange",u);let l=null;return!r&&t.isProducing&&(l=setInterval(()=>{if(!i)try{t.isProducing?.()&&a()}catch{}},15e3),l.unref?.()),a(),c(),{touch:a,dispose(){if(!i){if(i=!0,s)for(let h of av)s.removeEventListener(h,d,{capture:!0});n&&n.removeEventListener("visibilitychange",u),l&&(clearInterval(l),l=null)}}}}var UI="user_activity",MI="focus",MH=3e4;function hH(t){switch(t){case"connecting":case"renegotiating":return"connecting";case"connected":return"ready";case"reconnecting":case"disconnected":case"failed":return"transient_failure"}}var jI=class{_awareness;_now;_win;_state="idle";_stateHandlers=new Set;_transportUnsubs=new Set;_disposed=!1;_counts={typing:0,pointer:0,tty:0,consumer_reads:0};_inflight=0;_visibility;_focus;_lastSignalAt;_lastPublishedAt;_trailing=null;_onWindowFocus=null;_onWindowBlur=null;constructor(t={}){this._awareness=t.awareness??null,this._now=t.now??Date.now,this._win=t.windowTarget!==void 0?t.windowTarget:typeof window<"u"?window:null;let e=t.documentTarget!==void 0?t.documentTarget:typeof document<"u"?document:null;this._win&&e&&typeof e.hasFocus=="function"&&(this._onWindowFocus=()=>this.setFocus("focused"),this._onWindowBlur=()=>this.setFocus("unfocused"),this._win.addEventListener("focus",this._onWindowFocus),this._win.addEventListener("blur",this._onWindowBlur),this.setFocus(e.hasFocus()?"focused":"unfocused"))}get state(){return this._state}onState(t){return this._stateHandlers.add(t),()=>this._stateHandlers.delete(t)}transportConnecting(){this._setState("connecting")}transportReady(){this._setState("ready")}transportClosed(){this._setState("transient_failure")}attachTransport(t){if(this._disposed)return()=>{};this._setState(hH(t.state));let e=t.on("stateChange",s=>{this._setState(hH(s))}),r=()=>{e(),this._transportUnsubs.delete(r)};return this._transportUnsubs.add(r),r}_setState(t){if(!(this._disposed||t===this._state)){this._state=t;for(let e of this._stateHandlers)try{e(t)}catch{}}}interaction(t,e=1){this._disposed||!Number.isFinite(e)||e<=0||t==="pointer"&&this._focus==="unfocused"||(this._counts[t]+=e,this._signal())}consumerRead(t=1){this._disposed||!Number.isFinite(t)||t<=0||(this._counts.consumer_reads+=t,this._signal())}get inflight(){return this._inflight}workBegin(){if(this._disposed)return()=>{};this._inflight+=1,this._inflight===1&&this._publishNow();let t=!1;return()=>{t||this._disposed||(t=!0,this._inflight-=1,this._inflight===0&&this._publishNow())}}setVisibility(t){this._disposed||(this._visibility=t)}setFocus(t){if(!(this._disposed||t===this._focus)){this._focus=t;try{this._awareness?.setLocalStateField(MI,t)}catch{}}}_signal(){this._lastSignalAt=this._now();let t=this._lastPublishedAt===void 0?1/0:this._lastSignalAt-this._lastPublishedAt;if(t>=3e4){this._publishNow();return}if(this._trailing)return;let e=Math.max(3e4-t,0);this._trailing=setTimeout(()=>{this._trailing=null,this._disposed||this._publishNow()},e),this._trailing.unref?.()}_publishNow(){this._trailing&&(clearTimeout(this._trailing),this._trailing=null),this._lastPublishedAt=this._now();let t={at:this._lastSignalAt??this._lastPublishedAt,counts:{...this._counts},inflight:this._inflight};this._visibility!==void 0&&(t.visibility=this._visibility),this._focus!==void 0&&(t.focus=this._focus);try{this._awareness?.setLocalStateField(UI,t)}catch{}}dispose(){if(!this._disposed){for(let t of Array.from(this._transportUnsubs))t();this._transportUnsubs.clear(),this._win&&(this._onWindowFocus&&this._win.removeEventListener("focus",this._onWindowFocus),this._onWindowBlur&&this._win.removeEventListener("blur",this._onWindowBlur)),this._onWindowFocus=null,this._onWindowBlur=null,this._trailing&&(clearTimeout(this._trailing),this._trailing=null),this._state="idle",this._stateHandlers.clear(),this._disposed=!0}}},jH=250;function $I(t){if(typeof document>"u"||typeof window>"u"||typeof document.addEventListener!="function"||typeof window.addEventListener!="function")return()=>{};let e=0,r=()=>{if(document.visibilityState==="hidden")return;let s=Date.now();s-e<250||(e=s,t())};return document.addEventListener("visibilitychange",r),window.addEventListener("pageshow",r),window.addEventListener("focus",r),()=>{document.removeEventListener("visibilitychange",r),window.removeEventListener("pageshow",r),window.removeEventListener("focus",r)}}function FI(t){if(typeof window>"u"||typeof window.addEventListener!="function")return()=>{};let e=!1,r=s=>{s.persisted||e||(e=!0,t())};return window.addEventListener("pagehide",r),()=>{window.removeEventListener("pagehide",r)}}function HI(t){if(typeof window>"u"||typeof window.addEventListener!="function")return()=>{};let e=r=>{t()&&(r.preventDefault(),r.returnValue="")};return window.addEventListener("beforeunload",e),()=>{window.removeEventListener("beforeunload",e)}}var fH="video/mp4";function qI(t,e={}){let r=e.timesliceMs??1e3,s=null,n=null,i=!1,o=(a,c,d)=>{let u=typeof MediaRecorder>"u"?void 0:MediaRecorder;if(!u)throw new Error("[urun] stream.chunks(): MediaRecorder is unavailable in this runtime. Pass { source } to chunks() to inject a byte-tap (e.g. a Node/werift consumer).");let l=e.mimeType??(typeof u.isTypeSupported=="function"&&u.isTypeSupported(fH)?fH:void 0),h=new MediaStream([a]),p=new u(h,l?{mimeType:l}:void 0);s=p;let m=Promise.resolve();p.ondataavailable=_=>{let f=_.data;i||!f||f.size===0||(m=m.then(async()=>{let b=new Uint8Array(await f.arrayBuffer());i||c(b)}))},p.onstop=()=>{m.then(()=>{i||d()})},p.onerror=()=>{m.then(()=>{i||d()})},p.start(r)};return{start(a,c){if(s||i)return;let d=t.track();if(d){o(d,a,c);return}n=t.onTrack(u=>{!u||s||i||(n?.(),n=null,o(u,a,c))})},stop(){if(i)return;i=!0,n?.(),n=null;let a=s;if(s=null,a&&a.state!=="inactive")try{a.stop()}catch{}}}}function uie(t){let e=t;return typeof e[Symbol.asyncIterator]=="function"||(e[Symbol.asyncIterator]=function(){let r=t.getReader();return{next(){return r.read()},async return(){try{await r.cancel()}catch{}try{r.releaseLock()}catch{}return{value:void 0,done:!0}},[Symbol.asyncIterator](){return this}}}),e}function hie(t,e){let r=null,s=!1,n=!1,i=new ReadableStream({pull(o){s||(s=!0,r=t(e),r.start(a=>{if(!n)try{o.enqueue(a)}catch{}},()=>{if(!n){n=!0;try{o.close()}catch{}}}))},cancel(){n=!0,r?.stop(),r=null}},new CountQueuingStrategy({highWaterMark:0}));return uie(i)}var VI=65536;function zI(t){let e=dI(t),r=new Uint8Array(4+e.byteLength);return new DataView(r.buffer).setUint32(0,e.byteLength,!0),r.set(e,4),r}var WI=class{buf=new Uint8Array(0);push(t){if(t.byteLength>0){let r=new Uint8Array(this.buf.byteLength+t.byteLength);r.set(this.buf),r.set(t,this.buf.byteLength),this.buf=r}let e=[];for(;this.buf.byteLength>=4;){let r=new DataView(this.buf.buffer,this.buf.byteOffset).getUint32(0,!0);if(r>VI)throw new Error("[urun] wt control frame too large");if(this.buf.byteLength<4+r)break;let s=this.buf.subarray(4,4+r);this.buf=this.buf.subarray(4+r),e.push(Object.assign(fI(s),{raw:s}))}return e}};function fie(t,e){let r=new DataView(t.buffer,t.byteOffset,t.byteLength),s=r.getUint8(0),n=(s&240)===128,i=s===222;if(!n&&!i&&s!==223)throw new Error("[urun] mirrorControlBody: source control frame is not a msgpack map");let o=n?s&15:i?r.getUint16(1,!1):r.getUint32(1,!1),a=n?1:i?3:5,c=[];c.push(t.subarray(0,a));for(let h=0;h<o;h++){let p=a,m=Ig(t,r,a);a=m.end;let _=Ig(t,r,a).end;if(pie(r.getUint8(p))){let f=r.getUint8(p),b=(f&224)===160?1:f===217?2:f===218?3:5;if(new TextDecoder().decode(t.subarray(p+b,m.end))==="t"){c.push(t.subarray(p,m.end));let w=new TextEncoder().encode(e);if(w.byteLength>31)throw new Error("[urun] mirrorControlBody: replacement tag too long");c.push(new Uint8Array([160|w.byteLength]),w)}else c.push(t.subarray(p,_))}else c.push(t.subarray(p,_));a=_}let d=c.reduce((h,p)=>h+p.byteLength,0),u=new Uint8Array(d),l=0;for(let h of c)u.set(h,l),l+=h.byteLength;return u}function pie(t){return(t&224)===160?!0:t===217||t===218||t===219}function Ig(t,e,r){let s=e.getUint8(r),n=r;if(s<=127||s>=224)return{start:n,end:r+1};if((s&224)===160)return{start:n,end:r+1+(s&31)};if((s&240)===128||(s&240)===144){let o=s&15;r+=1;let a=(s&240)===128?o*2:o;for(let c=0;c<a;c++)r=Ig(t,e,r).end;return{start:n,end:r}}let i={192:0,194:0,195:0,204:1,205:2,206:4,207:8,208:1,209:2,210:4,211:8,202:4,203:8};if(i[s]!==void 0)return{start:n,end:r+1+i[s]};if(s===217||s===196)return{start:n,end:r+2+e.getUint8(r+1)};if(s===218||s===197)return{start:n,end:r+3+e.getUint16(r+1,!1)};if(s===219||s===198)return{start:n,end:r+5+e.getUint32(r+1,!1)};if(s===220||s===221){let o=s===220?e.getUint16(r+1,!1):e.getUint32(r+1,!1);r+=s===220?3:5;for(let a=0;a<o;a++)r=Ig(t,e,r).end;return{start:n,end:r}}if(s===222||s===223){let o=s===222?e.getUint16(r+1,!1):e.getUint32(r+1,!1);r+=s===222?3:5;for(let a=0;a<o*2;a++)r=Ig(t,e,r).end;return{start:n,end:r}}throw new Error(`[urun] mirrorControlBody: unsupported msgpack prefix 0x${s.toString(16)} at byte ${n}`)}var ei=12,wI=1,mie=0,$H=1,gie=2;function uv(t){let e=t.getUint8(8);return{groupId:t.getUint32(0,!0),frameSeq:t.getUint32(4,!0),keyframe:(e&wI)===wI,fragIndex:t.getUint8(9),fragCount:t.getUint8(10),lane:t.getUint8(11)}}function KI(t){let e=new Uint8Array(ei),r=new DataView(e.buffer);return r.setUint32(0,t.groupId,!0),r.setUint32(4,t.frameSeq,!0),r.setUint8(8,t.keyframe?wI:0),r.setUint8(9,t.fragIndex),r.setUint8(10,t.fragCount),r.setUint8(11,t.lane??mie),e}var yie=100,pH=100,GI=class{constructor(t,e={}){this.cb=t,this.now=e.now??(()=>performance.now()),this.debounceMs=e.keyframeRequestDebounceMs??yie}cb;pending=new Map;newestGroupSeen=-1;newestFrameDelivered=-1;needKeyframe=!0;kfRequestedAt=-1/0;now;debounceMs;bytesInWindow=0;framesDelivered=0;framesAbandoned=0;push(t){if(t.byteLength<ei)return;let e=uv(new DataView(t.buffer,t.byteOffset));if(this.bytesInWindow+=t.byteLength,this.isSourceRestart(e.groupId,e.frameSeq))this.resync(e.groupId);else if(e.groupId<this.newestGroupSeen||(e.groupId>this.newestGroupSeen&&(this.framesAbandoned+=this.pending.size,this.pending.clear(),this.newestGroupSeen=e.groupId,this.needKeyframe=!0),e.frameSeq<=this.newestFrameDelivered))return;let r=this.pending.get(e.frameSeq);if(r||(r={groupId:e.groupId,keyframe:e.keyframe,fragCount:e.fragCount,received:0,chunks:new Array(e.fragCount)},this.pending.set(e.frameSeq,r)),!r.chunks[e.fragIndex]){r.chunks[e.fragIndex]=t.subarray(ei),r.received++,r.received===r.fragCount&&(this.pending.delete(e.frameSeq),this.deliver(e.frameSeq,r));for(let s of this.pending.keys())s<e.frameSeq-1&&(this.pending.delete(s),this.framesAbandoned++)}}isSourceRestart(t,e){return this.newestGroupSeen<0?!1:t<this.newestGroupSeen-pH?!0:t!==this.newestGroupSeen?!1:e<this.newestFrameDelivered-pH}resync(t){this.framesAbandoned+=this.pending.size,this.pending.clear(),this.newestGroupSeen=t,this.newestFrameDelivered=-1,this.needKeyframe=!0,this.requestKeyframe()}requireKeyframe(){this.needKeyframe=!0}drainWindow(){let t={bytes:this.bytesInWindow,delivered:this.framesDelivered,abandoned:this.framesAbandoned};return this.bytesInWindow=0,this.framesDelivered=0,this.framesAbandoned=0,t}deliver(t,e){if(this.needKeyframe&&!e.keyframe){this.framesAbandoned++,this.requestKeyframe();return}if(t!==this.newestFrameDelivered+1&&!e.keyframe&&this.newestFrameDelivered>=0){this.needKeyframe=!0,this.framesAbandoned++,this.requestKeyframe();return}let r=e.chunks.reduce((i,o)=>i+o.byteLength,0),s=new Uint8Array(r),n=0;for(let i of e.chunks)s.set(i,n),n+=i.byteLength;this.needKeyframe=!1,this.newestFrameDelivered=t,this.framesDelivered++,this.cb.onFrame({seq:t,groupId:e.groupId,keyframe:e.keyframe,data:s})}requestKeyframe(){let t=this.now();t-this.kfRequestedAt<this.debounceMs||(this.kfRequestedAt=t,this.cb.onKeyframeNeeded())}},bie=/^avc[13]\.[0-9a-fA-F]{6}$/;function xie(t){return bie.test(t)?null:`codec ${JSON.stringify(t)} is not a fully-qualified WebCodecs H.264 string \u2014 the WT pipeline carries H.264, which VideoDecoder.configure needs as "avc1.PPCCLL" (e.g. "avc1.42E01F"); RTP MIMEs ("video/H264") and bare names ("h264") are rejected by WebCodecs as "Unknown or ambiguous codec name"`}function mH(t,e){let r=xie(t);if(r)throw new Error(`[urun] webtransport ${e} ${r}`)}var XI=1,YI=class{buf=new Uint8Array(0);name=null;ended=!1;get streamName(){return this.name}push(t){if(t.byteLength>0){let r=new Uint8Array(this.buf.byteLength+t.byteLength);r.set(this.buf),r.set(t,this.buf.byteLength),this.buf=r}if(this.name===null){if(this.buf.byteLength<2)return[];let r=this.buf[0];if(r!==XI)throw new Error(`[urun] wt data stream: unknown header version 0x${r.toString(16)} \u2014 rejecting stream`);let s=this.buf[1];if(s===0)throw new Error("[urun] wt data stream: empty stream name in header \u2014 rejecting stream");if(this.buf.byteLength<2+s)return[];this.name=new TextDecoder().decode(this.buf.subarray(2,2+s)),this.buf=this.buf.subarray(2+s)}let e=[];for(;this.buf.byteLength>=4;){let r=new DataView(this.buf.buffer,this.buf.byteOffset).getUint32(0,!0);if(this.buf.byteLength<4+r)break;if(this.ended)throw new Error(`[urun] wt data stream "${this.name}": envelope after the END envelope \u2014 rejecting stream`);let s=Z1(this.buf.subarray(4,4+r));this.buf=this.buf.subarray(4+r),s===Cl&&(this.ended=!0),e.push({name:this.name,payload:s})}if(this.ended&&this.buf.byteLength>0)throw new Error(`[urun] wt data stream "${this.name}": trailing bytes after the END envelope \u2014 rejecting stream`);return e}finish(){if(this.ended&&this.buf.byteLength===0)return;let t=this.name===null?"<incomplete header>":`"${this.name}"`;throw this.buf.byteLength>0?new Error(`[urun] wt data stream ${t}: truncated \u2014 FIN mid-${this.name===null?"header":"envelope"} (${this.buf.byteLength} dangling byte(s), no END envelope)`):new Error(`[urun] wt data stream ${t}: truncated \u2014 FIN without an END envelope`)}};async function JI(t,e){let r=t.getReader();for(;;){let{value:s,done:n}=await r.read();if(n)return;s&&wie(s,e).catch(i=>{e.onLaneError(i instanceof Error?i:new Error(String(i)))})}}async function wie(t,e){let r=t.getReader(),s=new YI;try{for(;;){let{value:n,done:i}=await r.read();if(i)break;if(!(!n||n.byteLength===0))for(let{name:o,payload:a}of s.push(n))e.onData(o,a)}s.finish()}catch(n){try{await r.cancel?.(n)}catch{}throw n}}var pI=40,gH=2,kl=48e3,vie=64,_ie=100,Sie=class{constructor(t){this.onFrame=t}onFrame;pending=new Map;newestDelivered=-1;framesDelivered=0;framesAbandoned=0;bytesInWindow=0;push(t){if(t.byteLength<ei)return;let e=uv(new DataView(t.buffer,t.byteOffset));if(this.bytesInWindow+=t.byteLength,this.newestDelivered>=0&&e.frameSeq<this.newestDelivered-_ie)this.framesAbandoned+=this.pending.size,this.pending.clear(),this.newestDelivered=-1;else if(e.frameSeq<=this.newestDelivered)return;if(e.fragCount===0)return;let r=this.pending.get(e.frameSeq);if(!r)for(r={timestamp:e.groupId,fragCount:e.fragCount,received:0,chunks:new Array(e.fragCount)},this.pending.set(e.frameSeq,r);this.pending.size>vie;){let o=1/0;for(let a of this.pending.keys())a<o&&(o=a);this.pending.delete(o),this.framesAbandoned++}if(e.fragIndex>=r.fragCount||r.chunks[e.fragIndex]||(r.chunks[e.fragIndex]=t.subarray(ei),r.received++,r.received<r.fragCount))return;this.pending.delete(e.frameSeq);for(let o of this.pending.keys())o<e.frameSeq&&(this.pending.delete(o),this.framesAbandoned++);let s=r.chunks.reduce((o,a)=>o+(a?.byteLength??0),0),n=new Uint8Array(s),i=0;for(let o of r.chunks)n.set(o,i),i+=o.byteLength;this.newestDelivered=e.frameSeq,this.framesDelivered++,this.onFrame({seq:e.frameSeq,timestamp:r.timestamp,data:n})}drainWindow(){let t={bytes:this.bytesInWindow,delivered:this.framesDelivered,abandoned:this.framesAbandoned};return this.bytesInWindow=0,this.framesDelivered=0,this.framesAbandoned=0,t}},Eie=class{constructor(t,e){this.config=t,this.seam=e;let r=this.seam.jitterBufferTargetMs??pI;Number.isFinite(r)||(E.warn(`[urun] WT audio jitterBufferTargetMs=${r} is not finite \u2014 using default ${pI}ms`),r=pI),this.targetS=Math.max(0,r)/1e3}config;seam;decoder=null;ctx=null;ownsCtx=!1;resumeAttempts=0;resumeInFlight=!1;notRunningFrames=0;dest=null;trackSurfaced=!1;stopped=!1;playhead=0;targetS;contentBaseS=null;wallBaseS=0;reanchorLogged=!1;lastTsS=null;pendingTs=[];bridgeTrack=null;scheduledCount=0;lastScheduledAt=0;rebuildGen=0;rebuildTimes=[];rebuildBudgetLoggedAt=-1e4;lastRemote=null;assembler=new Sie(t=>this.decodeFrame(t));start(){let t=globalThis.AudioDecoder,e=globalThis.AudioContext;if(typeof t!="function")throw new Error("[urun] WT audio lane engaged without AudioDecoder/AudioContext");if(this.seam.ctx)this.ctx=this.seam.ctx,this.ownsCtx=!1;else{if(typeof e!="function")throw new Error("[urun] WT audio lane engaged without AudioDecoder/AudioContext");this.ctx=new e({sampleRate:this.config.sampleRate}),this.ownsCtx=!0}this.dest=this.ctx.createMediaStreamDestination();let r=()=>{this.ctx&&this.ctx.state!=="running"&&this.resumeLoudly("statechange")},s=this.ctx;typeof s.addEventListener=="function"?s.addEventListener("statechange",r):this.ctx.onstatechange=r;try{this.initDecoder(t)}catch(i){throw this.ownsCtx&&this.ctx.close().catch(()=>{}),this.ctx=null,this.dest=null,i}this.trackSurfaced=!0,this.resumeLoudly("start");let n=this.dest.stream.getAudioTracks()[0];if(!n)throw new Error("[urun] playout start produced no bridge track");this.surfaceTrack(n)}resumeLoudly(t){let e=this.ctx;if(!e||!e.resume||this.resumeInFlight)return;let r=e.state!=="running"?++this.resumeAttempts:0;this.resumeInFlight=!0,e.resume().catch(s=>{E.warn(`[urun] WT audio playout context ${t}: resume FAILED (state=${e.state}, attempt=${r||"n/a"}): ${s instanceof Error?s.message:String(s)} \u2014 decoded reply audio would be scheduled into a graph that never renders; retrying per frame`)}).finally(()=>{this.resumeInFlight=!1})}stop(){if(!this.stopped){this.stopped=!0;try{this.seam.renderHop?.setSource(null)}catch{}this.trackSurfaced&&(this.trackSurfaced=!1,this.seam.onTrack(null));try{this.decoder?.close()}catch{}this.ownsCtx&&this.ctx?.close().catch(()=>{})}}initDecoder(t){let e=new t({output:r=>this.schedule(r,this.pendingTs.shift()),error:r=>this.onDecoderError(r)});e.configure({codec:this.config.codec,sampleRate:this.config.sampleRate,numberOfChannels:this.config.channels}),this.decoder=e}decodeFrame(t){let e=globalThis.EncodedAudioChunk;if(typeof e!="function"||this.stopped)return;if(!this.decoder){let s=globalThis.AudioDecoder;if(typeof s!="function")return;try{this.initDecoder(s)}catch{return}}let r=this.decoder;r&&(this.pendingTs.push(t.timestamp),r.decode(new e({type:"key",timestamp:Math.round(t.timestamp*(1e6/kl)),data:t.data})))}schedule(t,e){let r=this.ctx,s=this.dest;if(!r||!s||this.stopped){t.close();return}if(r.state!=="running"){t.close(),this.contentBaseS=null,this.lastTsS=null,this.notRunningFrames++,(this.notRunningFrames===1||this.notRunningFrames%50===0)&&E.warn(`[urun] WT audio playout context not RUNNING (state=${r.state}): dropping decoded frames instead of scheduling into a graph that never renders \u2014 resume re-armed per frame (attempts=${this.resumeAttempts}, dropped=${this.notRunningFrames})`),this.resumeLoudly("per-frame");return}let n=t.numberOfFrames,i=Math.max(1,t.numberOfChannels),o=r.createBuffer(i,n,t.sampleRate);for(let u=0;u<i;u++){let l=new Float32Array(n);t.copyTo(l,{planeIndex:u,format:"f32-planar"}),o.copyToChannel(l,u)}let a=n/t.sampleRate;t.close();let c=r.createBufferSource();c.buffer=o,c.connect(s);let d;if(e===void 0)d=Math.max(this.playhead,r.currentTime+this.targetS);else{this.contentBaseS===null&&(this.contentBaseS=e/kl,this.wallBaseS=r.currentTime+this.targetS),d=this.wallBaseS+e/kl-this.contentBaseS;let u=null;this.lastTsS!==null&&(e<this.lastTsS?(d=r.currentTime+this.targetS,u=`backward ts step ${(this.lastTsS-e/kl).toFixed(3)}s (producer clock reset)`):d>r.currentTime+this.targetS+Math.max(a,this.targetS)&&(u=`forward jump ${(d-r.currentTime).toFixed(3)}s out (lead + ${a.toFixed(3)}s tolerance exceeded \u2014 barge flush / producer re-anchor)`),u&&(this.reanchorLogged||(this.reanchorLogged=!0,E.warn(`[urun] WT audio playout re-anchored on a content-timeline discontinuity: ${u} \u2014 the gap is honest silence at rate 1.0, never a stretch`)),this.contentBaseS=e/kl,this.wallBaseS=r.currentTime+this.targetS,d=this.wallBaseS)),d<r.currentTime&&(this.reanchorLogged||(this.reanchorLogged=!0,E.warn(`[urun] WT audio playout re-anchored ${(r.currentTime-d).toFixed(3)}s past its content position (arrival deficit exceeded the lead) \u2014 the gap is honest silence at rate 1.0, never a catch-up stretch`)),this.contentBaseS=e/kl,this.wallBaseS=r.currentTime+this.targetS,d=this.wallBaseS)}c.start(d),this.scheduledCount++,this.lastScheduledAt=performance.now(),e!==void 0&&(this.lastTsS=e/kl),this.playhead=d+a}armBridgeEndedWatch(t){let e=this.rebuildGen;t.addEventListener?.("ended",()=>{if(!this.stopped&&!(e!==this.rebuildGen||this.bridgeTrack!==t)){E.warn("[urun] WT audio bridge track ENDED while the lane is live \u2014 rebuilding the WebAudio playout surface and re-delivering the bridge track");try{this.rebuildSurface()}catch(r){E.error(`[urun] WT audio bridge rebuild failed \u2014 the reply stays silent until the next lane death re-delivers: ${r instanceof Error?r.message:String(r)}`)}}},{once:!0})}playoutProgress(){return{scheduled:this.scheduledCount,lastScheduledAt:this.lastScheduledAt,surfaced:this.trackSurfaced&&this.bridgeTrack?.readyState!=="ended",droppedNotRunning:this.notRunningFrames,ctxState:this.ctx?.state??"closed"}}rebuildSurface(){if(this.stopped)return;let t=performance.now();if(this.rebuildTimes=this.rebuildTimes.filter(n=>t-n<1e4),this.rebuildTimes.length>=gH){t-this.rebuildBudgetLoggedAt>1e4&&(this.rebuildBudgetLoggedAt=t,E.error(`[urun] WT audio bridge rebuild budget spent (${gH} in 10s) \u2014 standing down; the media-dead playout-progress verdict escalates to a re-dial if the surface stays dead`));return}this.rebuildTimes.push(t),this.rebuildGen++;let e=globalThis.AudioContext;if(typeof e!="function")throw new Error("[urun] AudioContext unavailable for the playout rebuild");let r=new e({sampleRate:this.config.sampleRate});this.ctx=r,r.resume?.().catch(()=>{}),this.dest=r.createMediaStreamDestination(),this.playhead=0,this.contentBaseS=null,this.lastTsS=null,this.trackSurfaced=!0;let s=this.dest.stream.getAudioTracks()[0];if(!s)throw new Error("[urun] rebuilt playout produced no bridge track");this.surfaceTrack(s)}surfaceTrack(t){this.bridgeTrack=t,this.armBridgeEndedWatch(t),this.lastRemote&&this.lastRemote.readyState==="live"?this.seam.onTrack(this.lastRemote):this.seam.onTrack(t);let e=this.seam.renderHop;e&&(e.onRemote(r=>{if(this.stopped)return;if(r?this.lastRemote=r:this.lastRemote&&this.lastRemote.readyState!=="live"&&(this.lastRemote=null),r){this.seam.onTrack(r);return}if(this.lastRemote&&this.lastRemote.readyState==="live"){this.seam.onTrack(this.lastRemote);return}let s=this.bridgeTrack&&this.bridgeTrack.readyState==="live"?this.bridgeTrack:null;this.seam.onTrack(s)}),e.setSource(t))}onDecoderError(t){if(this.stopped)return;E.warn("[urun] WT audio decoder error \u2014 re-initializing the decoder:",t.message);try{this.decoder?.close()}catch{}this.decoder=null;let e=globalThis.AudioDecoder;if(typeof e=="function")try{this.initDecoder(e)}catch(r){E.error(`[urun] WT audio decoder re-init failed \u2014 lane silent until a later frame re-inits; transport unaffected: ${r instanceof Error?r.message:String(r)}`)}}},QI=1200;function FH(t,e,r,s,n){let i=s-ei;if(i<=0)return null;let o=Math.max(1,Math.ceil(r.byteLength/i));if(o>255)return null;let a=[];for(let c=0;c<o;c++){let d=r.subarray(c*i,Math.min((c+1)*i,r.byteLength)),u=KI({groupId:e>>>0,frameSeq:t>>>0,keyframe:n?.keyframe??!0,fragIndex:c,fragCount:o,lane:n?.lane??$H}),l=new Uint8Array(ei+d.byteLength);l.set(u,0),l.set(d,ei),a.push(l)}return a}var Cie=`
|
|
147
|
+
`}}),wc=nt(t=>{"use strict";var e=Fre(),r=Hre(),s=GA();t.grammar=s,t.write=r,t.parse=e.parse,t.parseParams=e.parseParams,t.parseFmtpConfig=e.parseFmtpConfig,t.parsePayloads=e.parsePayloads,t.parseRemoteCandidates=e.parseRemoteCandidates,t.parseImageAttributes=e.parseImageAttributes,t.parseSimulcastStreamList=e.parseSimulcastStreamList}),Jh=nt(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parse=r;var e=new RegExp("^[LS]([1-9]\\d{0,1})T([1-9]\\d{0,1})");function r(s){let n=e.exec(s??"");return n?{spatialLayers:Number(n[1]),temporalLayers:Number(n[2])}:{spatialLayers:1,temporalLayers:1}}}),qre=nt(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OfferMediaSection=t.AnswerMediaSection=t.MediaSection=void 0;var e=wc(),r=Yh(),s=class{_mediaObject;constructor({iceParameters:a,iceCandidates:c,dtlsParameters:d}){if(this._mediaObject={type:"",port:0,protocol:"",payloads:"",rtp:[],fmtp:[]},a&&this.setIceParameters(a),c){this._mediaObject.candidates=[];for(let u of c){let l={foundation:u.foundation,component:1,ip:u.address??u.ip,port:u.port,priority:u.priority,transport:u.protocol,type:u.type};u.tcpType&&(l.tcptype=u.tcpType),this._mediaObject.candidates.push(l)}this._mediaObject.endOfCandidates="end-of-candidates",this._mediaObject.iceOptions="renomination"}d&&this.setDtlsRole(d.role)}get mid(){return String(this._mediaObject.mid)}get closed(){return this._mediaObject.port===0}getObject(){return this._mediaObject}setIceParameters(a){this._mediaObject.iceUfrag=a.usernameFragment,this._mediaObject.icePwd=a.password}pause(){this._mediaObject.direction="inactive"}disable(){this.pause()}close(){this.disable(),this._mediaObject.port=0,delete this._mediaObject.candidates,delete this._mediaObject.endOfCandidates,delete this._mediaObject.iceUfrag,delete this._mediaObject.icePwd,delete this._mediaObject.iceOptions,this._mediaObject.rtp=[],this._mediaObject.fmtp=[],delete this._mediaObject.rtcp,delete this._mediaObject.rtcpFb,delete this._mediaObject.ssrcs,delete this._mediaObject.ssrcGroups,delete this._mediaObject.simulcast,delete this._mediaObject.simulcast_03,delete this._mediaObject.rids,delete this._mediaObject.extmapAllowMixed}};t.MediaSection=s;var n=class extends s{constructor({iceParameters:a,iceCandidates:c,dtlsParameters:d,sctpParameters:u,plainRtpParameters:l,offerMediaObject:h,offerRtpParameters:p,answerRtpParameters:m,codecOptions:_}){switch(super({iceParameters:a,iceCandidates:c,dtlsParameters:d}),this._mediaObject.mid=String(h.mid),this._mediaObject.type=h.type,this._mediaObject.protocol=h.protocol,l?(this._mediaObject.connection={ip:l.ip,version:l.ipVersion},this._mediaObject.port=l.port):(this._mediaObject.connection={ip:"127.0.0.1",version:4},this._mediaObject.port=7),h.type){case"audio":case"video":{this._mediaObject.direction="recvonly",this._mediaObject.rtp=[],this._mediaObject.rtcpFb=[],this._mediaObject.fmtp=[];for(let f of m.codecs){let b={payload:f.payloadType,codec:o(f),rate:f.clockRate};f.channels>1&&(b.encoding=f.channels),this._mediaObject.rtp.push(b);let w=r.clone(f.parameters)??{},S=r.clone(f.rtcpFeedback)??[];if(_){let{opusStereo:j,opusFec:P,opusDtx:k,opusMaxPlaybackRate:C,opusMaxAverageBitrate:D,opusPtime:H,opusNack:W,videoGoogleStartBitrate:J,videoGoogleMaxBitrate:F,videoGoogleMinBitrate:q}=_,Q=p.codecs.find(R=>R.payloadType===f.payloadType);switch(f.mimeType.toLowerCase()){case"audio/opus":case"audio/multiopus":{j!==void 0&&(Q.parameters["sprop-stereo"]=j?1:0,w.stereo=j?1:0),P!==void 0&&(Q.parameters.useinbandfec=P?1:0,w.useinbandfec=P?1:0),k!==void 0&&(Q.parameters.usedtx=k?1:0,w.usedtx=k?1:0),C!==void 0&&(w.maxplaybackrate=C),D!==void 0&&(w.maxaveragebitrate=D),H!==void 0&&(Q.parameters.ptime=H,w.ptime=H),W||(Q.rtcpFeedback=Q.rtcpFeedback.filter(R=>R.type!=="nack"||R.parameter),S=S.filter(R=>R.type!=="nack"||R.parameter));break}case"video/vp8":case"video/vp9":case"video/h264":case"video/h265":case"video/av1":{J!==void 0&&(w["x-google-start-bitrate"]=J),F!==void 0&&(w["x-google-max-bitrate"]=F),q!==void 0&&(w["x-google-min-bitrate"]=q);break}}}let O={payload:f.payloadType,config:""};for(let j of Object.keys(w))O.config&&(O.config+=";"),O.config+=`${j}=${w[j]}`;O.config&&this._mediaObject.fmtp.push(O);for(let j of S)this._mediaObject.rtcpFb.push({payload:f.payloadType,type:j.type,subtype:j.parameter})}this._mediaObject.payloads=m.codecs.map(f=>f.payloadType).join(" "),this._mediaObject.ext=[];for(let f of m.headerExtensions)(h.ext??[]).some(b=>b.uri===f.uri)&&this._mediaObject.ext.push({uri:f.uri,value:f.id});if(h.extmapAllowMixed==="extmap-allow-mixed"&&(this._mediaObject.extmapAllowMixed="extmap-allow-mixed"),h.simulcast){this._mediaObject.simulcast={dir1:"recv",list1:h.simulcast.list1},this._mediaObject.rids=[];for(let f of h.rids??[])f.direction==="send"&&this._mediaObject.rids.push({id:f.id,direction:"recv"})}else if(h.simulcast_03){this._mediaObject.simulcast_03={value:h.simulcast_03.value.replace(/send/g,"recv")},this._mediaObject.rids=[];for(let f of h.rids??[])f.direction==="send"&&this._mediaObject.rids.push({id:f.id,direction:"recv"})}this._mediaObject.rtcpMux="rtcp-mux",this._mediaObject.rtcpRsize="rtcp-rsize";break}case"application":{typeof h.sctpPort=="number"?(this._mediaObject.payloads="webrtc-datachannel",this._mediaObject.sctpPort=u.port,this._mediaObject.maxMessageSize=u.maxMessageSize):h.sctpmap&&(this._mediaObject.payloads=String(u.port),this._mediaObject.sctpmap={app:"webrtc-datachannel",sctpmapNumber:u.port,maxMessageSize:u.maxMessageSize});break}}}setDtlsRole(a){switch(a){case"client":{this._mediaObject.setup="active";break}case"server":{this._mediaObject.setup="passive";break}case"auto":{this._mediaObject.setup="actpass";break}}}resume(){this._mediaObject.direction="recvonly"}muxSimulcastStreams(a){if(!this._mediaObject.simulcast?.list1)return;let c={};for(let l of a)l.rid&&(c[l.rid]=l);let d=this._mediaObject.simulcast.list1,u=e.parseSimulcastStreamList(d);for(let l of u)for(let h of l)h.paused=!c[h.scid]?.active;this._mediaObject.simulcast.list1=u.map(l=>l.map(h=>`${h.paused?"~":""}${h.scid}`).join(",")).join(";")}};t.AnswerMediaSection=n;var i=class extends s{constructor({iceParameters:a,iceCandidates:c,dtlsParameters:d,sctpParameters:u,plainRtpParameters:l,mid:h,kind:p,offerRtpParameters:m,streamId:_,trackId:f}){switch(super({iceParameters:a,iceCandidates:c,dtlsParameters:d}),this._mediaObject.mid=String(h),this._mediaObject.type=p,l?(this._mediaObject.connection={ip:l.ip,version:l.ipVersion},this._mediaObject.protocol="RTP/AVP",this._mediaObject.port=l.port):(this._mediaObject.connection={ip:"127.0.0.1",version:4},u?this._mediaObject.protocol="UDP/DTLS/SCTP":this._mediaObject.protocol="UDP/TLS/RTP/SAVPF",this._mediaObject.port=7),this._mediaObject.extmapAllowMixed="extmap-allow-mixed",p){case"audio":case"video":{this._mediaObject.direction="sendonly",this._mediaObject.rtp=[],this._mediaObject.rtcpFb=[],this._mediaObject.fmtp=[],this._mediaObject.msid=[{id:_,appdata:f}];for(let O of m.codecs){let j={payload:O.payloadType,codec:o(O),rate:O.clockRate};O.channels>1&&(j.encoding=O.channels),this._mediaObject.rtp.push(j);let P={payload:O.payloadType,config:""};for(let k of Object.keys(O.parameters??{}))P.config&&(P.config+=";"),P.config+=`${k}=${O.parameters[k]}`;P.config&&this._mediaObject.fmtp.push(P);for(let k of O.rtcpFeedback)this._mediaObject.rtcpFb.push({payload:O.payloadType,type:k.type,subtype:k.parameter})}this._mediaObject.payloads=m.codecs.map(O=>O.payloadType).join(" "),this._mediaObject.ext=[];for(let O of m.headerExtensions)this._mediaObject.ext.push({uri:O.uri,value:O.id});this._mediaObject.rtcpMux="rtcp-mux",this._mediaObject.rtcpRsize="rtcp-rsize";let b=m.encodings[0],w=b.ssrc,S=b.rtx?.ssrc;this._mediaObject.ssrcs=[],this._mediaObject.ssrcGroups=[],w&&m.rtcp.cname&&this._mediaObject.ssrcs.push({id:w,attribute:"cname",value:m.rtcp.cname}),S&&(m.rtcp.cname&&this._mediaObject.ssrcs.push({id:S,attribute:"cname",value:m.rtcp.cname}),w&&this._mediaObject.ssrcGroups.push({semantics:"FID",ssrcs:`${w} ${S}`}));break}case"application":{this._mediaObject.payloads="webrtc-datachannel",this._mediaObject.sctpPort=u.port,this._mediaObject.maxMessageSize=u.maxMessageSize;break}}}setDtlsRole(a){this._mediaObject.setup="actpass"}resume(){this._mediaObject.direction="sendonly"}};t.OfferMediaSection=i;function o(a){let c=new RegExp("^(audio|video)/(.+)","i").exec(a.mimeType);if(!c)throw new TypeError("invalid codec.mimeType");return c[2]}}),gg=nt(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RemoteSdp=void 0;var e=wc(),r=Os(),s=qre(),n=CF(),i=["av1","h264"],o=new r.Logger("RemoteSdp"),a=class{_iceParameters;_iceCandidates;_dtlsParameters;_sctpParameters;_plainRtpParameters;_mediaSections=[];_midToIndex=new Map;_firstMid;_sdpObject;constructor({iceParameters:c,iceCandidates:d,dtlsParameters:u,sctpParameters:l,plainRtpParameters:h}){if(this._iceParameters=c,this._iceCandidates=d,this._dtlsParameters=u,this._sctpParameters=l,this._plainRtpParameters=h,this._sdpObject={version:0,origin:{address:"0.0.0.0",ipVer:4,netType:"IN",sessionId:"10000",sessionVersion:0,username:`media-client-v${n.version}`},name:"-",timing:{start:0,stop:0},media:[]},this._sdpObject.iceOptions="ice2",c?.iceLite&&(this._sdpObject.icelite="ice-lite"),u){this._sdpObject.msidSemantic={semantic:"WMS",token:"*"};let p=this._dtlsParameters.fingerprints.length;this._sdpObject.fingerprint={type:u.fingerprints[p-1].algorithm,hash:u.fingerprints[p-1].value},this._sdpObject.groups=[{type:"BUNDLE",mids:""}]}h&&(this._sdpObject.origin.address=h.ip,this._sdpObject.origin.ipVer=h.ipVersion)}updateIceParameters(c){o.debug("updateIceParameters() [iceParameters:%o]",c),this._iceParameters=c,this._sdpObject.icelite=c.iceLite?"ice-lite":void 0;for(let d of this._mediaSections)d.setIceParameters(c)}updateDtlsRole(c){o.debug("updateDtlsRole() [role:%s]",c),this._dtlsParameters.role=c;for(let d of this._mediaSections)d.setDtlsRole(c)}setSessionExtmapAllowMixed(){o.debug("setSessionExtmapAllowMixed()"),this._sdpObject.extmapAllowMixed="extmap-allow-mixed"}getNextMediaSectionIdx(){for(let c=0;c<this._mediaSections.length;++c){let d=this._mediaSections[c];if(d.closed)return{idx:c,reuseMid:d.mid}}return{idx:this._mediaSections.length}}send({offerMediaObject:c,reuseMid:d,offerRtpParameters:u,answerRtpParameters:l,codecOptions:h}){let p=new s.AnswerMediaSection({iceParameters:this._iceParameters,iceCandidates:this._iceCandidates,dtlsParameters:this._dtlsParameters,plainRtpParameters:this._plainRtpParameters,offerMediaObject:c,offerRtpParameters:u,answerRtpParameters:l,codecOptions:h}),m=p.getObject();m.rtp.find(_=>i.includes(_.codec.toLowerCase()))||(m.ext=m.ext?.filter(_=>_.uri!=="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension")),d?this.replaceMediaSection(p,d):this._midToIndex.has(p.mid)?this.replaceMediaSection(p):this.addMediaSection(p)}receive({mid:c,kind:d,offerRtpParameters:u,streamId:l,trackId:h}){this.setSessionExtmapAllowMixed();let p=new s.OfferMediaSection({iceParameters:this._iceParameters,iceCandidates:this._iceCandidates,dtlsParameters:this._dtlsParameters,plainRtpParameters:this._plainRtpParameters,mid:c,kind:d,offerRtpParameters:u,streamId:l,trackId:h}),m=this._mediaSections.find(_=>_.closed&&_.getObject().type===d);m?this.replaceMediaSection(p,m.mid):this.addMediaSection(p)}pauseMediaSection(c){this.findMediaSection(c).pause()}resumeSendingMediaSection(c){this.findMediaSection(c).resume()}resumeReceivingMediaSection(c){this.findMediaSection(c).resume()}disableMediaSection(c){this.findMediaSection(c).disable()}closeMediaSection(c){let d=this.findMediaSection(c);return c===this._firstMid?(o.debug("closeMediaSection() | cannot close first media section, disabling it instead [mid:%s]",c),this.disableMediaSection(c),!1):(d.close(),this.regenerateBundleMids(),!0)}muxMediaSectionSimulcast(c,d){let u=this.findMediaSection(c);u.muxSimulcastStreams(d),this.replaceMediaSection(u)}sendSctpAssociation({offerMediaObject:c}){let d=new s.AnswerMediaSection({iceParameters:this._iceParameters,iceCandidates:this._iceCandidates,dtlsParameters:this._dtlsParameters,sctpParameters:this._sctpParameters,plainRtpParameters:this._plainRtpParameters,offerMediaObject:c});this.addMediaSection(d)}receiveSctpAssociation(){let c=new s.OfferMediaSection({iceParameters:this._iceParameters,iceCandidates:this._iceCandidates,dtlsParameters:this._dtlsParameters,sctpParameters:this._sctpParameters,plainRtpParameters:this._plainRtpParameters,mid:"datachannel",kind:"application"});this.addMediaSection(c)}getSdp(){return this._sdpObject.origin.sessionVersion++,e.write(this._sdpObject)}addMediaSection(c){this._firstMid||(this._firstMid=c.mid),this._mediaSections.push(c),this._midToIndex.set(c.mid,this._mediaSections.length-1),this._sdpObject.media.push(c.getObject()),this.regenerateBundleMids()}replaceMediaSection(c,d){if(typeof d=="string"){let u=this._midToIndex.get(d);if(u===void 0)throw new Error(`no media section found for reuseMid '${d}'`);let l=this._mediaSections[u];this._mediaSections[u]=c,this._midToIndex.delete(l.mid),this._midToIndex.set(c.mid,u),this._sdpObject.media[u]=c.getObject(),this.regenerateBundleMids()}else{let u=this._midToIndex.get(c.mid);if(u===void 0)throw new Error(`no media section found with mid '${c.mid}'`);this._mediaSections[u]=c,this._sdpObject.media[u]=c.getObject()}}findMediaSection(c){let d=this._midToIndex.get(c);if(d===void 0)throw new Error(`no media section found with mid '${c}'`);return this._mediaSections[d]}regenerateBundleMids(){this._dtlsParameters&&(this._sdpObject.groups[0].mids=this._mediaSections.filter(c=>!c.closed).map(c=>c.mid).join(" "))}};t.RemoteSdp=a}),yg=nt(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractRtpCapabilities=r,t.extractDtlsParameters=s,t.getCname=n,t.applyCodecParameters=i,t.addHeaderExtension=o;var e=wc();function r({sdpObject:a}){let c=new Map,d=new Map;for(let u of a.media){let l=u.type;switch(l){case"audio":case"video":break;default:continue}for(let h of u.rtp){let p={kind:l,mimeType:`${l}/${h.codec}`,preferredPayloadType:h.payload,clockRate:h.rate,channels:h.encoding,parameters:{},rtcpFeedback:[]};c.set(p.preferredPayloadType,p)}for(let h of u.fmtp??[]){let p=e.parseParams(h.config),m=c.get(h.payload);m&&(p?.hasOwnProperty("profile-level-id")&&(p["profile-level-id"]=String(p["profile-level-id"])),m.parameters=p)}for(let h of u.rtcpFb??[]){let p={type:h.type,parameter:h.subtype};if(p.parameter||delete p.parameter,h.payload!=="*"){let m=c.get(Number(h.payload));if(!m)continue;m.rtcpFeedback.push(p)}else for(let m of c.values())m.kind===l&&!/.+\/rtx$/i.test(m.mimeType)&&m.rtcpFeedback.push(p)}for(let h of u.ext??[]){if(h["encrypt-uri"])continue;let p={kind:l,uri:h.uri,preferredId:h.value};d.set(p.preferredId,p)}}return{codecs:Array.from(c.values()),headerExtensions:Array.from(d.values())}}function s({sdpObject:a}){let c=a.setup,d=a.fingerprint;if(!c||!d){let l=(a.media??[]).find(h=>h.port!==0);l&&(c=c??l.setup,d=d??l.fingerprint)}if(c){if(!d)throw new Error("no a=fingerprint found at SDP session or media level")}else throw new Error("no a=setup found at SDP session or media level");let u;switch(c){case"active":{u="client";break}case"passive":{u="server";break}case"actpass":{u="auto";break}}return{role:u,fingerprints:[{algorithm:d.type,value:d.hash}]}}function n({offerMediaObject:a}){let c=(a.ssrcs??[]).find(d=>d.attribute==="cname");return c?c.value:""}function i({offerRtpParameters:a,answerMediaObject:c}){for(let d of a.codecs){let u=d.mimeType.toLowerCase();if(u!=="audio/opus"||!(c.rtp??[]).find(p=>p.payload===d.payloadType))continue;c.fmtp=c.fmtp??[];let l=c.fmtp.find(p=>p.payload===d.payloadType);l||(l={payload:d.payloadType,config:""},c.fmtp.push(l));let h=e.parseParams(l.config);if(u==="audio/opus"){let p=d.parameters?.["sprop-stereo"];p!==void 0&&(h.stereo=Number(p)?1:0)}l.config="";for(let p of Object.keys(h))l.config&&(l.config+=";"),l.config+=`${p}=${h[p]}`}}function o({offerMediaObject:a,headerExtensionUri:c,headerExtensionId:d}){a.ext||(a.ext=[]),a.ext.push({uri:c,value:d})}}),bg=nt(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getRtpEncodings=e,t.addLegacySimulcast=r;function e({offerMediaObject:s,codecs:n}){let i=new Set;for(let c of s.ssrcs??[]){let d=c.id;d&&i.add(d)}if(i.size===0)throw new Error("no a=ssrc lines found");let o=new Map;for(let c of s.ssrcGroups??[]){if(c.semantics!=="FID")continue;let d=c.ssrcs.split(/\s+/),u=Number(d[0]),l=Number(d[1]);i.has(u)&&(i.delete(u),i.delete(l),o.set(u,l))}for(let c of i)o.set(c,void 0);let a=[];for(let[c,d]of o){let u={ssrc:c};d&&n.length>1&&(u.rtx={ssrc:d}),a.push(u)}return a}function r({offerMediaObject:s,numStreams:n}){if(n<=1)throw new TypeError("numStreams must be greater than 1");let i=(s.ssrcs??[]).find(m=>m.attribute==="msid");if(!i)throw new Error("a=ssrc line with msid information not found");let[o,a]=i.value.split(" "),c=Number(i.id),d;(s.ssrcGroups??[]).some(m=>{if(m.semantics!=="FID")return!1;let _=m.ssrcs.split(/\s+/);return Number(_[0])===c?(d=Number(_[1]),!0):!1});let u=(s.ssrcs??[]).find(m=>m.attribute==="cname");if(!u)throw new Error("a=ssrc line with cname information not found");let l=u.value,h=[],p=[];for(let m=0;m<n;++m)h.push(c+m),d&&p.push(d+m);s.ssrcGroups=[],s.ssrcs=[],s.ssrcGroups.push({semantics:"SIM",ssrcs:h.join(" ")});for(let m of h)s.ssrcs.push({id:m,attribute:"cname",value:l}),s.ssrcs.push({id:m,attribute:"msid",value:`${o} ${a}`});for(let m=0;m<p.length;++m){let _=h[m],f=p[m];s.ssrcs.push({id:f,attribute:"cname",value:l}),s.ssrcs.push({id:f,attribute:"msid",value:`${o} ${a}`}),s.ssrcGroups.push({semantics:"FID",ssrcs:`${_} ${f}`})}}}),xg=nt(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addNackSupportForOpus=e,t.addHeaderExtensionSupport=r,t.getMsidStreamIdAndTrackId=s;function e(n){for(let i of n.codecs??[])(i.mimeType.toLowerCase()==="audio/opus"||i.mimeType.toLowerCase()==="audio/multiopus")&&!i.rtcpFeedback?.some(o=>o.type==="nack"&&!o.parameter)&&(i.rtcpFeedback||(i.rtcpFeedback=[]),i.rtcpFeedback.push({type:"nack"}))}function r(n,i){let o,a=n.headerExtensions?.find(d=>d.uri===i.uri);if(a){if(a.kind===i.kind)return;o=a.preferredId}if(n.headerExtensions||(n.headerExtensions=[]),o===void 0){o=1;let d=new Set(n.headerExtensions.map(u=>u.preferredId));for(;d.has(o);)++o}let c={kind:i.kind,uri:i.uri,preferredId:o,preferredEncrypt:!1,direction:i.direction};n.headerExtensions.push(c)}function s(n){if(!n||typeof n!="string")return{msidStreamId:void 0,msidTrackId:void 0};let[i,o]=n.trim().split(/\s+/);return i?{msidStreamId:i,msidTrackId:o}:{msidStreamId:void 0,msidTrackId:void 0}}}),Vre=nt(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Chrome111=void 0;var e=wc(),r=Xs(),s=Os(),n=ea(),i=Zn(),o=Jh(),a=gg(),c=yg(),d=bg(),u=xg(),l=new s.Logger("Chrome111"),h="Chrome111",p={OS:65535,MIS:65535},m=class E1 extends r.EnhancedEventEmitter{_closed=!1;_direction;_remoteSdp;_getSendExtendedRtpCapabilities;_forcedLocalDtlsRole;_pc;_mapMidTransceiver=new Map;_sendStream=new MediaStream;_hasDataChannelMediaSection=!1;_nextSendSctpStreamId=0;_transportReady=!1;static createFactory(){return{name:h,factory:f=>new E1(f),getNativeRtpCapabilities:async({direction:f})=>{l.debug("getNativeRtpCapabilities() [direction:%o]",f);let b=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{b.addTransceiver("audio",{direction:f}),b.addTransceiver("video",{direction:f,sendEncodings:[{scalabilityMode:"L3T3"}]});let w=await b.createOffer();try{b.close()}catch{}b=void 0;let S=e.parse(w.sdp);return E1.getLocalRtpCapabilities(S)}catch(w){try{b?.close()}catch{}throw b=void 0,w}},getNativeSctpCapabilities:async()=>(l.debug("getNativeSctpCapabilities()"),{numStreams:p})}}static getLocalRtpCapabilities(f,b=[]){let w=c.extractRtpCapabilities({sdpObject:f});n.validateAndNormalizeRtpCapabilities(w),u.addNackSupportForOpus(w);for(let S of b)u.addHeaderExtensionSupport(w,S);return w}constructor({direction:f,iceParameters:b,iceCandidates:w,dtlsParameters:S,sctpParameters:O,iceServers:j,iceTransportPolicy:P,additionalSettings:k,getSendExtendedRtpCapabilities:C}){super(),l.debug("constructor()"),this._direction=f,this._remoteSdp=new a.RemoteSdp({iceParameters:b,iceCandidates:w,dtlsParameters:S,sctpParameters:O}),this._getSendExtendedRtpCapabilities=C,S.role&&S.role!=="auto"&&(this._forcedLocalDtlsRole=S.role==="server"?"client":"server"),this._pc=new RTCPeerConnection({iceServers:j??[],iceTransportPolicy:P??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...k}),this._pc.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.addEventListener("icecandidateerror",this.onIceCandidateError),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",this.onConnectionStateChange):(l.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return h}close(){if(l.debug("close()"),!this._closed){this._closed=!0;try{this._pc.close()}catch{}this._pc.removeEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.removeEventListener("icecandidateerror",this.onIceCandidateError),this._pc.removeEventListener("connectionstatechange",this.onConnectionStateChange),this._pc.removeEventListener("iceconnectionstatechange",this.onIceConnectionStateChange),this.emit("@close"),super.close()}}async updateIceServers(f){this.assertNotClosed(),l.debug("updateIceServers()");let b=this._pc.getConfiguration();b.iceServers=f,this._pc.setConfiguration(b)}async restartIce(f){if(this.assertNotClosed(),l.debug("restartIce()"),this._remoteSdp.updateIceParameters(f),!!this._transportReady)if(this._direction==="send"){let b=await this._pc.createOffer({iceRestart:!0});l.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",b),await this._pc.setLocalDescription(b);let w={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",w),await this._pc.setRemoteDescription(w)}else{let b={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",b),await this._pc.setRemoteDescription(b);let w=await this._pc.createAnswer();l.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",w),await this._pc.setLocalDescription(w)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:f,streamId:b,encodings:w,codecOptions:S,headerExtensionOptions:O,codec:j,onRtpSender:P}){if(this.assertNotClosed(),this.assertSendDirection(),l.debug("send() [kind:%s, track.id:%s, streamId:%s]",f.kind,f.id,b),w&&w.length>1){let I=1;for(let U of w){let K=U.scalabilityMode?(0,o.parse)(U.scalabilityMode).temporalLayers:3;K>I&&(I=K)}w.forEach((U,K)=>{U.rid=`r${K}`,U.scalabilityMode=`L1T${I}`})}let k=this._remoteSdp.getNextMediaSectionIdx(),C=this._pc.addTransceiver(f,{direction:"sendonly",streams:[this._sendStream],sendEncodings:w});P&&P(C.sender);let D=await this._pc.createOffer(),H=e.parse(D.sdp);H.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();let W=[];W.push({uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",kind:f.kind,direction:"sendonly"});let J=E1.getLocalRtpCapabilities(H,W),F=this._getSendExtendedRtpCapabilities(J),q=n.getSendingRtpParameters(f.kind,F);q.codecs=n.reduceCodecs(q.codecs,j);let Q=n.getSendingRemoteRtpParameters(f.kind,F);if(Q.codecs=n.reduceCodecs(Q.codecs,j),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:H}),O?.absCaptureTime){let I=H.media[k.idx];c.addHeaderExtension({offerMediaObject:I,headerExtensionUri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",headerExtensionId:Q.headerExtensions.find(U=>U.uri==="http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time").id}),D={type:"offer",sdp:e.write(H)}}l.debug("send() | calling pc.setLocalDescription() [offer:%o]",D),await this._pc.setLocalDescription(D);let R=C.mid;q.mid=R,H=e.parse(this._pc.localDescription.sdp);let Y=H.media[k.idx];if(q.rtcp.cname=c.getCname({offerMediaObject:Y}),q.msid=`${b??this._sendStream.id} ${f.id}`,!w)q.encodings=d.getRtpEncodings({offerMediaObject:Y,codecs:q.codecs});else if(w.length===1){let I=d.getRtpEncodings({offerMediaObject:Y,codecs:q.codecs});Object.assign(I[0],w[0]),q.encodings=I}else q.encodings=w;this._remoteSdp.send({offerMediaObject:Y,reuseMid:k.reuseMid,offerRtpParameters:q,answerRtpParameters:Q,codecOptions:S});let Z={type:"answer",sdp:this._remoteSdp.getSdp()};return l.debug("send() | calling pc.setRemoteDescription() [answer:%o]",Z),await this._pc.setRemoteDescription(Z),this._mapMidTransceiver.set(R,C),{localId:R,rtpParameters:q,rtpSender:C.sender}}async stopSending(f){if(this.assertSendDirection(),l.debug("stopSending() [localId:%s]",f),this._closed)return;let b=this._mapMidTransceiver.get(f);if(!b)throw new Error("associated RTCRtpTransceiver not found");if(b.sender.replaceTrack(null),this._pc.removeTrack(b.sender),this._remoteSdp.closeMediaSection(b.mid))try{b.stop()}catch{}let w=await this._pc.createOffer();l.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",w),await this._pc.setLocalDescription(w);let S={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",S),await this._pc.setRemoteDescription(S),this._mapMidTransceiver.delete(f)}async pauseSending(f){this.assertNotClosed(),this.assertSendDirection(),l.debug("pauseSending() [localId:%s]",f);let b=this._mapMidTransceiver.get(f);if(!b)throw new Error("associated RTCRtpTransceiver not found");b.direction="inactive",this._remoteSdp.pauseMediaSection(f);let w=await this._pc.createOffer();l.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",w),await this._pc.setLocalDescription(w);let S={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",S),await this._pc.setRemoteDescription(S)}async resumeSending(f){this.assertNotClosed(),this.assertSendDirection(),l.debug("resumeSending() [localId:%s]",f);let b=this._mapMidTransceiver.get(f);if(this._remoteSdp.resumeSendingMediaSection(f),!b)throw new Error("associated RTCRtpTransceiver not found");b.direction="sendonly";let w=await this._pc.createOffer();l.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",w),await this._pc.setLocalDescription(w);let S={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",S),await this._pc.setRemoteDescription(S)}async replaceTrack(f,b){this.assertNotClosed(),this.assertSendDirection(),b?l.debug("replaceTrack() [localId:%s, track.id:%s]",f,b.id):l.debug("replaceTrack() [localId:%s, no track]",f);let w=this._mapMidTransceiver.get(f);if(!w)throw new Error("associated RTCRtpTransceiver not found");await w.sender.replaceTrack(b)}async setMaxSpatialLayer(f,b){this.assertNotClosed(),this.assertSendDirection(),l.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",f,b);let w=this._mapMidTransceiver.get(f);if(!w)throw new Error("associated RTCRtpTransceiver not found");let S=w.sender.getParameters();S.encodings.forEach((P,k)=>{k<=b?P.active=!0:P.active=!1}),await w.sender.setParameters(S),this._remoteSdp.muxMediaSectionSimulcast(f,S.encodings);let O=await this._pc.createOffer();l.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",O),await this._pc.setLocalDescription(O);let j={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",j),await this._pc.setRemoteDescription(j)}async setRtpEncodingParameters(f,b){this.assertNotClosed(),this.assertSendDirection(),l.debug("setRtpEncodingParameters() [localId:%s, params:%o]",f,b);let w=this._mapMidTransceiver.get(f);if(!w)throw new Error("associated RTCRtpTransceiver not found");let S=w.sender.getParameters();S.encodings.forEach((P,k)=>{S.encodings[k]={...P,...b}}),await w.sender.setParameters(S),this._remoteSdp.muxMediaSectionSimulcast(f,S.encodings);let O=await this._pc.createOffer();l.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",O),await this._pc.setLocalDescription(O);let j={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",j),await this._pc.setRemoteDescription(j)}async getSenderStats(f){this.assertNotClosed(),this.assertSendDirection();let b=this._mapMidTransceiver.get(f);if(!b)throw new Error("associated RTCRtpTransceiver not found");return b.sender.getStats()}async sendDataChannel({sctpStreamParameters:f}){this.assertNotClosed(),this.assertSendDirection();let b={negotiated:!0,id:this._nextSendSctpStreamId,ordered:f.ordered,maxPacketLifeTime:f.maxPacketLifeTime,maxRetransmits:f.maxRetransmits,protocol:f.protocol};l.debug("sendDataChannel() [options:%o]",b);let w=this._pc.createDataChannel(f.label,b);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%p.MIS,!this._hasDataChannelMediaSection){let O=await this._pc.createOffer(),j=e.parse(O.sdp),P=j.media.find(C=>C.type==="application");this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:j}),l.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",O),await this._pc.setLocalDescription(O),this._remoteSdp.sendSctpAssociation({offerMediaObject:P});let k={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",k),await this._pc.setRemoteDescription(k),this._hasDataChannelMediaSection=!0}let S={streamId:b.id,ordered:b.ordered,maxPacketLifeTime:b.maxPacketLifeTime,maxRetransmits:b.maxRetransmits};return{dataChannel:w,sctpStreamParameters:S}}async receive(f){this.assertNotClosed(),this.assertRecvDirection();let b=[],w=new Map;for(let P of f){let{trackId:k,kind:C,rtpParameters:D,streamId:H}=P;l.debug("receive() [trackId:%s, kind:%s]",k,C);let W=D.mid??String(this._mapMidTransceiver.size);w.set(k,W);let{msidStreamId:J}=u.getMsidStreamIdAndTrackId(D.msid);this._remoteSdp.receive({mid:W,kind:C,offerRtpParameters:D,streamId:H??J??D.rtcp?.cname??"-",trackId:k})}let S={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",S),await this._pc.setRemoteDescription(S);for(let P of f){let{trackId:k,onRtpReceiver:C}=P;if(C){let D=w.get(k),H=this._pc.getTransceivers().find(W=>W.mid===D);if(!H)throw new Error("transceiver not found");C(H.receiver)}}let O=await this._pc.createAnswer(),j=e.parse(O.sdp);for(let P of f){let{trackId:k,rtpParameters:C}=P,D=w.get(k),H=j.media.find(W=>String(W.mid)===D);c.applyCodecParameters({offerRtpParameters:C,answerMediaObject:H})}O={type:"answer",sdp:e.write(j)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:j}),l.debug("receive() | calling pc.setLocalDescription() [answer:%o]",O),await this._pc.setLocalDescription(O);for(let P of f){let{trackId:k}=P,C=w.get(k),D=this._pc.getTransceivers().find(H=>H.mid===C);if(D)this._mapMidTransceiver.set(C,D),b.push({localId:C,track:D.receiver.track,rtpReceiver:D.receiver});else throw new Error("new RTCRtpTransceiver not found")}return b}async stopReceiving(f){if(this.assertRecvDirection(),this._closed)return;for(let S of f){l.debug("stopReceiving() [localId:%s]",S);let O=this._mapMidTransceiver.get(S);if(!O)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(O.mid)}let b={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",b),await this._pc.setRemoteDescription(b);let w=await this._pc.createAnswer();l.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",w),await this._pc.setLocalDescription(w);for(let S of f)this._mapMidTransceiver.delete(S)}async pauseReceiving(f){this.assertNotClosed(),this.assertRecvDirection();for(let S of f){l.debug("pauseReceiving() [localId:%s]",S);let O=this._mapMidTransceiver.get(S);if(!O)throw new Error("associated RTCRtpTransceiver not found");O.direction="inactive",this._remoteSdp.pauseMediaSection(S)}let b={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",b),await this._pc.setRemoteDescription(b);let w=await this._pc.createAnswer();l.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",w),await this._pc.setLocalDescription(w)}async resumeReceiving(f){this.assertNotClosed(),this.assertRecvDirection();for(let S of f){l.debug("resumeReceiving() [localId:%s]",S);let O=this._mapMidTransceiver.get(S);if(!O)throw new Error("associated RTCRtpTransceiver not found");O.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(S)}let b={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",b),await this._pc.setRemoteDescription(b);let w=await this._pc.createAnswer();l.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",w),await this._pc.setLocalDescription(w)}async getReceiverStats(f){this.assertNotClosed(),this.assertRecvDirection();let b=this._mapMidTransceiver.get(f);if(!b)throw new Error("associated RTCRtpTransceiver not found");return b.receiver.getStats()}async receiveDataChannel({maxMessageSize:f,sctpStreamParameters:b,label:w,protocol:S}){this.assertNotClosed(),this.assertRecvDirection();let{streamId:O,ordered:j,maxPacketLifeTime:P,maxRetransmits:k}=b,C={negotiated:!0,id:O,ordered:j,maxPacketLifeTime:P,maxRetransmits:k,protocol:S};l.debug("receiveDataChannel() [options:%o]",C);let D=this._pc.createDataChannel(w,C);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();let H={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",H),await this._pc.setRemoteDescription(H);let W=await this._pc.createAnswer(),J=e.parse(W.sdp),F=J.media.find(q=>q.type==="application");F.maxMessageSize=f,this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:J}),W={type:"answer",sdp:e.write(J)},l.debug("receiveDataChannel() | calling pc.setLocalDescription() [answer:%o]",W),await this._pc.setLocalDescription(W),this._hasDataChannelMediaSection=!0}return{dataChannel:D}}getDataChannelMaxMessageSize(){return this._pc.sctp?.maxMessageSize}async setupTransport({localDtlsRole:f,localSdpObject:b}){b||(b=e.parse(this._pc.localDescription.sdp));let w=c.extractDtlsParameters({sdpObject:b});w.role=f,this._remoteSdp.updateDtlsRole(f==="client"?"server":"client"),await new Promise((S,O)=>{this.safeEmit("@connect",{dtlsParameters:w},S,O)}),this._transportReady=!0}onIceGatheringStateChange=()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)};onIceCandidateError=f=>{this.emit("@icecandidateerror",f)};onConnectionStateChange=()=>{this.emit("@connectionstatechange",this._pc.connectionState)};onIceConnectionStateChange=()=>{switch(this._pc.iceConnectionState){case"checking":{this.emit("@connectionstatechange","connecting");break}case"connected":case"completed":{this.emit("@connectionstatechange","connected");break}case"failed":{this.emit("@connectionstatechange","failed");break}case"disconnected":{this.emit("@connectionstatechange","disconnected");break}case"closed":{this.emit("@connectionstatechange","closed");break}}};assertNotClosed(){if(this._closed)throw new i.InvalidStateError("method called in a closed handler")}assertSendDirection(){if(this._direction!=="send")throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if(this._direction!=="recv")throw new Error('method can just be called for handlers with "recv" direction')}};t.Chrome111=m}),zre=nt(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Chrome74=void 0;var e=wc(),r=Os(),s=Xs(),n=ea(),i=Zn(),o=Jh(),a=gg(),c=yg(),d=bg(),u=xg(),l=new r.Logger("Chrome74"),h="Chrome74",p={OS:1024,MIS:1024},m=class C1 extends s.EnhancedEventEmitter{_closed=!1;_direction;_remoteSdp;_getSendExtendedRtpCapabilities;_forcedLocalDtlsRole;_pc;_mapMidTransceiver=new Map;_sendStream=new MediaStream;_hasDataChannelMediaSection=!1;_nextSendSctpStreamId=0;_transportReady=!1;static createFactory(){return{name:h,factory:f=>new C1(f),getNativeRtpCapabilities:async({direction:f})=>{l.debug("getNativeRtpCapabilities() [direction:%o]",f);let b=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{b.addTransceiver("audio",{direction:f}),b.addTransceiver("video",{direction:f});let w=await b.createOffer();try{b.close()}catch{}b=void 0;let S=e.parse(w.sdp);return C1.getLocalRtpCapabilities(S)}catch(w){try{b?.close()}catch{}throw b=void 0,w}},getNativeSctpCapabilities:async()=>(l.debug("getNativeSctpCapabilities()"),{numStreams:p})}}static getLocalRtpCapabilities(f,b=[]){let w=c.extractRtpCapabilities({sdpObject:f});n.validateAndNormalizeRtpCapabilities(w),u.addNackSupportForOpus(w);for(let S of b)u.addHeaderExtensionSupport(w,S);return w}constructor({direction:f,iceParameters:b,iceCandidates:w,dtlsParameters:S,sctpParameters:O,iceServers:j,iceTransportPolicy:P,additionalSettings:k,getSendExtendedRtpCapabilities:C}){super(),l.debug("constructor()"),this._direction=f,this._remoteSdp=new a.RemoteSdp({iceParameters:b,iceCandidates:w,dtlsParameters:S,sctpParameters:O}),this._getSendExtendedRtpCapabilities=C,S.role&&S.role!=="auto"&&(this._forcedLocalDtlsRole=S.role==="server"?"client":"server"),this._pc=new RTCPeerConnection({iceServers:j??[],iceTransportPolicy:P??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...k}),this._pc.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.addEventListener("icecandidateerror",this.onIceCandidateError),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",this.onConnectionStateChange):(l.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return h}close(){if(l.debug("close()"),!this._closed){this._closed=!0;try{this._pc.close()}catch{}this._pc.removeEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.removeEventListener("icecandidateerror",this.onIceCandidateError),this._pc.removeEventListener("connectionstatechange",this.onConnectionStateChange),this._pc.removeEventListener("iceconnectionstatechange",this.onIceConnectionStateChange),this.emit("@close"),super.close()}}async updateIceServers(f){this.assertNotClosed(),l.debug("updateIceServers()");let b=this._pc.getConfiguration();b.iceServers=f,this._pc.setConfiguration(b)}async restartIce(f){if(this.assertNotClosed(),l.debug("restartIce()"),this._remoteSdp.updateIceParameters(f),!!this._transportReady)if(this._direction==="send"){let b=await this._pc.createOffer({iceRestart:!0});l.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",b),await this._pc.setLocalDescription(b);let w={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",w),await this._pc.setRemoteDescription(w)}else{let b={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",b),await this._pc.setRemoteDescription(b);let w=await this._pc.createAnswer();l.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",w),await this._pc.setLocalDescription(w)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:f,streamId:b,encodings:w,codecOptions:S,headerExtensionOptions:O,codec:j}){this.assertNotClosed(),this.assertSendDirection(),l.debug("send() [kind:%s, track.id:%s, streamId:%s]",f.kind,f.id,b),w&&w.length>1&&w.forEach((U,K)=>{U.rid=`r${K}`});let P=this._remoteSdp.getNextMediaSectionIdx(),k=this._pc.addTransceiver(f,{direction:"sendonly",streams:[this._sendStream],sendEncodings:w}),C=await this._pc.createOffer(),D=e.parse(C.sdp);D.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();let H=[];H.push({uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",kind:f.kind,direction:"sendonly"});let W=C1.getLocalRtpCapabilities(D,H),J=this._getSendExtendedRtpCapabilities(W),F=n.getSendingRtpParameters(f.kind,J);F.codecs=n.reduceCodecs(F.codecs,j);let q=n.getSendingRemoteRtpParameters(f.kind,J);q.codecs=n.reduceCodecs(q.codecs,j),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:D});let Q=!1,R=(0,o.parse)((w??[{}])[0].scalabilityMode),Y;w?.length===1&&R.spatialLayers>1&&F.codecs[0].mimeType.toLowerCase()==="video/vp9"&&(l.debug("send() | enabling legacy simulcast for VP9 SVC"),Q=!0,D=e.parse(C.sdp),Y=D.media[P.idx],d.addLegacySimulcast({offerMediaObject:Y,numStreams:R.spatialLayers}),C={type:"offer",sdp:e.write(D)}),l.debug("send() | calling pc.setLocalDescription() [offer:%o]",C),O?.absCaptureTime&&(Y=D.media[P.idx],c.addHeaderExtension({offerMediaObject:Y,headerExtensionUri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",headerExtensionId:q.headerExtensions.find(U=>U.uri==="http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time").id}),C={type:"offer",sdp:e.write(D)}),await this._pc.setLocalDescription(C);let Z=k.mid;if(F.mid=Z,D=e.parse(this._pc.localDescription.sdp),Y=D.media[P.idx],F.rtcp.cname=c.getCname({offerMediaObject:Y}),F.msid=`${b??this._sendStream.id} ${f.id}`,!w)F.encodings=d.getRtpEncodings({offerMediaObject:Y,codecs:F.codecs});else if(w.length===1){let U=d.getRtpEncodings({offerMediaObject:Y,codecs:F.codecs});Object.assign(U[0],w[0]),Q&&(U=[U[0]]),F.encodings=U}else F.encodings=w;if(F.encodings.length>1&&(F.codecs[0].mimeType.toLowerCase()==="video/vp8"||F.codecs[0].mimeType.toLowerCase()==="video/h264"))for(let U of F.encodings)U.scalabilityMode?U.scalabilityMode=`L1T${R.temporalLayers}`:U.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:Y,reuseMid:P.reuseMid,offerRtpParameters:F,answerRtpParameters:q,codecOptions:S});let I={type:"answer",sdp:this._remoteSdp.getSdp()};return l.debug("send() | calling pc.setRemoteDescription() [answer:%o]",I),await this._pc.setRemoteDescription(I),this._mapMidTransceiver.set(Z,k),{localId:Z,rtpParameters:F,rtpSender:k.sender}}async stopSending(f){if(this.assertSendDirection(),l.debug("stopSending() [localId:%s]",f),this._closed)return;let b=this._mapMidTransceiver.get(f);if(!b)throw new Error("associated RTCRtpTransceiver not found");if(b.sender.replaceTrack(null),this._pc.removeTrack(b.sender),this._remoteSdp.closeMediaSection(b.mid))try{b.stop()}catch{}let w=await this._pc.createOffer();l.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",w),await this._pc.setLocalDescription(w);let S={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",S),await this._pc.setRemoteDescription(S),this._mapMidTransceiver.delete(f)}async pauseSending(f){this.assertNotClosed(),this.assertSendDirection(),l.debug("pauseSending() [localId:%s]",f);let b=this._mapMidTransceiver.get(f);if(!b)throw new Error("associated RTCRtpTransceiver not found");b.direction="inactive",this._remoteSdp.pauseMediaSection(f);let w=await this._pc.createOffer();l.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",w),await this._pc.setLocalDescription(w);let S={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",S),await this._pc.setRemoteDescription(S)}async resumeSending(f){this.assertNotClosed(),this.assertSendDirection(),l.debug("resumeSending() [localId:%s]",f);let b=this._mapMidTransceiver.get(f);if(this._remoteSdp.resumeSendingMediaSection(f),!b)throw new Error("associated RTCRtpTransceiver not found");b.direction="sendonly";let w=await this._pc.createOffer();l.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",w),await this._pc.setLocalDescription(w);let S={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",S),await this._pc.setRemoteDescription(S)}async replaceTrack(f,b){this.assertNotClosed(),this.assertSendDirection(),b?l.debug("replaceTrack() [localId:%s, track.id:%s]",f,b.id):l.debug("replaceTrack() [localId:%s, no track]",f);let w=this._mapMidTransceiver.get(f);if(!w)throw new Error("associated RTCRtpTransceiver not found");await w.sender.replaceTrack(b)}async setMaxSpatialLayer(f,b){this.assertNotClosed(),this.assertSendDirection(),l.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",f,b);let w=this._mapMidTransceiver.get(f);if(!w)throw new Error("associated RTCRtpTransceiver not found");let S=w.sender.getParameters();S.encodings.forEach((P,k)=>{k<=b?P.active=!0:P.active=!1}),await w.sender.setParameters(S),this._remoteSdp.muxMediaSectionSimulcast(f,S.encodings);let O=await this._pc.createOffer();l.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",O),await this._pc.setLocalDescription(O);let j={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",j),await this._pc.setRemoteDescription(j)}async setRtpEncodingParameters(f,b){this.assertNotClosed(),this.assertSendDirection(),l.debug("setRtpEncodingParameters() [localId:%s, params:%o]",f,b);let w=this._mapMidTransceiver.get(f);if(!w)throw new Error("associated RTCRtpTransceiver not found");let S=w.sender.getParameters();S.encodings.forEach((P,k)=>{S.encodings[k]={...P,...b}}),await w.sender.setParameters(S),this._remoteSdp.muxMediaSectionSimulcast(f,S.encodings);let O=await this._pc.createOffer();l.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",O),await this._pc.setLocalDescription(O);let j={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",j),await this._pc.setRemoteDescription(j)}async getSenderStats(f){this.assertNotClosed(),this.assertSendDirection();let b=this._mapMidTransceiver.get(f);if(!b)throw new Error("associated RTCRtpTransceiver not found");return b.sender.getStats()}async sendDataChannel({sctpStreamParameters:f}){this.assertNotClosed(),this.assertSendDirection();let b={negotiated:!0,id:this._nextSendSctpStreamId,ordered:f.ordered,maxPacketLifeTime:f.maxPacketLifeTime,maxRetransmits:f.maxRetransmits,protocol:f.protocol};l.debug("sendDataChannel() [options:%o]",b);let w=this._pc.createDataChannel(f.label,b);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%p.MIS,!this._hasDataChannelMediaSection){let O=await this._pc.createOffer(),j=e.parse(O.sdp),P=j.media.find(C=>C.type==="application");this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:j}),l.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",O),await this._pc.setLocalDescription(O),this._remoteSdp.sendSctpAssociation({offerMediaObject:P});let k={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",k),await this._pc.setRemoteDescription(k),this._hasDataChannelMediaSection=!0}let S={streamId:b.id,ordered:b.ordered,maxPacketLifeTime:b.maxPacketLifeTime,maxRetransmits:b.maxRetransmits};return{dataChannel:w,sctpStreamParameters:S}}async receive(f){this.assertNotClosed(),this.assertRecvDirection();let b=[],w=new Map;for(let P of f){let{trackId:k,kind:C,rtpParameters:D,streamId:H}=P;l.debug("receive() [trackId:%s, kind:%s]",k,C);let W=D.mid??String(this._mapMidTransceiver.size);w.set(k,W);let{msidStreamId:J}=u.getMsidStreamIdAndTrackId(D.msid);this._remoteSdp.receive({mid:W,kind:C,offerRtpParameters:D,streamId:H??J??D.rtcp?.cname??"-",trackId:k})}let S={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",S),await this._pc.setRemoteDescription(S);let O=await this._pc.createAnswer(),j=e.parse(O.sdp);for(let P of f){let{trackId:k,rtpParameters:C}=P,D=w.get(k),H=j.media.find(W=>String(W.mid)===D);c.applyCodecParameters({offerRtpParameters:C,answerMediaObject:H})}O={type:"answer",sdp:e.write(j)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:j}),l.debug("receive() | calling pc.setLocalDescription() [answer:%o]",O),await this._pc.setLocalDescription(O);for(let P of f){let{trackId:k}=P,C=w.get(k),D=this._pc.getTransceivers().find(H=>H.mid===C);if(D)this._mapMidTransceiver.set(C,D),b.push({localId:C,track:D.receiver.track,rtpReceiver:D.receiver});else throw new Error("new RTCRtpTransceiver not found")}return b}async stopReceiving(f){if(this.assertRecvDirection(),this._closed)return;for(let S of f){l.debug("stopReceiving() [localId:%s]",S);let O=this._mapMidTransceiver.get(S);if(!O)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(O.mid)}let b={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",b),await this._pc.setRemoteDescription(b);let w=await this._pc.createAnswer();l.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",w),await this._pc.setLocalDescription(w);for(let S of f)this._mapMidTransceiver.delete(S)}async pauseReceiving(f){this.assertNotClosed(),this.assertRecvDirection();for(let S of f){l.debug("pauseReceiving() [localId:%s]",S);let O=this._mapMidTransceiver.get(S);if(!O)throw new Error("associated RTCRtpTransceiver not found");O.direction="inactive",this._remoteSdp.pauseMediaSection(S)}let b={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",b),await this._pc.setRemoteDescription(b);let w=await this._pc.createAnswer();l.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",w),await this._pc.setLocalDescription(w)}async resumeReceiving(f){this.assertNotClosed(),this.assertRecvDirection();for(let S of f){l.debug("resumeReceiving() [localId:%s]",S);let O=this._mapMidTransceiver.get(S);if(!O)throw new Error("associated RTCRtpTransceiver not found");O.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(S)}let b={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",b),await this._pc.setRemoteDescription(b);let w=await this._pc.createAnswer();l.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",w),await this._pc.setLocalDescription(w)}async getReceiverStats(f){this.assertNotClosed(),this.assertRecvDirection();let b=this._mapMidTransceiver.get(f);if(!b)throw new Error("associated RTCRtpTransceiver not found");return b.receiver.getStats()}async receiveDataChannel({maxMessageSize:f,sctpStreamParameters:b,label:w,protocol:S}){this.assertNotClosed(),this.assertRecvDirection();let{streamId:O,ordered:j,maxPacketLifeTime:P,maxRetransmits:k}=b,C={negotiated:!0,id:O,ordered:j,maxPacketLifeTime:P,maxRetransmits:k,protocol:S};l.debug("receiveDataChannel() [options:%o]",C);let D=this._pc.createDataChannel(w,C);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();let H={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",H),await this._pc.setRemoteDescription(H);let W=await this._pc.createAnswer(),J=e.parse(W.sdp),F=J.media.find(q=>q.type==="application");F.maxMessageSize=f,this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:J}),W={type:"answer",sdp:e.write(J)},l.debug("receiveDataChannel() | calling pc.setLocalDescription() [answer:%o]",W),await this._pc.setLocalDescription(W),this._hasDataChannelMediaSection=!0}return{dataChannel:D}}getDataChannelMaxMessageSize(){return this._pc.sctp?.maxMessageSize}async setupTransport({localDtlsRole:f,localSdpObject:b}){b||(b=e.parse(this._pc.localDescription.sdp));let w=c.extractDtlsParameters({sdpObject:b});w.role=f,this._remoteSdp.updateDtlsRole(f==="client"?"server":"client"),await new Promise((S,O)=>{this.safeEmit("@connect",{dtlsParameters:w},S,O)}),this._transportReady=!0}onIceGatheringStateChange=()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)};onIceCandidateError=f=>{this.emit("@icecandidateerror",f)};onConnectionStateChange=()=>{this.emit("@connectionstatechange",this._pc.connectionState)};onIceConnectionStateChange=()=>{switch(this._pc.iceConnectionState){case"checking":{this.emit("@connectionstatechange","connecting");break}case"connected":case"completed":{this.emit("@connectionstatechange","connected");break}case"failed":{this.emit("@connectionstatechange","failed");break}case"disconnected":{this.emit("@connectionstatechange","disconnected");break}case"closed":{this.emit("@connectionstatechange","closed");break}}};assertNotClosed(){if(this._closed)throw new i.InvalidStateError("method called in a closed handler")}assertSendDirection(){if(this._direction!=="send")throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if(this._direction!=="recv")throw new Error('method can just be called for handlers with "recv" direction')}};t.Chrome74=m}),Wre=nt(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Firefox120=void 0;var e=wc(),r=Xs(),s=Os(),n=Zn(),i=ea(),o=Jh(),a=gg(),c=yg(),d=bg(),u=xg(),l=new s.Logger("Firefox120"),h="Firefox120",p={OS:16,MIS:2048},m=class T1 extends r.EnhancedEventEmitter{_closed=!1;_direction;_remoteSdp;_getSendExtendedRtpCapabilities;_pc;_mapMidTransceiver=new Map;_sendStream=new MediaStream;_hasDataChannelMediaSection=!1;_nextSendSctpStreamId=0;_transportReady=!1;static createFactory(){return{name:h,factory:f=>new T1(f),getNativeRtpCapabilities:async({direction:f})=>{l.debug("getNativeRtpCapabilities() [direction:%o]",f);let b=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"}),w=document.createElement("canvas");w.getContext("2d");let S=w.captureStream().getVideoTracks()[0];try{b.addTransceiver("audio",{direction:f}),b.addTransceiver(S,{direction:f,sendEncodings:[{rid:"r0",maxBitrate:1e5},{rid:"r1",maxBitrate:5e5}]});let O=await b.createOffer();try{w.remove()}catch{}try{S.stop()}catch{}try{b.close()}catch{}b=void 0;let j=e.parse(O.sdp);return T1.getLocalRtpCapabilities(j)}catch(O){try{w.remove()}catch{}try{S.stop()}catch{}try{b?.close()}catch{}throw b=void 0,O}},getNativeSctpCapabilities:async()=>(l.debug("getNativeSctpCapabilities()"),{numStreams:p})}}static getLocalRtpCapabilities(f){let b=c.extractRtpCapabilities({sdpObject:f});return i.validateAndNormalizeRtpCapabilities(b),b}constructor({direction:f,iceParameters:b,iceCandidates:w,dtlsParameters:S,sctpParameters:O,iceServers:j,iceTransportPolicy:P,additionalSettings:k,getSendExtendedRtpCapabilities:C}){super(),l.debug("constructor()"),this._direction=f,this._remoteSdp=new a.RemoteSdp({iceParameters:b,iceCandidates:w,dtlsParameters:S,sctpParameters:O}),this._getSendExtendedRtpCapabilities=C,this._pc=new RTCPeerConnection({iceServers:j??[],iceTransportPolicy:P??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...k}),this._pc.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.addEventListener("icecandidateerror",this.onIceCandidateError),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",this.onConnectionStateChange):(l.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return h}close(){if(l.debug("close()"),!this._closed){this._closed=!0;try{this._pc.close()}catch{}this._pc.removeEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.removeEventListener("icecandidateerror",this.onIceCandidateError),this._pc.removeEventListener("connectionstatechange",this.onConnectionStateChange),this._pc.removeEventListener("iceconnectionstatechange",this.onIceConnectionStateChange),this.emit("@close"),super.close()}}async updateIceServers(f){throw this.assertNotClosed(),new n.UnsupportedError("not supported")}async restartIce(f){if(this.assertNotClosed(),l.debug("restartIce()"),this._remoteSdp.updateIceParameters(f),!!this._transportReady)if(this._direction==="send"){let b=await this._pc.createOffer({iceRestart:!0});l.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",b),await this._pc.setLocalDescription(b);let w={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",w),await this._pc.setRemoteDescription(w)}else{let b={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",b),await this._pc.setRemoteDescription(b);let w=await this._pc.createAnswer();l.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",w),await this._pc.setLocalDescription(w)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:f,streamId:b,encodings:w,codecOptions:S,codec:O,onRtpSender:j}){this.assertNotClosed(),this.assertSendDirection(),l.debug("send() [kind:%s, track.id:%s, streamId:%s]",f.kind,f.id,b),w&&w.length>1&&w.forEach((Y,Z)=>{Y.rid=`r${Z}`});let P=this._pc.addTransceiver(f,{direction:"sendonly",streams:[this._sendStream],sendEncodings:w});j&&j(P.sender);let k=await this._pc.createOffer(),C=e.parse(k.sdp);C.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();let D=T1.getLocalRtpCapabilities(C),H=this._getSendExtendedRtpCapabilities(D),W=i.getSendingRtpParameters(f.kind,H);W.codecs=i.reduceCodecs(W.codecs,O);let J=i.getSendingRemoteRtpParameters(f.kind,H);J.codecs=i.reduceCodecs(J.codecs,O),this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:C});let F=(0,o.parse)((w??[{}])[0].scalabilityMode);l.debug("send() | calling pc.setLocalDescription() [offer:%o]",k),await this._pc.setLocalDescription(k);let q=P.mid;W.mid=q,C=e.parse(this._pc.localDescription.sdp);let Q=C.media[C.media.length-1];if(W.rtcp.cname=c.getCname({offerMediaObject:Q}),W.msid=`${b??this._sendStream.id} ${f.id}`,!w)W.encodings=d.getRtpEncodings({offerMediaObject:Q,codecs:W.codecs});else if(w.length===1){let Y=d.getRtpEncodings({offerMediaObject:Q,codecs:W.codecs});Object.assign(Y[0],w[0]),W.encodings=Y}else W.encodings=w;if(W.encodings.length>1&&(W.codecs[0].mimeType.toLowerCase()==="video/vp8"||W.codecs[0].mimeType.toLowerCase()==="video/h264"))for(let Y of W.encodings)Y.scalabilityMode?Y.scalabilityMode=`L1T${F.temporalLayers}`:Y.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:Q,offerRtpParameters:W,answerRtpParameters:J,codecOptions:S});let R={type:"answer",sdp:this._remoteSdp.getSdp()};return l.debug("send() | calling pc.setRemoteDescription() [answer:%o]",R),await this._pc.setRemoteDescription(R),this._mapMidTransceiver.set(q,P),{localId:q,rtpParameters:W,rtpSender:P.sender}}async stopSending(f){if(this.assertSendDirection(),l.debug("stopSending() [localId:%s]",f),this._closed)return;let b=this._mapMidTransceiver.get(f);if(!b)throw new Error("associated transceiver not found");b.sender.replaceTrack(null),this._pc.removeTrack(b.sender),this._remoteSdp.disableMediaSection(b.mid);let w=await this._pc.createOffer();l.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",w),await this._pc.setLocalDescription(w);let S={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",S),await this._pc.setRemoteDescription(S),this._mapMidTransceiver.delete(f)}async pauseSending(f){this.assertNotClosed(),this.assertSendDirection(),l.debug("pauseSending() [localId:%s]",f);let b=this._mapMidTransceiver.get(f);if(!b)throw new Error("associated RTCRtpTransceiver not found");b.direction="inactive",this._remoteSdp.pauseMediaSection(f);let w=await this._pc.createOffer();l.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",w),await this._pc.setLocalDescription(w);let S={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",S),await this._pc.setRemoteDescription(S)}async resumeSending(f){this.assertNotClosed(),this.assertSendDirection(),l.debug("resumeSending() [localId:%s]",f);let b=this._mapMidTransceiver.get(f);if(!b)throw new Error("associated RTCRtpTransceiver not found");b.direction="sendonly",this._remoteSdp.resumeSendingMediaSection(f);let w=await this._pc.createOffer();l.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",w),await this._pc.setLocalDescription(w);let S={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",S),await this._pc.setRemoteDescription(S)}async replaceTrack(f,b){this.assertNotClosed(),this.assertSendDirection(),b?l.debug("replaceTrack() [localId:%s, track.id:%s]",f,b.id):l.debug("replaceTrack() [localId:%s, no track]",f);let w=this._mapMidTransceiver.get(f);if(!w)throw new Error("associated RTCRtpTransceiver not found");await w.sender.replaceTrack(b)}async setMaxSpatialLayer(f,b){this.assertNotClosed(),this.assertSendDirection(),l.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",f,b);let w=this._mapMidTransceiver.get(f);if(!w)throw new Error("associated transceiver not found");let S=w.sender.getParameters();S.encodings.forEach((P,k)=>{k<=b?P.active=!0:P.active=!1}),await w.sender.setParameters(S),this._remoteSdp.muxMediaSectionSimulcast(f,S.encodings);let O=await this._pc.createOffer();l.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",O),await this._pc.setLocalDescription(O);let j={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",j),await this._pc.setRemoteDescription(j)}async setRtpEncodingParameters(f,b){this.assertNotClosed(),this.assertSendDirection(),l.debug("setRtpEncodingParameters() [localId:%s, params:%o]",f,b);let w=this._mapMidTransceiver.get(f);if(!w)throw new Error("associated RTCRtpTransceiver not found");let S=w.sender.getParameters();S.encodings.forEach((P,k)=>{S.encodings[k]={...P,...b}}),await w.sender.setParameters(S),this._remoteSdp.muxMediaSectionSimulcast(f,S.encodings);let O=await this._pc.createOffer();l.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",O),await this._pc.setLocalDescription(O);let j={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",j),await this._pc.setRemoteDescription(j)}async getSenderStats(f){this.assertNotClosed(),this.assertSendDirection();let b=this._mapMidTransceiver.get(f);if(!b)throw new Error("associated RTCRtpTransceiver not found");return b.sender.getStats()}async sendDataChannel({sctpStreamParameters:f}){this.assertNotClosed(),this.assertSendDirection();let b={negotiated:!0,id:this._nextSendSctpStreamId,ordered:f.ordered,maxPacketLifeTime:f.maxPacketLifeTime,maxRetransmits:f.maxRetransmits,protocol:f.protocol};l.debug("sendDataChannel() [options:%o]",b);let w=this._pc.createDataChannel(f.label,b);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%p.MIS,!this._hasDataChannelMediaSection){let O=await this._pc.createOffer(),j=e.parse(O.sdp),P=j.media.find(C=>C.type==="application");this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:j}),l.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",O),await this._pc.setLocalDescription(O),this._remoteSdp.sendSctpAssociation({offerMediaObject:P});let k={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",k),await this._pc.setRemoteDescription(k),this._hasDataChannelMediaSection=!0}let S={streamId:b.id,ordered:b.ordered,maxPacketLifeTime:b.maxPacketLifeTime,maxRetransmits:b.maxRetransmits};return{dataChannel:w,sctpStreamParameters:S}}async receive(f){this.assertNotClosed(),this.assertRecvDirection();let b=[],w=new Map;for(let P of f){let{trackId:k,kind:C,rtpParameters:D,streamId:H}=P;l.debug("receive() [trackId:%s, kind:%s]",k,C);let W=D.mid??String(this._mapMidTransceiver.size);w.set(k,W);let{msidStreamId:J}=u.getMsidStreamIdAndTrackId(D.msid);this._remoteSdp.receive({mid:W,kind:C,offerRtpParameters:D,streamId:H??J??D.rtcp?.cname??"-",trackId:k})}let S={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",S),await this._pc.setRemoteDescription(S);for(let P of f){let{trackId:k,onRtpReceiver:C}=P;if(C){let D=w.get(k),H=this._pc.getTransceivers().find(W=>W.mid===D);if(!H)throw new Error("transceiver not found");C(H.receiver)}}let O=await this._pc.createAnswer(),j=e.parse(O.sdp);for(let P of f){let{trackId:k,rtpParameters:C}=P,D=w.get(k),H=j.media.find(W=>String(W.mid)===D);c.applyCodecParameters({offerRtpParameters:C,answerMediaObject:H}),O={type:"answer",sdp:e.write(j)}}this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:j}),l.debug("receive() | calling pc.setLocalDescription() [answer:%o]",O),await this._pc.setLocalDescription(O);for(let P of f){let{trackId:k}=P,C=w.get(k),D=this._pc.getTransceivers().find(H=>H.mid===C);if(!D)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(C,D),b.push({localId:C,track:D.receiver.track,rtpReceiver:D.receiver})}return b}async stopReceiving(f){if(this.assertRecvDirection(),this._closed)return;for(let S of f){l.debug("stopReceiving() [localId:%s]",S);let O=this._mapMidTransceiver.get(S);if(!O)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(O.mid)}let b={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",b),await this._pc.setRemoteDescription(b);let w=await this._pc.createAnswer();l.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",w),await this._pc.setLocalDescription(w);for(let S of f)this._mapMidTransceiver.delete(S)}async pauseReceiving(f){this.assertNotClosed(),this.assertRecvDirection();for(let S of f){l.debug("pauseReceiving() [localId:%s]",S);let O=this._mapMidTransceiver.get(S);if(!O)throw new Error("associated RTCRtpTransceiver not found");O.direction="inactive",this._remoteSdp.pauseMediaSection(S)}let b={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",b),await this._pc.setRemoteDescription(b);let w=await this._pc.createAnswer();l.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",w),await this._pc.setLocalDescription(w)}async resumeReceiving(f){this.assertNotClosed(),this.assertRecvDirection();for(let S of f){l.debug("resumeReceiving() [localId:%s]",S);let O=this._mapMidTransceiver.get(S);if(!O)throw new Error("associated RTCRtpTransceiver not found");O.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(S)}let b={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",b),await this._pc.setRemoteDescription(b);let w=await this._pc.createAnswer();l.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",w),await this._pc.setLocalDescription(w)}async getReceiverStats(f){this.assertRecvDirection();let b=this._mapMidTransceiver.get(f);if(!b)throw new Error("associated RTCRtpTransceiver not found");return b.receiver.getStats()}async receiveDataChannel({maxMessageSize:f,sctpStreamParameters:b,label:w,protocol:S}){this.assertNotClosed(),this.assertRecvDirection();let{streamId:O,ordered:j,maxPacketLifeTime:P,maxRetransmits:k}=b,C={negotiated:!0,id:O,ordered:j,maxPacketLifeTime:P,maxRetransmits:k,protocol:S};l.debug("receiveDataChannel() [options:%o]",C);let D=this._pc.createDataChannel(w,C);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();let H={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",H),await this._pc.setRemoteDescription(H);let W=await this._pc.createAnswer(),J=e.parse(W.sdp),F=J.media.find(q=>q.type==="application");F.maxMessageSize=f,this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:J}),W={type:"answer",sdp:e.write(J)},l.debug("receiveDataChannel() | calling pc.setLocalDescription() [answer:%o]",W),await this._pc.setLocalDescription(W),this._hasDataChannelMediaSection=!0}return{dataChannel:D}}getDataChannelMaxMessageSize(){return this._pc.sctp?.maxMessageSize}async setupTransport({localDtlsRole:f,localSdpObject:b}){b||(b=e.parse(this._pc.localDescription.sdp));let w=c.extractDtlsParameters({sdpObject:b});w.role=f,this._remoteSdp.updateDtlsRole(f==="client"?"server":"client"),await new Promise((S,O)=>{this.safeEmit("@connect",{dtlsParameters:w},S,O)}),this._transportReady=!0}onIceGatheringStateChange=()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)};onIceCandidateError=f=>{this.emit("@icecandidateerror",f)};onConnectionStateChange=()=>{this.emit("@connectionstatechange",this._pc.connectionState)};onIceConnectionStateChange=()=>{switch(this._pc.iceConnectionState){case"checking":{this.emit("@connectionstatechange","connecting");break}case"connected":case"completed":{this.emit("@connectionstatechange","connected");break}case"failed":{this.emit("@connectionstatechange","failed");break}case"disconnected":{this.emit("@connectionstatechange","disconnected");break}case"closed":{this.emit("@connectionstatechange","closed");break}}};assertNotClosed(){if(this._closed)throw new n.InvalidStateError("method called in a closed handler")}assertSendDirection(){if(this._direction!=="send")throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if(this._direction!=="recv")throw new Error('method can just be called for handlers with "recv" direction')}};t.Firefox120=m}),Kre=nt(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Safari12=void 0;var e=wc(),r=Xs(),s=Os(),n=ea(),i=Zn(),o=Jh(),a=gg(),c=yg(),d=bg(),u=xg(),l=new s.Logger("Safari12"),h="Safari12",p={OS:65535,MIS:65535},m=class k1 extends r.EnhancedEventEmitter{_closed=!1;_direction;_remoteSdp;_getSendExtendedRtpCapabilities;_forcedLocalDtlsRole;_pc;_mapMidTransceiver=new Map;_sendStream=new MediaStream;_hasDataChannelMediaSection=!1;_nextSendSctpStreamId=0;_transportReady=!1;static createFactory(){return{name:h,factory:f=>new k1(f),getNativeRtpCapabilities:async({direction:f})=>{l.debug("getNativeRtpCapabilities() [direction:%o]",f);let b=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{b.addTransceiver("audio",{direction:f}),b.addTransceiver("video",{direction:f});let w=await b.createOffer();try{b.close()}catch{}b=void 0;let S=e.parse(w.sdp);return k1.getLocalRtpCapabilities(S)}catch(w){try{b?.close()}catch{}throw b=void 0,w}},getNativeSctpCapabilities:async()=>(l.debug("getNativeSctpCapabilities()"),{numStreams:p})}}static getLocalRtpCapabilities(f,b=[]){let w=c.extractRtpCapabilities({sdpObject:f});n.validateAndNormalizeRtpCapabilities(w),u.addNackSupportForOpus(w);for(let S of b)u.addHeaderExtensionSupport(w,S);return w}constructor({direction:f,iceParameters:b,iceCandidates:w,dtlsParameters:S,sctpParameters:O,iceServers:j,iceTransportPolicy:P,additionalSettings:k,getSendExtendedRtpCapabilities:C}){super(),l.debug("constructor()"),this._direction=f,this._remoteSdp=new a.RemoteSdp({iceParameters:b,iceCandidates:w,dtlsParameters:S,sctpParameters:O}),this._getSendExtendedRtpCapabilities=C,S.role&&S.role!=="auto"&&(this._forcedLocalDtlsRole=S.role==="server"?"client":"server"),this._pc=new RTCPeerConnection({iceServers:j??[],iceTransportPolicy:P??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...k}),this._pc.addEventListener("icegatheringstatechange",()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)}),this._pc.addEventListener("icecandidateerror",D=>{this.emit("@icecandidateerror",D)}),this._pc.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.addEventListener("icecandidateerror",this.onIceCandidateError),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",this.onConnectionStateChange):(l.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return h}close(){if(l.debug("close()"),!this._closed){this._closed=!0;try{this._pc.close()}catch{}this._pc.removeEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.removeEventListener("icecandidateerror",this.onIceCandidateError),this._pc.removeEventListener("connectionstatechange",this.onConnectionStateChange),this._pc.removeEventListener("iceconnectionstatechange",this.onIceConnectionStateChange),this.emit("@close"),super.close()}}async updateIceServers(f){this.assertNotClosed(),l.debug("updateIceServers()");let b=this._pc.getConfiguration();b.iceServers=f,this._pc.setConfiguration(b)}async restartIce(f){if(this.assertNotClosed(),l.debug("restartIce()"),this._remoteSdp.updateIceParameters(f),!!this._transportReady)if(this._direction==="send"){let b=await this._pc.createOffer({iceRestart:!0});l.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",b),await this._pc.setLocalDescription(b);let w={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",w),await this._pc.setRemoteDescription(w)}else{let b={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",b),await this._pc.setRemoteDescription(b);let w=await this._pc.createAnswer();l.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",w),await this._pc.setLocalDescription(w)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:f,streamId:b,encodings:w,codecOptions:S,headerExtensionOptions:O,codec:j,onRtpSender:P}){this.assertNotClosed(),this.assertSendDirection(),l.debug("send() [kind:%s, track.id:%s, streamId:%s]",f.kind,f.id,b);let k=this._remoteSdp.getNextMediaSectionIdx(),C=this._pc.addTransceiver(f,{direction:"sendonly",streams:[this._sendStream]});P&&P(C.sender);let D=await this._pc.createOffer(),H=e.parse(D.sdp);H.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();let W=[];W.push({uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",kind:f.kind,direction:"sendonly"});let J=k1.getLocalRtpCapabilities(H,W),F=this._getSendExtendedRtpCapabilities(J),q=n.getSendingRtpParameters(f.kind,F);q.codecs=n.reduceCodecs(q.codecs,j);let Q=n.getSendingRemoteRtpParameters(f.kind,F);Q.codecs=n.reduceCodecs(Q.codecs,j);let R;this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:H});let Y=(0,o.parse)((w??[{}])[0].scalabilityMode);w&&w.length>1&&(l.debug("send() | enabling legacy simulcast"),H=e.parse(D.sdp),R=H.media[k.idx],d.addLegacySimulcast({offerMediaObject:R,numStreams:w.length}),D={type:"offer",sdp:e.write(H)}),O?.absCaptureTime&&(R=H.media[k.idx],c.addHeaderExtension({offerMediaObject:R,headerExtensionUri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",headerExtensionId:Q.headerExtensions.find(U=>U.uri==="http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time").id}),D={type:"offer",sdp:e.write(H)}),l.debug("send() | calling pc.setLocalDescription() [offer:%o]",D),await this._pc.setLocalDescription(D);let Z=C.mid;if(q.mid=Z,H=e.parse(this._pc.localDescription.sdp),R=H.media[k.idx],q.rtcp.cname=c.getCname({offerMediaObject:R}),q.msid=`${b??this._sendStream.id} ${f.id}`,q.encodings=d.getRtpEncodings({offerMediaObject:R,codecs:q.codecs}),w)for(let U=0;U<q.encodings.length;++U)w[U]&&Object.assign(q.encodings[U],w[U]);if(q.encodings.length>1&&(q.codecs[0].mimeType.toLowerCase()==="video/vp8"||q.codecs[0].mimeType.toLowerCase()==="video/h264"))for(let U of q.encodings)U.scalabilityMode?U.scalabilityMode=`L1T${Y.temporalLayers}`:U.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:R,reuseMid:k.reuseMid,offerRtpParameters:q,answerRtpParameters:Q,codecOptions:S});let I={type:"answer",sdp:this._remoteSdp.getSdp()};return l.debug("send() | calling pc.setRemoteDescription() [answer:%o]",I),await this._pc.setRemoteDescription(I),this._mapMidTransceiver.set(Z,C),{localId:Z,rtpParameters:q,rtpSender:C.sender}}async stopSending(f){if(this.assertSendDirection(),this._closed)return;l.debug("stopSending() [localId:%s]",f);let b=this._mapMidTransceiver.get(f);if(!b)throw new Error("associated RTCRtpTransceiver not found");if(b.sender.replaceTrack(null),this._pc.removeTrack(b.sender),this._remoteSdp.closeMediaSection(b.mid))try{b.stop()}catch{}let w=await this._pc.createOffer();l.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",w),await this._pc.setLocalDescription(w);let S={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",S),await this._pc.setRemoteDescription(S),this._mapMidTransceiver.delete(f)}async pauseSending(f){this.assertNotClosed(),this.assertSendDirection(),l.debug("pauseSending() [localId:%s]",f);let b=this._mapMidTransceiver.get(f);if(!b)throw new Error("associated RTCRtpTransceiver not found");b.direction="inactive",this._remoteSdp.pauseMediaSection(f);let w=await this._pc.createOffer();l.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",w),await this._pc.setLocalDescription(w);let S={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",S),await this._pc.setRemoteDescription(S)}async resumeSending(f){this.assertNotClosed(),this.assertSendDirection(),l.debug("resumeSending() [localId:%s]",f);let b=this._mapMidTransceiver.get(f);if(!b)throw new Error("associated RTCRtpTransceiver not found");b.direction="sendonly",this._remoteSdp.resumeSendingMediaSection(f);let w=await this._pc.createOffer();l.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",w),await this._pc.setLocalDescription(w);let S={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",S),await this._pc.setRemoteDescription(S)}async replaceTrack(f,b){this.assertNotClosed(),this.assertSendDirection(),b?l.debug("replaceTrack() [localId:%s, track.id:%s]",f,b.id):l.debug("replaceTrack() [localId:%s, no track]",f);let w=this._mapMidTransceiver.get(f);if(!w)throw new Error("associated RTCRtpTransceiver not found");await w.sender.replaceTrack(b)}async setMaxSpatialLayer(f,b){this.assertNotClosed(),this.assertSendDirection(),l.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",f,b);let w=this._mapMidTransceiver.get(f);if(!w)throw new Error("associated RTCRtpTransceiver not found");let S=w.sender.getParameters();S.encodings.forEach((P,k)=>{k<=b?P.active=!0:P.active=!1}),await w.sender.setParameters(S),this._remoteSdp.muxMediaSectionSimulcast(f,S.encodings);let O=await this._pc.createOffer();l.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",O),await this._pc.setLocalDescription(O);let j={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",j),await this._pc.setRemoteDescription(j)}async setRtpEncodingParameters(f,b){this.assertNotClosed(),this.assertSendDirection(),l.debug("setRtpEncodingParameters() [localId:%s, params:%o]",f,b);let w=this._mapMidTransceiver.get(f);if(!w)throw new Error("associated RTCRtpTransceiver not found");let S=w.sender.getParameters();S.encodings.forEach((P,k)=>{S.encodings[k]={...P,...b}}),await w.sender.setParameters(S),this._remoteSdp.muxMediaSectionSimulcast(f,S.encodings);let O=await this._pc.createOffer();l.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",O),await this._pc.setLocalDescription(O);let j={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",j),await this._pc.setRemoteDescription(j)}async getSenderStats(f){this.assertNotClosed(),this.assertSendDirection();let b=this._mapMidTransceiver.get(f);if(!b)throw new Error("associated RTCRtpTransceiver not found");return b.sender.getStats()}async sendDataChannel({sctpStreamParameters:f}){this.assertNotClosed(),this.assertSendDirection();let b={negotiated:!0,id:this._nextSendSctpStreamId,ordered:f.ordered,maxPacketLifeTime:f.maxPacketLifeTime,maxRetransmits:f.maxRetransmits,protocol:f.protocol};l.debug("sendDataChannel() [options:%o]",b);let w=this._pc.createDataChannel(f.label,b);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%p.MIS,!this._hasDataChannelMediaSection){let O=await this._pc.createOffer(),j=e.parse(O.sdp),P=j.media.find(C=>C.type==="application");this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:j}),l.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",O),await this._pc.setLocalDescription(O),this._remoteSdp.sendSctpAssociation({offerMediaObject:P});let k={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",k),await this._pc.setRemoteDescription(k),this._hasDataChannelMediaSection=!0}let S={streamId:b.id,ordered:b.ordered,maxPacketLifeTime:b.maxPacketLifeTime,maxRetransmits:b.maxRetransmits};return{dataChannel:w,sctpStreamParameters:S}}async receive(f){this.assertNotClosed(),this.assertRecvDirection();let b=[],w=new Map;for(let P of f){let{trackId:k,kind:C,rtpParameters:D,streamId:H}=P;l.debug("receive() [trackId:%s, kind:%s]",k,C);let W=D.mid??String(this._mapMidTransceiver.size);w.set(k,W);let{msidStreamId:J}=u.getMsidStreamIdAndTrackId(D.msid);this._remoteSdp.receive({mid:W,kind:C,offerRtpParameters:D,streamId:H??J??D.rtcp?.cname??"-",trackId:k})}let S={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",S),await this._pc.setRemoteDescription(S);for(let P of f){let{trackId:k,onRtpReceiver:C}=P;if(C){let D=w.get(k),H=this._pc.getTransceivers().find(W=>W.mid===D);if(!H)throw new Error("transceiver not found");C(H.receiver)}}let O=await this._pc.createAnswer(),j=e.parse(O.sdp);for(let P of f){let{trackId:k,rtpParameters:C}=P,D=w.get(k),H=j.media.find(W=>String(W.mid)===D);c.applyCodecParameters({offerRtpParameters:C,answerMediaObject:H})}O={type:"answer",sdp:e.write(j)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:j}),l.debug("receive() | calling pc.setLocalDescription() [answer:%o]",O),await this._pc.setLocalDescription(O);for(let P of f){let{trackId:k}=P,C=w.get(k),D=this._pc.getTransceivers().find(H=>H.mid===C);if(!D)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(C,D),b.push({localId:C,track:D.receiver.track,rtpReceiver:D.receiver})}return b}async stopReceiving(f){if(this.assertRecvDirection(),this._closed)return;for(let S of f){l.debug("stopReceiving() [localId:%s]",S);let O=this._mapMidTransceiver.get(S);if(!O)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(O.mid)}let b={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",b),await this._pc.setRemoteDescription(b);let w=await this._pc.createAnswer();l.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",w),await this._pc.setLocalDescription(w);for(let S of f)this._mapMidTransceiver.delete(S)}async pauseReceiving(f){this.assertNotClosed(),this.assertRecvDirection();for(let S of f){l.debug("pauseReceiving() [localId:%s]",S);let O=this._mapMidTransceiver.get(S);if(!O)throw new Error("associated RTCRtpTransceiver not found");O.direction="inactive",this._remoteSdp.pauseMediaSection(S)}let b={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",b),await this._pc.setRemoteDescription(b);let w=await this._pc.createAnswer();l.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",w),await this._pc.setLocalDescription(w)}async resumeReceiving(f){this.assertNotClosed(),this.assertRecvDirection();for(let S of f){l.debug("resumeReceiving() [localId:%s]",S);let O=this._mapMidTransceiver.get(S);if(!O)throw new Error("associated RTCRtpTransceiver not found");O.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(S)}let b={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",b),await this._pc.setRemoteDescription(b);let w=await this._pc.createAnswer();l.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",w),await this._pc.setLocalDescription(w)}async getReceiverStats(f){this.assertNotClosed(),this.assertRecvDirection();let b=this._mapMidTransceiver.get(f);if(!b)throw new Error("associated RTCRtpTransceiver not found");return b.receiver.getStats()}async receiveDataChannel({maxMessageSize:f,sctpStreamParameters:b,label:w,protocol:S}){this.assertNotClosed(),this.assertRecvDirection();let{streamId:O,ordered:j,maxPacketLifeTime:P,maxRetransmits:k}=b,C={negotiated:!0,id:O,ordered:j,maxPacketLifeTime:P,maxRetransmits:k,protocol:S};l.debug("receiveDataChannel() [options:%o]",C);let D=this._pc.createDataChannel(w,C);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();let H={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",H),await this._pc.setRemoteDescription(H);let W=await this._pc.createAnswer(),J=e.parse(W.sdp),F=J.media.find(q=>q.type==="application");F.maxMessageSize=f,this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:J}),W={type:"answer",sdp:e.write(J)},l.debug("receiveDataChannel() | calling pc.setLocalDescription() [answer:%o]",W),await this._pc.setLocalDescription(W),this._hasDataChannelMediaSection=!0}return{dataChannel:D}}getDataChannelMaxMessageSize(){return this._pc.sctp?.maxMessageSize}async setupTransport({localDtlsRole:f,localSdpObject:b}){b||(b=e.parse(this._pc.localDescription.sdp));let w=c.extractDtlsParameters({sdpObject:b});w.role=f,this._remoteSdp.updateDtlsRole(f==="client"?"server":"client"),await new Promise((S,O)=>{this.safeEmit("@connect",{dtlsParameters:w},S,O)}),this._transportReady=!0}onIceGatheringStateChange=()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)};onIceCandidateError=f=>{this.emit("@icecandidateerror",f)};onConnectionStateChange=()=>{this.emit("@connectionstatechange",this._pc.connectionState)};onIceConnectionStateChange=()=>{switch(this._pc.iceConnectionState){case"checking":{this.emit("@connectionstatechange","connecting");break}case"connected":case"completed":{this.emit("@connectionstatechange","connected");break}case"failed":{this.emit("@connectionstatechange","failed");break}case"disconnected":{this.emit("@connectionstatechange","disconnected");break}case"closed":{this.emit("@connectionstatechange","closed");break}}};assertNotClosed(){if(this._closed)throw new i.InvalidStateError("method called in a closed handler")}assertSendDirection(){if(this._direction!=="send")throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if(this._direction!=="recv")throw new Error('method can just be called for handlers with "recv" direction')}};t.Safari12=m}),Gre=nt(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ReactNative106=void 0;var e=wc(),r=Xs(),s=Os(),n=ea(),i=Zn(),o=Jh(),a=gg(),c=yg(),d=bg(),u=xg(),l=new s.Logger("ReactNative106"),h="ReactNative106",p={OS:65535,MIS:65535},m=class A1 extends r.EnhancedEventEmitter{_closed=!1;_direction;_remoteSdp;_getSendExtendedRtpCapabilities;_forcedLocalDtlsRole;_pc;_mapMidTransceiver=new Map;_sendStream=new MediaStream;_hasDataChannelMediaSection=!1;_nextSendSctpStreamId=0;_transportReady=!1;static createFactory(){return{name:h,factory:f=>new A1(f),getNativeRtpCapabilities:async({direction:f})=>{l.debug("getNativeRtpCapabilities() [direction:%o]",f);let b=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{b.addTransceiver("audio",{direction:f}),b.addTransceiver("video",{direction:f});let w=await b.createOffer();try{b.close()}catch{}b=void 0;let S=e.parse(w.sdp);return A1.getLocalRtpCapabilities(S)}catch(w){try{b?.close()}catch{}throw b=void 0,w}},getNativeSctpCapabilities:async()=>(l.debug("getNativeSctpCapabilities()"),{numStreams:p})}}static getLocalRtpCapabilities(f,b=[]){let w=c.extractRtpCapabilities({sdpObject:f});n.validateAndNormalizeRtpCapabilities(w),u.addNackSupportForOpus(w);for(let S of b)u.addHeaderExtensionSupport(w,S);return w}constructor({direction:f,iceParameters:b,iceCandidates:w,dtlsParameters:S,sctpParameters:O,iceServers:j,iceTransportPolicy:P,additionalSettings:k,getSendExtendedRtpCapabilities:C}){super(),l.debug("constructor()"),this._direction=f,this._remoteSdp=new a.RemoteSdp({iceParameters:b,iceCandidates:w,dtlsParameters:S,sctpParameters:O}),this._getSendExtendedRtpCapabilities=C,S.role&&S.role!=="auto"&&(this._forcedLocalDtlsRole=S.role==="server"?"client":"server"),this._pc=new RTCPeerConnection({iceServers:j??[],iceTransportPolicy:P??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...k}),this._pc.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.addEventListener("icecandidateerror",this.onIceCandidateError),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",this.onConnectionStateChange):(l.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return h}close(){if(l.debug("close()"),!this._closed){this._closed=!0,this._sendStream.release(!1);try{this._pc.close()}catch{}this._pc.removeEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.removeEventListener("icecandidateerror",this.onIceCandidateError),this._pc.removeEventListener("connectionstatechange",this.onConnectionStateChange),this._pc.removeEventListener("iceconnectionstatechange",this.onIceConnectionStateChange),this.emit("@close"),super.close()}}async updateIceServers(f){this.assertNotClosed(),l.debug("updateIceServers()");let b=this._pc.getConfiguration();b.iceServers=f,this._pc.setConfiguration(b)}async restartIce(f){if(this.assertNotClosed(),l.debug("restartIce()"),this._remoteSdp.updateIceParameters(f),!!this._transportReady)if(this._direction==="send"){let b=await this._pc.createOffer({iceRestart:!0});l.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",b),await this._pc.setLocalDescription(b);let w={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",w),await this._pc.setRemoteDescription(w)}else{let b={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",b),await this._pc.setRemoteDescription(b);let w=await this._pc.createAnswer();l.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",w),await this._pc.setLocalDescription(w)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:f,streamId:b,encodings:w,codecOptions:S,headerExtensionOptions:O,codec:j,onRtpSender:P}){this.assertNotClosed(),this.assertSendDirection(),l.debug("send() [kind:%s, track.id:%s, streamId:%s]",f.kind,f.id,b),w&&w.length>1&&w.forEach((K,z)=>{K.rid=`r${z}`});let k=this._remoteSdp.getNextMediaSectionIdx(),C=this._pc.addTransceiver(f,{direction:"sendonly",streams:[this._sendStream],sendEncodings:w});P&&P(C.sender);let D=await this._pc.createOffer(),H=e.parse(D.sdp);H.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();let W=[];W.push({uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",kind:f.kind,direction:"sendonly"});let J=A1.getLocalRtpCapabilities(H,W),F=this._getSendExtendedRtpCapabilities(J),q=n.getSendingRtpParameters(f.kind,F);q.codecs=n.reduceCodecs(q.codecs,j);let Q=n.getSendingRemoteRtpParameters(f.kind,F);Q.codecs=n.reduceCodecs(Q.codecs,j),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:H});let R=!1,Y=(0,o.parse)((w??[{}])[0].scalabilityMode),Z;w?.length===1&&Y.spatialLayers>1&&q.codecs[0].mimeType.toLowerCase()==="video/vp9"&&(l.debug("send() | enabling legacy simulcast for VP9 SVC"),R=!0,H=e.parse(D.sdp),Z=H.media[k.idx],d.addLegacySimulcast({offerMediaObject:Z,numStreams:Y.spatialLayers}),D={type:"offer",sdp:e.write(H)}),O?.absCaptureTime&&(Z=H.media[k.idx],c.addHeaderExtension({offerMediaObject:Z,headerExtensionUri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",headerExtensionId:Q.headerExtensions.find(K=>K.uri==="http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time").id}),D={type:"offer",sdp:e.write(H)}),l.debug("send() | calling pc.setLocalDescription() [offer:%o]",D),await this._pc.setLocalDescription(D);let I=C.mid??void 0;if(I||l.warn("send() | missing transceiver.mid (bug in react-native-webrtc, using a workaround"),q.mid=I,H=e.parse(this._pc.localDescription.sdp),Z=H.media[k.idx],q.rtcp.cname=c.getCname({offerMediaObject:Z}),q.msid=`${b??this._sendStream.id} ${f.id}`,!w)q.encodings=d.getRtpEncodings({offerMediaObject:Z,codecs:q.codecs});else if(w.length===1){let K=d.getRtpEncodings({offerMediaObject:Z,codecs:q.codecs});Object.assign(K[0],w[0]),R&&(K=[K[0]]),q.encodings=K}else q.encodings=w;if(q.encodings.length>1&&(q.codecs[0].mimeType.toLowerCase()==="video/vp8"||q.codecs[0].mimeType.toLowerCase()==="video/h264"))for(let K of q.encodings)K.scalabilityMode?K.scalabilityMode=`L1T${Y.temporalLayers}`:K.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:Z,reuseMid:k.reuseMid,offerRtpParameters:q,answerRtpParameters:Q,codecOptions:S});let U={type:"answer",sdp:this._remoteSdp.getSdp()};return l.debug("send() | calling pc.setRemoteDescription() [answer:%o]",U),await this._pc.setRemoteDescription(U),I||(I=C.mid,q.mid=I),this._mapMidTransceiver.set(I,C),{localId:I,rtpParameters:q,rtpSender:C.sender}}async stopSending(f){if(this.assertSendDirection(),this._closed)return;l.debug("stopSending() [localId:%s]",f);let b=this._mapMidTransceiver.get(f);if(!b)throw new Error("associated RTCRtpTransceiver not found");if(b.sender.replaceTrack(null),this._pc.removeTrack(b.sender),this._remoteSdp.closeMediaSection(b.mid))try{b.stop()}catch{}let w=await this._pc.createOffer();l.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",w),await this._pc.setLocalDescription(w);let S={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",S),await this._pc.setRemoteDescription(S),this._mapMidTransceiver.delete(f)}async pauseSending(f){this.assertNotClosed(),this.assertSendDirection(),l.debug("pauseSending() [localId:%s]",f);let b=this._mapMidTransceiver.get(f);if(!b)throw new Error("associated RTCRtpTransceiver not found");b.direction="inactive",this._remoteSdp.pauseMediaSection(f);let w=await this._pc.createOffer();l.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",w),await this._pc.setLocalDescription(w);let S={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",S),await this._pc.setRemoteDescription(S)}async resumeSending(f){this.assertNotClosed(),this.assertSendDirection(),l.debug("resumeSending() [localId:%s]",f);let b=this._mapMidTransceiver.get(f);if(this._remoteSdp.resumeSendingMediaSection(f),!b)throw new Error("associated RTCRtpTransceiver not found");b.direction="sendonly";let w=await this._pc.createOffer();l.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",w),await this._pc.setLocalDescription(w);let S={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",S),await this._pc.setRemoteDescription(S)}async replaceTrack(f,b){this.assertNotClosed(),this.assertSendDirection(),b?l.debug("replaceTrack() [localId:%s, track.id:%s]",f,b.id):l.debug("replaceTrack() [localId:%s, no track]",f);let w=this._mapMidTransceiver.get(f);if(!w)throw new Error("associated RTCRtpTransceiver not found");await w.sender.replaceTrack(b)}async setMaxSpatialLayer(f,b){this.assertNotClosed(),this.assertSendDirection(),l.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",f,b);let w=this._mapMidTransceiver.get(f);if(!w)throw new Error("associated RTCRtpTransceiver not found");let S=w.sender.getParameters();S.encodings.forEach((P,k)=>{k<=b?P.active=!0:P.active=!1}),await w.sender.setParameters(S),this._remoteSdp.muxMediaSectionSimulcast(f,S.encodings);let O=await this._pc.createOffer();l.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",O),await this._pc.setLocalDescription(O);let j={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",j),await this._pc.setRemoteDescription(j)}async setRtpEncodingParameters(f,b){this.assertNotClosed(),this.assertSendDirection(),l.debug("setRtpEncodingParameters() [localId:%s, params:%o]",f,b);let w=this._mapMidTransceiver.get(f);if(!w)throw new Error("associated RTCRtpTransceiver not found");let S=w.sender.getParameters();S.encodings.forEach((P,k)=>{S.encodings[k]={...P,...b}}),await w.sender.setParameters(S),this._remoteSdp.muxMediaSectionSimulcast(f,S.encodings);let O=await this._pc.createOffer();l.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",O),await this._pc.setLocalDescription(O);let j={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",j),await this._pc.setRemoteDescription(j)}async getSenderStats(f){this.assertNotClosed(),this.assertSendDirection();let b=this._mapMidTransceiver.get(f);if(!b)throw new Error("associated RTCRtpTransceiver not found");return b.sender.getStats()}async sendDataChannel({sctpStreamParameters:f}){this.assertNotClosed(),this.assertSendDirection();let b={negotiated:!0,id:this._nextSendSctpStreamId,ordered:f.ordered,maxPacketLifeTime:f.maxPacketLifeTime,maxRetransmits:f.maxRetransmits,protocol:f.protocol};l.debug("sendDataChannel() [options:%o]",b);let w=this._pc.createDataChannel(f.label,b);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%p.MIS,!this._hasDataChannelMediaSection){let O=await this._pc.createOffer(),j=e.parse(O.sdp),P=j.media.find(C=>C.type==="application");this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:j}),l.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",O),await this._pc.setLocalDescription(O),this._remoteSdp.sendSctpAssociation({offerMediaObject:P});let k={type:"answer",sdp:this._remoteSdp.getSdp()};l.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",k),await this._pc.setRemoteDescription(k),this._hasDataChannelMediaSection=!0}let S={streamId:b.id,ordered:b.ordered,maxPacketLifeTime:b.maxPacketLifeTime,maxRetransmits:b.maxRetransmits};return{dataChannel:w,sctpStreamParameters:S}}async receive(f){this.assertNotClosed(),this.assertRecvDirection();let b=[],w=new Map;for(let P of f){let{trackId:k,kind:C,rtpParameters:D,streamId:H}=P;l.debug("receive() [trackId:%s, kind:%s]",k,C);let W=D.mid??String(this._mapMidTransceiver.size);w.set(k,W);let{msidStreamId:J}=u.getMsidStreamIdAndTrackId(D.msid);this._remoteSdp.receive({mid:W,kind:C,offerRtpParameters:D,streamId:H??J??D.rtcp?.cname??"-",trackId:k})}let S={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",S),await this._pc.setRemoteDescription(S);for(let P of f){let{trackId:k,onRtpReceiver:C}=P;if(C){let D=w.get(k),H=this._pc.getTransceivers().find(W=>W.mid===D);if(!H)throw new Error("transceiver not found");C(H.receiver)}}let O=await this._pc.createAnswer(),j=e.parse(O.sdp);for(let P of f){let{trackId:k,rtpParameters:C}=P,D=w.get(k),H=j.media.find(W=>String(W.mid)===D);c.applyCodecParameters({offerRtpParameters:C,answerMediaObject:H})}O={type:"answer",sdp:e.write(j)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:j}),l.debug("receive() | calling pc.setLocalDescription() [answer:%o]",O),await this._pc.setLocalDescription(O);for(let P of f){let{trackId:k}=P,C=w.get(k),D=this._pc.getTransceivers().find(H=>H.mid===C);if(D)this._mapMidTransceiver.set(C,D),b.push({localId:C,track:D.receiver.track,rtpReceiver:D.receiver});else throw new Error("new RTCRtpTransceiver not found")}return b}async stopReceiving(f){if(this.assertRecvDirection(),this._closed)return;for(let S of f){l.debug("stopReceiving() [localId:%s]",S);let O=this._mapMidTransceiver.get(S);if(!O)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(O.mid)}let b={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",b),await this._pc.setRemoteDescription(b);let w=await this._pc.createAnswer();l.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",w),await this._pc.setLocalDescription(w);for(let S of f)this._mapMidTransceiver.delete(S)}async pauseReceiving(f){this.assertNotClosed(),this.assertRecvDirection();for(let S of f){l.debug("pauseReceiving() [localId:%s]",S);let O=this._mapMidTransceiver.get(S);if(!O)throw new Error("associated RTCRtpTransceiver not found");O.direction="inactive",this._remoteSdp.pauseMediaSection(S)}let b={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",b),await this._pc.setRemoteDescription(b);let w=await this._pc.createAnswer();l.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",w),await this._pc.setLocalDescription(w)}async resumeReceiving(f){this.assertNotClosed(),this.assertRecvDirection();for(let S of f){l.debug("resumeReceiving() [localId:%s]",S);let O=this._mapMidTransceiver.get(S);if(!O)throw new Error("associated RTCRtpTransceiver not found");O.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(S)}let b={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",b),await this._pc.setRemoteDescription(b);let w=await this._pc.createAnswer();l.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",w),await this._pc.setLocalDescription(w)}async getReceiverStats(f){this.assertNotClosed(),this.assertRecvDirection();let b=this._mapMidTransceiver.get(f);if(!b)throw new Error("associated RTCRtpTransceiver not found");return b.receiver.getStats()}async receiveDataChannel({maxMessageSize:f,sctpStreamParameters:b,label:w,protocol:S}){this.assertNotClosed(),this.assertRecvDirection();let{streamId:O,ordered:j,maxPacketLifeTime:P,maxRetransmits:k}=b,C={negotiated:!0,id:O,ordered:j,maxPacketLifeTime:P,maxRetransmits:k,protocol:S};l.debug("receiveDataChannel() [options:%o]",C);let D=this._pc.createDataChannel(w,C);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();let H={type:"offer",sdp:this._remoteSdp.getSdp()};l.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",H),await this._pc.setRemoteDescription(H);let W=await this._pc.createAnswer(),J=e.parse(W.sdp),F=J.media.find(q=>q.type==="application");F.maxMessageSize=f,this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:J}),W={type:"answer",sdp:e.write(J)},l.debug("receiveDataChannel() | calling pc.setLocalDescription() [answer:%o]",W),await this._pc.setLocalDescription(W),this._hasDataChannelMediaSection=!0}return{dataChannel:D}}getDataChannelMaxMessageSize(){return this._pc.sctp?.maxMessageSize}async setupTransport({localDtlsRole:f,localSdpObject:b}){b||(b=e.parse(this._pc.localDescription.sdp));let w=c.extractDtlsParameters({sdpObject:b});w.role=f,this._remoteSdp.updateDtlsRole(f==="client"?"server":"client"),await new Promise((S,O)=>{this.safeEmit("@connect",{dtlsParameters:w},S,O)}),this._transportReady=!0}onIceGatheringStateChange=()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)};onIceCandidateError=f=>{this.emit("@icecandidateerror",f)};onConnectionStateChange=()=>{this.emit("@connectionstatechange",this._pc.connectionState)};onIceConnectionStateChange=()=>{switch(this._pc.iceConnectionState){case"checking":{this.emit("@connectionstatechange","connecting");break}case"connected":case"completed":{this.emit("@connectionstatechange","connected");break}case"failed":{this.emit("@connectionstatechange","failed");break}case"disconnected":{this.emit("@connectionstatechange","disconnected");break}case"closed":{this.emit("@connectionstatechange","closed");break}}};assertNotClosed(){if(this._closed)throw new i.InvalidStateError("method called in a closed handler")}assertSendDirection(){if(this._direction!=="send")throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if(this._direction!=="recv")throw new Error('method can just be called for handlers with "recv" direction')}};t.ReactNative106=m}),Xre=nt(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Device=void 0,t.detectDevice=p,t.detectDeviceAsync=m;var e=Os(),r=Xs(),s=Zn(),n=Yh(),i=ea(),o=$re(),a=Vre(),c=zre(),d=Wre(),u=Kre(),l=Gre(),h=new e.Logger("Device");function p(k,C){return h.debug("detectDevice()"),!k&&typeof navigator=="object"&&(k=navigator.userAgent),!C&&typeof navigator=="object"&&(C=navigator.userAgentData),f(k,C)}async function m(k,C){return h.debug("detectDeviceAsync()"),!k&&typeof navigator=="object"&&(k=navigator.userAgent),!C&&typeof navigator=="object"&&(C=navigator.userAgentData),f(k,C)}var _=class SF{_handlerFactory;_handlerName;_loaded=!1;_getSendExtendedRtpCapabilities;_recvRtpCapabilities;_sendRtpCapabilities;_canProduceByKind={audio:!1,video:!1};_sctpCapabilities;_observer=new r.EnhancedEventEmitter;static async factory({handlerName:C,handlerFactory:D}={}){if(h.debug("factory()"),C&&D)throw new TypeError("just one of handlerName or handlerInterface can be given");if(!C&&!D&&(C=await m(),!C))throw new s.UnsupportedError("device not supported");return new SF({handlerName:C,handlerFactory:D})}constructor({handlerName:C,handlerFactory:D}={}){if(h.debug("constructor()"),C&&D)throw new TypeError("just one of handlerName or handlerInterface can be given");if(D)this._handlerFactory=D;else{if(C)h.debug("constructor() | handler given: %s",C);else if(C=p(),C)h.debug("constructor() | detected handler: %s",C);else throw new s.UnsupportedError("device not supported");switch(C){case"Chrome111":{this._handlerFactory=a.Chrome111.createFactory();break}case"Chrome74":{this._handlerFactory=c.Chrome74.createFactory();break}case"Firefox120":{this._handlerFactory=d.Firefox120.createFactory();break}case"Safari12":{this._handlerFactory=u.Safari12.createFactory();break}case"ReactNative106":{this._handlerFactory=l.ReactNative106.createFactory();break}default:throw new TypeError(`unknown handlerName "${C}"`)}}this._handlerName=this._handlerFactory.name}get handlerName(){return this._handlerName}get loaded(){return this._loaded}get rtpCapabilities(){return this.recvRtpCapabilities}get recvRtpCapabilities(){if(!this._loaded)throw new s.InvalidStateError("not loaded");return this._recvRtpCapabilities}get sendRtpCapabilities(){if(!this._loaded)throw new s.InvalidStateError("not loaded");return this._sendRtpCapabilities}get sctpCapabilities(){if(!this._loaded)throw new s.InvalidStateError("not loaded");return this._sctpCapabilities}get observer(){return this._observer}async load({routerRtpCapabilities:C,preferLocalCodecsOrder:D=!1}){if(h.debug("load() [routerRtpCapabilities:%o]",C),this._loaded)throw new s.InvalidStateError("already loaded");let H=n.clone(C);i.validateAndNormalizeRtpCapabilities(H);let{getNativeRtpCapabilities:W,getNativeSctpCapabilities:J}=this._handlerFactory,F=n.clone(await W({direction:"recvonly"}));h.debug("load() | got native receiving RTP capabilities:%o",F),i.validateAndNormalizeRtpCapabilities(F);let q=n.clone(await W({direction:"sendonly"}));h.debug("load() | got native sending RTP capabilities:%o",q),i.validateAndNormalizeRtpCapabilities(q),this._getSendExtendedRtpCapabilities=Y=>n.clone(i.getExtendedRtpCapabilities(Y,H,D));let Q=i.getExtendedRtpCapabilities(F,H,!1);this._recvRtpCapabilities=i.getRecvRtpCapabilities(Q),h.debug("load() | got receiving RTP capabilities:%o",this._recvRtpCapabilities),i.validateAndNormalizeRtpCapabilities(this._recvRtpCapabilities);let R=i.getExtendedRtpCapabilities(q,H,D);this._sendRtpCapabilities=i.getSendRtpCapabilities(R),h.debug("load() | got sending RTP capabilities:%o",this._sendRtpCapabilities),i.validateAndNormalizeRtpCapabilities(this._sendRtpCapabilities),this._canProduceByKind.audio=i.canSend("audio",this._sendRtpCapabilities),this._canProduceByKind.video=i.canSend("video",this._sendRtpCapabilities),this._sctpCapabilities=await J(),i.validateSctpCapabilities(this._sctpCapabilities),h.debug("load() | got native SCTP capabilities:%o",this._sctpCapabilities),h.debug("load() succeeded"),this._loaded=!0}canProduce(C){if(this._loaded){if(C!=="audio"&&C!=="video")throw new TypeError(`invalid kind "${C}"`)}else throw new s.InvalidStateError("not loaded");return this._canProduceByKind[C]}createSendTransport({id:C,iceParameters:D,iceCandidates:H,dtlsParameters:W,sctpParameters:J,iceServers:F,iceTransportPolicy:q,additionalSettings:Q,appData:R}){return h.debug("createSendTransport()"),this.createTransport({direction:"send",id:C,iceParameters:D,iceCandidates:H,dtlsParameters:W,sctpParameters:J,iceServers:F,iceTransportPolicy:q,additionalSettings:Q,appData:R})}createRecvTransport({id:C,iceParameters:D,iceCandidates:H,dtlsParameters:W,sctpParameters:J,iceServers:F,iceTransportPolicy:q,additionalSettings:Q,appData:R}){return h.debug("createRecvTransport()"),this.createTransport({direction:"recv",id:C,iceParameters:D,iceCandidates:H,dtlsParameters:W,sctpParameters:J,iceServers:F,iceTransportPolicy:q,additionalSettings:Q,appData:R})}createTransport({direction:C,id:D,iceParameters:H,iceCandidates:W,dtlsParameters:J,sctpParameters:F,iceServers:q,iceTransportPolicy:Q,additionalSettings:R,appData:Y}){if(this._loaded){if(typeof D!="string")throw new TypeError("missing id");if(typeof H!="object")throw new TypeError("missing iceParameters");if(Array.isArray(W)){if(typeof J!="object")throw new TypeError("missing dtlsParameters");if(F&&typeof F!="object")throw new TypeError("wrong sctpParameters");if(Y&&typeof Y!="object")throw new TypeError("if given, appData must be an object")}else throw new TypeError("missing iceCandidates")}else throw new s.InvalidStateError("not loaded");let Z=new o.Transport({direction:C,id:D,iceParameters:H,iceCandidates:W,dtlsParameters:J,sctpParameters:F,iceServers:q,iceTransportPolicy:Q,additionalSettings:R,appData:Y,handlerFactory:this._handlerFactory,getSendExtendedRtpCapabilities:this._getSendExtendedRtpCapabilities,recvRtpCapabilities:this._recvRtpCapabilities,canProduceByKind:this._canProduceByKind});return this._observer.safeEmit("newtransport",Z),Z}};t.Device=_;function f(k,C){h.debug('detectDeviceImpl() [userAgent:"%s", userAgentData:%o]',k,C);let D=b(k,C);if(D){if(D>=111)return h.debug("detectDeviceImpl() | using Chrome111 handler"),"Chrome111";if(D>=74)return h.debug("detectDeviceImpl() | using Chrome74 handler"),"Chrome74";h.warn("detectDeviceImpl() | unsupported Chromium based browser/version");return}let H=w(k);if(H){if(H>=120)return h.debug("detectDeviceImpl() | using Firefox120 handler"),"Firefox120";h.warn("detectDeviceImpl() | unsupported Firefox browser/version");return}let W=S(k);if(W){if(W>=605)return h.debug("detectDeviceImpl() | using Safari12 handler"),"Safari12";h.warn("detectDeviceImpl() | unsupported desktop Safari browser/version");return}let J=O(k);if(J){if(J>=605)return h.debug("detectDeviceImpl() | using Safari12 handler"),"Safari12";h.warn("detectDeviceImpl() | unsupported iOS Safari based browser/version");return}if(P()){if(typeof RTCPeerConnection<"u"&&typeof RTCRtpTransceiver<"u")return h.debug("detectDeviceImpl() | using ReactNative106 handler"),"ReactNative106";h.warn("detectDeviceImpl() | unsupported react-native-webrtc version without RTCPeerConnection or RTCRtpTransceiver, forgot to call registerGlobals() on it?");return}h.warn('detectDeviceImpl() | device not supported [userAgent:"%s", userAgentData:%o]',k,C)}function b(k,C){if(h.debug("getChromiumMajorVersion()"),j(k,C)){h.debug("getChromiumMajorVersion() | this is iOS => undefined");return}if(P()){h.debug("getChromiumMajorVersion() | this is React-Native => undefined");return}if(C){let H=(Array.isArray(C.brands)?C.brands:[]).find(W=>W.brand==="Chromium");if(H){let W=Number(H.version);return h.debug(`getChromiumMajorVersion() | Chromium major version based on NavigatorUAData => ${W}`),W}}let D=k?.match(/\b(?:Chrome|Chromium)\/(\w+)/i);if(D?.[1]){let H=Number(D[1]);return h.debug(`getChromiumMajorVersion() | Chromium major version based on User-Agent => ${H}`),H}h.debug("getChromiumMajorVersion() | this is not Chromium => undefined")}function w(k){if(h.debug("getFirefoxMajorVersion()"),j(k)){h.debug("getFirefoxMajorVersion() | this is iOS => undefined");return}if(P()){h.debug("getFirefoxMajorVersion() | this is React-Native => undefined");return}let C=k?.match(/\bFirefox\/(\w+)/i);if(C?.[1]){let D=Number(C[1]);return h.debug(`getFirefoxMajorVersion() | Firefox major version based on User-Agent => ${D}`),D}h.debug("getFirefoxMajorVersion() | this is not Firefox => undefined")}function S(k){if(h.debug("getMacOSWebKitMajorVersion()"),j(k)){h.debug("getMacOSWebKitMajorVersion() | this is iOS => undefined");return}if(P()){h.debug("getMacOSWebKitMajorVersion() | this is React-Native => undefined");return}if(!(k&&/\bSafari\b/i.test(k)&&!/\bChrome\b/i.test(k)&&!/\bChromium\b/i.test(k)&&!/\bFirefox\b/i.test(k))){h.debug("getMacOSWebKitMajorVersion() | this is not Safari => undefined");return}let C=k.match(/AppleWebKit\/(\w+)/i);if(C?.[1]){let D=Number(C[1]);return h.debug(`getMacOSWebKitMajorVersion() | WebKit major version based on User-Agent => ${D}`),D}h.debug("getMacOSWebKitMajorVersion() | this is not WebKit => undefined")}function O(k){if(h.debug("getIOSWebKitMajorVersion()"),!j(k)){h.debug("getIOSWebKitMajorVersion() | this is not iOS => undefined");return}if(P()){h.debug("getIOSWebKitMajorVersion() | this is React-Native => undefined");return}let C=k?.match(/AppleWebKit\/(\w+)/i);if(C?.[1]){let D=Number(C[1]);return h.debug(`getIOSWebKitMajorVersion() | WebKit major version based on User-Agent => ${D}`),D}h.debug("getIOSWebKitMajorVersion() | this is not WebKit => undefined")}function j(k,C){return h.debug("isIOS()"),C?.platform==="iOS"?(h.debug("isIOS() | this is iOS based on NavigatorUAData.platform => true"),!0):C?.platform?(h.debug("isIOS() | this is not iOS based on NavigatorUAData.platform => false"),!1):k&&/iPad|iPhone|iPod/.test(k)?(h.debug("isIOS() | this is iOS based on User-Agent => true"),!0):typeof navigator=="object"&&navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1?(h.debug("isIOS() | this is iPadOS 13+ based on User-Agent => true"),!0):(h.debug("isIOS() | this is not iOS => false"),!1)}function P(){return h.debug("isReactNative()"),typeof navigator=="object"&&navigator.product==="ReactNative"?(h.debug("isReactNative() | this is React-Native based on navigator.product"),!0):(h.debug("isReactNative() | this is not React-Native => false"),!1)}}),Yre=nt(t=>{"use strict";for(var e=256,r=[],s;e--;)r[e]=(e+256).toString(16).substring(1);function n(){var i=0,o,a="";if(!s||e+16>256){for(s=Array(i=256);i--;)s[i]=256*Math.random()|0;i=e=0}for(;i<16;i++)o=s[e+i],i==6?a+=r[o&15|64]:i==8?a+=r[o&63|128]:a+=r[o],i&1&&i>1&&i<11&&(a+="-");return e++,a}t.v4=n}),Jre=nt(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.FakeEventTarget=void 0;var e=class{listeners={};addEventListener(r,s,n){s&&(this.listeners[r]=this.listeners[r]??[],this.listeners[r].push({callback:typeof s=="function"?s:s.handleEvent,once:typeof n=="object"&&n.once===!0}))}removeEventListener(r,s,n){this.listeners[r]&&s&&(this.listeners[r]=this.listeners[r].filter(i=>i.callback!==(typeof s=="function"?s:s.handleEvent)))}dispatchEvent(r){if(!r||typeof r.type!="string")throw new Error("invalid event object");let s=this.listeners[r.type];if(!s)return!0;for(let n of[...s]){try{n.callback.call(this,r)}catch(i){setTimeout(()=>{throw i},0)}n.once&&this.removeEventListener(r.type,n.callback)}return!r.defaultPrevented}};t.FakeEventTarget=e}),Qre=nt(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.FakeEvent=void 0;var e=class{NONE=0;CAPTURING_PHASE=1;AT_TARGET=2;BUBBLING_PHASE=3;type;bubbles;cancelable;defaultPrevented=!1;composed=!1;currentTarget=null;eventPhase=this.NONE;isTrusted=!0;target=null;timeStamp=0;cancelBubble=!1;returnValue=!0;srcElement=null;constructor(r,s={}){this.type=r,this.bubbles=s.bubbles??!1,this.cancelable=s.cancelable??!1}preventDefault(){this.cancelable&&(this.defaultPrevented=!0)}stopPropagation(){}stopImmediatePropagation(){}composedPath(){return[]}initEvent(r,s,n){}};t.FakeEvent=e}),Zre=nt(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.clone=e;function e(r){if(r!==void 0)return Number.isNaN(r)?NaN:typeof structuredClone=="function"?structuredClone(r):JSON.parse(JSON.stringify(r))}}),ese=nt(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.FakeMediaStreamTrack=void 0;var e=Yre(),r=Jre(),s=Qre(),n=Zre(),i=class EF extends r.FakeEventTarget{#m;#u;#h;#e;#r;#t;#s;#f;#n;#p;#i;#o=null;#a=null;#c=null;#d=null;#l=null;constructor({kind:a,id:c,label:d,contentHint:u,enabled:l,muted:h,readyState:p,capabilities:m,constraints:_,settings:f,data:b}){super(),this.#m=c??(0,e.v4)(),this.#u=a,this.#h=d??"",this.#s=u??"",this.#r=l??!0,this.#t=h??!1,this.#e=p??"live",this.#f=m??{},this.#n=_??{},this.#p=f??{},this.#i=b??{}}get id(){return this.#m}get kind(){return this.#u}get label(){return this.#h}get contentHint(){return this.#s}set contentHint(a){this.#s=a}get enabled(){return this.#r}set enabled(a){let c=this.#r!==a;this.#r=a,c&&this.dispatchEvent(new s.FakeEvent("enabledchange"))}get muted(){return this.#t}get readyState(){return this.#e}get data(){return this.#i}set data(a){this.#i=a}get onmute(){return this.#o}set onmute(a){this.#o&&this.removeEventListener("mute",this.#o),this.#o=a,a&&this.addEventListener("mute",a)}get onunmute(){return this.#a}set onunmute(a){this.#a&&this.removeEventListener("unmute",this.#a),this.#a=a,a&&this.addEventListener("unmute",a)}get onended(){return this.#c}set onended(a){this.#c&&this.removeEventListener("ended",this.#c),this.#c=a,a&&this.addEventListener("ended",a)}get onenabledchange(){return this.#d}set onenabledchange(a){this.#d&&this.removeEventListener("enabledchange",this.#d),this.#d=a,a&&this.addEventListener("enabledchange",a)}get onstopped(){return this.#l}set onstopped(a){this.#l&&this.removeEventListener("stopped",this.#l),this.#l=a,a&&this.addEventListener("stopped",a)}addEventListener(a,c,d){super.addEventListener(a,c,d)}removeEventListener(a,c,d){super.removeEventListener(a,c,d)}stop(){this.#e!=="ended"&&(this.#e="ended",this.dispatchEvent(new s.FakeEvent("stopped")))}clone({id:a,data:c}={}){return new EF({id:a??(0,e.v4)(),kind:this.#u,label:this.#h,contentHint:this.#s,enabled:this.#r,muted:this.#t,readyState:this.#e,capabilities:(0,n.clone)(this.#f),constraints:(0,n.clone)(this.#n),settings:(0,n.clone)(this.#p),data:c??(0,n.clone)(this.#i)})}getCapabilities(){return this.#f}getConstraints(){return this.#n}async applyConstraints(a={}){return this.#n=a,Promise.resolve()}getSettings(){return this.#p}remoteStop(){this.#e!=="ended"&&(this.#e="ended",this.dispatchEvent(new s.FakeEvent("stopped")),this.dispatchEvent(new s.FakeEvent("ended")))}remoteMute(){this.#t||(this.#t=!0,this.dispatchEvent(new s.FakeEvent("mute")))}remoteUnmute(){this.#t&&(this.#t=!1,this.dispatchEvent(new s.FakeEvent("unmute")))}};t.FakeMediaStreamTrack=i}),tse=nt(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.FakeEventTarget=void 0;var e=class{listeners={};addEventListener(r,s,n){s&&(this.listeners[r]=this.listeners[r]??[],this.listeners[r].push({callback:typeof s=="function"?s:s.handleEvent,once:typeof n=="object"&&n.once===!0}))}removeEventListener(r,s,n){this.listeners[r]&&s&&(this.listeners[r]=this.listeners[r].filter(i=>i.callback!==(typeof s=="function"?s:s.handleEvent)))}dispatchEvent(r){if(!r||typeof r.type!="string")throw new Error("invalid event object");let s=this.listeners[r.type];if(!s)return!0;for(let n of[...s]){try{n.callback.call(this,r)}catch(i){setTimeout(()=>{throw i},0)}n.once&&this.removeEventListener(r.type,n.callback)}return!r.defaultPrevented}};t.FakeEventTarget=e}),rse=nt(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.FakeHandler=void 0;var e=ese(),r=Xs(),s=Os(),n=Yh(),i=ea(),o=Zn(),a=tse(),c=new s.Logger("FakeHandler"),d="FakeHandler",u=class I1 extends r.EnhancedEventEmitter{_closed=!1;_fakeParameters;_getSendExtendedRtpCapabilities;_cname=`CNAME-${n.generateRandomNumber()}`;_defaultSendStreamId=`${n.generateRandomNumber()}`;_transportReady=!1;_nextLocalId=1;_tracks=new Map;_nextSctpStreamId=0;static createFactory(p){return{name:d,factory:m=>new I1(m,p),getNativeRtpCapabilities:async({direction:m})=>(c.debug("getNativeRtpCapabilities() [direction:%o]",m),I1.getLocalRtpCapabilities(p)),getNativeSctpCapabilities:async()=>(c.debug("getNativeSctpCapabilities()"),p.generateNativeSctpCapabilities())}}static getLocalRtpCapabilities(p){let m=p.generateNativeRtpCapabilities();return i.validateAndNormalizeRtpCapabilities(m),m}constructor({getSendExtendedRtpCapabilities:p},m){super(),c.debug("constructor()"),this._getSendExtendedRtpCapabilities=p,this._fakeParameters=m}get name(){return d}close(){c.debug("close()"),!this._closed&&(this._closed=!0,super.close())}setIceGatheringState(p){this.emit("@icegatheringstatechange",p)}setConnectionState(p){this.emit("@connectionstatechange",p)}async updateIceServers(p){this.assertNotClosed(),c.debug("updateIceServers()")}async restartIce(p){this.assertNotClosed(),c.debug("restartIce()")}async getTransportStats(){return this.assertNotClosed(),new Map}async send({track:p,streamId:m,encodings:_,codecOptions:f,codec:b}){this.assertNotClosed(),c.debug("send() [kind:%s, track.id:%s]",p.kind,p.id),this._transportReady||await this.setupTransport({localDtlsRole:"server"});let w=I1.getLocalRtpCapabilities(this._fakeParameters),S=this._getSendExtendedRtpCapabilities(w),O=i.getSendingRtpParameters(p.kind,S);O.codecs=i.reduceCodecs(O.codecs,b);let j=O.codecs.some(k=>/.+\/rtx$/i.test(k.mimeType));O.mid=`mid-${n.generateRandomNumber()}`,O.msid=`${m??"-"} ${p.id}`,_||(_=[{}]);for(let k of _)k.ssrc=n.generateRandomNumber(),j&&(k.rtx={ssrc:n.generateRandomNumber()});O.encodings=_,O.rtcp={cname:this._cname,reducedSize:!0,mux:!0},O.msid=`${m??this._defaultSendStreamId} ${p.id}`;let P=this._nextLocalId++;return this._tracks.set(P,p),{localId:String(P),rtpParameters:O}}async stopSending(p){if(c.debug("stopSending() [localId:%s]",p),!this._closed){if(!this._tracks.has(Number(p)))throw new Error("local track not found");this._tracks.delete(Number(p))}}async pauseSending(p){this.assertNotClosed()}async resumeSending(p){this.assertNotClosed()}async replaceTrack(p,m){this.assertNotClosed(),m?c.debug("replaceTrack() [localId:%s, track.id:%s]",p,m.id):c.debug("replaceTrack() [localId:%s, no track]",p),this._tracks.delete(Number(p)),this._tracks.set(Number(p),m)}async setMaxSpatialLayer(p,m){this.assertNotClosed(),c.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",p,m)}async setRtpEncodingParameters(p,m){this.assertNotClosed(),c.debug("setRtpEncodingParameters() [localId:%s, params:%o]",p,m)}async getSenderStats(p){return this.assertNotClosed(),new Map}async sendDataChannel({sctpStreamParameters:p}){this.assertNotClosed(),this._transportReady||await this.setupTransport({localDtlsRole:"server"}),c.debug("sendDataChannel()");let m=new l({id:this._nextSctpStreamId++,ordered:p.ordered,maxPacketLifeTime:p.maxPacketLifeTime,maxRetransmits:p.maxRetransmits,label:p.label,protocol:p.protocol}),_={streamId:this._nextSctpStreamId,ordered:p.ordered,maxPacketLifeTime:p.maxPacketLifeTime,maxRetransmits:p.maxRetransmits};return{dataChannel:m,sctpStreamParameters:_}}async receive(p){this.assertNotClosed();let m=[];for(let _ of p){let{trackId:f,kind:b}=_;this._transportReady||await this.setupTransport({localDtlsRole:"client"}),c.debug("receive() [trackId:%s, kind:%s]",f,b);let w=this._nextLocalId++,S=new e.FakeMediaStreamTrack({kind:b});this._tracks.set(w,S),m.push({localId:String(w),track:S})}return m}async stopReceiving(p){if(!this._closed)for(let m of p)c.debug("stopReceiving() [localId:%s]",m),this._tracks.delete(Number(m))}async pauseReceiving(p){this.assertNotClosed()}async resumeReceiving(p){this.assertNotClosed()}async getReceiverStats(p){return this.assertNotClosed(),new Map}async receiveDataChannel({sctpStreamParameters:p,label:m,protocol:_}){return this.assertNotClosed(),this._transportReady||await this.setupTransport({localDtlsRole:"client"}),c.debug("receiveDataChannel()"),{dataChannel:new l({id:p.streamId,ordered:p.ordered,maxPacketLifeTime:p.maxPacketLifeTime,maxRetransmits:p.maxRetransmits,label:m,protocol:_})}}getDataChannelMaxMessageSize(){return 5e5}async setupTransport({localDtlsRole:p,localSdpObject:m}){let _=n.clone(this._fakeParameters.generateLocalDtlsParameters());p&&(_.role=p),this.emit("@connectionstatechange","connecting"),await new Promise((f,b)=>this.emit("@connect",{dtlsParameters:_},f,b)),this._transportReady=!0}assertNotClosed(){if(this._closed)throw new o.InvalidStateError("method called in a closed handler")}};t.FakeHandler=u;var l=class extends a.FakeEventTarget{_id;_negotiated=!0;_ordered;_maxPacketLifeTime;_maxRetransmits;_label;_protocol;_readyState="connecting";_bufferedAmount=0;_bufferedAmountLowThreshold=0;_binaryType="arraybuffer";_onopen=null;_onclosing=null;_onclose=null;_onmessage=null;_onbufferedamountlow=null;_onerror=null;constructor({id:h,ordered:p=!0,maxPacketLifeTime:m=null,maxRetransmits:_=null,label:f="",protocol:b=""}){super(),c.debug(`constructor() [id:${h}, ordered:${p}, maxPacketLifeTime:${m}, maxRetransmits:${_}, label:${f}, protocol:${b}`),this._id=h,this._ordered=p,this._maxPacketLifeTime=m,this._maxRetransmits=_,this._label=f,this._protocol=b}get id(){return this._id}get negotiated(){return this._negotiated}get ordered(){return this._ordered}get maxPacketLifeTime(){return this._maxPacketLifeTime}get maxRetransmits(){return this._maxRetransmits}get label(){return this._label}get protocol(){return this._protocol}get readyState(){return this._readyState}get bufferedAmount(){return this._bufferedAmount}get bufferedAmountLowThreshold(){return this._bufferedAmountLowThreshold}set bufferedAmountLowThreshold(h){this._bufferedAmountLowThreshold=h}get binaryType(){return this._binaryType}set binaryType(h){this._binaryType=h}get onopen(){return this._onopen}set onopen(h){this._onopen&&this.removeEventListener("open",this._onopen),this._onopen=h,h&&this.addEventListener("open",h)}get onclosing(){return this._onclosing}set onclosing(h){this._onclosing&&this.removeEventListener("closing",this._onclosing),this._onclosing=h,h&&this.addEventListener("closing",h)}get onclose(){return this._onclose}set onclose(h){this._onclose&&this.removeEventListener("close",this._onclose),this._onclose=h,h&&this.addEventListener("close",h)}get onmessage(){return this._onmessage}set onmessage(h){this._onmessage&&this.removeEventListener("message",this._onmessage),this._onmessage=h,h&&this.addEventListener("message",h)}get onbufferedamountlow(){return this._onbufferedamountlow}set onbufferedamountlow(h){this._onbufferedamountlow&&this.removeEventListener("bufferedamountlow",this._onbufferedamountlow),this._onbufferedamountlow=h,h&&this.addEventListener("bufferedamountlow",h)}get onerror(){return this._onerror}set onerror(h){this._onerror&&this.removeEventListener("error",this._onerror),this._onerror=h,h&&this.addEventListener("error",h)}addEventListener(h,p,m){super.addEventListener(h,p,m)}removeEventListener(h,p,m){super.removeEventListener(h,p,m)}close(){["closing","closed"].includes(this._readyState)||(this._readyState="closed")}send(h){if(this._readyState!=="open")throw new o.InvalidStateError("not open")}}}),sse=nt(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.generateRouterRtpCapabilities=s,t.generateNativeRtpCapabilities=n,t.generateNativeSctpCapabilities=i,t.generateLocalDtlsParameters=o,t.generateTransportRemoteParameters=a,t.generateProducerRemoteParameters=c,t.generateConsumerRemoteParameters=d,t.generateDataProducerRemoteParameters=u,t.generateDataConsumerRemoteParameters=l;var e=Yh();function r(){return String(e.generateRandomNumber())}function s(){return e.deepFreeze({codecs:[{mimeType:"audio/opus",kind:"audio",preferredPayloadType:100,clockRate:48e3,channels:2,rtcpFeedback:[{type:"transport-cc"}],parameters:{useinbandfec:1,foo:"bar"}},{mimeType:"video/VP8",kind:"video",preferredPayloadType:101,clockRate:9e4,rtcpFeedback:[{type:"nack"},{type:"nack",parameter:"pli"},{type:"ccm",parameter:"fir"},{type:"goog-remb"},{type:"transport-cc"}],parameters:{"x-google-start-bitrate":1500}},{mimeType:"video/rtx",kind:"video",preferredPayloadType:102,clockRate:9e4,rtcpFeedback:[],parameters:{apt:101}},{mimeType:"video/H264",kind:"video",preferredPayloadType:103,clockRate:9e4,rtcpFeedback:[{type:"nack"},{type:"nack",parameter:"pli"},{type:"ccm",parameter:"fir"},{type:"goog-remb"},{type:"transport-cc"}],parameters:{"level-asymmetry-allowed":1,"packetization-mode":1,"profile-level-id":"42e01f"}},{mimeType:"video/rtx",kind:"video",preferredPayloadType:104,clockRate:9e4,rtcpFeedback:[],parameters:{apt:103}},{mimeType:"video/VP9",kind:"video",preferredPayloadType:105,clockRate:9e4,rtcpFeedback:[{type:"nack"},{type:"nack",parameter:"pli"},{type:"ccm",parameter:"fir"},{type:"goog-remb"},{type:"transport-cc"}],parameters:{"profile-id":0,"x-google-start-bitrate":1500}},{mimeType:"video/rtx",kind:"video",preferredPayloadType:106,clockRate:9e4,rtcpFeedback:[],parameters:{apt:105}}],headerExtensions:[{kind:"audio",uri:"urn:ietf:params:rtp-hdrext:sdes:mid",preferredId:1,preferredEncrypt:!1,direction:"sendrecv"},{kind:"video",uri:"urn:ietf:params:rtp-hdrext:sdes:mid",preferredId:1,preferredEncrypt:!1,direction:"sendrecv"},{kind:"video",uri:"urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id",preferredId:2,preferredEncrypt:!1,direction:"recvonly"},{kind:"video",uri:"urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id",preferredId:3,preferredEncrypt:!1,direction:"recvonly"},{kind:"audio",uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time",preferredId:4,preferredEncrypt:!1,direction:"sendrecv"},{kind:"video",uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time",preferredId:4,preferredEncrypt:!1,direction:"sendrecv"},{kind:"audio",uri:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",preferredId:5,preferredEncrypt:!1,direction:"recvonly"},{kind:"video",uri:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",preferredId:5,preferredEncrypt:!1,direction:"sendrecv"},{kind:"audio",uri:"urn:ietf:params:rtp-hdrext:ssrc-audio-level",preferredId:10,preferredEncrypt:!1,direction:"sendrecv"},{kind:"video",uri:"urn:3gpp:video-orientation",preferredId:11,preferredEncrypt:!1,direction:"sendrecv"},{kind:"video",uri:"urn:ietf:params:rtp-hdrext:toffset",preferredId:12,preferredEncrypt:!1,direction:"sendrecv"}]})}function n(){return{codecs:[{mimeType:"audio/opus",kind:"audio",preferredPayloadType:111,clockRate:48e3,channels:2,rtcpFeedback:[{type:"transport-cc"}],parameters:{minptime:10,useinbandfec:1}},{mimeType:"audio/ISAC",kind:"audio",preferredPayloadType:103,clockRate:16e3,channels:1,rtcpFeedback:[{type:"transport-cc"}],parameters:{}},{mimeType:"audio/CN",kind:"audio",preferredPayloadType:106,clockRate:32e3,channels:1,rtcpFeedback:[{type:"transport-cc"}],parameters:{}},{mimeType:"audio/foo",kind:"audio",preferredPayloadType:107,clockRate:9e4,channels:4,rtcpFeedback:[{type:"foo-qwe-qwe"}],parameters:{foo:"lalala"}},{mimeType:"video/BAZCODEC",kind:"video",preferredPayloadType:100,clockRate:9e4,rtcpFeedback:[{type:"foo"},{type:"transport-cc"},{type:"ccm",parameter:"fir"},{type:"nack"},{type:"nack",parameter:"pli"}],parameters:{baz:"1234abcd"}},{mimeType:"video/rtx",kind:"video",preferredPayloadType:101,clockRate:9e4,rtcpFeedback:[],parameters:{apt:100}},{mimeType:"video/VP8",kind:"video",preferredPayloadType:96,clockRate:9e4,rtcpFeedback:[{type:"goog-remb"},{type:"transport-cc"},{type:"ccm",parameter:"fir"},{type:"nack"},{type:"nack",parameter:"pli"}],parameters:{baz:"1234abcd"}},{mimeType:"video/rtx",kind:"video",preferredPayloadType:97,clockRate:9e4,rtcpFeedback:[],parameters:{apt:96}},{mimeType:"video/VP9",kind:"video",preferredPayloadType:98,clockRate:9e4,rtcpFeedback:[{type:"goog-remb"},{type:"transport-cc"},{type:"ccm",parameter:"fir"},{type:"nack"},{type:"nack",parameter:"pli"}],parameters:{"profile-id":0}},{mimeType:"video/rtx",kind:"video",preferredPayloadType:99,clockRate:9e4,rtcpFeedback:[],parameters:{apt:98}}],headerExtensions:[{kind:"audio",uri:"urn:ietf:params:rtp-hdrext:sdes:mid",preferredId:1},{kind:"video",uri:"urn:ietf:params:rtp-hdrext:sdes:mid",preferredId:1},{kind:"video",uri:"urn:ietf:params:rtp-hdrext:toffset",preferredId:2},{kind:"video",uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time",preferredId:3},{kind:"video",uri:"urn:3gpp:video-orientation",preferredId:4},{kind:"video",uri:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",preferredId:5},{kind:"video",uri:"http://www.webrtc.org/experiments/rtp-hdrext/playout-delay",preferredId:6},{kind:"video",uri:"http://www.webrtc.org/experiments/rtp-hdrext/video-content-type",preferredId:7},{kind:"video",uri:"http://www.webrtc.org/experiments/rtp-hdrext/video-timing",preferredId:8},{kind:"audio",uri:"urn:ietf:params:rtp-hdrext:ssrc-audio-level",preferredId:10}]}}function i(){return e.deepFreeze({numStreams:{OS:2048,MIS:2048}})}function o(){return e.deepFreeze({fingerprints:[{algorithm:"sha-256",value:"82:5A:68:3D:36:C3:0A:DE:AF:E7:32:43:D2:88:83:57:AC:2D:65:E5:80:C4:B6:FB:AF:1A:A0:21:9F:6D:0C:AD"}],role:"auto"})}function a(){return{id:r(),iceParameters:e.deepFreeze({iceLite:!0,password:"yku5ej8nvfaor28lvtrabcx0wkrpkztz",usernameFragment:"h3hk1iz6qqlnqlne"}),iceCandidates:e.deepFreeze([{foundation:"udpcandidate",address:"9.9.9.9",ip:"9.9.9.9",port:40533,priority:1078862079,protocol:"udp",type:"host",tcpType:"passive"},{foundation:"udpcandidate",address:"9.9.9.9",ip:"9:9:9:9:9:9",port:41333,priority:1078862089,protocol:"udp",type:"host",tcpType:"passive"}]),dtlsParameters:e.deepFreeze({fingerprints:[{algorithm:"sha-256",value:"A9:F4:E0:D2:74:D3:0F:D9:CA:A5:2F:9F:7F:47:FA:F0:C4:72:DD:73:49:D0:3B:14:90:20:51:30:1B:90:8E:71"},{algorithm:"sha-384",value:"03:D9:0B:87:13:98:F6:6D:BC:FC:92:2E:39:D4:E1:97:32:61:30:56:84:70:81:6E:D1:82:97:EA:D9:C1:21:0F:6B:C5:E7:7F:E1:97:0C:17:97:6E:CF:B3:EF:2E:74:B0"},{algorithm:"sha-512",value:"84:27:A4:28:A4:73:AF:43:02:2A:44:68:FF:2F:29:5C:3B:11:9A:60:F4:A8:F0:F5:AC:A0:E3:49:3E:B1:34:53:A9:85:CE:51:9B:ED:87:5E:B8:F4:8E:3D:FA:20:51:B8:96:EE:DA:56:DC:2F:5C:62:79:15:23:E0:21:82:2B:2C"}],role:"auto"}),sctpParameters:e.deepFreeze({port:5e3,OS:2048,MIS:2048,maxMessageSize:2e6})}}function c(){return e.deepFreeze({id:r()})}function d({id:h,codecMimeType:p}={}){switch(p){case"audio/opus":return{id:h??r(),producerId:r(),kind:"audio",rtpParameters:e.deepFreeze({codecs:[{mimeType:"audio/opus",payloadType:100,clockRate:48e3,channels:2,rtcpFeedback:[{type:"transport-cc"}],parameters:{useinbandfec:1,foo:"bar"}}],encodings:[{ssrc:46687003}],headerExtensions:[{uri:"urn:ietf:params:rtp-hdrext:sdes:mid",id:1},{uri:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",id:5},{uri:"urn:ietf:params:rtp-hdrext:ssrc-audio-level",id:10}],rtcp:{cname:"wB4Ql4lrsxYLjzuN",reducedSize:!0,mux:!0}})};case"audio/ISAC":return{id:h??r(),producerId:r(),kind:"audio",rtpParameters:e.deepFreeze({codecs:[{mimeType:"audio/ISAC",payloadType:111,clockRate:16e3,channels:1,rtcpFeedback:[{type:"transport-cc"}],parameters:{}}],encodings:[{ssrc:46687004}],headerExtensions:[{uri:"urn:ietf:params:rtp-hdrext:sdes:mid",id:1},{uri:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",id:5}],rtcp:{cname:"wB4Ql4lrsxYLjzuN",reducedSize:!0,mux:!0}})};case"video/VP8":return{id:h??r(),producerId:r(),kind:"video",rtpParameters:e.deepFreeze({codecs:[{mimeType:"video/VP8",payloadType:101,clockRate:9e4,rtcpFeedback:[{type:"nack"},{type:"nack",parameter:"pli"},{type:"ccm",parameter:"fir"},{type:"goog-remb"},{type:"transport-cc"}],parameters:{"x-google-start-bitrate":1500}},{mimeType:"video/rtx",payloadType:102,clockRate:9e4,rtcpFeedback:[],parameters:{apt:101}}],encodings:[{ssrc:99991111,rtx:{ssrc:99991112}}],headerExtensions:[{uri:"urn:ietf:params:rtp-hdrext:sdes:mid",id:1},{uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time",id:4},{uri:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",id:5},{uri:"urn:3gpp:video-orientation",id:11},{uri:"urn:ietf:params:rtp-hdrext:toffset",id:12}],rtcp:{cname:"wB4Ql4lrsxYLjzuN",reducedSize:!0,mux:!0}})};case"video/H264":return{id:h??r(),producerId:r(),kind:"video",rtpParameters:e.deepFreeze({codecs:[{mimeType:"video/H264",payloadType:103,clockRate:9e4,rtcpFeedback:[{type:"nack"},{type:"nack",parameter:"pli"},{type:"ccm",parameter:"fir"},{type:"goog-remb"},{type:"transport-cc"}],parameters:{"level-asymmetry-allowed":1,"packetization-mode":1,"profile-level-id":"42e01f"}},{mimeType:"video/rtx",payloadType:104,clockRate:9e4,rtcpFeedback:[],parameters:{apt:103}}],encodings:[{ssrc:99991113,rtx:{ssrc:99991114}}],headerExtensions:[{uri:"urn:ietf:params:rtp-hdrext:sdes:mid",id:1},{uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time",id:4},{uri:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",id:5},{uri:"urn:3gpp:video-orientation",id:11},{uri:"urn:ietf:params:rtp-hdrext:toffset",id:12}],rtcp:{cname:"wB4Ql4lrsxYLjzuN",reducedSize:!0,mux:!0}})};default:throw new TypeError(`unknown codecMimeType '${p}'`)}}function u(){return e.deepFreeze({id:r()})}function l({id:h}={}){return{id:h??r(),dataProducerId:r(),sctpStreamParameters:e.deepFreeze({streamId:666,maxPacketLifeTime:5e3,maxRetransmits:void 0})}}}),CF=nt(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.debug=t.testFakeParameters=t.FakeHandler=t.enhancedEvents=t.ortc=t.parseScalabilityMode=t.detectDeviceAsync=t.detectDevice=t.Device=t.version=t.types=void 0;var e=$1();t.debug=e.default,t.types=Ire(),t.version="3.20.0";var r=Xre();Object.defineProperty(t,"Device",{enumerable:!0,get:function(){return r.Device}}),Object.defineProperty(t,"detectDevice",{enumerable:!0,get:function(){return r.detectDevice}}),Object.defineProperty(t,"detectDeviceAsync",{enumerable:!0,get:function(){return r.detectDeviceAsync}});var s=Jh();Object.defineProperty(t,"parseScalabilityMode",{enumerable:!0,get:function(){return s.parse}}),t.ortc=ea(),t.enhancedEvents=Xs();var n=rse();Object.defineProperty(t,"FakeHandler",{enumerable:!0,get:function(){return n.FakeHandler}}),t.testFakeParameters=sse()}),nse=nt((t,e)=>{"use strict";var r=Object.prototype.hasOwnProperty,s="~";function n(){}Object.create&&(n.prototype=Object.create(null),new n().__proto__||(s=!1));function i(d,u,l){this.fn=d,this.context=u,this.once=l||!1}function o(d,u,l,h,p){if(typeof l!="function")throw new TypeError("The listener must be a function");var m=new i(l,h||d,p),_=s?s+u:u;return d._events[_]?d._events[_].fn?d._events[_]=[d._events[_],m]:d._events[_].push(m):(d._events[_]=m,d._eventsCount++),d}function a(d,u){--d._eventsCount===0?d._events=new n:delete d._events[u]}function c(){this._events=new n,this._eventsCount=0}c.prototype.eventNames=function(){var d=[],u,l;if(this._eventsCount===0)return d;for(l in u=this._events)r.call(u,l)&&d.push(s?l.slice(1):l);return Object.getOwnPropertySymbols?d.concat(Object.getOwnPropertySymbols(u)):d},c.prototype.listeners=function(d){var u=s?s+d:d,l=this._events[u];if(!l)return[];if(l.fn)return[l.fn];for(var h=0,p=l.length,m=new Array(p);h<p;h++)m[h]=l[h].fn;return m},c.prototype.listenerCount=function(d){var u=s?s+d:d,l=this._events[u];return l?l.fn?1:l.length:0},c.prototype.emit=function(d,u,l,h,p,m){var _=s?s+d:d;if(!this._events[_])return!1;var f=this._events[_],b=arguments.length,w,S;if(f.fn){switch(f.once&&this.removeListener(d,f.fn,void 0,!0),b){case 1:return f.fn.call(f.context),!0;case 2:return f.fn.call(f.context,u),!0;case 3:return f.fn.call(f.context,u,l),!0;case 4:return f.fn.call(f.context,u,l,h),!0;case 5:return f.fn.call(f.context,u,l,h,p),!0;case 6:return f.fn.call(f.context,u,l,h,p,m),!0}for(S=1,w=new Array(b-1);S<b;S++)w[S-1]=arguments[S];f.fn.apply(f.context,w)}else{var O=f.length,j;for(S=0;S<O;S++)switch(f[S].once&&this.removeListener(d,f[S].fn,void 0,!0),b){case 1:f[S].fn.call(f[S].context);break;case 2:f[S].fn.call(f[S].context,u);break;case 3:f[S].fn.call(f[S].context,u,l);break;case 4:f[S].fn.call(f[S].context,u,l,h);break;default:if(!w)for(j=1,w=new Array(b-1);j<b;j++)w[j-1]=arguments[j];f[S].fn.apply(f[S].context,w)}}return!0},c.prototype.on=function(d,u,l){return o(this,d,u,l,!1)},c.prototype.once=function(d,u,l){return o(this,d,u,l,!0)},c.prototype.removeListener=function(d,u,l,h){var p=s?s+d:d;if(!this._events[p])return this;if(!u)return a(this,p),this;var m=this._events[p];if(m.fn)m.fn===u&&(!h||m.once)&&(!l||m.context===l)&&a(this,p);else{for(var _=0,f=[],b=m.length;_<b;_++)(m[_].fn!==u||h&&!m[_].once||l&&m[_].context!==l)&&f.push(m[_]);f.length?this._events[p]=f.length===1?f[0]:f:a(this,p)}return this},c.prototype.removeAllListeners=function(d){var u;return d?(u=s?s+d:d,this._events[u]&&a(this,u)):(this._events=new n,this._eventsCount=0),this},c.prototype.off=c.prototype.removeListener,c.prototype.addListener=c.prototype.on,c.prefixed=s,c.EventEmitter=c,typeof e<"u"&&(e.exports=c)}),XA=class{_handlers=new Map;_ws;_onMessage;_onOpen;_listeningForOpen=!1;_pendingSends=[];_disposed=!1;constructor(t){this._ws=t,this._onMessage=e=>{if(typeof e.data!="string")return;let r;try{r=JSON.parse(e.data)}catch{E.warn("[ChannelMultiplexer] Failed to parse WebSocket message as JSON");return}if(!r.channel)return;let s=this._handlers.get(r.channel);if(s)for(let n of s)n(r)},this._ws.addEventListener("message",this._onMessage),this._onOpen=()=>{this.flushPendingSends()}}on(t,e){let r=this._handlers.get(t);return r||(r=new Set,this._handlers.set(t,r)),r.add(e),()=>{r.delete(e),r.size===0&&this._handlers.delete(t)}}emit(t,e){if(this._disposed)return;let r=JSON.stringify({channel:t,...e});if(this._ws.readyState===WebSocket.OPEN){this._ws.send(r);return}this._ws.readyState===WebSocket.CONNECTING&&(this._pendingSends.push(r),this.listenForOpen())}dispose(){this._disposed=!0,this._pendingSends=[],this._handlers.clear(),this._ws.removeEventListener("message",this._onMessage),this._ws.removeEventListener("open",this._onOpen),this._listeningForOpen=!1}flushPendingSends(){if(this._disposed||this._ws.readyState!==WebSocket.OPEN)return;this._ws.removeEventListener("open",this._onOpen),this._listeningForOpen=!1;let t=this._pendingSends;this._pendingSends=[];for(let e of t)this._ws.send(e)}listenForOpen(){this._listeningForOpen||(this._listeningForOpen=!0,this._ws.addEventListener("open",this._onOpen))}},YA=class{_handlers=new Map;_pendingSends=[];_target=null;_targetUnsubscribes=[];_disposed=!1;setTarget(t){if(this._disposed)return;this.detachTarget(),this._target=t;for(let[r,s]of this._handlers)for(let n of s)this._targetUnsubscribes.push(t.on(r,n));let e=this._pendingSends;this._pendingSends=[];for(let r of e)t.emit(r.channel,r.data)}rewriteSessionChannels(t,e){if(t===e)return;let r=`session:${t}:`,s=`session:${e}:`,n=new Map;for(let[i,o]of this._handlers)n.set(i.startsWith(r)?s+i.slice(r.length):i,o);this._handlers=n,this._pendingSends=this._pendingSends.map(i=>({...i,channel:i.channel.startsWith(r)?s+i.channel.slice(r.length):i.channel}))}on(t,e){if(this._disposed)return()=>{};let r=this._handlers.get(t);r||(r=new Set,this._handlers.set(t,r)),r.add(e);let s=this._target?.on(t,e);return s&&this._targetUnsubscribes.push(s),()=>{r?.delete(e),r?.size===0&&this._handlers.delete(t),s?.(),s&&(this._targetUnsubscribes=this._targetUnsubscribes.filter(n=>n!==s))}}emit(t,e){if(!this._disposed){if(this._target){this._target.emit(t,e);return}this._pendingSends.push({channel:t,data:e})}}dispose(){this._disposed=!0,this._pendingSends=[],this._handlers.clear(),this.detachTarget()}detachTarget(){for(let t of this._targetUnsubscribes)t();this._targetUnsubscribes=[],this._target=null}},El=class extends Error{code="session_end_unavailable";constructor(t="[urun] this session handle cannot terminally end the session; disconnect the viewer instead",e){super(t),this.name="SessionEndUnavailableError",e?.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,new.target.prototype)}},Sn=class extends Error{code;httpStatus;requestId;sessionId;constructor(t,e){super(t),this.name="SessionEndError",this.code=e.code??"session_end_failed",this.httpStatus=e.httpStatus,this.requestId=e.requestId,this.sessionId=e.sessionId,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,new.target.prototype)}},Gi=class extends Error{code;httpStatus;constructor(t,e){super(t),this.name="SessionDirectoryError",this.code=e?.code??"session_directory_failed",this.httpStatus=e?.httpStatus,e?.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,new.target.prototype)}},ta=class extends Error{requestId;code;constructor(t,e){super(t),this.name="RequestError",this.requestId=e?.requestId,this.code=e?.code,e?.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,new.target.prototype)}},F1=class extends ta{timeoutMs;constructor(t,e){super(`[urun] request timed out after ${t}ms`,{requestId:e}),this.name="RequestTimeoutError",this.timeoutMs=t,Object.setPrototypeOf(this,new.target.prototype)}},H1=class extends ta{timeoutMs;constructor(t,e){super(`[urun] request doc-sync did not establish within ${t}ms \u2014 the request was never delivered to the runtime (the session doc never synced with the session-server; check the doc-sync transport / connection)`,{requestId:e}),this.name="RequestDocSyncError",this.timeoutMs=t,Object.setPrototypeOf(this,new.target.prototype)}},q1=class extends Error{stream;owner;attempted;constructor(t,e,r){super(`[urun] stream "${t}" is already produced by the ${e}; this (${r}) peer cannot also produce it \u2014 a named stream has exactly one producer (consume it instead, or use a distinct name for the reverse direction)`),this.name="StreamDirectionConflict",this.stream=t,this.owner=e,this.attempted=r,Object.setPrototypeOf(this,new.target.prototype)}},fg=15e3,JA=class extends Error{kind;stream;timeoutMs;constructor(t,e){let r=e?.timeoutMs??fg,s=e?.stream??t,n=s!==t?` "${s}"`:"";super(`[urun] SFU did not ack producer ${t}${n} within ${Math.round(r/1e3)}s \u2014 the server never replied to 'produce'. The runtime's inbound port for this stream is likely unadvertised (a cold or capacity-queued runtime), so the SFU has nothing to forward the track to; the published track never reached the runtime.`),this.name="ProduceAckTimeout",this.kind=t,this.stream=s,this.timeoutMs=r,Object.setPrototypeOf(this,new.target.prototype)}},wg=class extends ta{constructor(t){super("[urun] request aborted",{requestId:t}),this.name="RequestAbortError",Object.setPrototypeOf(this,new.target.prototype)}},V1=class extends ta{constructor(t){super("[urun] request cancelled: session disconnected",{requestId:t}),this.name="RequestCancelledError",Object.setPrototypeOf(this,new.target.prototype)}},ise=/^\[urun\] (?:timed out waiting for session allocation at|session allocation wait expired at|session allocation poll failed at|session allocation failed at|session allocation at|session create at) \S+(?::[ \t]+|[ \t]+|$)/;function ose(t){return t.replace(/\bhttps?:\/\/[^\s)]+/g,"the session gateway")}function $$(t){let e=t.replace(ise,"");return ose(e||t.replace(/^\[urun\] /,""))}function F$(t){let e=t.error?.httpStatus;if(e===401||e===403)return"The backend rejected this client \u2014 sign in again or check the auth token / org access.";if(t.error?.code==="session_archived")return"This session is archived \u2014 call directory.unarchive(sessionId) (the session directory's un-archive verb), then reconnect with the same id.";let r=t.error?.retryAfterSeconds,s=r!==void 0?` It asked for ${Math.round(r)}s.`:"";return e===429?`The backend is shedding load \u2014 its admission queue is full, so this is capacity, not your request.${s} The SDK already retried with backoff; try again in a moment.`:e===408?`The request timed out before the backend answered \u2014 that is a timeout, not a verdict on your request.${s} The SDK already retried with backoff; try again in a moment.`:e!==void 0&&e>=500?"The backend is having an outage (nothing is wrong with your request) \u2014 the SDK already retried with backoff, so try again shortly and report the status above if it persists.":"The backend could not create a session \u2014 check the app/function name and auth, then retry."}function z1(t,e){let r=e.error?.reason,s=e.elapsedMs!==void 0?Math.round(e.elapsedMs/1e3):void 0;switch(t){case"create-failed":{let n=e.error?.httpStatus!==void 0?` (HTTP ${e.error.httpStatus})`:"",i=e.error?.code;return i==="queue_ttl_expired"||i==="stale_poll_expired"?{message:`[urun] the queued session REQUEST timed out while waiting${n} (${i}) \u2014 the session itself is untouched`,hint:"Nothing was lost and nothing needs replacing: connect again with the same session and the control plane re-admits the request (a poll that arrives in time re-drives it on its own)."}:i==="session_archived"?{message:`[urun] this session is archived${n} \u2014 un-archive it before resuming`+(r?`: ${$$(r)}`:""),hint:F$(e)}:i==="client_release"?{message:`[urun] the session's admission request was closed (client_release)${n} \u2014 this dial cannot attach through it`,hint:"The request row is terminal; retrying the same dial only repeats the 410. Create a fresh session (a new dial). The SDK itself never closes a request \u2014 a whenLive timeout only rejects."}:{message:`[urun] session create failed${n}${r?`: ${$$(r)}`:""}`,hint:F$(e)}}case"never-live":{let n=s!==void 0?` after ${s}s`:"",i=` (last server status: ${e.lastServerStatus??"none"})`,o=e.lastServerStatus!==void 0&&["requested","queued","pending","allocating","provisioning","waking","waiting_for_capacity","unavailable","allocated","starting"].includes(e.lastServerStatus);return e.error?.code==="expired"?o?{message:`[urun] session${e.sessionId?` ${e.sessionId}`:""} expired before a runtime picked it up${n}${i} \u2014 the backend never dispatched the session (no runtime pulled it), so no media transport could ever connect`,hint:"Not a network problem \u2014 the session was still waiting for a runtime. Retry in a moment; if it persists, the backend dispatch lane is stuck."}:{message:`[urun] session${e.sessionId?` ${e.sessionId}`:""} expired before media connected${n} \u2014 the control plane reclaims sessions whose media transport never establishes (~80s after create)`,hint:"Retry to mint a fresh session, and connect promptly after start (a backgrounded tab or paused debugger can miss the window)."}:e.sessionId?o?{message:`[urun] session ${e.sessionId} was created but no runtime ever picked it up${n}${i} \u2014 the backend has not dispatched the session yet (a runtime pulls the demand, then the session server exists)`,hint:"Waiting for a runtime \u2014 not a network, VPN, or firewall problem. Retry in a moment; if it persists, the session id above is what to report."}:{message:`[urun] session ${e.sessionId} was created but never went live${n}${i} \u2014 the backend is busy or wedged (no runtime picked the session up)`,hint:"The backend is at capacity or stuck. Retry in a moment; if it persists, the session id above is what to report."}:{message:`[urun] no session went live${n} (phase=${e.phase}${e.lastServerStatus?`, last server status: ${e.lastServerStatus}`:""})`,hint:"The session never got past admission. Retry; if it persists, check the backend deployment."}}case"transport-failed":return e.error?.code==="transport-consumed"?{message:`[urun] the retry reused a session whose media transport was already connected${e.sessionId?` (id ${e.sessionId})`:""} \u2014 the session was consumed by an earlier attempt`,hint:"Start a fresh session (reload the page) \u2014 this session leg cannot be connected again."}:{message:`[urun] media/transport connection failed${r?`: ${r}`:""} (transport state: ${e.transportState})`,hint:"The network is likely blocking the media connection (WebRTC/WebSocket) \u2014 try a different network or disable VPN/proxy, then retry."};case"media-permission":return{message:`[urun] microphone/camera unavailable${r?`: ${r}`:""}`,hint:e.error?.code==="NotFoundError"||e.error?.code==="OverconstrainedError"?"No matching input device was found \u2014 connect or select a microphone/camera and retry.":"Allow microphone/camera access for this site (browser permission \u2014 or, when embedded, the parent page's permissions policy), then retry."};case"runtime-failed":return{message:`[urun] session${e.sessionId?` ${e.sessionId}`:""} failed at runtime${r?`: ${r}`:""}`,hint:"The session function crashed on the backend \u2014 check the app logs. The session itself is parked, not gone: attach to it again once the app is fixed."};case"produce-timeout":return{message:`[urun] publishing a track timed out${r?`: ${r}`:""} \u2014 the SFU never acked the produce (the runtime\u2019s inbound port for the stream was not advertised in time)`,hint:"The runtime was still cold or the backend was at capacity when the track was published. Retry in a moment; if it persists, the backend never opened the stream to receive it."};case"insufficient-credits":return{message:`[urun] session create refused${e.error?.httpStatus!==void 0?` (HTTP ${e.error.httpStatus})`:""} \u2014 the org has insufficient credits${r?`: ${r}`:""}`,hint:"Out of credits \u2014 add credits to keep running sessions."}}}var Sl=class extends Error{kind;status;hint;constructor(t,e,r){let{message:s,hint:n}=z1(t,e);super(s),this.name="SessionFailedError",this.kind=t,this.status=e,this.hint=n,r?.cause!==void 0&&(this.cause=r.cause),Object.setPrototypeOf(this,new.target.prototype)}};function TF(t,e){if(t instanceof Sl)return t;let r=t instanceof Error?t:new Error(String(t)),s={phase:e?.phase??"idle",transportState:e?.transportState??"disconnected",...e,error:{reason:r.message,code:r.name,kind:"media-permission"}};return new Sl("media-permission",s,{cause:t})}var B1=class extends Error{code="transport_session_mismatch";connectedSessionId;requestedSessionId;constructor(t,e){super(`[urun] cannot retarget a connected transport to a different session: this leg is live on ${t??"(unknown)"} but setConnection() asked for ${e} \u2014 disconnect() this leg first (or use a fresh session handle)`),this.name="TransportSessionMismatchError",this.connectedSessionId=t,this.requestedSessionId=e,Object.setPrototypeOf(this,new.target.prototype)}},Cr=class extends Error{httpStatus;code;balanceCredits;platformStatus;retryAfterSeconds;constructor(t,e){super(t),this.name="SessionAllocationError",this.httpStatus=e?.httpStatus,this.code=e?.code,this.balanceCredits=e?.balanceCredits,this.platformStatus=e?.platformStatus,this.retryAfterSeconds=e?.retryAfterSeconds,e?.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,new.target.prototype)}};function xc(t){if(!t)return!1;let e=typeof t=="string"?t:t.name;return e==="queued"||e==="unavailable"||e==="provisioning"||e==="waiting_for_capacity"}function kF(t){return t?(typeof t=="string"?t:t.name)==="paused":!1}var QA=45e3,L1=6e5;function W1(t,e={}){let{signal:r}=e;return new Promise((s,n)=>{if(r?.aborted){n(r.reason instanceof Error?r.reason:new Error("whenLive aborted"));return}if(t.phase?.name==="live"){s();return}if(t.phase?.name==="error"){let S=t.phase,O=t.status??{phase:S.name,transportState:"disconnected",sessionId:S.sessionId,requestId:S.requestId,queue:S.queue,error:S.error,region:S.region};n(new Sl(S.error?.kind??"transport-failed",O));return}let i,o,a=!1,c=S=>{a||(a=!0,o!==void 0&&clearTimeout(o),r?.removeEventListener("abort",d),i?.(),S?n(S):s())},d=()=>{c(r?.reason instanceof Error?r.reason:new Error("whenLive aborted"))};r?.addEventListener("abort",d,{once:!0});let u=()=>{let S=t.phase;return t.status??{phase:S?.name??"idle",transportState:"disconnected",sessionId:S?.sessionId,requestId:S?.requestId,queue:S?.queue,error:S?.error,region:S?.region}},l=S=>c(new Sl(S,u())),h=e.timeout!==void 0,p=Date.now(),m=h?e.timeout:QA,_=()=>{o!==void 0&&(clearTimeout(o),o=void 0)},f=()=>{if(a||m<=0)return;clearTimeout(o);let S=p+m-Date.now();o=setTimeout(()=>{if(!h&&xc(t.phase?.name)){o=void 0;return}let O=u();O.elapsedMs===void 0&&(O.elapsedMs=m),o=void 0,r?.removeEventListener("abort",d),i?.(),i=void 0,c(new Sl("never-live",O))},Math.max(0,S))},b=S=>{!h||a||m<=0||S?.runtime?.wake?.expectedWakePath==="cold-boot"&&(L1<=m||(m=L1,f()))},w=S=>{if(!a){if(!h&&xc(S?.name)){_();return}if(h){b(S),o===void 0&&m>0&&f();return}o===void 0&&(p=Date.now(),f())}};i=t.onPhase(S=>{S?.name==="live"?c():S?.name==="error"?l(S.error?.kind??"transport-failed"):w(S)}),a||w(t.phase),a&&i()})}function AF(t){switch(t.name){case"idle":return"Initializing\u2026";case"unavailable":return"Starting the app\u2026";case"queued":return t.queue?`Waiting in queue (position ${t.queue.position} of ${t.queue.depth})\u2026`:t.runtime?.state==="busy"?"All runtimes are busy \u2014 waiting for capacity\u2026":"Waiting for capacity\u2026";case"provisioning":return t.runtime?.state==="starting"?"Starting model\u2026":"Provisioning\u2026";case"waiting_for_capacity":return t.queue?`Waiting for GPU capacity (position ${t.queue.position} of ${t.queue.depth})\u2026`:"Waiting for GPU capacity";case"connecting":return"Connecting\u2026";case"live":return"Live";case"paused":return ase(t.reason);case"error":{if(t.error?.kind==="insufficient-credits")return"Out of credits \u2014 add credits to keep running sessions.";let e=t.error?.kind;if(e){let{message:r,hint:s}=z1(e,{phase:t.name,transportState:"disconnected",sessionId:t.sessionId,requestId:t.requestId,queue:t.queue,error:t.error});return`${r.replace(/^\[urun\] /,"")} \u2014 ${s}`}return t.error?.reason?`Session failed \u2014 ${t.error.reason}`:"Session failed"}case"unknown":return t.reason?`Session in an unrecognized state ("${t.reason}") \u2014 the client SDK may be out of date`:"Session in an unrecognized state \u2014 the client SDK may be out of date"}}function ase(t){switch(t){case"client_ended":return"Paused \u2014 you hung up. Resume any time.";case"client_paused":return"Paused \u2014 you paused it. Resume any time.";case"client_detached":return"Paused \u2014 this device let go. Resume any time.";case"client_gone":return"Paused \u2014 every device disconnected. Resume any time.";case"session_ended":case"ended":case"closed":return"Paused \u2014 the compute was released. Resume any time.";case"idle_timeout":return"Paused \u2014 idle. Resume any time.";case"max_session_age":return"Paused \u2014 reached its maximum length. Resume any time.";case"credits_exhausted":return"Paused \u2014 out of credits. Add credits, then resume.";case"capacity_pressure":return"Paused \u2014 the GPU was reclaimed while the platform was under load. Resume any time.";case"control_plane_release":return"Paused \u2014 the platform reclaimed the compute. Resume any time.";case"superseded":return"Paused \u2014 another client attached. Resume any time.";case"superseded_by_redial":return"Paused \u2014 a newer connection from this session took over. Resume any time.";case"connect_deadline":return"Paused \u2014 the runtime never finished connecting in time. Resume to try again.";case"adoption_expired":return"Paused \u2014 the runtime was assigned but never picked the session up. Resume to try again.";case"media_lane_bind_failed":return"Paused \u2014 the audio/video lane could not be set up. Resume to try again.";case"lease_lost":return"Paused \u2014 the runtime stopped renewing its lease. Resume any time.";case"presence_unconfirmed":return"Paused \u2014 the platform could not confirm anyone was still attached. Resume any time.";case"runtime_inert":case"assignment_unconfirmable":return"Paused \u2014 the runtime never acknowledged its assignment. Resume to try again.";case"runtime_unreachable":return"Paused \u2014 the platform could not reach the runtime. Resume to try again.";case"runtime_silent":return"Paused \u2014 the runtime stopped sending audio/video. Resume to try again.";case"assignment_undelivered":return"Paused \u2014 the assignment never reached a runtime. Resume to try again.";case"dispatch_released":return"Paused \u2014 the worker finished and gave its GPU seat back. Resume any time.";case"dispatch_parked":return"Paused \u2014 the worker finished and parked the session. Resume any time.";case"runtime_swap_exhausted":return"Paused \u2014 the platform ran out of runtimes to try. Resume any time.";case"dispatch_failed":return"Paused \u2014 handing the session to a worker did not succeed. Resume to try again.";default:return t?`Paused \u2014 ${t}. Resume any time.`:"Paused \u2014 resume any time."}}function lg(){return typeof process<"u"&&process.stdout!=null&&typeof process.stdout.write=="function"}function Qh(){return typeof window>"u"&&typeof process<"u"&&process.versions!=null&&process.versions.node!=null}function cse(){return Qh()?"Chrome111":void 0}var dse=["RTCSessionDescription","RTCIceCandidate","RTCRtpReceiver","RTCRtpSender","RTCRtpTransceiver","RTCDataChannel","MediaStream","MediaStreamTrack"],HA=null,IF=null;function lse(){return typeof globalThis.RTCPeerConnection<"u"?null:IF??"the WebRTC peer globals (RTCPeerConnection) are not installed in this runtime"}function K1(){return Qh()?HA||(HA=use(),HA):Promise.resolve()}async function use(){let t=globalThis;if(typeof t.WebSocket>"u")try{let e=await Promise.resolve().then(()=>(i8(),n8)),r=e.default??e;t.WebSocket=r}catch(e){H$("WebSocket",e)}if(typeof t.RTCPeerConnection>"u")try{let e=await Promise.resolve().then(()=>(M$(),U$));fse(t,e)}catch(e){IF=H$("werift",e)}}var hse=4;function fse(t,e){let{RTCPeerConnection:r,useH264:s,useVP8:n,useOPUS:i,useSdesMid:o,useSdesRTPStreamId:a,useAbsSendTime:c,useTransportWideCC:d,useVideoOrientation:u}=e,l=()=>({video:[s(),n()],audio:[i()]}),h=()=>({video:[o(),a(),c(),d(),u()],audio:[o(),c(),d()]});class p extends r{constructor(_){super({..._,codecs:_?.codecs??l(),headerExtensions:_?.headerExtensions??h()})}async setRemoteDescription(_){await super.setRemoteDescription(_);let f=this.sctpManager,b=f?.sctpTransport,w=f?.connectSctp;!b||typeof w!="function"||b.dtlsTransport?.state==="connected"&&b.sctp?.associationState!==hse&&await w.call(f)}}t.RTCPeerConnection=p;for(let m of dse)e[m]!=null&&typeof t[m]>"u"&&(t[m]=e[m])}function H$(t,e){let r=e instanceof Error?e.message:String(e),s=`optional dependency "${t}" unavailable (${r})`;return E.warn(`[urun-sh/core] Node WebRTC support: ${s}. Realtime media will not work in this Node process; install "${t}" to enable it. Doc/KV transport over WebSocket is unaffected.`),s}var G1=500,vg=15e3,Wh=6;function _g(t,e=Math.random){if(!Number.isFinite(t)||t<0)throw new Error(`[urun] computeBackoffDelay: attempt must be a non-negative number, got ${t}`);let r=Math.min(vg,G1*2**t);return Math.round(e()*r)}function X1(t){if(t instanceof Cr){let e=t.httpStatus;return e===408||e===429||e!==void 0&&e>=500}return t instanceof Error?t.name==="TypeError"||t.name==="TimeoutError"||t.name==="AbortError":!1}var RF=10,pse=.5,O1=RF;function PF(){return O1<1?!1:(O1-=1,!0)}function DF(){O1=Math.min(RF,O1+pse)}var mse="session-api.prod.cloud.urun.sh",gse=["https://session-api.use2.prod.cloud.urun.sh","https://session-api.usw2.prod.cloud.urun.sh"];function Tr(t){return t.trim().replace(/\/+$/,"")}function Sg(t,e){let r=[],s=n=>{if(!n)return;let i=Tr(n);i&&!r.includes(i)&&r.push(i)};s(t);for(let n of e??[])s(n);for(let n of zse(t))s(n);return r}function Eg(t){try{if(typeof fetch!="function")return;let e=Tr(t.baseUrl),r=t.sessionId?`${e}/api/sessions/${encodeURIComponent(t.sessionId)}/end`:`${e}/api/session-requests/${encodeURIComponent(t.requestId)}/cancel`;fetch(r,{method:"POST",headers:t.reason!==void 0?{...Qn(t,t.jwt),"Content-Type":"application/json"}:Qn(t,t.jwt),...t.reason!==void 0?{body:JSON.stringify({reason:t.reason})}:{},keepalive:!0}).catch(()=>{})}catch{}}async function ZA(t){try{let e=`${Tr(t.baseUrl)}/api/session-requests/${encodeURIComponent(t.requestId)}/cancel`,r=await Jn(t);if(t.getAccessToken&&!r)throw new Sn("[urun] session request cancel refused: getAccessToken resolved no token (an unauthenticated cancel is never sent)",{requestId:t.requestId,code:"no_access_token"});let s=await fetch(e,{method:"POST",headers:Qn(t,r),keepalive:!0});if((s.status===401||s.status===403)&&t.getAccessToken){let o=await Jn(t,{forceRefresh:!0,reason:"unauthorized"});o&&o!==r&&(s=await fetch(e,{method:"POST",headers:Qn(t,o),keepalive:!0}))}let n=await Kh(s);if(!s.ok)throw new Sn(`[urun] session request cancel failed: ${J1(n,s.status)}`,{requestId:t.requestId,code:n.error_code,httpStatus:s.status});let i=String(n.status??"");if(i==="cancelled"||i==="canceled"||i==="closed")return{status:"canceled",requestId:t.requestId};if(i==="failed"||i==="rejected"||i==="expired")return{status:"canceled",requestId:t.requestId,platformStatus:i};throw new Sn(`[urun] session request cancel returned an unrecognized request status ${JSON.stringify(i)} (recognized: cancelled/canceled, closed, failed, rejected, expired)`,{requestId:t.requestId,code:"invalid_release_response",httpStatus:s.status})}catch(e){throw e instanceof Sn?e:new Sn("[urun] session request cancel failed",{requestId:t.requestId,cause:e})}}async function eI(t){let e;try{e=await Y1(t,`/api/sessions/${encodeURIComponent(t.sessionId)}/end`,{method:"POST",keepalive:!0},"session end")}catch(n){if(n instanceof Sn)throw n;let i=n;throw new Sn(i?.message??"[urun] session end request failed",{sessionId:t.sessionId,...i?.code!==void 0?{code:i.code}:{},...i?.httpStatus!==void 0?{httpStatus:i.httpStatus}:{},cause:n})}let r=String(e.status??""),s=e.pause_reason;if(r==="paused")return{status:"paused",sessionId:String(e.logical_id??e.id??t.sessionId),reason:typeof s=="string"&&s.length>0?s:"client_ended"};throw new Sn(`[urun] session end returned ${JSON.stringify(r)} for session ${t.sessionId} \u2014 an end PARKS the session, so the only contract-valid answer is "paused" (a terminal word on this route would be a session-plane terminal write, which is forbidden)`,{sessionId:t.sessionId,code:"invalid_end_response"})}function BF(t){if(typeof t!="string"||t.length===0)return null;let e=new Date(t);return Number.isFinite(e.getTime())?e:null}var yse=120,bse=1e3,xse=20,wse=5,vse=5e3;function _se(t,e=Date.now()){if(!t)return null;let r=t.split(".")[1];if(!r)return null;try{let s=r.replace(/-/g,"+").replace(/_/g,"/"),n=s.padEnd(s.length+(4-s.length%4)%4,"="),i=JSON.parse(atob(n));return typeof i.exp!="number"||!Number.isFinite(i.exp)?null:i.exp*1e3-e}catch{return null}}var Sse=500,LF=1e4,Ese=new Set([502,503,504]),Cse=2,Tse=50,q$=1e4;async function V$(t,e){let r=Date.now()+q$;for(;;){await zh(Tse);let s=await Jn(t);if(s)return s;if(Date.now()>=r)throw new Cr(`[urun] session allocation at ${e} never got an access token: the wired getAccessToken resolved nothing within ${Math.round(q$/1e3)}s (no unauthenticated request was sent)`)}}function kse(t,e){if(!t)return null;try{let r=new URL(t),s=e?new URL(Tr(e)):null,n=r.pathname==="/api/sessions/create"||r.pathname==="/api/sessions/create/";return r.protocol!=="https:"||!n||!Pse(r,s)?null:Tr(r.origin)}catch{return null}}function Ase(t,e){if(!t||!t.trim())return{outcome:"absent"};if(!Ise(e))return{outcome:"bootstrap-only"};let r=t.includes("://")?t:`https://${t}`,s;try{s=new URL(r)}catch{return{outcome:"rejected",reason:"not a parseable URL or host"}}return s.protocol!=="https:"?{outcome:"rejected",reason:`scheme ${s.protocol} is not https:`}:s.pathname!=="/"&&s.pathname!==""?{outcome:"rejected",reason:`expected a bare origin, got path ${s.pathname}`}:N1(s.hostname)?{outcome:"pinned",base:Tr(s.origin)}:{outcome:"rejected",reason:`host ${s.hostname} is outside the urun.sh trust set`}}function Ise(t){if(!t)return!1;try{let e=new URL(Tr(t));return e.protocol==="https:"&&N1(e.hostname)}catch{return!1}}function Rse(t){let e=Tr(t);try{return Tr(new URL(e).origin)}catch{return e}}function Pse(t,e){return N1(t.hostname)&&(!e||N1(e.hostname))}function N1(t){let e=t.toLowerCase();return e==="urun.sh"||e.endsWith(".urun.sh")}function Dse(t){let e=t instanceof Cr?t.retryAfterSeconds:void 0;return e===void 0||!Number.isFinite(e)||e<=0?0:Math.min(e*1e3,vg)}function OF(t,e){let r=Dse(e);return r>0?Math.max(t,Date.now()+r):t}async function NF(t){let e=Sg(t.baseUrl,t.fallbackUrls),r=null,s=0,n=e.length>1;for(let i=0;i<Wh;i++){for(let o of e)try{let a=await Bse(o,t,{pollAttempts:yse,retryAfterLimitMs:n?bse:void 0});return DF(),a}catch(a){if(r=a instanceof Error?a:new Error(String(a)),s=OF(s,r),r instanceof Zo||r instanceof ug||Nse(r))throw r}if(!X1(r))break;if(i+1<Wh){if(!PF())break;await zh(Math.max(_g(i),s-Date.now()))}}throw r??new Error("[urun] session allocation failed")}async function Bse(t,e,r){let s,n,i,o,a=Rse(t),c=0,d=new Set,u=Date.now(),l=u+r.pollAttempts*LF,h=!1,p=12e4,m=10080*60,_=S=>{if(typeof S!="number"||!Number.isFinite(S)||S<=0||S>m)return;let O=u+S*1e3+p;O>l&&(l=O,h=!0)},f=()=>h?Number.POSITIVE_INFINITY:r.pollAttempts,b=8,w=0;for(let S=0;S<f();S++){if(h&&Date.now()>=l)throw dg(a,!!s,o);n=i??await Jn(e),i=void 0,e.getAccessToken&&!n&&(n=await V$(e,a));let O=!!s,j=Date.now(),P;if(s){let W=0,J=F=>{let q=Math.min(vg,G1*2**W),Q=Math.max(Math.ceil(q/2),_g(W));return W+=1,Math.min(Math.max(F,Q),Math.max(0,l-Date.now()))};for(;;){let F=l-Date.now();if(F<=0)throw dg(a,!0,o);let q=Math.max(1,Math.min(xse,Math.floor(F/1e3)));{let R=_se(n);if(R!==null&&R<q*1e3+vse)try{let Y=await Jn(e,{forceRefresh:!0});Y&&Y!==n&&(n=Y)}catch{}}j=Date.now();try{P=await fetch(`${a}/api/session-requests/${encodeURIComponent(s)}?wait_s=${q}`,{headers:Qn(e,n),redirect:"manual",signal:Hse((q+wse)*1e3)})}catch{let R=J(0);if(R<=0)throw dg(a,!0,o);await zh(R);continue}if(o=`HTTP ${P.status}`,!Ese.has(P.status))break;try{await P.body?.cancel()}catch(R){throw new ug(`[urun] session allocation poll response cleanup failed at ${a}`,{cause:R})}let Q=J(W$(P,{},r.retryAfterLimitMs));if(Q<=0)throw dg(a,!0,o);await zh(Q)}}else P=await fetch(`${a}/api/sessions/create`,{method:"POST",redirect:"manual",headers:{...Qn(e,n),"Content-Type":"application/json","Idempotency-Key":e.idempotencyKey},body:JSON.stringify(Lse(e))});if(P.type==="opaqueredirect"||P.status>=300&&P.status<400){try{await P.body?.cancel()}catch{}throw new Zo(`[urun] ${O?"session poll":"session create"} at ${a} answered an HTTP redirect (status ${P.status}) \u2014 browsers cannot follow a cross-origin redirect with credentials; the control plane must emit the JSON redirect envelope ({status:"redirect", location})`)}let k=await Kh(P);if(o=typeof k.status=="string"&&k.status?k.status:`HTTP ${P.status}`,P.status!==401&&P.status!==403&&(w=0),!s&&k.status==="redirect"){let W=kse(k.location,a);if(!W)throw new Cr(`[urun] session create at ${a} answered a redirect envelope without a usable location (${JSON.stringify(k.location??null)}) \u2014 refusing to re-issue an authenticated create to an untrusted target`);if(W===a)throw new Cr(`[urun] session create at ${a} redirected to ITSELF \u2014 control-plane region apex map misconfiguration`);if(c>=Cse)throw new Cr(`[urun] session create followed ${c} region redirects and was redirected AGAIN (${a} -> ${W}) \u2014 region forward loop, giving up loudly`);c+=1,a=W;continue}if(k.request_id)try{e.onRequest?.({requestId:k.request_id,baseUrl:a,...k.session_id?{sessionId:k.session_id}:{}})}catch{}if(P.ok&&(k.status==="allocated"||!k.status&&k.session_id)&&k.session_id){let W=k.session_id,J=Ase(k.session_api_base,a);if(J.outcome==="rejected")throw new Zo(`[urun] gateway allocated session ${k.session_id} with an unusable session_api_base (${JSON.stringify(k.session_api_base)}): ${J.reason} \u2014 refusing to pin the session to a region it may not belong to`);if(J.outcome==="pinned"&&J.base!==a&&(a=J.base,k.request_id))try{e.onRequest?.({requestId:k.request_id,baseUrl:a,...k.session_id?{sessionId:k.session_id}:{}})}catch{}let F=qF(k.ws_url,a,W,"gateway allocated session");return{baseUrl:a,sessionId:W,wsUrl:F,endsAt:BF(k.ends_at),response:k}}if(P.status===202||k.status==="pending"||k.status==="queued"||k.queued){if(s=k.request_id||s,!s)throw new Error("[urun] gateway queued session without request_id");if(_(k.effective_max_queue_time_s),e.onAdmission)try{e.onAdmission(Fse(k,s))}catch{}let W=Date.now()-j<Sse;O&&W&&await zh(W$(P,k,r.retryAfterLimitMs));continue}if((P.status===401||P.status===403)&&e.getAccessToken&&k.error_code!=="session_name_not_yours"){let W=n??"";if(d.add(W),h&&(w+=1,w>b))throw new ug(`[urun] session allocation failed at ${a}: authorization refused ${b} consecutive refreshes while the admission wait was extended (last server status: ${o??"none received"}) \u2014 the token provider keeps minting fresh tokens the control plane rejects`,{httpStatus:P.status,code:k.error_code,platformStatus:k.status});let J=await Jn(e,{forceRefresh:!0,reason:"unauthorized"});if(J&&!d.has(J)){i=J;continue}if(J===void 0){let F=await V$(e,a);if(!d.has(F)){i=F;continue}}}let C=J1(k,P.status),D=k.error_code??(P.status===402?"insufficient_credits":void 0),H=O?ug:Cr;throw new H(`[urun] session allocation failed at ${a}: ${C}`,{httpStatus:P.status,code:D,balanceCredits:typeof k.balance_credits=="number"?k.balance_credits:void 0,platformStatus:k.status,retryAfterSeconds:sI(P,k)})}throw dg(a,!!s,o)}function dg(t,e=!1,r){let s=e?ug:Cr;return new s(`[urun] session allocation wait expired at ${t} \u2014 the CLIENT-side wait budget elapsed (last server status: ${r??"none received"}; the gateway reported no failure)`)}function Qn(t,e){let r={"X-Tenant-Id":t.orgId,"X-Auth-Provider":t.authProvider||"default","X-User-Id":"anonymous"};return e&&(r.Authorization=`Bearer ${e}`),r}async function Jn(t,e){return t.getAccessToken?await t.getAccessToken(e)??void 0:t.jwt}function Lse(t){let e=t.priority==="preempt";return{app:t.app,function:t.functionName,gpus:1,idempotency_key:t.idempotencyKey,...t.sessionKey&&!e?{logical_id:t.sessionKey}:{},...t.concurrencyKey&&!e?{concurrency_key:t.concurrencyKey}:{},...t.label&&!t.sessionKey?{label:t.label}:{},...e?{priority:"preempt"}:{},...t.sharedApp?{shared_app:!0}:{}}}async function Y1(t,e,r,s){let n=await Jn(t);if(t.getAccessToken&&!n)throw new Gi(`[urun] ${s} refused: getAccessToken resolved no token (an unauthenticated request is never sent)`,{code:"no_access_token"});let i=Sg(t.baseUrl,t.fallbackUrls),o;for(let a of i){let c=`${Tr(a)}${e}`,d=h=>fetch(c,{method:r.method,headers:r.body!==void 0?{...Qn(t,h),"Content-Type":"application/json"}:Qn(t,h),...r.body!==void 0?{body:JSON.stringify(r.body)}:{},...r.keepalive?{keepalive:!0}:{}}),u;try{if(u=await d(n),(u.status===401||u.status===403)&&t.getAccessToken){let h=await Jn(t,{forceRefresh:!0,reason:"unauthorized"});h&&h!==n&&(u=await d(h))}}catch(h){o=h;continue}let l=await Kh(u);if(!u.ok)throw new Gi(`[urun] ${s} failed: ${J1(l,u.status)}`,{code:l.error_code,httpStatus:u.status});return l}throw new Gi(`[urun] ${s} request failed`,{cause:o})}async function UF(t){let e=new URLSearchParams;t.app&&e.set("app",t.app),t.functionName&&e.set("function",t.functionName),t.includeArchived&&e.set("include_archived","true"),t.limit!==void 0&&e.set("limit",String(t.limit)),t.cursor&&e.set("cursor",t.cursor);let r=e.toString(),s=await Y1(t,`/api/sessions${r?`?${r}`:""}`,{method:"GET"},"session list");if(!Array.isArray(s?.sessions))throw new Gi("[urun] session list returned no `sessions` array \u2014 the control plane and this SDK disagree on the response shape",{code:"invalid_list_response"});return{rows:s.sessions,nextCursor:s.next_cursor??null}}async function tI(t){let e=t.archived?"archive":"unarchive";await Y1(t,`/api/sessions/${encodeURIComponent(t.sessionId)}/${e}`,{method:"POST"},`session ${e}`)}async function MF(t){await eI(t)}async function jF(t){let e=t.name.trim();if(e.length===0)throw new Gi("[urun] session name refused: a name is required (an empty name is not a rename)",{code:"invalid_session_name"});await Y1(t,`/api/sessions/${encodeURIComponent(t.sessionId)}/name`,{method:"POST",body:{name:e,...t.source?{source:t.source}:{}}},"session name")}async function $F(t){let e=Sg(t.baseUrl,t.fallbackUrls),r=null,s=0;for(let n=0;n<Wh;n++){for(let i of e)try{let o={baseUrl:i,app:"",functionName:"",orgId:t.orgId,jwt:t.jwt,getAccessToken:t.getAccessToken,authProvider:t.authProvider,idempotencyKey:""},a=`${Tr(i)}/api/sessions/${encodeURIComponent(t.sessionId)}/viewer-connect`,c=await Jn(o);if(t.getAccessToken&&!c)throw new Cr(`[urun] viewer-connect for ${t.sessionId} refused: getAccessToken resolved no token (an unauthenticated viewer-connect is never sent)`);let d=await fetch(a,{headers:Qn(o,c)});if((d.status===401||d.status===403)&&t.getAccessToken){let h=await Jn(o,{forceRefresh:!0,reason:"unauthorized"});h&&h!==c&&(d=await fetch(a,{headers:Qn(o,h)}))}if(!d.ok){let h=await Kh(d);throw new Cr(`[urun] viewer-connect for ${t.sessionId} failed: `+J1(h,d.status),{httpStatus:d.status,retryAfterSeconds:sI(d,h)})}let u=await Kh(d),l=qF(u.ws_url,i,t.sessionId,"viewer-connect");return DF(),{baseUrl:Tr(i),sessionId:t.sessionId,wsUrl:l,endsAt:BF(u.ends_at),response:u}}catch(o){if(r=o instanceof Error?o:new Error(String(o)),s=OF(s,r),r instanceof Zo)throw r}if(!X1(r))break;if(n+1<Wh){if(!PF())break;await zh(Math.max(_g(n),s-Date.now()))}}throw r??new Error("[urun] viewer-connect failed")}async function FF(t){try{let e=Tr(t.baseUrl),r=await Jn(t);if(t.getAccessToken&&!r)return{status:"unavailable"};let s=await fetch(`${e}/api/sessions/prewake`,{method:"POST",headers:{...Qn(t,r),"Content-Type":"application/json"},body:JSON.stringify({app:t.app,function:t.functionName})});if(s.status===404)return{status:"unknown-app"};if(!s.ok)return{status:"unavailable"};let n=await Kh(s),i={status:n.status==="prebound"?"prebound":"warming"};return typeof n.expires_at=="string"&&(i.expiresAt=n.expires_at),typeof n.warm_capable=="boolean"&&(i.warmCapable=n.warm_capable),i}catch(e){return lg()?E.warn("[urun] prewake failed (advisory, ignored):",e):E.debug?.("[urun] prewake failed (advisory, ignored):",e),{status:"unavailable"}}}async function Kh(t){try{let e=await t.json();return e&&typeof e=="object"?e:{}}catch{return{}}}function J1(t,e){let r=t.error_code,s=t.error_message||t.message||t.error,n=r&&s&&s!==r?`${r}: ${s}`:s||r;return n?`${n} (HTTP ${e})`:`HTTP ${e}`}var Ose=new Set([400,402,409]);function Nse(t){return t instanceof Cr&&t.httpStatus!==void 0&&Ose.has(t.httpStatus)}var Use=new Set(["capture-attested","no-portable-golden","portable-golden-release-mismatch","portable-golden-attestation-invalid"]);function HF(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function zA(t){return typeof t=="string"&&t.trim().length>0}function z$(t){return typeof t=="number"&&Number.isSafeInteger(t)&&t>0}function Mse(t){return typeof t=="number"&&Number.isSafeInteger(t)&&t>=0}function jse(t){if(HF(t)&&!(!zA(t.snapshot_id)||!zA(t.snapshot_compat_key)||!z$(t.artifact_size_bytes)||!z$(t.durable_arena_bytes)||t.volatile_arena_bytes!==0||!Mse(t.uncovered_weight_bytes)))return{snapshotId:t.snapshot_id,snapshotCompatKey:t.snapshot_compat_key,artifactSizeBytes:t.artifact_size_bytes,durableArenaBytes:t.durable_arena_bytes,volatileArenaBytes:0,uncoveredWeightBytes:t.uncovered_weight_bytes}}function $se(t){if(!HF(t)||t.schema!=="urun.runtime.wake.v1"||t.portability!=="portable"&&t.portability!=="none"||t.expected_wake_path!=="portable-golden-restore"&&t.expected_wake_path!=="cold-boot"||typeof t.reason_code!="string"||!Use.has(t.reason_code)||t.expectation_basis!=="snapshot-registry"||t.restore_observation!=="not-observed")return;let e=t.reason_code;if(t.portability==="portable"&&t.expected_wake_path==="portable-golden-restore"&&e==="capture-attested"){let r=jse(t.golden);return r?{schema:"urun.runtime.wake.v1",portability:"portable",expectedWakePath:"portable-golden-restore",reasonCode:e,expectationBasis:"snapshot-registry",restoreObservation:"not-observed",golden:r}:void 0}if(t.portability==="none"&&t.expected_wake_path==="cold-boot"&&e!=="capture-attested"&&t.golden===void 0)return{schema:"urun.runtime.wake.v1",portability:"none",expectedWakePath:"cold-boot",reasonCode:e,expectationBasis:"snapshot-registry",restoreObservation:"not-observed"}}function rI(t){if("serving_region"in t)return typeof t.serving_region=="string"&&t.serving_region.length>0?t.serving_region:null}function Fse(t,e){let r={status:typeof t.status=="string"&&t.status.length>0?t.status:t.queued?"queued":"pending",requestId:e};zA(t.session_id)&&(r.sessionId=t.session_id);let s=rI(t);s!==void 0&&(r.region=s),typeof t.reason=="string"&&t.reason.length>0&&(r.reason=t.reason),typeof t.decision_reason=="string"&&t.decision_reason.length>0&&(r.decisionReason=t.decision_reason),typeof t.provisioning_refusal_source=="string"&&t.provisioning_refusal_source.length>0&&(r.refusalSource=t.provisioning_refusal_source),typeof t.provisioning_refusal_message=="string"&&t.provisioning_refusal_message.length>0&&(r.refusalMessage=t.provisioning_refusal_message),typeof t.queue_position=="number"&&typeof t.queue_depth=="number"&&(r.queue={position:t.queue_position,depth:t.queue_depth});let n=t.runtime_state;if(n==="unavailable"||n==="starting"||n==="busy"){r.runtime={state:n},typeof t.runtime_reason=="string"&&t.runtime_reason.length>0&&(r.runtime.reason=t.runtime_reason);let i=$se(t.runtime_wake);i&&(r.runtime.wake=i)}return r}function sI(t,e){let r=Number(t.headers.get("Retry-After")||""),s=Number(e.retry_after_seconds??r);return Number.isFinite(s)&&s>0?s:void 0}function W$(t,e,r){let s=sI(t,e),n=r??LF;return s!==void 0?Math.min(s*1e3,n):1e3}function zh(t){return new Promise(e=>setTimeout(e,t))}function Hse(t){let e=typeof AbortSignal<"u"?AbortSignal:void 0;return typeof e?.timeout=="function"?e.timeout(t):void 0}var Zo=class extends Error{},ug=class extends Cr{};function qF(t,e,r,s){if(!t)throw new Zo(`[urun] ${s} ${r} without ws_url`);let n,i;try{n=new URL(t)}catch{throw new Zo(s==="viewer-connect"?`[urun] viewer-connect returned no usable ws_url for ${r}`:`[urun] ${s} ${r} with non-absolute ws_url`)}try{i=new URL(Tr(e))}catch{throw new Zo(`[urun] ${s} ${r} has invalid gateway base URL`)}let o=qse(i.hostname)&&i.protocol==="http:";if(!(o&&n.protocol==="ws:"||n.protocol==="wss:"))throw new Zo(`[urun] ${s} ${r} with insecure ws_url`);if(!Vse(n,i,o))throw new Zo(`[urun] ${s} ${r} with cross-origin ws_url`);return n.toString()}function qse(t){return t==="localhost"||t==="127.0.0.1"||t==="::1"||t.endsWith(".localhost")}function Vse(t,e,r){return!!(r||t.hostname===e.hostname&&t.port===e.port||K$(t.hostname)&&K$(e.hostname))}function K$(t){return t==="urun.sh"||t.endsWith(".urun.sh")}function zse(t){try{return new URL(t).hostname!==mse?[]:gse}catch{return[]}}function Wse(t){return`stream:${t}`}var Kse="urun-stream-v1",nI=1,xs={BINARY:0,TEXT:1,JSON:2,END:3,CHUNK:4},Gh=2,G$=253952,Gse=[xs.BINARY,xs.TEXT,xs.JSON],Cl=Symbol("urun:stream:end");function Q1(t){if(t===Cl)return Uint8Array.from([nI,xs.END]);let{kind:e,body:r}=VF(t);return R1(e,r)}function VF(t){return t instanceof Uint8Array?{kind:xs.BINARY,body:t}:t instanceof ArrayBuffer?{kind:xs.BINARY,body:new Uint8Array(t)}:typeof t=="string"?{kind:xs.TEXT,body:new TextEncoder().encode(t)}:{kind:xs.JSON,body:new TextEncoder().encode(JSON.stringify(t))}}function R1(t,e){let r=new Uint8Array(Gh+e.length);return r[0]=nI,r[1]=t,r.set(e,Gh),r}function Xse(t){if(t===Cl)return[Q1(t)];let{kind:e,body:r}=VF(t);if(r.length+Gh<=G$)return[R1(e,r)];let s=G$-Gh,n=[],i=0;for(;r.length-i>s;)n.push(R1(xs.CHUNK,r.subarray(i,i+s))),i+=s;return n.push(R1(e,r.subarray(i))),n}function Z1(t){let{kind:e,body:r}=zF(t);if(e===xs.CHUNK)throw new Error("[urun] CHUNK envelope requires StreamFragmentReassembler (oversized payload)");return P1(e,r)}function zF(t){let e=t instanceof Uint8Array?t:new Uint8Array(t);if(e.length<Gh||e[0]!==nI)throw new Error(`[urun] bad stream envelope (version=${e[0]}, len=${e.length})`);return{kind:e[1],body:e.subarray(Gh)}}function P1(t,e){switch(t){case xs.BINARY:return e.slice();case xs.TEXT:return new TextDecoder().decode(e);case xs.JSON:return JSON.parse(new TextDecoder().decode(e));case xs.END:return Cl;default:throw new Error(`[urun] unknown stream envelope KIND 0x${t.toString(16)}`)}}var Yse=class{_chunks=[];_bufferedLength=0;feed(t){let{kind:e,body:r}=zF(t);if(e===xs.CHUNK){this._chunks.push(r.slice()),this._bufferedLength+=r.length;return}if(Gse.includes(e)){if(this._chunks.length===0)return P1(e,r);let s=new Uint8Array(this._bufferedLength+r.length),n=0;for(let i of this._chunks)s.set(i,n),n+=i.length;return s.set(r,n),this._chunks=[],this._bufferedLength=0,P1(e,s)}if(this._chunks.length>0)throw this._chunks=[],this._bufferedLength=0,new Error(`[urun] stream envelope KIND 0x${e.toString(16)} arrived mid-fragment-sequence; discarding partial payload`);return P1(e,r)}};function WF(t){return{get consumerId(){return t.consumerId},onData(e,r){return t.onStreamData(e,r)},sendData(e,r,s){return t.sendStreamData(e,r,s)}}}var Jse=Av(CF()),Qse=Av(nse(),1),X$="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function Zse(t){let e=globalThis.crypto,r=new Uint8Array(t);if(e?.getRandomValues)return e.getRandomValues(r),r;for(let s=0;s<t;s++)r[s]=Math.floor(Math.random()*256);return r}function ev(t=16){let e=Zse(t),r="";for(let s=0;s<t;s++)r+=X$[e[s]%X$.length];return r}var Y$=[1e3,2e3,4e3,8e3,3e4],J$=5,ene=15e3,Q$={closed:!0,released:!0,releasing:!0,reaped:!0,expired:!0,superseded:!0,cancelled:!0,canceled:!0,max_session_age:!0},tne=15e3,Z$=15e3,eF=15e3,rne=2e3,sne=6e3,nne=2e3,ine=300,tF=4e3,one=2,ane=750,cne=3,rF=[1e3,2e3,4e3],dne=15e3;var Xh="--",lne=["video","audio"];function U1(t){let e=t.lastIndexOf(Xh);if(e<=0)return;let r=t.slice(e+Xh.length);return lne.includes(r)?r:void 0}function KF(t,e){return`${t}${Xh}${e}`}var iI="v1";function une(t,e){return t.name!==e.name||t.reason!==e.reason||t.sessionId!==e.sessionId||t.requestId!==e.requestId||t.wakingSince!==e.wakingSince||t.region!==e.region||(t.endsAt?.getTime()??null)!==(e.endsAt?.getTime()??null)||t.queue?.position!==e.queue?.position||t.queue?.depth!==e.queue?.depth||t.runtime?.state!==e.runtime?.state||t.runtime?.reason!==e.runtime?.reason||t.runtime?.wake!==e.runtime?.wake?!1:t.error?.reason===e.error?.reason&&t.error?.code===e.error?.code&&t.error?.kind===e.error?.kind&&t.error?.httpStatus===e.error?.httpStatus&&t.error?.retryAfterSeconds===e.error?.retryAfterSeconds}var sF={requested:"provisioning",queued:"queued",pending:"provisioning",allocating:"provisioning",provisioning:"provisioning",waking:"provisioning",waiting_for_capacity:"waiting_for_capacity",allocated:"connecting",connecting:"connecting",establishing:"connecting",live:"live",running:"live",paused:"paused",error:"error",failed:"error",rejected:"error",expired:"paused",cancelled:"paused",canceled:"paused",closed:"paused",releasing:"paused",released:"paused",reaped:"paused",superseded:"paused"};function nF(t){return Object.prototype.hasOwnProperty.call(sF,t)?{phase:sF[t],unknown:!1}:{phase:"unknown",unknown:!0}}function hne(t){return t==="queued"||t==="pending"}function iF(t){return t==="credits_exhausted"}var oF=3,aF=4e3,cF=[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun1.l.google.com:19302"}];function dF(t){if(!t)return;let e=/\/(?:ws\/)?rtc\/([^/?#]+)/.exec(t);if(e)try{return decodeURIComponent(e[1])}catch{return e[1]}}var oI=class{_state="disconnected";_sessionId=null;_tracks=new Map;_tracksByName=new Map;_options;_emitter=new Qse.default;_ws=null;_connectedUrl=null;_device=null;_mediaUnavailableReason=null;_mediaVerdictResolve;_mediaVerdict=new Promise(t=>{this._mediaVerdictResolve=t});_recvTransport=null;_pendingConsumeData=[];_sendTransport=null;_consumers=new Map;_audioProducer=null;_videoProducer=null;_publishedAudio=null;_publishedVideo=null;_wtMicUplink=null;_wtCamUplink=null;_wtDataUpSender=null;_pendingProduce=null;_multiplexer=null;_reconnectAttempts=0;_reconnectExhaustedWarned=!1;_intentionalDisconnect=!1;_reconnectTimer=null;_cancelPendingDial=null;_stableResetTimer=null;_generation=0;_lastStartOptions;_resolveConnection=null;_recvIceRestartAttempts=0;_recvIceRestartTimer=null;_sendIceRestartAttempts=0;_sendIceRestartTimer=null;_phase={name:"idle"};_requestId;_liveReached=!1;_lastServerStatus;_endsAt=null;_forceResolveOnNextConnect=!1;_connectStartedAt;_wakingSince;_mediaProbeTimer=null;_statsTimer=null;_statsSampleInFlight=!1;_joinProbes=new Map;_decodeDeathHandled=!1;_selectedCandidatePair=XF();_reportedCandidatePairKey=null;_candidatePairRefreshSeq=0;_diagnosticSinkFailed=!1;_currentEpoch=0;_selfEpochAdoptUntil=0;_pausedIncarnation=null;_consumerId=null;_streamDataHandlers=new Map;_streamDataLane="sctp";_dataProducers=new Map;_dataProducerPromises=new Map;_dataConsumers=new Map;_pendingDataProduce=new Map;_sendTransportWaiters=[];get consumerId(){return this._consumerId===null&&(this._consumerId=fne()),this._consumerId}get state(){return this._state}get currentIncarnation(){return this._currentEpoch}get phase(){return this._phase}get isProducingMedia(){let t=r=>r!==null&&!r.closed&&!r.paused,e=(r,s)=>r!==null&&s!==null&&s.track.readyState!=="ended"&&r.deliveredDatagrams()>0;return t(this._audioProducer)||t(this._videoProducer)||e(this._wtMicUplink,this._publishedAudio)||e(this._wtCamUplink,this._publishedVideo)}get endsAt(){return this._endsAt}setEndsAt(t){this._endsAt=t}seedRegion(t){t!==void 0&&this._setPhase(this._phase.name,{reason:this._phase.reason,queue:this._phase.queue,runtime:this._phase.runtime,error:this._phase.error,region:t})}_pastDeadline(){return this._endsAt!==null&&Date.now()>=this._endsAt.getTime()}get status(){let t={phase:this._phase.name,transportState:this._state};return this._sessionId&&(t.sessionId=this._sessionId),this._requestId&&(t.requestId=this._requestId),this._lastServerStatus!==void 0&&(t.lastServerStatus=this._lastServerStatus),this._connectStartedAt!==void 0&&(t.elapsedMs=Date.now()-this._connectStartedAt),this._endsAt!==null&&(t.endsAt=this._endsAt),this._phase.queue&&(t.queue=this._phase.queue),this._phase.runtime&&(t.runtime=this._phase.runtime),this._phase.wakingSince!==void 0&&(t.wakingSince=this._phase.wakingSince),this._phase.error&&(t.error=this._phase.error),this._phase.region!==void 0&&(t.region=this._phase.region),t}get region(){return this._phase.region}get sessionId(){return this._sessionId}get tracks(){return this._tracks}get multiplexer(){return this._multiplexer}get isOpen(){return this._ws!==null&&this._ws.readyState===WebSocket.OPEN}signalingOpen(){return this.isOpen}onWtOnlyLegDeath(t){return this._wtOnlyLegDeath=t,()=>{this._wtOnlyLegDeath===t&&(this._wtOnlyLegDeath=null)}}_wtOnlyLegDeath=null;get connectedUrl(){return this._connectedUrl}get intentionalDisconnect(){return this._intentionalDisconnect}getTrackByName(t){if(U1(t)!==void 0)return;let e=this._tracksByName.get(t);if(e&&e.readyState!=="ended")return e;for(let r of this._tracks.values())if(!(r.kind!==t||r.readyState==="ended")&&this._streamNameOf(r)===void 0)return r;return e}_streamNameOf(t){for(let[e,r]of this._tracksByName)if(r===t)return e}setAuth(t){this._options={...this._options,...t},this.isOpen&&this._send({type:"auth",orgId:this._options.orgId,jwt:this._options.jwt,authProvider:this._options.authProvider})}constructor(t){this._options=t??{url:""},t?.sessionId&&(this._sessionId=t.sessionId)}setConnection(t){if(this.isOpen){let e=dF(t.url);if(t.sessionId!==void 0&&t.sessionId!==this._sessionId)throw new B1(this._sessionId,t.sessionId);if(e!==void 0&&e!==this._sessionId)throw new B1(this._sessionId,e);this._options={...this._options,...t};return}this._options={...this._options,...t},t.sessionId&&(this._sessionId=t.sessionId)}setConnectionResolver(t){this._resolveConnection=t}applyControlDocState(t){let e=t&&typeof t=="object"?t.session:void 0,r=xne(e);if(r!==void 0&&this.setIncarnation(r),!e||typeof e!="object")return;let s=e,n=typeof s.status=="string"?s.status:void 0;if(n&&!this.isStaleClosedMarker(s)){if(n==="error"){let i=s.error_reason??s.errorReason,o=typeof i=="string"&&i?i:"session failed";this._setPhase("error",{error:{reason:o,code:"runtime-failed",kind:"runtime-failed"}})}else if(n==="closed"||n==="ended"||n==="paused"){let i=s.close_reason??s.closeReason??s.pause_reason??s.pauseReason;if(iF(i)){this._setPhase("paused",{reason:"credits_exhausted"});return}if(this._pastDeadline()){this._setPhase("paused",{reason:"max_session_age"});return}this._setPhase("paused",{reason:typeof i=="string"&&i?i:n})}}}setIncarnation(t){if(!Number.isFinite(t)||t<=this._currentEpoch)return;let e=this._currentEpoch>0,r=this._state==="connected";this._currentEpoch=t;let s=this._selfEpochAdoptUntil>0&&Date.now()<=this._selfEpochAdoptUntil;this._selfEpochAdoptUntil=0,!s&&e&&r&&!this._intentionalDisconnect&&this._renegotiate()}isStaleIncarnation(t){return Number.isFinite(t)?t<this._currentEpoch:!1}isStaleClosedMarker(t){if(!t)return!1;let e=typeof t.status=="string"?t.status:void 0;if(e!=="closed"&&e!=="ended"&&e!=="paused"&&e!=="error")return!1;let r=t.status_epoch??t.statusEpoch,s=typeof r=="number"?r:Number(r);return Number.isFinite(s)?s<this._currentEpoch:!1}_isStaleLivenessEvidence(){return this._phase.name!=="paused"||this._pausedIncarnation===null?!1:this._currentEpoch<=this._pausedIncarnation}async connect(t){if(this.isOpen&&this._state==="connected"&&!this._intentionalDisconnect){t!==void 0&&(this._lastStartOptions=t);return}this._lastStartOptions=t,this._intentionalDisconnect=!1,this._pausedIncarnation=null,this._connectStartedAt??=Date.now(),this._cancelPendingDial?.(new Error("TransportSession: connect superseded by a newer connect()"));let e=++this._generation,r=this._state==="reconnecting"||this._state==="renegotiating";r||this._setState("connecting");let s=null,n=()=>e!==this._generation||this._intentionalDisconnect,i=()=>{if(n())throw new Error("TransportSession: connect cancelled")},o=async()=>{for(let u of this._connectUrls()){i();try{return await this._connectOnce(u,e,t),!0}catch(l){s=l instanceof Error?l:new Error(String(l)),n()||this._cleanupSocket()}}return!1},a=this._forceResolveOnNextConnect&&this._resolveConnection!==null;this._forceResolveOnNextConnect=!1;let c=a?0:this._resolveConnection?one:1;for(let u=0;u<c;u++)if(u>0&&(await lF(ane),i()),await o())return;if(this._resolveConnection)for(let u=0;u<cne;u++){this._setState("reconnecting"),await lF(rF[Math.min(u,rF.length-1)]),i();try{let l=await this._resolveConnection();i(),this.setAuth({jwt:l.jwt??this._options.jwt,authProvider:this._options.authProvider,orgId:this._options.orgId}),this.setConnection({url:l.url,sessionId:l.sessionId,iceServers:l.iceServers??this._options.iceServers}),l.endsAt!==void 0&&(this._endsAt=l.endsAt)}catch(l){if(n())throw new Error("TransportSession: connect cancelled");s=l instanceof Error?l:new Error(String(l));continue}if(await o())return}if(n())throw s??new Error("TransportSession: connect cancelled");this._setState("failed");let d=s??new Error("TransportSession: connect failed");throw r||this._emitError(d),d}leaveLeg(){if(!this.isOpen)return!1;this._intentionalDisconnect=!0,this._selfEpochAdoptUntil=0,this._stopMediaProbe(),this._stopStatsSampler(),this._clearRecvIceRestart(),this._clearSendIceRestart(),this._reconnectTimer&&(clearTimeout(this._reconnectTimer),this._reconnectTimer=null);try{this._send({type:"leave"})}catch{}try{this._ws?.close()}catch{}return!0}disconnect(t="client_detached"){this._generation+=1,this._intentionalDisconnect=!0,this._selfEpochAdoptUntil=0,this._cancelPendingDial?.(new Error("TransportSession: connect cancelled by disconnect()")),this._stopMediaProbe(),this._stopStatsSampler(),this._reconnectTimer&&(clearTimeout(this._reconnectTimer),this._reconnectTimer=null),this._clearReconnectBudgetReset(),this._reconnectAttempts=0;try{this._publishedAudio?.track.stop()}catch{}try{this._publishedVideo?.track.stop()}catch{}if(this._publishedAudio=null,this._publishedVideo=null,this._audioProducer){this._send({type:"stopAudio"});try{this._audioProducer.track?.stop()}catch{}try{this._audioProducer.close()}catch{}this._audioProducer=null}if(this._videoProducer){this._send({type:"stopVideo"});try{this._videoProducer.track?.stop()}catch{}try{this._videoProducer.close()}catch{}this._videoProducer=null}for(let e of this._consumers.values())try{e.close()}catch{}if(this._consumers.clear(),this._cleanupDataChannels(),this._settleSendTransportWaiters(null,new Error("[urun] sendStreamData: transport disconnected before the send transport arrived")),this._sendTransport){try{this._sendTransport.close()}catch{}this._sendTransport=null}if(this._recvTransport){try{this._recvTransport.close()}catch{}this._recvTransport=null}this._pendingConsumeData=[],this._pendingProduce&&(clearTimeout(this._pendingProduce.timeoutId),this._pendingProduce.reject(new Error("TransportSession: disconnected")),this._pendingProduce=null),this._device=null,this._multiplexer&&(this._multiplexer.dispose(),this._multiplexer=null),this._cleanupSocket(),this._tracks.clear(),this._tracksByName.clear(),this._setState("disconnected"),this._liveReached=!1,this._setPhase("paused",{reason:t}),this._emitter.emit("disconnected")}on(t,e){return this._emitter.on(t,e),()=>{this._emitter.off(t,e)}}_emitDiagnostic(t){let e=this._options.diagnosticSink;if(e)try{e(t)}catch(r){this._diagnosticSinkFailed||(this._diagnosticSinkFailed=!0,E.warn(`[urun] diagnosticSink threw (${String(r instanceof Error?r.message:r)}) \u2014 further diagnostics ride only the structured 'diagnostic' event`))}else t.level==="debug"?lg()?E.warn(`[urun] ${t.message}`,t.detail??{}):E.debug(`[urun] ${t.message}`,t.detail??{}):t.level==="error"?E.error(`[urun] ${t.message}`,t.detail??{}):E.warn(`[urun] ${t.message}`,t.detail??{});this._emitter.emit("diagnostic",t)}sendInput(t,e){this._send({type:"input",data:t,sequence:e})}sendSignal(t){return this._send(t)}onSignal(t){return this.on("signal",t)}emitDiagnostic(t){this._emitDiagnostic(t)}onStreamData(t,e){let r=this._streamDataHandlers.get(t);return r||(r=new Set,this._streamDataHandlers.set(t,r)),r.add(e),()=>{let s=this._streamDataHandlers.get(t);s?.delete(e),s&&s.size===0&&this._streamDataHandlers.delete(t)}}sendStreamData(t,e,r){try{this._requireMediaSupport("sendStreamData")}catch(s){return Promise.reject(s)}return this._wtDataUpSender?this._wtDataUpSender.send(t,Q1(e)):this._ensureDataProducer(t).then(s=>{for(let n of Xse(e))s.send(n)})}get wtDataUplinkSeam(){return{onUplink:t=>{this._wtDataUpSender=t},onUplinkLost:(t,e)=>{if(this._wtDataUpSender&&!(e&&this._wtDataUpSender!==e)){if(this._wtDataUpSender=null,!this._sendTransport){E.warn(`[urun-sh/core] WT data uplink lost (${t}) with NO WebRTC send transport \u2014 there is no SCTP to revert to; failing the WT leg so the re-dial ladder re-establishes it`),this._wtOnlyLegDeath?.(t);return}E.warn(`[urun-sh/core] WT data uplink lost (${t}) \u2014 data-up reverts to SCTP for this leg`)}}}}_awaitSendTransport(){return this._sendTransport?Promise.resolve(this._sendTransport):new Promise((t,e)=>{let r={resolve:n=>{clearTimeout(s),t(n)},reject:n=>{clearTimeout(s),e(n)}},s=setTimeout(()=>{let n=this._sendTransportWaiters.indexOf(r);n>=0&&this._sendTransportWaiters.splice(n,1),e(new Error(`[urun] no send transport after ${Z$}ms (the server never offered createSendTransport \u2014 media/data produce is impossible on this leg)`))},Z$);this._sendTransportWaiters.push(r)})}_settleSendTransportWaiters(t,e){let r=this._sendTransportWaiters;this._sendTransportWaiters=[];for(let s of r)t?s.resolve(t):s.reject(e??new Error("TransportSession: disconnected"))}_ensureDataProducer(t){let e=this._dataProducers.get(t);if(e&&!e.closed)return Promise.resolve(e);let r=this._dataProducerPromises.get(t);if(r)return r;let s=this._awaitSendTransport().then(n=>n.produceData({label:Wse(t),protocol:Kse,ordered:!0})).then(n=>this._awaitDataChannelOpen(n)).then(n=>(this._dataProducers.set(t,n),this._dataProducerPromises.delete(t),n)).catch(n=>{throw this._dataProducerPromises.delete(t),n});return this._dataProducerPromises.set(t,s),s}_awaitDataChannelOpen(t){if(t.closed)return Promise.reject(new Error("[urun] sendStreamData: DataProducer closed before its DataChannel opened"));let e=t.readyState;return e==="open"?Promise.resolve(t):e==="closing"||e==="closed"?Promise.reject(new Error(`[urun] sendStreamData: DataChannel is ${e} \u2014 cannot deliver data-up payloads`)):new Promise((r,s)=>{let n=()=>{c(),r(t)},i=u=>{d(new Error(`[urun] sendStreamData: DataChannel error before open: ${u.message}`))},o=()=>{c(),s(new Error("[urun] sendStreamData: DataProducer closed before its DataChannel opened"))},a=setTimeout(()=>{d(new Error(`[urun] sendStreamData: DataChannel not open after ${eF}ms (the SCTP handshake never completed \u2014 data-up produce is impossible on this channel)`))},eF),c=()=>{clearTimeout(a),t.off("open",n),t.off("error",i),t.observer.off("close",o)},d=u=>{c();try{t.close()}catch{}s(u)};t.on("open",n),t.on("error",i),t.observer.on("close",o)})}_dispatchStreamData(t,e){for(let r of this._streamDataHandlers.get(t)??[])r(e)}markStreamDataLaneQuic(){this._streamDataLane="quic"}noteQuicMediaFlowing(){this._intentionalDisconnect||this._phase.name==="error"&&this._isParkedPhase()||this._isStaleLivenessEvidence()||this._liveReached||this._setPhase("live")}dispatchQuicStreamData(t,e){this._dispatchStreamData(t,e)}raiseQuicStreamDataError(t){E.error(t.message),this._emitter.emit("error",t)}quicStreamDataLaneLost(t){if(this._streamDataLane!=="quic")return;this._streamDataLane="sctp";let e=[...this._streamDataHandlers.keys()];if(e.length===0)return;let r=new Error(`[urun] QUIC data lane lost mid-stream (${t}) \u2014 active named streams [${e.join(", ")}] resume over SCTP on the failover leg from now; envelopes in flight on the dead lane are gone (mid-stream-join semantics)`);E.error(r.message),this._emitter.emit("error",r)}_streamNameFromLabel(t){if(t)return t.startsWith("stream:")?t.slice(7):void 0}mediaUnavailableReason(){return this._mediaUnavailableReason}mediaAvailability(){return this._mediaVerdict}_requireMediaSupport(t){if(this._mediaUnavailableReason)throw new Error(`[urun-sh/core] ${t}: realtime media is unavailable in this process \u2014 ${this._mediaUnavailableReason}. This session joined in doc/KV-only mode (the media device was skipped); install the optional "werift" dependency to enable realtime media.`)}async addTrack(t,e){this._requireMediaSupport("addTrack"),await this._publishTrack(t,e)}async _publishTrack(t,e){let r=t.kind==="video";if(!r&&this._wtMicUplink){this._rememberPublishIntent(!1,t,e),this._wtMicUplink.setSource(t);return}if(r&&this._wtCamUplink){this._rememberPublishIntent(!0,t,e),this._wtCamUplink.setSource(t);return}let s=r?this._videoProducer:this._audioProducer;if(s&&!s.closed){if(s.track===t)return;await s.replaceTrack({track:t}),this._rememberPublishIntent(r,t,e);return}let n=await(await this._awaitSendTransport()).produce({track:t,...r?{}:{codecOptions:{opusStereo:!1,opusDtx:!1,opusFec:!1}},stopTracks:!1,...e?{appData:{name:e}}:{}});r?this._videoProducer=n:this._audioProducer=n,this._rememberPublishIntent(r,t,e)}_rememberPublishIntent(t,e,r){let s={track:e,...r!==void 0?{name:r}:{}};t?this._publishedVideo=s:this._publishedAudio=s}removeTrack(){let t=this._publishedAudio;if(this._publishedAudio=null,this._wtMicUplink){this._wtMicUplink.setSource(null);try{t?.track.stop()}catch{}}if(this._audioProducer){this._send({type:"stopAudio"});try{this._audioProducer.track?.stop()}catch{}this._audioProducer.close(),this._audioProducer=null}}async addVideoTrack(t,e){this._requireMediaSupport("addVideoTrack"),await this._publishTrack(t,e)}stopVideo(){let t=this._publishedVideo;if(this._publishedVideo=null,this._wtCamUplink){this._wtCamUplink.setSource(null);try{t?.track.stop()}catch{}}if(this._videoProducer){this._send({type:"stopVideo"});try{this._videoProducer.track?.stop()}catch{}this._videoProducer.close(),this._videoProducer=null}}requestDiagnostics(){this._send({type:"diagnostics"})}seekStream(t,e){this._send({type:"stream.seek",stream:t,target:e})}async _handleMessage(t){switch(t.type){case"routerRtpCapabilities":await this._onRouterCapabilities(t.rtpCapabilities);break;case"createWebRtcTransport":await this._onCreateRecvTransport(t);break;case"createSendTransport":await this._onCreateSendTransport(t);break;case"consume":await this._onConsume(t);break;case"consumerClosed":this._closeConsumer(t.consumerId);break;case"producerClosed":this._closeConsumersByProducer(t.producerId);break;case"consumerPaused":this._consumers.get(t.consumerId)?.pause();break;case"consumerResumed":this._consumers.get(t.consumerId)?.resume();break;case"iceRestarted":this._onIceRestarted(t);break;case"produced":if(this._pendingProduce){let e=this._pendingProduce;this._pendingProduce=null,clearTimeout(e.timeoutId),e.resolve(t.id)}break;case"dataProduced":{let e=t.label,r=e?this._pendingDataProduce.get(e):void 0;r&&e&&(this._pendingDataProduce.delete(e),r.resolve(t.id));break}case"consumeData":await this._onConsumeData(t);break;case"started":this._emitter.emit("started");break;case"status":this._onStatus(t);break;case"stream.seeked":this._onStreamSeeked(t);break;case"error":this._onServerError(t);break;default:this._emitter.emit("signal",t);break}}_onServerError(t){let e=typeof t.message=="string"?t.message:"signaling error",r=typeof t.code=="string"?t.code:void 0;if(/connect\(\) already called/i.test(e)){if(this._resolveConnection){this._generation++;let s=this._ws;this._ws=null;try{s?.close()}catch{}this._cleanupMedia(),this._forceResolveOnNextConnect=!0,this._renegotiate();return}this._setPhase("error",{error:{reason:e,code:"transport-consumed",kind:"transport-failed"}}),this._emitter.emit("error",new Error(e));return}if(r==="TRANSPORT_BIND_FAILED"){this._emitError(new Error(e),r);return}if(r==="PROTOCOL_VERSION_UNSUPPORTED"){this._setPhase("error",{error:{reason:e,code:r,kind:"create-failed"},reason:e}),this._emitter.emit("error",new Error(e));return}E.warn("[urun] signaling error from server:",e)}_onStreamSeeked(t){let e=typeof t.stream=="string"?t.stream:void 0;if(!e)return;let r=t.target,s=r==="live"?"live":typeof r=="number"?r:Number(r);this._emitter.emit("seeked",e,s)}_reportUnknownServerStatus(t,e,r="signaling",s){let n=`server reported unrecognized ${r==="admission"?"admission response":"session status"} status ${JSON.stringify(t)}`+(e?` (reason: ${JSON.stringify(e)})`:"")+' \u2014 this @urun-sh/core build does not know this word; refusing to render it as "provisioning". The SDK may be out of date for this server.';this._emitDiagnostic({level:"error",kind:"unknown-server-status",message:n,detail:{status:t,origin:r,...e?{reason:e}:{}}}),!this._liveReached&&(this._lastServerStatus=t,this._setPhase("unknown",{reason:t,region:s}))}_onStatus(t){let e=t.request_id??t.requestId;e&&(this._requestId=e);let r=typeof t.status=="string"?t.status:void 0,s=typeof t.reason=="string"&&t.reason?t.reason:void 0,n="region"in t?typeof t.region=="string"&&t.region.length>0?t.region:null:void 0,i=r!==void 0?nF(r):void 0;if(r!==void 0&&i?.unknown){this._reportUnknownServerStatus(r,s,"signaling",n);return}let o=i?.phase??"provisioning";if(this._liveReached&&o!=="paused"&&o!=="error"){o==="live"&&n!==void 0&&n!==this._phase.region&&this._setPhase("live",{reason:s,region:n});return}if(this._isStaleLivenessEvidence()&&o!=="live"&&o!=="paused"&&o!=="error")return;r!==void 0&&(this._lastServerStatus=r);let a=t.queue_position??t.queuePosition,c=t.queue_depth??t.queueDepth,d=typeof a=="number"&&typeof c=="number";if(o==="paused"){let u=t.reason??t.close_reason??t.closeReason??t.pause_reason??t.pauseReason,l=typeof u=="string"&&u?u:void 0,h=iF(u)?"credits_exhausted":this._pastDeadline()?"max_session_age":s??l??r??"paused";this._setPhase("paused",{reason:h,region:n??null}),this._stopMediaProbe();return}if(o==="error"){let u=s??r??"admission failed";this._setPhase("error",{error:{reason:u,code:r,kind:r==="error"?"runtime-failed":"create-failed"},reason:u,region:n});return}if(o==="queued"){this._setPhase("queued",{...d?{queue:{position:a,depth:c}}:{},reason:s,region:n});return}if(o==="waiting_for_capacity"){this._setPhase("waiting_for_capacity",{...d?{queue:{position:a,depth:c}}:{},reason:s,region:n});return}if(o==="connecting"){this._setPhase("connecting",{reason:s,region:n});return}if(o==="live"){this._setPhase("live",{reason:s,region:n});return}this._setPhase("provisioning",{reason:s,region:n})}_webRtcDialHeld=!1;_heldRouterCaps=null;holdWebRtcDial(){return this._webRtcDialHeld=!0,{proceed:t=>{if(!this._webRtcDialHeld)return;this._webRtcDialHeld=!1;let e=this._heldRouterCaps;this._heldRouterCaps=null,e&&(lg()?E.warn(`[urun-sh/core] running the deferred WebRTC dial (${t})`):E.info(`[urun-sh/core] running the deferred WebRTC dial (${t})`),this._onRouterCapabilities(e).catch(r=>{E.error("[urun-sh/core] deferred WebRTC dial failed:",r)}))},skip:t=>{lg()?E.warn(`[urun-sh/core] WebRTC dial SKIPPED (${t}) \u2014 WT-only leg, no RTCPeerConnection`):E.info(`[urun-sh/core] WebRTC dial SKIPPED (${t}) \u2014 WT-only leg, no RTCPeerConnection`)}}}async _onRouterCapabilities(t){if(this._webRtcDialHeld){this._heldRouterCaps=t;return}Qh()&&await K1();let e=lse();if(e){this._mediaUnavailableReason=e,this._mediaVerdictResolve(e);return}this._mediaVerdictResolve(null);let r=cse(),s=new Jse.Device(r?{handlerName:r}:void 0);await s.load({routerRtpCapabilities:t}),this._device=s,this._send({type:"rtpCapabilities",rtpCapabilities:s.rtpCapabilities})}async _onCreateRecvTransport(t){this._device&&this._buildRecvTransport(t)}_buildRecvTransport(t){if(!this._device)return;let e=t.iceCandidates,r=this._device.createRecvTransport({id:t.id,iceParameters:t.iceParameters,iceCandidates:e,dtlsParameters:t.dtlsParameters,...t.sctpParameters?{sctpParameters:t.sctpParameters}:{},iceServers:this._options.iceServers??cF});this._recvIceRestartAttempts=0,this._clearRecvIceRestart();let s=this._generation;r.on("connect",({dtlsParameters:i},o,a)=>{try{this._send({type:"connectTransport",transportId:r.id,dtlsParameters:i}),o()}catch(c){a(c)}}),r.on("connectionstatechange",i=>{if(s===this._generation){if(i==="connected"){this._clearRecvIceRestart(),this._recvIceRestartAttempts=0,this._reportSelectedCandidatePair(r);return}if(!(this._intentionalDisconnect&&i==="closed")&&(i==="failed"||i==="disconnected")){if(this._tryRestartRecvIce())return;i==="failed"&&this._emitError(new Error(`media transport ${i}`),i),this._renegotiate()}}}),this._recvTransport=r;let n=this._pendingConsumeData.splice(0,this._pendingConsumeData.length);for(let i of n)this._onConsumeData(i).catch(()=>{})}async _reportSelectedCandidatePair(t){let e=++this._candidatePairRefreshSeq,r=null;if(typeof t.getStats=="function")try{r=await t.getStats()}catch{}if(this._recvTransport!==t||e!==this._candidatePairRefreshSeq)return;let s=bne(r);if(s.localType===null&&s.remoteType===null&&s.protocol===null&&s.remoteAddress===null&&s.remotePort===null&&this._reportedCandidatePairKey!==null)return;this._selectedCandidatePair=s;let n=JSON.stringify(s);if(this._reportedCandidatePairKey===n)return;this._reportedCandidatePairKey=n;let i=Object.values(this._selectedCandidatePair).some(o=>o!==null);this._emitDiagnostic({level:i?"info":"debug",kind:"ice-candidate-pair",message:`selected ICE candidate pair: local=${this._selectedCandidatePair.localType??"unknown"} remote=${this._selectedCandidatePair.remoteType??"unknown"} protocol=${this._selectedCandidatePair.protocol??"unknown"} remote=${this._selectedCandidatePair.remoteAddress??"unknown"}:${this._selectedCandidatePair.remotePort??"unknown"}`,detail:{sessionId:this._options.sessionId,...this._selectedCandidatePair}})}_tryRestartRecvIce(){let t=this._recvTransport;return!t||t.closed?!1:this._recvIceRestartTimer?!0:this._recvIceRestartAttempts>=oF?!1:(this._recvIceRestartAttempts++,this._armRecvIceRestartWatchdog(),this._requestIceRestart(t.id),!0)}_trySendIceRestart(){let t=this._sendTransport;return!t||t.closed?!1:this._sendIceRestartTimer?!0:this._sendIceRestartAttempts>=oF?!1:(this._sendIceRestartAttempts++,this._armSendIceRestartWatchdog(),this._requestIceRestart(t.id),!0)}_requestIceRestart(t){this._send({type:"restartIce",transportId:t})}_onIceRestarted(t){let e=t.transportId??t.id,r=t.iceParameters;if(!r)return;let s=!!this._recvTransport&&this._recvTransport.id===e,n=!s&&!!this._sendTransport&&this._sendTransport.id===e,i=s?this._recvTransport:n?this._sendTransport:null;i&&(Promise.resolve(i.restartIce({iceParameters:r})).catch(o=>{this._emitter.emit("error",o instanceof Error?o:new Error(String(o)))}),s&&this._recvIceRestartTimer?this._armRecvIceRestartWatchdog():n&&this._sendIceRestartTimer&&this._armSendIceRestartWatchdog())}_armRecvIceRestartWatchdog(){this._clearRecvIceRestart();let t=this._generation;this._recvIceRestartTimer=setTimeout(()=>{this._recvIceRestartTimer=null,!(t!==this._generation||this._intentionalDisconnect)&&this._recvTransport?.connectionState!=="connected"&&(this._emitError(new Error("media transport failed (ice restart timeout)"),"failed"),this._renegotiate())},aF)}_armSendIceRestartWatchdog(){this._clearSendIceRestart();let t=this._generation;this._sendIceRestartTimer=setTimeout(()=>{this._sendIceRestartTimer=null,!(t!==this._generation||this._intentionalDisconnect)&&this._sendTransport?.connectionState!=="connected"&&this._emitError(new Error("media send transport failed (ice restart timeout)"),"failed")},aF)}_clearRecvIceRestart(){this._recvIceRestartTimer&&(clearTimeout(this._recvIceRestartTimer),this._recvIceRestartTimer=null)}_clearSendIceRestart(){this._sendIceRestartTimer&&(clearTimeout(this._sendIceRestartTimer),this._sendIceRestartTimer=null)}async _onCreateSendTransport(t){if(!this._device)return;let e=this._device.createSendTransport({id:t.id,iceParameters:t.iceParameters,iceCandidates:t.iceCandidates,dtlsParameters:t.dtlsParameters,...t.sctpParameters?{sctpParameters:t.sctpParameters}:{},iceServers:this._options.iceServers??cF});this._sendIceRestartAttempts=0,this._clearSendIceRestart();let r=this._generation;e.on("connect",({dtlsParameters:s},n,i)=>{try{this._send({type:"connectSendTransport",transportId:e.id,dtlsParameters:s}),n()}catch(o){i(o)}}),e.on("produce",({kind:s,rtpParameters:n,appData:i},o,a)=>{if(this._pendingProduce){a(new Error("produce already pending"));return}let c=i&&typeof i.name=="string"?i.name:void 0,d=setTimeout(()=>{let u=this._pendingProduce;if(!u||u.timeoutId!==d)return;this._pendingProduce=null;let l=new JA(s,{stream:c,timeoutMs:fg});this._setPhase("error",{error:{reason:l.message,code:"produce-ack-timeout",kind:"produce-timeout"}}),this._emitter.emit("error",l),u.reject(l)},fg);this._pendingProduce={timeoutId:d,resolve:u=>{o({id:u})},reject:a};try{this._send(c?{type:"produce",kind:s,name:c,rtpParameters:n}:{type:"produce",kind:s,rtpParameters:n})}catch(u){this._pendingProduce?.timeoutId===d&&(this._pendingProduce=null,clearTimeout(d)),a(u)}}),e.on("producedata",({sctpStreamParameters:s,label:n,protocol:i},o,a)=>{try{n&&this._pendingDataProduce.set(n,{resolve:c=>o({id:c}),reject:a}),this._send({type:"produceData",sctpStreamParameters:s,label:n,protocol:i})}catch(c){n&&this._pendingDataProduce.delete(n),a(c)}}),e.on("connectionstatechange",s=>{if(r===this._generation){if(s==="connected"){this._clearSendIceRestart(),this._sendIceRestartAttempts=0;return}this._intentionalDisconnect&&s==="closed"||(s==="failed"||s==="disconnected")&&this._trySendIceRestart()||(s==="failed"||s==="closed")&&this._emitError(new Error(`media send transport ${s}`),s)}}),this._sendTransport=e,this._settleSendTransportWaiters(e),this._emitter.emit("audioTransportReady"),this._republishPublishedTracks()}async _republishPublishedTracks(){let t=this._publishedAudio;if(t&&t.track.readyState!=="ended"&&(!this._audioProducer||this._audioProducer.closed))try{await this.addTrack(t.track,t.name)}catch(r){E.warn("[urun] republish: mic re-produce after reconnect failed",r)}else t&&t.track.readyState==="ended"&&E.warn("[urun] republish: published mic track is ended \u2014 not republishing (device re-acquisition is the app/page-recovery pass)");let e=this._publishedVideo;if(e&&e.track.readyState!=="ended"&&(!this._videoProducer||this._videoProducer.closed))try{await this.addVideoTrack(e.track,e.name)}catch(r){E.warn("[urun] republish: camera re-produce after reconnect failed",r)}else e&&e.track.readyState==="ended"&&E.warn("[urun] republish: published camera track is ended \u2014 not republishing (device re-acquisition is the app/page-recovery pass)")}async _onConsumeData(t){if(this._streamDataLane==="quic"){this.raiseQuicStreamDataError(new Error(`[urun] consumeData (label=${String(t.label)}) pushed on a leg whose data lane is QUIC \u2014 refusing (one canonical data path per leg, contract urun-infra#1605)`));return}let e=this._recvTransport;if(!e){this._pendingConsumeData.push(t);return}let r=t.label,s=this._streamNameFromLabel(r);if(!s){E.error(`[urun] consumeData pushed with an unparseable label ${JSON.stringify(r??null)} \u2014 no DataConsumer will be attached and no ack sent; the server egress will strand envelopes for this stream (expected label form: "stream:<name>")`),this._emitter.emit("error",new Error(`[urun] consumeData pushed with unparseable label ${JSON.stringify(r??null)}`));return}let n=this._generation,i;try{i=await e.consumeData({id:t.id,dataProducerId:t.dataProducerId,sctpStreamParameters:t.sctpStreamParameters,label:r,protocol:t.protocol})}catch(u){E.error(`[urun] consumeData for named stream "${s}" failed \u2014 no channel will open and no dataConsumerReady ack will be sent; the server egress will strand envelopes on this lane:`,u),this._emitter.emit("error",u instanceof Error?u:new Error(String(u)));return}if(n!==this._generation||this._recvTransport!==e||e.closed||this._intentionalDisconnect){try{i.close()}catch{}return}this._dataConsumers.set(s,i);let o=new Yse;i.on("message",u=>{try{let l=typeof u=="string"?new TextEncoder().encode(u):new Uint8Array(u),h=o.feed(l);h!==void 0&&this._dispatchStreamData(s,h)}catch(l){this._emitter.emit("error",l instanceof Error?l:new Error(String(l)))}});let a=!1,c=setTimeout(()=>{if(a||i.closed||i.readyState==="open")return;let u=new Error(`[urun] data channel for named stream "${s}" did not open within 10s (consumeData resolved at creation; the SCTP association never established) \u2014 no dataConsumerReady ack was sent and the server egress will strand envelopes on this lane`);E.error(u.message),this._emitter.emit("error",u)},1e4),d=()=>{a||i.closed||(a=!0,clearTimeout(c),this._send({type:"dataConsumerReady",id:t.id}))};i.readyState==="open"?d():i.on("open",d),i.once?.("close",()=>clearTimeout(c))}async _onConsume(t){let e=this._recvTransport;if(!e)return;let r=this._generation,s=await e.consume({id:t.id,producerId:t.producerId,kind:t.kind,rtpParameters:t.rtpParameters});if(r!==this._generation||this._recvTransport!==e||e.closed||this._intentionalDisconnect){try{s.close()}catch{}return}this._consumers.set(s.id,s),this._tracks.set(s.track.id,s.track),this._capJitterBuffer(s,s.kind==="video"?"video":"audio");let n=t.streamName??t.label;n&&this._tracksByName.set(n,s.track),s.track.addEventListener?.("unmute",()=>{r!==this._generation||this._intentionalDisconnect||this._phase.name==="error"&&this._isParkedPhase()||this._isStaleLivenessEvidence()||this._liveReached||this._setPhase("live")},{once:!0}),this._emitter.emit("track",s.track);let i=s.id;s.track.addEventListener("ended",()=>{r!==this._generation||this._intentionalDisconnect||this._closeConsumer(i)},{once:!0}),this._send({type:"resumeConsumer",consumerId:s.id}),this._startMediaProbe(),this._startStatsSampler()}get audioPlayoutOptions(){return this._options.audioPlayout}get wtMicUplinkSeam(){return{onUplink:t=>{this._wtMicUplink=t;let e=this._publishedAudio;if(this._audioProducer&&!this._audioProducer.closed){E.warn("[urun-sh/core] WT mic uplink engaged \u2014 moving the mic from WebRTC produce to the QUIC lane"),this._send({type:"stopAudio"});try{this._audioProducer.close()}catch{}this._audioProducer=null}e&&e.track.readyState!=="ended"&&t.setSource(e.track)},onUplinkLost:(t,e)=>{if(!this._wtMicUplink||e&&this._wtMicUplink!==e)return;this._wtMicUplink=null;let r=this._publishedAudio;if(!(!r||r.track.readyState==="ended")){if(E.warn(`[urun-sh/core] WT mic uplink lost (${t}) \u2014 republishing the mic over WebRTC`),!this._sendTransport){this._emitDiagnostic({level:"error",kind:"wt-mic-uplink-dead",message:`WT mic uplink lost (${t}) with NO WebRTC send transport \u2014 the republish above cannot run. If a reconnect is in flight this self-heals; on a WT-only leg (no RTCPeerConnection was dialled) the mic is now DEAD until the WT uplink re-engages.`,detail:{reason:t}});return}this._publishTrack(r.track,r.name).catch(s=>{E.error("[urun-sh/core] mic republish over WebRTC failed:",s)})}}}}get wtCamUplinkSeam(){return{onUplink:t=>{this._wtCamUplink=t;let e=this._publishedVideo;if(this._videoProducer&&!this._videoProducer.closed){E.warn("[urun-sh/core] WT video uplink engaged \u2014 moving the camera from WebRTC produce to the QUIC lane"),this._send({type:"stopVideo"});try{this._videoProducer.close()}catch{}this._videoProducer=null}e&&e.track.readyState!=="ended"&&t.setSource(e.track)},onUplinkLost:(t,e)=>{if(!this._wtCamUplink||e&&this._wtCamUplink!==e)return;this._wtCamUplink=null;let r=this._publishedVideo;if(!(!r||r.track.readyState==="ended")){if(E.warn(`[urun-sh/core] WT video uplink lost (${t}) \u2014 republishing the camera over WebRTC`),!this._sendTransport){this._emitDiagnostic({level:"error",kind:"wt-cam-uplink-dead",message:`WT camera uplink lost (${t}) with NO WebRTC send transport \u2014 the republish above cannot run. If a reconnect is in flight this self-heals; on a WT-only leg (no RTCPeerConnection was dialled) the camera is now DEAD until the WT uplink re-engages.`,detail:{reason:t}});return}this._publishTrack(r.track,r.name).catch(s=>{E.error("[urun-sh/core] camera republish over WebRTC failed:",s)})}}}}_jitterBufferTargetMs(t){if(t==="audio"){let e=this._options.audioPlayout?.jitterBufferTargetMs;return e===void 0?ine:e}return this._options.videoPlayout?.jitterBufferTargetMs}_capJitterBuffer(t,e){let r=this._jitterBufferTargetMs(e);if(r===void 0)return;let s=e==="video"?"videoPlayout":"audioPlayout",n={mediaKind:e,transportId:this._recvTransport?.id??null};if(!Number.isFinite(r)){this._emitDiagnostic({level:"warning",kind:`${e}-jitter-buffer-invalid`,message:`${s}.jitterBufferTargetMs must be a finite number of milliseconds; got ${String(r)}. No jitter-buffer cap applied.`,detail:{consumerId:t.id,targetMs:String(r),...n}});return}if(r<=0)return;if(r>tF){this._emitDiagnostic({level:"warning",kind:`${e}-jitter-buffer-invalid`,message:`${s}.jitterBufferTargetMs must be within the W3C jitterBufferTarget range 0-${tF}ms; got ${r}. No jitter-buffer cap applied.`,detail:{consumerId:t.id,targetMs:r,...n}});return}let i=t.rtpReceiver;if(!i){this._emitDiagnostic({level:"debug",kind:`${e}-jitter-buffer-unsupported`,message:`${e} consumer exposes no RTCRtpReceiver (node/werift leg); no jitter-buffer cap applied.`,detail:{consumerId:t.id,targetMs:r,reason:"no-receiver",...n}});return}let o=[];if("jitterBufferTarget"in i&&(i.jitterBufferTarget=r,o.push("jitterBufferTarget")),"playoutDelayHint"in i&&(i.playoutDelayHint=r/1e3,o.push("playoutDelayHint")),o.length===0){this._emitDiagnostic({level:"debug",kind:`${e}-jitter-buffer-unsupported`,message:`${e==="audio"?"Audio":"Video"} receiver exposes neither jitterBufferTarget nor playoutDelayHint; standing ${e} playout delay is unbounded on this engine.`,detail:{consumerId:t.id,targetMs:r,...n}});return}this._emitDiagnostic({level:"debug",kind:`${e}-jitter-buffer-capped`,message:`${e==="audio"?"Audio":"Video"} receiver jitter buffer capped at ${r}ms.`,detail:{consumerId:t.id,targetMs:r,applied:o,...n}})}_closeConsumer(t){let e=this._consumers.get(t);if(!e)return;this._consumers.delete(t);let r=e.track;try{e.close()}catch{}if(r){this._tracks.delete(r.id);for(let[s,n]of this._tracksByName)n===r&&this._tracksByName.delete(s)}}_closeConsumersByProducer(t){for(let[e,r]of this._consumers)r.producerId===t&&this._closeConsumer(e)}_mediaPollMs(){let t=this._options.mediaLiveness?.pollMs;return t===void 0?rne:t}_firstFrameWindowMs(){let t=this._options.mediaLiveness?.stallTimeoutMs;return t===void 0?sne:t}_startMediaProbe(){let t=this._mediaPollMs();if(t<=0||this._mediaProbeTimer)return;let e=this._generation;this._mediaProbeTimer=setInterval(()=>{e!==this._generation||this._intentionalDisconnect||this._phase.name==="error"&&this._isParkedPhase()||this._isStaleLivenessEvidence()||this._sampleMediaArrival(e)},t)}_stopMediaProbe(){this._mediaProbeTimer&&(clearInterval(this._mediaProbeTimer),this._mediaProbeTimer=null)}_statsPollMs(){let t=this._options.sessionStats;if(!t)return 0;let e=t.pollMs;return e===void 0?nne:Number.isFinite(e)&&e>0?e:0}_startStatsSampler(){let t=this._statsPollMs();if(t<=0||this._statsTimer)return;let e=this._generation;this._statsTimer=setInterval(()=>{e!==this._generation||this._intentionalDisconnect||this._isParkedPhase()||this._statsSampleInFlight||(this._statsSampleInFlight=!0,this._sampleSessionStats(e).catch(r=>{try{this._emitter.emit("error",r instanceof Error?r:new Error(String(r)))}catch{}}).finally(()=>{this._statsSampleInFlight=!1}))},t)}_stopStatsSampler(){this._statsTimer&&(clearInterval(this._statsTimer),this._statsTimer=null),this._statsSampleInFlight=!1}_lanePairKey(t){let e=t.track,r=e?this._streamNameOf(e):void 0;if(r===void 0)return null;let s=U1(r);return s===void 0?r:r.slice(0,r.length-Xh.length-s.length)}async _sampleSessionStats(t){if(this._consumers.size===0)return;let e=Array.from(this._consumers.values()),r=await Promise.all(e.map(async l=>({consumerId:l.id,kind:l.kind==="video"?"video":"audio",pairKey:this._lanePairKey(l),sample:await hF(l)})));if(t!==this._generation||this._intentionalDisconnect||this._isParkedPhase())return;let s=r.filter(l=>l.pairKey===null),n=r.filter(l=>l.pairKey!==null),i=null,o=r;if(n.length>0){let l=new Map;for(let m of n){let _=m.pairKey,f=l.get(_);f?f.push(m):l.set(_,[m])}let h=-1,p=-1;for(let[m,_]of l){let f=new Set(_.map(w=>w.kind)).size>=2?1:0,b=_.reduce((w,S)=>w+S.sample.total,0);(f>h||f===h&&b>p)&&(h=f,p=b,i=m,o=[..._,...s])}}let a=l=>{let h=null,p=-1;for(let{consumerId:m,kind:_,sample:f}of o)_===l&&f.total>p&&(p=f.total,h={consumerId:m,...f});return h},c=a("audio"),d=a("video"),u=d?.estimatedPlayoutTimestamp!=null&&c?.estimatedPlayoutTimestamp!=null?d.estimatedPlayoutTimestamp-c.estimatedPlayoutTimestamp:null;this._emitter.emit("stats",{timestamp:Date.now(),stream:i,avSyncMs:u,audio:c,video:d})}_resetJoinProbes(){this._joinProbes.clear(),this._decodeDeathHandled=!1}async _sampleMediaArrival(t){if(this._consumers.size===0)return;let e=Array.from(this._consumers.entries()),r=await Promise.all(e.map(async([o,a])=>[o,await hF(a)]));if(t!==this._generation||this._intentionalDisconnect||this._phase.name==="error"&&this._isParkedPhase()||this._isStaleLivenessEvidence())return;for(let o of this._joinProbes.keys())this._consumers.has(o)||this._joinProbes.delete(o);let s=Date.now();!this._liveReached&&r.some(([,o])=>o.total>0)&&this._setPhase("live");let n=null,i=!1;for(let[o,a]of r){if(a.total<=0){i=!0;continue}let c=this._joinProbes.get(o);if(c||(c={firstBytesAt:s,startSample:a,settled:!1},this._joinProbes.set(o,c)),!c.settled){if(a.framesDecoded===null){c.settled=!0;continue}if(a.framesDecoded>0){c.settled=!0;continue}if(s-c.firstBytesAt>=this._firstFrameWindowMs()){n??={id:o,probe:c,sample:a};continue}i=!0}}if(n&&!this._decodeDeathHandled){this._decodeDeathHandled=!0;let o=this._firstFrameWindowMs(),a=yne(n.probe.startSample,n.sample),c=a.lossPct!==null&&a.lossPct>=5?" \u2014 consistent with network packet loss between the SFU and this browser":"";this._emitDiagnostic({level:"warning",kind:"decode-wall",message:`video is arriving but the decoder never produced its first frame within ${o/1e3}s of join (framesDecoded still 0) \u2014 no keyframe to start from${c}; re-consuming the stream`,detail:{sessionId:this._options.sessionId,consumerId:n.id,firstFrameWindowMs:o,inboundTotal:n.sample.total,framesDecoded:n.sample.framesDecoded,...gne(n.sample),...a,likelyCause:a.lossPct!==null&&a.lossPct>=5?"network-packet-loss":null,...this._selectedCandidatePair}}),this._renegotiate();return}!i&&!n&&this._stopMediaProbe()}_renegotiate(){this._intentionalDisconnect||this._isExplicitEndPhase()||this._reconnectTimer||(this._stopMediaProbe(),this._stopStatsSampler(),this._setState("renegotiating"),this._attemptReconnect())}recover(){if(this._intentionalDisconnect||this._isExplicitEndPhase()||this._connectStartedAt===void 0||this._cancelPendingDial)return;if(!this.isOpen){this._reconnectTimer&&(clearTimeout(this._reconnectTimer),this._reconnectTimer=null),this._reconnectAttempts=0,this._attemptReconnect(void 0,!0);return}let t=this._recvTransport?.connectionState;(t==="disconnected"||t==="failed")&&(this._recvIceRestartTimer||(this._recvIceRestartAttempts=0),this._tryRestartRecvIce()||this._renegotiate());let e=this._sendTransport?.connectionState;(e==="disconnected"||e==="failed")&&(this._sendIceRestartTimer||(this._sendIceRestartAttempts=0),this._trySendIceRestart())}_attemptReconnect(t,e=!1){if(this._intentionalDisconnect||this._isExplicitEndPhase()||this._reconnectTimer)return;this._reconnectAttempts>=J$&&(this._reconnectExhaustedWarned||(this._reconnectExhaustedWarned=!0,this._emitDiagnostic({level:"warning",kind:"signaling-reconnect-forever",message:`signaling reconnect budget spent (${J$} attempts) \u2014 retrying forever with capped backoff while the session lives`})));let r=e?0:Y$[Math.min(this._reconnectAttempts,Y$.length-1)];this._reconnectAttempts++,this._state!=="renegotiating"&&this._setState("reconnecting"),this._reconnectTimer=setTimeout(async()=>{this._reconnectTimer=null,this._replaceCurrentLegForReconnect();try{await this.connect(t??this._lastStartOptions)}catch(s){if(s instanceof Error&&s.message==="TransportSession: connect cancelled")return;this._attemptReconnect(t)}},r)}_connectUrls(){let t=[],e=r=>{if(!r)return;let s=dF(r)!==void 0,n=this._sessionId&&!s?`${r}${r.includes("?")?"&":"?"}sessionId=${encodeURIComponent(this._sessionId)}`:r;t.includes(n)||t.push(n)};e(this._options.url);for(let r of this._options.fallbackUrls??[])e(r);return t}_connectOnce(t,e,r){return new Promise((s,n)=>{let i=!1,o=!1,a=null,c=new WebSocket(t);this._ws=c;let d=()=>this._ws!==c||e!==this._generation,u=h=>{o||(o=!0,a&&clearTimeout(a),this._cancelPendingDial===l&&(this._cancelPendingDial=null),n(h))},l=h=>{try{c.close()}catch{}u(h)};this._cancelPendingDial=l,a=setTimeout(()=>{try{c.close()}catch{}u(new Error("TransportSession: connect timed out"))},ene),c.onopen=()=>{if(!o){if(d()){try{c.close()}catch{}u(new Error("TransportSession: connect superseded during dial"));return}i=!0,a&&clearTimeout(a),this._connectedUrl=t,this._multiplexer=new XA(c),c.send(JSON.stringify(this._startMessage(r))),this._scheduleReconnectBudgetReset(),this._selfEpochAdoptUntil=Date.now()+tne,this._setState("connected"),this._liveReached||this._setPhase("connecting"),this._emitter.emit("connected"),o=!0,this._cancelPendingDial===l&&(this._cancelPendingDial=null),s()}},c.onerror=()=>{i||u(new Error("WebSocket connection error"))},c.onclose=()=>{if(!i){u(new Error("WebSocket closed before connecting"));return}if(!d()&&(this._clearReconnectBudgetReset(),a&&clearTimeout(a),this._setState("disconnected"),!this._intentionalDisconnect)){if(this._pastDeadline()&&this._phase.name!=="paused"){this._setPhase("paused",{reason:"max_session_age"}),this._emitter.emit("disconnected");return}this._emitter.emit("disconnected"),!this._isExplicitEndPhase()&&this._attemptReconnect(r)}},c.onmessage=h=>{if(!(this._ws!==c||e!==this._generation)&&typeof h.data=="string")try{this._handleMessage(JSON.parse(h.data)).catch(p=>{this._emitter.emit("error",p instanceof Error?p:new Error(String(p)))})}catch(p){this._emitter.emit("error",p instanceof Error?p:new Error(String(p)))}}})}_startMessage(t){let e={type:"start",version:iI,video:t?.video??{width:854,height:480,frameRate:16}};return t?.prompt&&(e.prompt=t.prompt),t?.cameraControl&&(e.camera_control=t.cameraControl),t?.args&&(e.args=t.args),t?.app&&(e.app=t.app),t?.functionName&&(e.function=t.functionName),t?.role&&(e.role=t.role),this._options.orgId&&(e.orgId=this._options.orgId),this._options.jwt&&(e.jwt=this._options.jwt),this._options.authProvider&&(e.authProvider=this._options.authProvider),e}_cleanupSocket(){if(this._clearReconnectBudgetReset(),!this._ws)return;let t=this._ws;this._ws=null,t.onopen=null,t.onmessage=null,t.onerror=null,t.onclose=null;try{t.close()}catch{}}_replaceCurrentLegForReconnect(){this._cleanupSocket(),this._cancelPendingDial?.(new Error("TransportSession: reconnect replacing current dial")),this._cleanupMedia()}_scheduleReconnectBudgetReset(){this._clearReconnectBudgetReset(),this._reconnectAttempts!==0&&(this._stableResetTimer=setTimeout(()=>{this._stableResetTimer=null,this._reconnectAttempts=0,this._reconnectExhaustedWarned=!1},dne))}_clearReconnectBudgetReset(){this._stableResetTimer&&(clearTimeout(this._stableResetTimer),this._stableResetTimer=null)}_cleanupDataChannels(){for(let t of this._dataProducers.values())try{t.close()}catch{}this._dataProducers.clear(),this._dataProducerPromises.clear();for(let t of this._dataConsumers.values())try{t.close()}catch{}this._dataConsumers.clear();for(let t of this._pendingDataProduce.values())try{t.reject(new Error("TransportSession: disconnected"))}catch{}this._pendingDataProduce.clear()}_cleanupMedia(){this._stopMediaProbe(),this._stopStatsSampler(),this._resetJoinProbes();for(let t of this._consumers.values())try{t.close()}catch{}if(this._consumers.clear(),this._cleanupDataChannels(),this._audioProducer){try{this._audioProducer.close()}catch{}this._audioProducer=null}if(this._videoProducer){try{this._videoProducer.close()}catch{}this._videoProducer=null}if(this._clearRecvIceRestart(),this._clearSendIceRestart(),this._recvTransport){try{this._recvTransport.close()}catch{}this._recvTransport=null}if(this._pendingConsumeData=[],this._sendTransport){try{this._sendTransport.close()}catch{}this._sendTransport=null}this._pendingProduce&&(clearTimeout(this._pendingProduce.timeoutId),this._pendingProduce=null),this._device=null,this._tracks.clear(),this._tracksByName.clear(),this._multiplexer&&(this._multiplexer.dispose(),this._multiplexer=null)}_send(t){return!this._ws||this._ws.readyState!==WebSocket.OPEN?!1:(this._ws.send(JSON.stringify(t)),!0)}_setState(t){this._state!==t&&(this._state=t,this._emitter.emit("stateChange",t))}_isParkedPhase(){return this._phase.name==="paused"?!0:this._phase.name!=="error"?!1:this._phase.error?.kind!=="transport-failed"}_isExplicitEndPhase(){if(this._phase.name==="paused"&&!this._isComputeReleasedPark())return!1;if(this._phase.name!=="error")return this._isComputeReleasedPark();let t=this._phase.error?.kind;return t!==void 0&&t!=="transport-failed"}_isComputeReleasedPark(){return this._phase.name!=="paused"?!1:Q$[this._phase.reason??""]===!0}_setPhase(t,e){let r=this._liveReached;t==="live"?this._liveReached=!0:(t==="paused"||t==="error")&&(this._liveReached=!1,t==="paused"&&!r&&Q$[e?.reason??""]!==!0&&(this._forceResolveOnNextConnect=!0,this._cancelPendingDial||this._attemptReconnect()));let s={name:t};e?.queue&&(s.queue=e.queue),e?.runtime&&(s.runtime=e.runtime),e?.reason&&(s.reason=e.reason),s.region=e?.region!==void 0?e.region:this._phase.region,xc(t)?(this._wakingSince??=Date.now(),s.wakingSince=this._wakingSince):this._wakingSince=void 0,this._requestId&&(s.requestId=this._requestId),this._sessionId&&(s.sessionId=this._sessionId),this._endsAt!==null&&(s.endsAt=this._endsAt),e?.error&&(s.error=e.error),!une(this._phase,s)&&(this._phase=s,this._pausedIncarnation=t==="paused"?this._currentEpoch:null,this._isParkedPhase()&&(this._stopMediaProbe(),this._stopStatsSampler(),this._clearRecvIceRestart(),this._clearSendIceRestart()),this._emitter.emit("phase",s))}reportAdmission(t){t.requestId&&(this._requestId=t.requestId),this._lastServerStatus=t.status;let e=nF(t.status);if(e.unknown){this._reportUnknownServerStatus(t.status,t.reason,"admission",t.region);return}if(this._liveReached)return;t.sessionId&&!this._sessionId&&(this._sessionId=t.sessionId);let{runtime:r,queue:s}=t,n=t.decisionReason==="provisioning_refused"?t.refusalMessage??t.decisionReason:t.reason,i={runtime:r,queue:s,...n?{reason:n}:{},...t.region!==void 0?{region:t.region}:{}};if(hne(t.status)){if(r?.state==="unavailable"){this._setPhase("unavailable",i);return}if(r?.state==="starting"){this._setPhase("provisioning",i);return}if(r?.state==="busy"||t.status==="queued"){this._setPhase("queued",i);return}this._setPhase("provisioning",i);return}this._setPhase(e.phase,e.phase==="paused"?{...i,region:i.region??null}:i)}_emitError(t,e){this._setPhase("error",{error:{reason:t.message,code:e,kind:"transport-failed"}}),this._emitter.emit("error",t)}reportAllocationFailure(t,e,r,s){r==="insufficient_credits"?this._setPhase("error",{error:{reason:t.message,code:r,kind:"insufficient-credits",httpStatus:e}}):this._setPhase("error",{error:{reason:t.message,code:r??"allocation-failed",kind:"create-failed",httpStatus:e,retryAfterSeconds:s}}),this._emitter.emit("error",t)}};function lF(t){return new Promise(e=>setTimeout(e,t))}function fne(){return ev()}var GF=["packetsReceived","packetsLost","nackCount","pliCount","firCount","keyFramesDecoded","framesReceived","framesDropped","retransmittedPacketsReceived","retransmittedBytesReceived","jitterBufferDelay","jitterBufferEmittedCount","estimatedPlayoutTimestamp","jitterBufferTargetDelay","jitterBufferMinimumDelay","concealedSamples","insertedSamplesForDeceleration"],pne=new Set(["estimatedPlayoutTimestamp"]);function mne(){return{total:0,framesDecoded:null,packetsReceived:null,packetsLost:null,nackCount:null,jitter:null,pliCount:null,firCount:null,keyFramesDecoded:null,framesReceived:null,framesDropped:null,retransmittedPacketsReceived:null,retransmittedBytesReceived:null,jitterBufferDelay:null,jitterBufferEmittedCount:null,estimatedPlayoutTimestamp:null,jitterBufferTargetDelay:null,jitterBufferMinimumDelay:null,concealedSamples:null,insertedSamplesForDeceleration:null}}function gne(t){return Object.fromEntries(GF.map(e=>[e,t[e]]))}function uF(t,e){return t===null||e===null||e<t?null:e-t}function yne(t,e){let r=t.packetsLost!==null&&e.packetsLost!==null?e.packetsLost-t.packetsLost:null,s=uF(t.packetsReceived,e.packetsReceived),n=uF(t.nackCount,e.nackCount),i=r===null?null:Math.max(0,r),o=i!==null&&s!==null?i+s:0;return{packetsLostWindow:r,packetsReceivedWindow:s,nackCountWindow:n,jitterSec:e.jitter,lossPct:o>0&&i!==null?i/o*100:null}}function XF(){return{localType:null,remoteType:null,protocol:null,remoteAddress:null,remotePort:null}}function bne(t){let e=new Map;YF(t,a=>{let c=typeof a.id=="string"?a.id:null;c&&e.set(c,a)});let r=Array.from(e.values()).find(a=>a.type==="transport"),s=typeof r?.selectedCandidatePairId=="string"?r.selectedCandidatePairId:null,n=(s?e.get(s):void 0)??Array.from(e.values()).find(a=>a.type==="candidate-pair"&&a.selected===!0)??Array.from(e.values()).find(a=>a.type==="candidate-pair"&&a.nominated===!0);if(!n)return XF();let i=typeof n.localCandidateId=="string"?e.get(n.localCandidateId):void 0,o=typeof n.remoteCandidateId=="string"?e.get(n.remoteCandidateId):void 0;return{localType:typeof i?.candidateType=="string"?i.candidateType:null,remoteType:typeof o?.candidateType=="string"?o.candidateType:null,protocol:typeof i?.protocol=="string"?i.protocol:typeof o?.protocol=="string"?o.protocol:null,remoteAddress:typeof o?.address=="string"?o.address:typeof o?.ip=="string"?o.ip:null,remotePort:typeof o?.port=="number"?o.port:null}}function YF(t,e){let r=s=>{s&&typeof s=="object"&&e(s)};if(t instanceof Map)for(let[s,n]of t.entries()){if(!n||typeof n!="object")continue;let i=n;e(typeof i.id=="string"?i:{...i,id:s})}else(Array.isArray(t)||t&&typeof t.forEach=="function")&&t.forEach(r)}async function hF(t){let e=mne();if(typeof t.getStats!="function")return e;let r;try{r=await t.getStats()}catch{return e}return YF(r,s=>{if(s.type==="inbound-rtp"){let n=typeof s.bytesReceived=="number"?s.bytesReceived:0,i=typeof s.packetsReceived=="number"?s.packetsReceived:0;e.total+=n+i,typeof s.framesDecoded=="number"&&(e.framesDecoded=(e.framesDecoded??0)+s.framesDecoded),typeof s.jitter=="number"&&(e.jitter=e.jitter===null?s.jitter:Math.max(e.jitter,s.jitter));for(let o of GF)typeof s[o]=="number"&&(e[o]=pne.has(o)?e[o]===null?s[o]:Math.max(e[o],s[o]):(e[o]??0)+s[o])}}),e}function xne(t){if(!t||typeof t!="object")return;let e=t.epoch,r=typeof e=="number"?e:Number(e);return Number.isFinite(r)?r:void 0}var wne=1;function aI(t){let e=new URL(t);return`${e.protocol}//${e.host}/doc`}var vne=2500,_ne=3e4,Sne=1e4,Ene=3;function JF(t){let e=t.WebSocketPolyfill??globalThis.WebSocket;if(!e)throw new Error("[urun] no WebSocket implementation available for the yjs doc provider (browser global missing and no WebSocketPolyfill passed)");return(r,s,n)=>{let i=`${t.sessionId}/${r}`,o=typeof t.token=="function"?t.token:null,a=typeof t.token=="string"?t.token:void 0,c=t.maxBackoffTimeMs??vne,d=t.dialTimeoutMs??_ne,u=new Py(t.serverUrl,i,s,{awareness:n,params:{dsv:String(wne),...a?{token:a}:{}},WebSocketPolyfill:e,disableBc:!0,maxBackoffTime:c,resyncInterval:Sne,connect:o===null}),l=!1,h,p=!1,m=I=>{p||(p=!0,E.error(`[urun] doc token refresh failed for room ${i} (redialing with previous token):`,I))},_=()=>{if(o){if(h)return h;try{let I=o();if(typeof I=="string"){u.params.token=I,p=!1;return}if(I&&typeof I.then=="function"){let U=I.then(K=>{typeof K=="string"&&(u.params.token=K,p=!1)},K=>{m(K)}).finally(()=>{h===U&&(h=void 0)});return h=U,U}}catch(I){m(I)}}},f=t.resolveServerUrl,b=0,w=!1,S=I=>{if(typeof I!="string"||I==="")return;let U=I.replace(/\/+$/,"");U!==u.serverUrl&&(u.serverUrl=U,w=!1)},O=()=>{if(!f)return;let I=++b,U=K=>{w||(w=!0,E.error(`[urun] doc endpoint re-resolve failed for room ${i} (redialing previous host):`,K))};try{let K=f();if(K&&typeof K.then=="function")return K.then(z=>{I===b&&S(z)},U);S(K)}catch(K){U(K)}},j={connected:!1,consecutiveFailures:0,lastCloseCode:null,lastCloseReason:null},P=new Set,k=!1,C=()=>{let I={...j};for(let U of[...P])U(I)},D=null,H=()=>{D!==null&&(clearTimeout(D),D=null)},W=()=>{H(),D=setTimeout(()=>{if(D=null,!l&&u.wsconnecting&&u.ws)try{u.ws.close()}catch{}},d)},J=null,F=()=>{J!==null&&(clearTimeout(J),J=null)},q=()=>{F(),J=setTimeout(()=>{if(J=null,!l&&u.shouldConnect&&!u.wsconnected&&!u.wsconnecting&&u.ws===null)try{u.connect()}catch(I){k||(k=!0,E.error(`[urun] doc connection redial threw for room ${i} (still retrying):`,I)),q()}},c+500)},Q=({status:I})=>{if(I==="connecting"){F(),W();return}if(I==="connected"){H(),F(),j={...j,connected:!0},C();return}j.connected&&(j={...j,connected:!1},C())},R=I=>{I&&(k&&(lg()?E.warn(`[urun] doc connection recovered for room ${i}`):E.info(`[urun] doc connection recovered for room ${i}`),k=!1),j.consecutiveFailures!==0&&(j={...j,consecutiveFailures:0},C()))},Y=I=>{H(),j={connected:!1,consecutiveFailures:j.consecutiveFailures+1,lastCloseCode:I?I.code:null,lastCloseReason:I&&I.reason?I.reason:null},!k&&j.consecutiveFailures>=Ene&&(k=!0,E.error(`[urun] doc connection failing for room ${i}: ${j.consecutiveFailures} consecutive failures (last close ${j.lastCloseCode===null?"by provider liveness reap":`code ${j.lastCloseCode}`}${j.lastCloseReason?`, reason "${j.lastCloseReason}"`:""}). Still retrying \u2014 the doc provider never gives up.`)),C(),_(),O(),q()};u.on("status",Q),u.on("sync",R),u.on("connection-close",Y),u.wsconnecting?W():u.wsconnected&&(j={...j,connected:!0});let Z=!1;return o!==null&&_(),Z||u.connect(),{get awareness(){return u.awareness},get synced(){return u.synced},onSync(I){let U=K=>I(K);return u.on("sync",U),()=>u.off("sync",U)},onConnectionState(I){return P.add(I),I({...j}),()=>P.delete(I)},ensureConnected(){Z=!1,u.wsconnected||u.connect()},disconnect(){Z=!0,u.disconnect()},destroy(){l=!0,H(),F(),u.off("status",Q),u.off("sync",R),u.off("connection-close",Y),P.clear(),u.destroy()}}}}var Cne=class{constructor(t,e,r){this._name=t,this._doc=e,this.awareness=r}_name;_doc;awareness;_inner=null;_innerUnsub=null;_innerStateUnsub=null;_syncHandlers=new Set;_stateHandlers=new Set;_lastState={connected:!1,consecutiveFailures:0,lastCloseCode:null,lastCloseReason:null};_destroyed=!1;_suspended=!1;get synced(){return this._inner?.synced??!1}get destroyed(){return this._destroyed}onSync(t){return this._syncHandlers.add(t),()=>this._syncHandlers.delete(t)}onConnectionState(t){return this._stateHandlers.add(t),t({...this._lastState}),()=>this._stateHandlers.delete(t)}attach(t){if(!this._destroyed){if(this._inner&&(this._innerUnsub?.(),this._innerUnsub=null,this._innerStateUnsub?.(),this._innerStateUnsub=null,this._inner.destroy(),this._inner=null),this._inner=t(this._name,this._doc,this.awareness),this._innerUnsub=this._inner.onSync(e=>{for(let r of[...this._syncHandlers])r(e)}),this._inner.onConnectionState)this._innerStateUnsub=this._inner.onConnectionState(e=>{this._lastState=e;for(let r of[...this._stateHandlers])r(e)});else{this._innerStateUnsub=null,this._lastState={connected:!0,consecutiveFailures:0,lastCloseCode:null,lastCloseReason:null};for(let e of[...this._stateHandlers])e({...this._lastState})}if(this._suspended&&this._inner.disconnect?.(),this._inner.synced)for(let e of[...this._syncHandlers])e(!0)}}ensureConnected(){this._suspended=!1,this._inner?.ensureConnected?.()}get disconnect(){return this._inner?.disconnect?()=>{this._suspended=!0,this._inner.disconnect()}:void 0}destroy(){this._destroyed=!0,this._innerUnsub?.(),this._innerUnsub=null,this._innerStateUnsub?.(),this._innerStateUnsub=null,this._inner?.destroy(),this._inner=null,this._syncHandlers.clear(),this._stateHandlers.clear()}},QF=class{_target=null;_bridges=[];connect=(t,e,r)=>{let s=new Cne(t,e,r);return this._bridges.push(s),this._target&&s.attach(this._target),s};get connected(){return this._target!==null}setTarget(t){if(this._target!==t){this._target=t,this._bridges=this._bridges.filter(e=>!e.destroyed);for(let e of this._bridges)e.attach(t)}}};function mg(t){if(t===null||typeof t!="object"||Array.isArray(t))return!1;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}var M1="$bytes";function Tne(t){return t instanceof Uint8Array||t instanceof ArrayBuffer}function kne(t){if(!mg(t))return!1;let e=Object.keys(t);return e.length===1&&e[0]===M1&&typeof t[M1]=="string"}function Ane(t){return t instanceof ArrayBuffer?new Uint8Array(t):t}function Ine(t){if(typeof Buffer<"u")return Buffer.from(t).toString("base64");let e="";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return btoa(e)}function Rne(t){if(typeof Buffer<"u")return new Uint8Array(Buffer.from(t,"base64"));let e=atob(t),r=new Uint8Array(e.length);for(let s=0;s<e.length;s++)r[s]=e.charCodeAt(s);return r}function WA(t){if(Tne(t))return{[M1]:Ine(Ane(t))};if(Array.isArray(t))return t.map(WA);if(mg(t)){let e={};for(let[r,s]of Object.entries(t))e[r]=WA(s);return e}return t}function hg(t){if(kne(t))return Rne(t[M1]);if(Array.isArray(t))return t.map(hg);if(mg(t)){let e={};for(let[r,s]of Object.entries(t))e[r]=hg(s);return e}return t}var ZF=Symbol("urun:doc:path-absent");function Pne(t,e){let r=e.split("."),s=t;for(let n of r){if(s===null||typeof s!="object"||!(n in s))return ZF;s=s[n]}return s}function Dne(t,e){return t===e?!0:JSON.stringify(t)===JSON.stringify(e)}function KA(t,e){for(let[r,s]of Object.entries(e))if(mg(s)){let n=t.get(r);if(!(n instanceof pg.Map)){let i=n;n=new pg.Map,t.set(r,n),mg(i)&&KA(n,i)}KA(n,s)}else{if(Dne(t.get(r),s))continue;t.set(r,s)}}var Bne=Symbol("urun:doc:local"),eH=class{_doc=new pg.Doc;_root=this._doc.getMap("session");_awareness=new nu(this._doc);_listeners=new Set;_key;_sessionId;_connection=null;_connUnsub=null;_synced;_syncWaiters=new Set;_texts=new Map;_observer=()=>this.notify();constructor(t,e,r){this._key=t,this._sessionId=e,this._root.observeDeep(this._observer),r?(this._connection=r(t,this._doc,this._awareness),this._synced=this._connection.synced,this._connUnsub=this._connection.onSync(s=>{s&&this._markSynced()}),this._synced&&this._markSynced()):this._synced=!0}get awareness(){return this._awareness}setSessionId(t){this._sessionId=t}get synced(){return this._synced}ensureConnected(){this._connection?.ensureConnected?.()}reconnect(){this.ensureConnected()}disconnect(){let t=this._connection;if(!t?.disconnect)throw new Error(`[urun-sh/core] doc('${this._key}').disconnect(): no disconnect-capable connection to sever (a local-only doc, or a connector with no live socket) \u2014 there is nothing to disconnect`);t.disconnect()}onConnectionState(t){return this._connection?.onConnectionState?this._connection.onConnectionState(t):(t({connected:!0,consecutiveFailures:0,lastCloseCode:null,lastCloseReason:null}),()=>{})}onSynced(t){return this._synced?(t(),()=>{}):(this._syncWaiters.add(t),()=>this._syncWaiters.delete(t))}set(t){t=WA(t),this.applyPatch(t)}get(t,e){let r=this.snapshot();if(!t)return hg(r);let s=Pne(r,t);return s===ZF?e:hg(s)}on(t,e){return this._listeners.add(e),()=>this._listeners.delete(e)}text(t){let e=this._texts.get(t);return e||(e=new Lne(this._doc.getText(`text:${t}`)),this._texts.set(t,e)),e}dispose(){this._root.unobserveDeep(this._observer),this._connUnsub?.(),this._connUnsub=null,this._connection?.destroy(),this._connection=null,this._listeners.clear(),this._syncWaiters.clear();for(let t of this._texts.values())t.dispose();this._texts.clear(),this._awareness.destroy(),this._doc.destroy()}_markSynced(){let t=[...this._syncWaiters];this._synced=!0,this._syncWaiters.clear();for(let e of t)e()}applyPatch(t){this._doc.transact(()=>{KA(this._root,t)},Bne)}snapshot(){return this._root.toJSON()}notify(){let t=hg(this.snapshot());for(let e of this._listeners)e(t)}},Lne=class{constructor(t){this._ytext=t,this._observer=e=>{for(let r of e.delta)if(typeof r.insert=="string"&&r.insert.length>0){let s=r.insert;for(let n of this._delta)n(s)}},this._ytext.observe(this._observer)}_ytext;_delta=new Set;_observer;append(t){t.length!==0&&this._ytext.insert(this._ytext.length,t)}toString(){return this._ytext.toString()}get length(){return this._ytext.length}on(t,e){return this._delta.add(e),()=>this._delta.delete(e)}dispose(){this._ytext.unobserve(this._observer),this._delta.clear()}};function tH(t){return{get clientId(){return t.clientID},set(e){t.setLocalState(e)},setField(e,r){t.setLocalStateField(e,r)},getLocal(){return t.getLocalState()??null},getStates(){return t.getStates()},on(e,r){let s=()=>r(t.getStates());return t.on("change",s),s(),()=>t.off("change",s)}}}g();y();g();y();g();y();g();y();function rH(t){let e=t.length,r=0,s=0;for(;s<e;){let n=t.charCodeAt(s++);if((n&4294967168)===0){r++;continue}else if((n&4294965248)===0)r+=2;else{if(n>=55296&&n<=56319&&s<e){let i=t.charCodeAt(s);(i&64512)===56320&&(++s,n=((n&1023)<<10)+(i&1023)+65536)}(n&4294901760)===0?r+=3:r+=4}}return r}function One(t,e,r){let s=t.length,n=r,i=0;for(;i<s;){let o=t.charCodeAt(i++);if((o&4294967168)===0){e[n++]=o;continue}else if((o&4294965248)===0)e[n++]=o>>6&31|192;else{if(o>=55296&&o<=56319&&i<s){let a=t.charCodeAt(i);(a&64512)===56320&&(++i,o=((o&1023)<<10)+(a&1023)+65536)}(o&4294901760)===0?(e[n++]=o>>12&15|224,e[n++]=o>>6&63|128):(e[n++]=o>>18&7|240,e[n++]=o>>12&63|128,e[n++]=o>>6&63|128)}e[n++]=o&63|128}}var Nne=new TextEncoder,Une=50;function Mne(t,e,r){Nne.encodeInto(t,e.subarray(r))}function sH(t,e,r){t.length>Une?Mne(t,e,r):One(t,e,r)}var jne=4096;function cI(t,e,r){let s=e,n=s+r,i=[],o="";for(;s<n;){let a=t[s++];if((a&128)===0)i.push(a);else if((a&224)===192){let c=t[s++]&63;i.push((a&31)<<6|c)}else if((a&240)===224){let c=t[s++]&63,d=t[s++]&63;i.push((a&31)<<12|c<<6|d)}else if((a&248)===240){let c=t[s++]&63,d=t[s++]&63,u=t[s++]&63,l=(a&7)<<18|c<<12|d<<6|u;l>65535&&(l-=65536,i.push(l>>>10&1023|55296),l=56320|l&1023),i.push(l)}else i.push(a);i.length>=jne&&(o+=String.fromCharCode(...i),i.length=0)}return i.length>0&&(o+=String.fromCharCode(...i)),o}var $ne=new TextDecoder,Fne=200;function Hne(t,e,r){let s=t.subarray(e,e+r);return $ne.decode(s)}function nH(t,e,r){return r>Fne?Hne(t,e,r):cI(t,e,r)}g();y();g();y();var Tl=class{type;data;constructor(e,r){this.type=e,this.data=r}};g();y();g();y();var Ns=class t extends Error{constructor(e){super(e);let r=Object.create(t.prototype);Object.setPrototypeOf(this,r),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:t.name})}};g();y();function iH(t,e,r){let s=r/4294967296,n=r;t.setUint32(e,s),t.setUint32(e+4,n)}function tv(t,e,r){let s=Math.floor(r/4294967296),n=r;t.setUint32(e,s),t.setUint32(e+4,n)}function rv(t,e){let r=t.getInt32(e),s=t.getUint32(e+4);return r*4294967296+s}function oH(t,e){let r=t.getUint32(e),s=t.getUint32(e+4);return r*4294967296+s}var qne=-1,Vne=4294967296-1,zne=17179869184-1;function Wne({sec:t,nsec:e}){if(t>=0&&e>=0&&t<=zne)if(e===0&&t<=Vne){let r=new Uint8Array(4);return new DataView(r.buffer).setUint32(0,t),r}else{let r=t/4294967296,s=t&4294967295,n=new Uint8Array(8),i=new DataView(n.buffer);return i.setUint32(0,e<<2|r&3),i.setUint32(4,s),n}else{let r=new Uint8Array(12),s=new DataView(r.buffer);return s.setUint32(0,e),tv(s,4,t),r}}function Kne(t){let e=t.getTime(),r=Math.floor(e/1e3),s=(e-r*1e3)*1e6,n=Math.floor(s/1e9);return{sec:r+n,nsec:s-n*1e9}}function Gne(t){if(t instanceof Date){let e=Kne(t);return Wne(e)}else return null}function Xne(t){let e=new DataView(t.buffer,t.byteOffset,t.byteLength);switch(t.byteLength){case 4:return{sec:e.getUint32(0),nsec:0};case 8:{let r=e.getUint32(0),s=e.getUint32(4),n=(r&3)*4294967296+s,i=r>>>2;return{sec:n,nsec:i}}case 12:{let r=rv(e,4),s=e.getUint32(0);return{sec:r,nsec:s}}default:throw new Ns(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${t.length}`)}}function Yne(t){let e=Xne(t);return new Date(e.sec*1e3+e.nsec/1e6)}var aH={type:qne,encode:Gne,decode:Yne};var Zh=class t{static defaultCodec=new t;__brand;builtInEncoders=[];builtInDecoders=[];encoders=[];decoders=[];constructor(){this.register(aH)}register({type:e,encode:r,decode:s}){if(e>=0)this.encoders[e]=r,this.decoders[e]=s;else{let n=-1-e;this.builtInEncoders[n]=r,this.builtInDecoders[n]=s}}tryToEncode(e,r){for(let s=0;s<this.builtInEncoders.length;s++){let n=this.builtInEncoders[s];if(n!=null){let i=n(e,r);if(i!=null){let o=-1-s;return new Tl(o,i)}}}for(let s=0;s<this.encoders.length;s++){let n=this.encoders[s];if(n!=null){let i=n(e,r);if(i!=null){let o=s;return new Tl(o,i)}}}return e instanceof Tl?e:null}decode(e,r,s){let n=r<0?this.builtInDecoders[-1-r]:this.decoders[r];return n?n(e,r,s):new Tl(r,e)}};g();y();function Jne(t){return t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer}function Cg(t){return t instanceof Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):Jne(t)?new Uint8Array(t):Uint8Array.from(t)}var Qne=100,Zne=2048,sv=class t{extensionCodec;context;useBigInt64;maxDepth;initialBufferSize;sortKeys;forceFloat32;ignoreUndefined;forceIntegerToFloat;pos;view;bytes;entered=!1;constructor(e){this.extensionCodec=e?.extensionCodec??Zh.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.maxDepth=e?.maxDepth??Qne,this.initialBufferSize=e?.initialBufferSize??Zne,this.sortKeys=e?.sortKeys??!1,this.forceFloat32=e?.forceFloat32??!1,this.ignoreUndefined=e?.ignoreUndefined??!1,this.forceIntegerToFloat=e?.forceIntegerToFloat??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new t({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(e){if(this.entered)return this.clone().encodeSharedRef(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(e){if(this.entered)return this.clone().encode(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(e,r){if(r>this.maxDepth)throw new Error(`Too deep objects in depth ${r}`);e==null?this.encodeNil():typeof e=="boolean"?this.encodeBoolean(e):typeof e=="number"?this.forceIntegerToFloat?this.encodeNumberAsFloat(e):this.encodeNumber(e):typeof e=="string"?this.encodeString(e):this.useBigInt64&&typeof e=="bigint"?this.encodeBigInt64(e):this.encodeObject(e,r)}ensureBufferSizeToWrite(e){let r=this.pos+e;this.view.byteLength<r&&this.resizeBuffer(r*2)}resizeBuffer(e){let r=new ArrayBuffer(e),s=new Uint8Array(r),n=new DataView(r);s.set(this.bytes),this.view=n,this.bytes=s}encodeNil(){this.writeU8(192)}encodeBoolean(e){e===!1?this.writeU8(194):this.writeU8(195)}encodeNumber(e){!this.forceIntegerToFloat&&Number.isSafeInteger(e)?e>=0?e<128?this.writeU8(e):e<256?(this.writeU8(204),this.writeU8(e)):e<65536?(this.writeU8(205),this.writeU16(e)):e<4294967296?(this.writeU8(206),this.writeU32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(207),this.writeU64(e)):e>=-32?this.writeU8(224|e+32):e>=-128?(this.writeU8(208),this.writeI8(e)):e>=-32768?(this.writeU8(209),this.writeI16(e)):e>=-2147483648?(this.writeU8(210),this.writeI32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(211),this.writeI64(e)):this.encodeNumberAsFloat(e)}encodeNumberAsFloat(e){this.forceFloat32?(this.writeU8(202),this.writeF32(e)):(this.writeU8(203),this.writeF64(e))}encodeBigInt64(e){e>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(e)):(this.writeU8(211),this.writeBigInt64(e))}writeStringHeader(e){if(e<32)this.writeU8(160+e);else if(e<256)this.writeU8(217),this.writeU8(e);else if(e<65536)this.writeU8(218),this.writeU16(e);else if(e<4294967296)this.writeU8(219),this.writeU32(e);else throw new Error(`Too long string: ${e} bytes in UTF-8`)}encodeString(e){let s=rH(e);this.ensureBufferSizeToWrite(5+s),this.writeStringHeader(s),sH(e,this.bytes,this.pos),this.pos+=s}encodeObject(e,r){let s=this.extensionCodec.tryToEncode(e,this.context);if(s!=null)this.encodeExtension(s);else if(Array.isArray(e))this.encodeArray(e,r);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else if(typeof e=="object")this.encodeMap(e,r);else throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(e)}`)}encodeBinary(e){let r=e.byteLength;if(r<256)this.writeU8(196),this.writeU8(r);else if(r<65536)this.writeU8(197),this.writeU16(r);else if(r<4294967296)this.writeU8(198),this.writeU32(r);else throw new Error(`Too large binary: ${r}`);let s=Cg(e);this.writeU8a(s)}encodeArray(e,r){let s=e.length;if(s<16)this.writeU8(144+s);else if(s<65536)this.writeU8(220),this.writeU16(s);else if(s<4294967296)this.writeU8(221),this.writeU32(s);else throw new Error(`Too large array: ${s}`);for(let n of e)this.doEncode(n,r+1)}countWithoutUndefined(e,r){let s=0;for(let n of r)e[n]!==void 0&&s++;return s}encodeMap(e,r){let s=Object.keys(e);this.sortKeys&&s.sort();let n=this.ignoreUndefined?this.countWithoutUndefined(e,s):s.length;if(n<16)this.writeU8(128+n);else if(n<65536)this.writeU8(222),this.writeU16(n);else if(n<4294967296)this.writeU8(223),this.writeU32(n);else throw new Error(`Too large map object: ${n}`);for(let i of s){let o=e[i];this.ignoreUndefined&&o===void 0||(this.encodeString(i),this.doEncode(o,r+1))}}encodeExtension(e){if(typeof e.data=="function"){let s=e.data(this.pos+6),n=s.length;if(n>=4294967296)throw new Error(`Too large extension object: ${n}`);this.writeU8(201),this.writeU32(n),this.writeI8(e.type),this.writeU8a(s);return}let r=e.data.length;if(r===1)this.writeU8(212);else if(r===2)this.writeU8(213);else if(r===4)this.writeU8(214);else if(r===8)this.writeU8(215);else if(r===16)this.writeU8(216);else if(r<256)this.writeU8(199),this.writeU8(r);else if(r<65536)this.writeU8(200),this.writeU16(r);else if(r<4294967296)this.writeU8(201),this.writeU32(r);else throw new Error(`Too large extension object: ${r}`);this.writeI8(e.type),this.writeU8a(e.data)}writeU8(e){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,e),this.pos++}writeU8a(e){let r=e.length;this.ensureBufferSizeToWrite(r),this.bytes.set(e,this.pos),this.pos+=r}writeI8(e){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,e),this.pos++}writeU16(e){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,e),this.pos+=2}writeI16(e){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,e),this.pos+=2}writeU32(e){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,e),this.pos+=4}writeI32(e){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,e),this.pos+=4}writeF32(e){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,e),this.pos+=4}writeF64(e){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,e),this.pos+=8}writeU64(e){this.ensureBufferSizeToWrite(8),iH(this.view,this.pos,e),this.pos+=8}writeI64(e){this.ensureBufferSizeToWrite(8),tv(this.view,this.pos,e),this.pos+=8}writeBigUint64(e){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,e),this.pos+=8}writeBigInt64(e){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,e),this.pos+=8}};function dI(t,e){return new sv(e).encodeSharedRef(t)}g();y();g();y();g();y();function nv(t){return`${t<0?"-":""}0x${Math.abs(t).toString(16).padStart(2,"0")}`}g();y();var eie=16,tie=16,iv=class{hit=0;miss=0;caches;maxKeyLength;maxLengthPerKey;constructor(e=eie,r=tie){this.maxKeyLength=e,this.maxLengthPerKey=r,this.caches=[];for(let s=0;s<this.maxKeyLength;s++)this.caches.push([])}canBeCached(e){return e>0&&e<=this.maxKeyLength}find(e,r,s){let n=this.caches[s-1];e:for(let i of n){let o=i.bytes;for(let a=0;a<s;a++)if(o[a]!==e[r+a])continue e;return i.str}return null}store(e,r){let s=this.caches[e.length-1],n={bytes:e,str:r};s.length>=this.maxLengthPerKey?s[Math.random()*s.length|0]=n:s.push(n)}decode(e,r,s){let n=this.find(e,r,s);if(n!=null)return this.hit++,n;this.miss++;let i=cI(e,r,s),o=Uint8Array.prototype.slice.call(e,r,r+s);return this.store(o,i),i}};var lI="array",Ag="map_key",dH="map_value",rie=t=>{if(typeof t=="string"||typeof t=="number")return t;throw new Ns("The type of key must be string or number but "+typeof t)},uI=class{stack=[];stackHeadPosition=-1;get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(e){let r=this.getUninitializedStateFromPool();r.type=lI,r.position=0,r.size=e,r.array=new Array(e)}pushMapState(e){let r=this.getUninitializedStateFromPool();r.type=Ag,r.readCount=0,r.size=e,r.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){let e={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(e)}return this.stack[this.stackHeadPosition]}release(e){if(this.stack[this.stackHeadPosition]!==e)throw new Error("Invalid stack state. Released state is not on top of the stack.");if(e.type===lI){let s=e;s.size=0,s.array=void 0,s.position=0,s.type=void 0}if(e.type===Ag||e.type===dH){let s=e;s.size=0,s.map=void 0,s.readCount=0,s.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}},kg=-1,hI=new DataView(new ArrayBuffer(0)),sie=new Uint8Array(hI.buffer);try{hI.getInt8(0)}catch(t){if(!(t instanceof RangeError))throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}var cH=new RangeError("Insufficient data"),nie=new iv,ov=class t{extensionCodec;context;useBigInt64;rawStrings;maxStrLength;maxBinLength;maxArrayLength;maxMapLength;maxExtLength;keyDecoder;mapKeyConverter;totalPos=0;pos=0;view=hI;bytes=sie;headByte=kg;stack=new uI;entered=!1;constructor(e){this.extensionCodec=e?.extensionCodec??Zh.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.rawStrings=e?.rawStrings??!1,this.maxStrLength=e?.maxStrLength??4294967295,this.maxBinLength=e?.maxBinLength??4294967295,this.maxArrayLength=e?.maxArrayLength??4294967295,this.maxMapLength=e?.maxMapLength??4294967295,this.maxExtLength=e?.maxExtLength??4294967295,this.keyDecoder=e?.keyDecoder!==void 0?e.keyDecoder:nie,this.mapKeyConverter=e?.mapKeyConverter??rie}clone(){return new t({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=kg,this.stack.reset()}setBuffer(e){let r=Cg(e);this.bytes=r,this.view=new DataView(r.buffer,r.byteOffset,r.byteLength),this.pos=0}appendBuffer(e){if(this.headByte===kg&&!this.hasRemaining(1))this.setBuffer(e);else{let r=this.bytes.subarray(this.pos),s=Cg(e),n=new Uint8Array(r.length+s.length);n.set(r),n.set(s,r.length),this.setBuffer(n)}}hasRemaining(e){return this.view.byteLength-this.pos>=e}createExtraByteError(e){let{view:r,pos:s}=this;return new RangeError(`Extra ${r.byteLength-s} of ${r.byteLength} byte(s) found at buffer[${e}]`)}decode(e){if(this.entered)return this.clone().decode(e);try{this.entered=!0,this.reinitializeState(),this.setBuffer(e);let r=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return r}finally{this.entered=!1}}*decodeMulti(e){if(this.entered){yield*this.clone().decodeMulti(e);return}try{for(this.entered=!0,this.reinitializeState(),this.setBuffer(e);this.hasRemaining(1);)yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(e){if(this.entered)return this.clone().decodeAsync(e);try{this.entered=!0;let r=!1,s;for await(let a of e){if(r)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(a);try{s=this.doDecodeSync(),r=!0}catch(c){if(!(c instanceof RangeError))throw c}this.totalPos+=this.pos}if(r){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return s}let{headByte:n,pos:i,totalPos:o}=this;throw new RangeError(`Insufficient data in parsing ${nv(n)} at ${o} (${i} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(e){return this.decodeMultiAsync(e,!0)}decodeStream(e){return this.decodeMultiAsync(e,!1)}async*decodeMultiAsync(e,r){if(this.entered){yield*this.clone().decodeMultiAsync(e,r);return}try{this.entered=!0;let s=r,n=-1;for await(let i of e){if(r&&n===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(i),s&&(n=this.readArraySize(),s=!1,this.complete());try{for(;yield this.doDecodeSync(),--n!==0;);}catch(o){if(!(o instanceof RangeError))throw o}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){e:for(;;){let e=this.readHeadByte(),r;if(e>=224)r=e-256;else if(e<192)if(e<128)r=e;else if(e<144){let n=e-128;if(n!==0){this.pushMapState(n),this.complete();continue e}else r={}}else if(e<160){let n=e-144;if(n!==0){this.pushArrayState(n),this.complete();continue e}else r=[]}else{let n=e-160;r=this.decodeString(n,0)}else if(e===192)r=null;else if(e===194)r=!1;else if(e===195)r=!0;else if(e===202)r=this.readF32();else if(e===203)r=this.readF64();else if(e===204)r=this.readU8();else if(e===205)r=this.readU16();else if(e===206)r=this.readU32();else if(e===207)this.useBigInt64?r=this.readU64AsBigInt():r=this.readU64();else if(e===208)r=this.readI8();else if(e===209)r=this.readI16();else if(e===210)r=this.readI32();else if(e===211)this.useBigInt64?r=this.readI64AsBigInt():r=this.readI64();else if(e===217){let n=this.lookU8();r=this.decodeString(n,1)}else if(e===218){let n=this.lookU16();r=this.decodeString(n,2)}else if(e===219){let n=this.lookU32();r=this.decodeString(n,4)}else if(e===220){let n=this.readU16();if(n!==0){this.pushArrayState(n),this.complete();continue e}else r=[]}else if(e===221){let n=this.readU32();if(n!==0){this.pushArrayState(n),this.complete();continue e}else r=[]}else if(e===222){let n=this.readU16();if(n!==0){this.pushMapState(n),this.complete();continue e}else r={}}else if(e===223){let n=this.readU32();if(n!==0){this.pushMapState(n),this.complete();continue e}else r={}}else if(e===196){let n=this.lookU8();r=this.decodeBinary(n,1)}else if(e===197){let n=this.lookU16();r=this.decodeBinary(n,2)}else if(e===198){let n=this.lookU32();r=this.decodeBinary(n,4)}else if(e===212)r=this.decodeExtension(1,0);else if(e===213)r=this.decodeExtension(2,0);else if(e===214)r=this.decodeExtension(4,0);else if(e===215)r=this.decodeExtension(8,0);else if(e===216)r=this.decodeExtension(16,0);else if(e===199){let n=this.lookU8();r=this.decodeExtension(n,1)}else if(e===200){let n=this.lookU16();r=this.decodeExtension(n,2)}else if(e===201){let n=this.lookU32();r=this.decodeExtension(n,4)}else throw new Ns(`Unrecognized type byte: ${nv(e)}`);this.complete();let s=this.stack;for(;s.length>0;){let n=s.top();if(n.type===lI)if(n.array[n.position]=r,n.position++,n.position===n.size)r=n.array,s.release(n);else continue e;else if(n.type===Ag){if(r==="__proto__")throw new Ns("The key __proto__ is not allowed");n.key=this.mapKeyConverter(r),n.type=dH;continue e}else if(n.map[n.key]=r,n.readCount++,n.readCount===n.size)r=n.map,s.release(n);else{n.key=null,n.type=Ag;continue e}}return r}}readHeadByte(){return this.headByte===kg&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=kg}readArraySize(){let e=this.readHeadByte();switch(e){case 220:return this.readU16();case 221:return this.readU32();default:{if(e<160)return e-144;throw new Ns(`Unrecognized array type byte: ${nv(e)}`)}}}pushMapState(e){if(e>this.maxMapLength)throw new Ns(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new Ns(`Max length exceeded: array length (${e}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(e)}decodeString(e,r){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(e,r):this.decodeBinary(e,r)}decodeUtf8String(e,r){if(e>this.maxStrLength)throw new Ns(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+r+e)throw cH;let s=this.pos+r,n;return this.stateIsMapKey()&&this.keyDecoder?.canBeCached(e)?n=this.keyDecoder.decode(this.bytes,s,e):n=nH(this.bytes,s,e),this.pos+=r+e,n}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===Ag:!1}decodeBinary(e,r){if(e>this.maxBinLength)throw new Ns(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+r))throw cH;let s=this.pos+r,n=this.bytes.subarray(s,s+e);return this.pos+=r+e,n}decodeExtension(e,r){if(e>this.maxExtLength)throw new Ns(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);let s=this.view.getInt8(this.pos+r),n=this.decodeBinary(e,r+1);return this.extensionCodec.decode(n,s,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){let e=this.view.getUint8(this.pos);return this.pos++,e}readI8(){let e=this.view.getInt8(this.pos);return this.pos++,e}readU16(){let e=this.view.getUint16(this.pos);return this.pos+=2,e}readI16(){let e=this.view.getInt16(this.pos);return this.pos+=2,e}readU32(){let e=this.view.getUint32(this.pos);return this.pos+=4,e}readI32(){let e=this.view.getInt32(this.pos);return this.pos+=4,e}readU64(){let e=oH(this.view,this.pos);return this.pos+=8,e}readI64(){let e=rv(this.view,this.pos);return this.pos+=8,e}readU64AsBigInt(){let e=this.view.getBigUint64(this.pos);return this.pos+=8,e}readI64AsBigInt(){let e=this.view.getBigInt64(this.pos);return this.pos+=8,e}readF32(){let e=this.view.getFloat32(this.pos);return this.pos+=4,e}readF64(){let e=this.view.getFloat64(this.pos);return this.pos+=8,e}};function fI(t,e){return new ov(e).decode(t)}var dOe=globalThis.require??(0,AH.createRequire)(L),IH=15e3,RH=45e3,PH=12e4,_I="platform",SI="activation",EI="desired.activation";function CI(t){if(typeof t=="string"&&t.length>0)return t;if(t&&typeof t=="object"){let e=t.note;if(typeof e=="string"&&e.length>0)return e}}var iie=[{state:"still-activating",afterMs:15e3},{state:"cold-boot",afterMs:45e3},{state:"degraded",afterMs:12e4}],TI=class{constructor(t){this._options=t,this._offPhase=t.onPhase(e=>{if(!this._stopped)if(e?.name==="live"){if(this._liveAt===null){this._liveAt=Date.now();for(let r of this._watches.values())this._arm(r)}}else(e?.name==="error"||e?.name==="paused")&&this._park()})}_options;_watches=new Map;_handlers=new Set;_liveAt=null;_stopped=!1;_offPhase=null;_park(){this._liveAt=null;for(let t of this._watches.values())if(!t.done){for(let e of t.timers)clearTimeout(e);t.timers=[],t.startedAt=null,t.lastEvent=null}}watch(t,e){if(this._stopped||this._watches.has(t))return;let r={name:t,stream:e,startedAt:null,done:!1,timers:[],cleanups:[],lastEvent:null};this._watches.set(t,r),this._hookFirstMediaSignals(r),!r.done&&this._liveAt!==null&&this._arm(r)}unwatch(t){let e=this._watches.get(t);!e||e.done||this._settle(e)}onActivation(t){for(let e of this._watches.values())!e.done&&e.lastEvent&&t(e.lastEvent);return this._handlers.add(t),()=>this._handlers.delete(t)}dispose(){if(!this._stopped){this._stopped=!0;for(let t of this._watches.values())t.done||this._settle(t);this._offPhase?.(),this._offPhase=null,this._handlers.clear()}}_hookFirstMediaSignals(t){let e=r=>{if(!(!r||t.done)){if(r.muted===!0&&typeof r.addEventListener=="function"){let s=()=>this._firstMedia(t);r.addEventListener("unmute",s,{once:!0}),t.cleanups.push(()=>r.removeEventListener?.("unmute",s));return}this._firstMedia(t)}};t.cleanups.push(t.stream.on("track",r=>e(r))),this._options.onData&&t.cleanups.push(this._options.onData(t.name,()=>this._firstMedia(t))),e(t.stream.track)}_arm(t){if(!(t.done||t.startedAt!==null||this._stopped)){t.startedAt=Date.now(),this._emit(t,"activating",0);for(let e of iie){let r=setTimeout(()=>{t.done||this._stopped||this._emit(t,e.state,Date.now()-t.startedAt)},e.afterMs);r.unref?.(),t.timers.push(r)}}}_firstMedia(t){if(t.done||this._stopped)return;let e=t.startedAt;this._settle(t),this._emit(t,"first-media",e===null?0:Date.now()-e)}_settle(t){t.done=!0;for(let e of t.timers)clearTimeout(e);t.timers=[];for(let e of t.cleanups.splice(0))e()}_emit(t,e,r){let s={state:e,elapsedMs:r,stream:t.name},n=CI(this._options.hint());n!==void 0&&(s.hint=n),t.lastEvent=s;for(let i of Array.from(this._handlers))i(s)}},Ys=class extends Error{status;code;constructor(t,e,r=e>0?`http_${e}`:"runtime_artifacts_error",s){super(t),this.name="RuntimeArtifactsError",this.status=e,this.code=r,s!==void 0&&(this.cause=s),Object.setPrototypeOf(this,new.target.prototype)}},kI=class extends Ys{constructor(t="[urun] runtime artifacts: unauthorized",e="unauthorized"){super(t,401,e),this.name="RuntimeArtifactsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},AI=class extends Ys{constructor(t="[urun] runtime artifacts: not found",e="not_found"){super(t,404,e),this.name="RuntimeArtifactNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}};function xI(t){return{baseUrl:t.baseUrl,fallbackUrls:t.fallbackUrls,orgId:t.orgId,jwt:t.jwt,getAccessToken:t.getAccessToken,authProvider:t.authProvider}}function DH(t){return new Rg(t)}var Rg=class{_options;constructor(t){this._options=t}async list(t){let e=uH(await this._request(t,"")).artifacts;if(!Array.isArray(e))throw new Ys("[urun] runtime artifacts: response missing `artifacts`",0,"bad_response");return e.map(lH)}async getDownloadUrl(t,e){let r=uH(await this._request(e,`/${encodeURIComponent(t)}/download`)),s=r.download_url;if(typeof s!="string"||!aie(s))throw new Ys("[urun] runtime artifacts: response missing HTTPS download_url",0,"bad_response");return{artifact:lH(r.artifact),downloadUrl:s}}async _request(t,e){let r=Sg(this._options.baseUrl,this._options.fallbackUrls),s=null;for(let n of r)try{return await this._requestFromBase(n,t,e)}catch(i){if(s=i instanceof Error?i:new Error(String(i)),s instanceof Ys&&cie(s.status))throw s}throw s??new Ys("[urun] runtime artifacts request failed",0)}async _requestFromBase(t,e,r){let s=`${Tr(t)}/api/sessions/${encodeURIComponent(e)}/artifacts${r}`,n=await this._resolveToken(),i=await fetch(s,{method:"GET",headers:this._headers(n)});if(i.status===401&&this._options.getAccessToken){let o=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});o&&o!==n&&(n=o,i=await fetch(s,{method:"GET",headers:this._headers(n)}))}if(!i.ok){let{code:o,message:a}=await this._readError(i,t);throw die(i.status,o,a)}try{return await i.json()}catch(o){throw new Ys(`[urun] runtime artifacts: invalid JSON response from ${Tr(t)}`,0,"bad_response",o)}}async _resolveToken(){return this._options.getAccessToken?await this._options.getAccessToken()??void 0:this._options.jwt}_headers(t){let e={Accept:"application/json","X-Tenant-Id":this._options.orgId,"X-Auth-Provider":this._options.authProvider||"default"};return t&&(e.Authorization=`Bearer ${t}`),e}async _readError(t,e){let r=Tr(e);try{let s=(await t.json()).error;if(s&&typeof s=="object"){let{code:n,message:i}=s;return{code:typeof n=="string"&&n.length>0?n:`http_${t.status}`,message:typeof i=="string"&&i.length>0?`[urun] runtime artifacts request failed at ${r}: ${i}`:`[urun] runtime artifacts request failed at ${r}: HTTP ${t.status}`}}}catch{}return{code:`http_${t.status}`,message:`[urun] runtime artifacts request failed at ${r}: HTTP ${t.status}`}}};function lH(t){if(!t||typeof t!="object")throw new Ys("[urun] runtime artifacts: malformed artifact",0,"malformed_artifact");let e=t,r=ra(e,"artifact_id")||ra(e,"id"),s=ra(e,"filename"),n=ra(e,"kind"),i=ra(e,"status")||"ready",o=oie(e,"size_bytes"),a=ra(e,"sha256");if(!r||!s||!n||o==null||!a)throw new Ys("[urun] runtime artifacts: malformed artifact metadata",0,"malformed_artifact");return{artifactId:r,kind:n,filename:s,contentType:ra(e,"content_type")||"application/octet-stream",sizeBytes:o,sha256:a,status:i,createdAt:ra(e,"created_at"),expiresAt:ra(e,"expires_at")}}function ra(t,e){let r=t[e];return typeof r=="string"&&r.length>0?r:void 0}function oie(t,e){let r=t[e];return typeof r=="number"&&Number.isFinite(r)&&Number.isInteger(r)&&r>=0?r:void 0}function aie(t){try{return new URL(t).protocol==="https:"}catch{return!1}}function cie(t){return t===401||t===403}function die(t,e,r){return t===401?new kI(r,e):t===404?new AI(r,e):new Ys(r,t,e)}function uH(t){if(!t||typeof t!="object"||Array.isArray(t))throw new Ys("[urun] runtime artifacts: malformed response",0,"bad_response");return t}var Xi=class extends Error{status;code;constructor(t,e){super(t),this.name="RecordingsError",this.status=e.status,this.code=e.code,e.cause!==void 0&&(this.cause=e.cause),Object.setPrototypeOf(this,new.target.prototype)}},cv=class extends Xi{constructor(t="[urun] recordings: unauthorized",e="unauthorized"){super(t,{status:401,code:e}),this.name="RecordingsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},II=class extends Xi{constructor(t="[urun] recordings: not found",e="not_found"){super(t,{status:404,code:e}),this.name="RecordingNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}},RI=class extends Xi{constructor(t="[urun] recordings: retain requires a temp recording",e="retain_not_temp"){super(t,{status:409,code:e}),this.name="RetainNotTempError",Object.setPrototypeOf(this,new.target.prototype)}},PI=class extends Xi{constructor(t="[urun] recordings: pin requires an active temp recording",e="pin_requires_active_temp"){super(t,{status:409,code:e}),this.name="PinRequiresActiveTempError",Object.setPrototypeOf(this,new.target.prototype)}},DI=class extends Xi{constructor(t="[urun] recordings: recording is permanent and locked",e="permanent_locked"){super(t,{status:409,code:e}),this.name="PermanentLockedError",Object.setPrototypeOf(this,new.target.prototype)}},Pg=class extends Xi{constructor(t="[urun] recordings: invalid retention duration",e="bad_duration",r=400){super(t,{status:r,code:e}),this.name="InvalidDurationError",Object.setPrototypeOf(this,new.target.prototype)}};function dv(t){return/^(\d+[smhdw])+$/.test(t)}function BH(t){if(t==="pin")return{action:"pin"};if(dv(t))return{action:"retain",duration:t};throw new Pg(`[urun] recordings: "${t}" is not a duration or "pin"`)}function lie(t,e,r){let s=r||e||`HTTP ${t}`;if(t===401)return new cv(s,e??"unauthorized");if(t===404)return new II(s,e??"not_found");if(t===400)return new Pg(s,e??"bad_request",400);if(t===409)switch(e){case"retain_not_temp":return new RI(s,e);case"pin_requires_active_temp":return new PI(s,e);case"permanent_locked":return new DI(s,e)}return new Xi(s,{status:t,code:e??`http_${t}`})}var lv=class{constructor(t){this._options=t,this._base=`${t.functionsUrl.replace(/\/+$/,"")}/recordings`}_options;_base;async list(t){let e=(await this._request("GET","",{params:t?{session_id:t}:void 0})).recordings;return Array.isArray(e)?e:[]}async get(t){return this._one(await this._request("GET",`/${encodeURIComponent(t)}`))}async retain(t,e){if(!dv(e))throw new Pg(`[urun] recordings: "${e}" is not a valid retention duration`);return this._one(await this._request("POST",`/${encodeURIComponent(t)}/retain`,{body:{duration:e}}))}async pin(t){return this._one(await this._request("POST",`/${encodeURIComponent(t)}/pin`))}async unpin(t){return this._one(await this._request("POST",`/${encodeURIComponent(t)}/unpin`))}async permanent(t){return this._one(await this._request("POST",`/${encodeURIComponent(t)}/permanent`))}async delete(t){return this._one(await this._request("POST",`/${encodeURIComponent(t)}/delete`))}_one(t){let e=t.recording;if(!e||typeof e!="object")throw new Xi("[urun] recordings: response missing `recording`",{status:0,code:"bad_response"});return e}async _request(t,e,r={}){let s=this._buildUrl(e,r.params),n=await this._resolveToken(),i=await this._fetch(s,t,n,r.body);if(i.status===401&&this._options.getAccessToken){let o=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});o&&o!==n&&(n=o,i=await this._fetch(s,t,n,r.body))}if(!i.ok){let{code:o,message:a}=await this._readError(i);throw lie(i.status,o,a)}return this._readJson(i)}_buildUrl(t,e){let r=`${this._base}${t}`,s=Object.entries(e??{}).filter(([,n])=>n!=null&&n!=="").map(([n,i])=>`${encodeURIComponent(n)}=${encodeURIComponent(i)}`).join("&");return s&&(r+=`?${s}`),r}_fetch(t,e,r,s){let n={Authorization:`Bearer ${r}`,apikey:r,Accept:"application/json","X-Tenant-Id":this._options.orgId};this._options.authProvider&&(n["X-Auth-Provider"]=this._options.authProvider);let i={method:e,headers:n};return s!==void 0&&(n["Content-Type"]="application/json",i.body=JSON.stringify(s)),fetch(t,i)}async _resolveToken(){if(this._options.getAccessToken){let e=await this._options.getAccessToken();if(e)return e}let t=this._options.jwt??this._options.apiKey;if(!t)throw new cv("[urun] recordings: no credential \u2014 provide one of apiKey, jwt, or getAccessToken");return t}async _readJson(t){try{return await t.json()}catch{return{}}}async _readError(t){try{let e=(await t.json()).error;if(e&&typeof e=="object"){let{code:r,message:s}=e;return{code:typeof r=="string"?r:void 0,message:typeof s=="string"?s:`HTTP ${t.status}`}}}catch{}return{message:`HTTP ${t.status}`}}};function LH(t){return new lv(t)}var OH=1e3,NH=12e3;function BI(t,e,r={}){let s=null,n=0,i=0,o=null,a=-1,c=()=>{let f=t.get("desired.billing.generationSeconds");if(typeof f!="number"||!Number.isFinite(f)||f<=0)return null;let b=t.get("desired.billing.epoch"),w=t.get("desired.billing.updatedAtMs");return{seconds:f,epoch:typeof b=="number"&&Number.isFinite(b)?b:0,updatedAtMs:typeof w=="number"&&Number.isFinite(w)?w:null}},d=()=>{if(s===null)return null;let f=Math.min(Math.max(0,Date.now()-n),i);return s+f/1e3},u=()=>{let f=r.creditsPerSecond;if(typeof f=="number"&&Number.isFinite(f)&&f>0)return f;let b=t.get("desired.billing.creditsPerSecond");return typeof b=="number"&&Number.isFinite(b)&&b>0?b:null},l=()=>{let f=d();if(f===null)return;let b=Math.floor(f);if(b<=a)return;a=b;let w={seconds:b},S=u();S!==null&&(w.estimatedCredits=b*S),e(w)},h=f=>{n=Date.now();let b=f===null?0:Math.max(0,n-f);i=Math.max(0,12e3-b)},p=()=>{let f=c();if(f!==null){if(o!==null&&f.epoch!==o){o=f.epoch,s=f.seconds,a=-1,h(f.updatedAtMs),l();return}s!==null&&f.seconds<=s||(o=f.epoch,s=f.seconds,h(f.updatedAtMs),l())}};p();let m=t.on("change",p),_=setInterval(l,1e3);return _.unref?.(),()=>{clearInterval(_),m()}}var LI="activity",OI="visibility",UH=15e3,av=["pointerdown","pointermove","keydown","wheel","touchstart"];function NI(t){let e=t.now??Date.now,r=t.mode==="explicit",s=r?null:t.windowTarget!==void 0?t.windowTarget:typeof window<"u"?window:null,n=r?null:t.documentTarget!==void 0?t.documentTarget:typeof document<"u"?document:null,i=!1,o,a=()=>{if(i)return;let h=e();if(!(o!==void 0&&h-o<15e3)){o=h;try{t.awareness.setLocalStateField(LI,{at:h})}catch{}}},c=()=>{if(!(i||!n||n.visibilityState===void 0))try{t.awareness.setLocalStateField(OI,n.visibilityState)}catch{}},d=()=>a(),u=()=>{c(),(!n||n.visibilityState===void 0||n.visibilityState==="visible")&&a()};if(s)for(let h of av)s.addEventListener(h,d,{passive:!0,capture:!0});n&&n.addEventListener("visibilitychange",u);let l=null;return!r&&t.isProducing&&(l=setInterval(()=>{if(!i)try{t.isProducing?.()&&a()}catch{}},15e3),l.unref?.()),a(),c(),{touch:a,dispose(){if(!i){if(i=!0,s)for(let h of av)s.removeEventListener(h,d,{capture:!0});n&&n.removeEventListener("visibilitychange",u),l&&(clearInterval(l),l=null)}}}}var UI="user_activity",MI="focus",MH=3e4;function hH(t){switch(t){case"connecting":case"renegotiating":return"connecting";case"connected":return"ready";case"reconnecting":case"disconnected":case"failed":return"transient_failure"}}var jI=class{_awareness;_now;_win;_state="idle";_stateHandlers=new Set;_transportUnsubs=new Set;_disposed=!1;_counts={typing:0,pointer:0,tty:0,consumer_reads:0};_inflight=0;_visibility;_focus;_lastSignalAt;_lastPublishedAt;_trailing=null;_onWindowFocus=null;_onWindowBlur=null;constructor(t={}){this._awareness=t.awareness??null,this._now=t.now??Date.now,this._win=t.windowTarget!==void 0?t.windowTarget:typeof window<"u"?window:null;let e=t.documentTarget!==void 0?t.documentTarget:typeof document<"u"?document:null;this._win&&e&&typeof e.hasFocus=="function"&&(this._onWindowFocus=()=>this.setFocus("focused"),this._onWindowBlur=()=>this.setFocus("unfocused"),this._win.addEventListener("focus",this._onWindowFocus),this._win.addEventListener("blur",this._onWindowBlur),this.setFocus(e.hasFocus()?"focused":"unfocused"))}get state(){return this._state}onState(t){return this._stateHandlers.add(t),()=>this._stateHandlers.delete(t)}transportConnecting(){this._setState("connecting")}transportReady(){this._setState("ready")}transportClosed(){this._setState("transient_failure")}attachTransport(t){if(this._disposed)return()=>{};this._setState(hH(t.state));let e=t.on("stateChange",s=>{this._setState(hH(s))}),r=()=>{e(),this._transportUnsubs.delete(r)};return this._transportUnsubs.add(r),r}_setState(t){if(!(this._disposed||t===this._state)){this._state=t;for(let e of this._stateHandlers)try{e(t)}catch{}}}interaction(t,e=1){this._disposed||!Number.isFinite(e)||e<=0||t==="pointer"&&this._focus==="unfocused"||(this._counts[t]+=e,this._signal())}consumerRead(t=1){this._disposed||!Number.isFinite(t)||t<=0||(this._counts.consumer_reads+=t,this._signal())}get inflight(){return this._inflight}workBegin(){if(this._disposed)return()=>{};this._inflight+=1,this._inflight===1&&this._publishNow();let t=!1;return()=>{t||this._disposed||(t=!0,this._inflight-=1,this._inflight===0&&this._publishNow())}}setVisibility(t){this._disposed||(this._visibility=t)}setFocus(t){if(!(this._disposed||t===this._focus)){this._focus=t;try{this._awareness?.setLocalStateField(MI,t)}catch{}}}_signal(){this._lastSignalAt=this._now();let t=this._lastPublishedAt===void 0?1/0:this._lastSignalAt-this._lastPublishedAt;if(t>=3e4){this._publishNow();return}if(this._trailing)return;let e=Math.max(3e4-t,0);this._trailing=setTimeout(()=>{this._trailing=null,this._disposed||this._publishNow()},e),this._trailing.unref?.()}_publishNow(){this._trailing&&(clearTimeout(this._trailing),this._trailing=null),this._lastPublishedAt=this._now();let t={at:this._lastSignalAt??this._lastPublishedAt,counts:{...this._counts},inflight:this._inflight};this._visibility!==void 0&&(t.visibility=this._visibility),this._focus!==void 0&&(t.focus=this._focus);try{this._awareness?.setLocalStateField(UI,t)}catch{}}dispose(){if(!this._disposed){for(let t of Array.from(this._transportUnsubs))t();this._transportUnsubs.clear(),this._win&&(this._onWindowFocus&&this._win.removeEventListener("focus",this._onWindowFocus),this._onWindowBlur&&this._win.removeEventListener("blur",this._onWindowBlur)),this._onWindowFocus=null,this._onWindowBlur=null,this._trailing&&(clearTimeout(this._trailing),this._trailing=null),this._state="idle",this._stateHandlers.clear(),this._disposed=!0}}},jH=250;function $I(t){if(typeof document>"u"||typeof window>"u"||typeof document.addEventListener!="function"||typeof window.addEventListener!="function")return()=>{};let e=0,r=()=>{if(document.visibilityState==="hidden")return;let s=Date.now();s-e<250||(e=s,t())};return document.addEventListener("visibilitychange",r),window.addEventListener("pageshow",r),window.addEventListener("focus",r),()=>{document.removeEventListener("visibilitychange",r),window.removeEventListener("pageshow",r),window.removeEventListener("focus",r)}}function FI(t){if(typeof window>"u"||typeof window.addEventListener!="function")return()=>{};let e=!1,r=s=>{s.persisted||e||(e=!0,t())};return window.addEventListener("pagehide",r),()=>{window.removeEventListener("pagehide",r)}}function HI(t){if(typeof window>"u"||typeof window.addEventListener!="function")return()=>{};let e=r=>{t()&&(r.preventDefault(),r.returnValue="")};return window.addEventListener("beforeunload",e),()=>{window.removeEventListener("beforeunload",e)}}var fH="video/mp4";function qI(t,e={}){let r=e.timesliceMs??1e3,s=null,n=null,i=!1,o=(a,c,d)=>{let u=typeof MediaRecorder>"u"?void 0:MediaRecorder;if(!u)throw new Error("[urun] stream.chunks(): MediaRecorder is unavailable in this runtime. Pass { source } to chunks() to inject a byte-tap (e.g. a Node/werift consumer).");let l=e.mimeType??(typeof u.isTypeSupported=="function"&&u.isTypeSupported(fH)?fH:void 0),h=new MediaStream([a]),p=new u(h,l?{mimeType:l}:void 0);s=p;let m=Promise.resolve();p.ondataavailable=_=>{let f=_.data;i||!f||f.size===0||(m=m.then(async()=>{let b=new Uint8Array(await f.arrayBuffer());i||c(b)}))},p.onstop=()=>{m.then(()=>{i||d()})},p.onerror=()=>{m.then(()=>{i||d()})},p.start(r)};return{start(a,c){if(s||i)return;let d=t.track();if(d){o(d,a,c);return}n=t.onTrack(u=>{!u||s||i||(n?.(),n=null,o(u,a,c))})},stop(){if(i)return;i=!0,n?.(),n=null;let a=s;if(s=null,a&&a.state!=="inactive")try{a.stop()}catch{}}}}function uie(t){let e=t;return typeof e[Symbol.asyncIterator]=="function"||(e[Symbol.asyncIterator]=function(){let r=t.getReader();return{next(){return r.read()},async return(){try{await r.cancel()}catch{}try{r.releaseLock()}catch{}return{value:void 0,done:!0}},[Symbol.asyncIterator](){return this}}}),e}function hie(t,e){let r=null,s=!1,n=!1,i=new ReadableStream({pull(o){s||(s=!0,r=t(e),r.start(a=>{if(!n)try{o.enqueue(a)}catch{}},()=>{if(!n){n=!0;try{o.close()}catch{}}}))},cancel(){n=!0,r?.stop(),r=null}},new CountQueuingStrategy({highWaterMark:0}));return uie(i)}var VI=65536;function zI(t){let e=dI(t),r=new Uint8Array(4+e.byteLength);return new DataView(r.buffer).setUint32(0,e.byteLength,!0),r.set(e,4),r}var WI=class{buf=new Uint8Array(0);push(t){if(t.byteLength>0){let r=new Uint8Array(this.buf.byteLength+t.byteLength);r.set(this.buf),r.set(t,this.buf.byteLength),this.buf=r}let e=[];for(;this.buf.byteLength>=4;){let r=new DataView(this.buf.buffer,this.buf.byteOffset).getUint32(0,!0);if(r>VI)throw new Error("[urun] wt control frame too large");if(this.buf.byteLength<4+r)break;let s=this.buf.subarray(4,4+r);this.buf=this.buf.subarray(4+r),e.push(Object.assign(fI(s),{raw:s}))}return e}};function fie(t,e){let r=new DataView(t.buffer,t.byteOffset,t.byteLength),s=r.getUint8(0),n=(s&240)===128,i=s===222;if(!n&&!i&&s!==223)throw new Error("[urun] mirrorControlBody: source control frame is not a msgpack map");let o=n?s&15:i?r.getUint16(1,!1):r.getUint32(1,!1),a=n?1:i?3:5,c=[];c.push(t.subarray(0,a));for(let h=0;h<o;h++){let p=a,m=Ig(t,r,a);a=m.end;let _=Ig(t,r,a).end;if(pie(r.getUint8(p))){let f=r.getUint8(p),b=(f&224)===160?1:f===217?2:f===218?3:5;if(new TextDecoder().decode(t.subarray(p+b,m.end))==="t"){c.push(t.subarray(p,m.end));let w=new TextEncoder().encode(e);if(w.byteLength>31)throw new Error("[urun] mirrorControlBody: replacement tag too long");c.push(new Uint8Array([160|w.byteLength]),w)}else c.push(t.subarray(p,_))}else c.push(t.subarray(p,_));a=_}let d=c.reduce((h,p)=>h+p.byteLength,0),u=new Uint8Array(d),l=0;for(let h of c)u.set(h,l),l+=h.byteLength;return u}function pie(t){return(t&224)===160?!0:t===217||t===218||t===219}function Ig(t,e,r){let s=e.getUint8(r),n=r;if(s<=127||s>=224)return{start:n,end:r+1};if((s&224)===160)return{start:n,end:r+1+(s&31)};if((s&240)===128||(s&240)===144){let o=s&15;r+=1;let a=(s&240)===128?o*2:o;for(let c=0;c<a;c++)r=Ig(t,e,r).end;return{start:n,end:r}}let i={192:0,194:0,195:0,204:1,205:2,206:4,207:8,208:1,209:2,210:4,211:8,202:4,203:8};if(i[s]!==void 0)return{start:n,end:r+1+i[s]};if(s===217||s===196)return{start:n,end:r+2+e.getUint8(r+1)};if(s===218||s===197)return{start:n,end:r+3+e.getUint16(r+1,!1)};if(s===219||s===198)return{start:n,end:r+5+e.getUint32(r+1,!1)};if(s===220||s===221){let o=s===220?e.getUint16(r+1,!1):e.getUint32(r+1,!1);r+=s===220?3:5;for(let a=0;a<o;a++)r=Ig(t,e,r).end;return{start:n,end:r}}if(s===222||s===223){let o=s===222?e.getUint16(r+1,!1):e.getUint32(r+1,!1);r+=s===222?3:5;for(let a=0;a<o*2;a++)r=Ig(t,e,r).end;return{start:n,end:r}}throw new Error(`[urun] mirrorControlBody: unsupported msgpack prefix 0x${s.toString(16)} at byte ${n}`)}var ei=12,wI=1,mie=0,$H=1,gie=2;function uv(t){let e=t.getUint8(8);return{groupId:t.getUint32(0,!0),frameSeq:t.getUint32(4,!0),keyframe:(e&wI)===wI,fragIndex:t.getUint8(9),fragCount:t.getUint8(10),lane:t.getUint8(11)}}function KI(t){let e=new Uint8Array(ei),r=new DataView(e.buffer);return r.setUint32(0,t.groupId,!0),r.setUint32(4,t.frameSeq,!0),r.setUint8(8,t.keyframe?wI:0),r.setUint8(9,t.fragIndex),r.setUint8(10,t.fragCount),r.setUint8(11,t.lane??mie),e}var yie=100,pH=100,GI=class{constructor(t,e={}){this.cb=t,this.now=e.now??(()=>performance.now()),this.debounceMs=e.keyframeRequestDebounceMs??yie}cb;pending=new Map;newestGroupSeen=-1;newestFrameDelivered=-1;needKeyframe=!0;kfRequestedAt=-1/0;now;debounceMs;bytesInWindow=0;framesDelivered=0;framesAbandoned=0;push(t){if(t.byteLength<ei)return;let e=uv(new DataView(t.buffer,t.byteOffset));if(this.bytesInWindow+=t.byteLength,this.isSourceRestart(e.groupId,e.frameSeq))this.resync(e.groupId);else if(e.groupId<this.newestGroupSeen||(e.groupId>this.newestGroupSeen&&(this.framesAbandoned+=this.pending.size,this.pending.clear(),this.newestGroupSeen=e.groupId,this.needKeyframe=!0),e.frameSeq<=this.newestFrameDelivered))return;let r=this.pending.get(e.frameSeq);if(r||(r={groupId:e.groupId,keyframe:e.keyframe,fragCount:e.fragCount,received:0,chunks:new Array(e.fragCount)},this.pending.set(e.frameSeq,r)),!r.chunks[e.fragIndex]){r.chunks[e.fragIndex]=t.subarray(ei),r.received++,r.received===r.fragCount&&(this.pending.delete(e.frameSeq),this.deliver(e.frameSeq,r));for(let s of this.pending.keys())s<e.frameSeq-1&&(this.pending.delete(s),this.framesAbandoned++)}}isSourceRestart(t,e){return this.newestGroupSeen<0?!1:t<this.newestGroupSeen-pH?!0:t!==this.newestGroupSeen?!1:e<this.newestFrameDelivered-pH}resync(t){this.framesAbandoned+=this.pending.size,this.pending.clear(),this.newestGroupSeen=t,this.newestFrameDelivered=-1,this.needKeyframe=!0,this.requestKeyframe()}requireKeyframe(){this.needKeyframe=!0}drainWindow(){let t={bytes:this.bytesInWindow,delivered:this.framesDelivered,abandoned:this.framesAbandoned};return this.bytesInWindow=0,this.framesDelivered=0,this.framesAbandoned=0,t}deliver(t,e){if(this.needKeyframe&&!e.keyframe){this.framesAbandoned++,this.requestKeyframe();return}if(t!==this.newestFrameDelivered+1&&!e.keyframe&&this.newestFrameDelivered>=0){this.needKeyframe=!0,this.framesAbandoned++,this.requestKeyframe();return}let r=e.chunks.reduce((i,o)=>i+o.byteLength,0),s=new Uint8Array(r),n=0;for(let i of e.chunks)s.set(i,n),n+=i.byteLength;this.needKeyframe=!1,this.newestFrameDelivered=t,this.framesDelivered++,this.cb.onFrame({seq:t,groupId:e.groupId,keyframe:e.keyframe,data:s})}requestKeyframe(){let t=this.now();t-this.kfRequestedAt<this.debounceMs||(this.kfRequestedAt=t,this.cb.onKeyframeNeeded())}},bie=/^avc[13]\.[0-9a-fA-F]{6}$/;function xie(t){return bie.test(t)?null:`codec ${JSON.stringify(t)} is not a fully-qualified WebCodecs H.264 string \u2014 the WT pipeline carries H.264, which VideoDecoder.configure needs as "avc1.PPCCLL" (e.g. "avc1.42E01F"); RTP MIMEs ("video/H264") and bare names ("h264") are rejected by WebCodecs as "Unknown or ambiguous codec name"`}function mH(t,e){let r=xie(t);if(r)throw new Error(`[urun] webtransport ${e} ${r}`)}var XI=1,YI=class{buf=new Uint8Array(0);name=null;ended=!1;get streamName(){return this.name}push(t){if(t.byteLength>0){let r=new Uint8Array(this.buf.byteLength+t.byteLength);r.set(this.buf),r.set(t,this.buf.byteLength),this.buf=r}if(this.name===null){if(this.buf.byteLength<2)return[];let r=this.buf[0];if(r!==XI)throw new Error(`[urun] wt data stream: unknown header version 0x${r.toString(16)} \u2014 rejecting stream`);let s=this.buf[1];if(s===0)throw new Error("[urun] wt data stream: empty stream name in header \u2014 rejecting stream");if(this.buf.byteLength<2+s)return[];this.name=new TextDecoder().decode(this.buf.subarray(2,2+s)),this.buf=this.buf.subarray(2+s)}let e=[];for(;this.buf.byteLength>=4;){let r=new DataView(this.buf.buffer,this.buf.byteOffset).getUint32(0,!0);if(this.buf.byteLength<4+r)break;if(this.ended)throw new Error(`[urun] wt data stream "${this.name}": envelope after the END envelope \u2014 rejecting stream`);let s=Z1(this.buf.subarray(4,4+r));this.buf=this.buf.subarray(4+r),s===Cl&&(this.ended=!0),e.push({name:this.name,payload:s})}if(this.ended&&this.buf.byteLength>0)throw new Error(`[urun] wt data stream "${this.name}": trailing bytes after the END envelope \u2014 rejecting stream`);return e}finish(){if(this.ended&&this.buf.byteLength===0)return;let t=this.name===null?"<incomplete header>":`"${this.name}"`;throw this.buf.byteLength>0?new Error(`[urun] wt data stream ${t}: truncated \u2014 FIN mid-${this.name===null?"header":"envelope"} (${this.buf.byteLength} dangling byte(s), no END envelope)`):new Error(`[urun] wt data stream ${t}: truncated \u2014 FIN without an END envelope`)}};async function JI(t,e){let r=t.getReader();for(;;){let{value:s,done:n}=await r.read();if(n)return;s&&wie(s,e).catch(i=>{e.onLaneError(i instanceof Error?i:new Error(String(i)))})}}async function wie(t,e){let r=t.getReader(),s=new YI;try{for(;;){let{value:n,done:i}=await r.read();if(i)break;if(!(!n||n.byteLength===0))for(let{name:o,payload:a}of s.push(n))e.onData(o,a)}s.finish()}catch(n){try{await r.cancel?.(n)}catch{}throw n}}var pI=40,gH=2,kl=48e3,vie=64,_ie=100,Sie=class{constructor(t){this.onFrame=t}onFrame;pending=new Map;newestDelivered=-1;framesDelivered=0;framesAbandoned=0;bytesInWindow=0;push(t){if(t.byteLength<ei)return;let e=uv(new DataView(t.buffer,t.byteOffset));if(this.bytesInWindow+=t.byteLength,this.newestDelivered>=0&&e.frameSeq<this.newestDelivered-_ie)this.framesAbandoned+=this.pending.size,this.pending.clear(),this.newestDelivered=-1;else if(e.frameSeq<=this.newestDelivered)return;if(e.fragCount===0)return;let r=this.pending.get(e.frameSeq);if(!r)for(r={timestamp:e.groupId,fragCount:e.fragCount,received:0,chunks:new Array(e.fragCount)},this.pending.set(e.frameSeq,r);this.pending.size>vie;){let o=1/0;for(let a of this.pending.keys())a<o&&(o=a);this.pending.delete(o),this.framesAbandoned++}if(e.fragIndex>=r.fragCount||r.chunks[e.fragIndex]||(r.chunks[e.fragIndex]=t.subarray(ei),r.received++,r.received<r.fragCount))return;this.pending.delete(e.frameSeq);for(let o of this.pending.keys())o<e.frameSeq&&(this.pending.delete(o),this.framesAbandoned++);let s=r.chunks.reduce((o,a)=>o+(a?.byteLength??0),0),n=new Uint8Array(s),i=0;for(let o of r.chunks)n.set(o,i),i+=o.byteLength;this.newestDelivered=e.frameSeq,this.framesDelivered++,this.onFrame({seq:e.frameSeq,timestamp:r.timestamp,data:n})}drainWindow(){let t={bytes:this.bytesInWindow,delivered:this.framesDelivered,abandoned:this.framesAbandoned};return this.bytesInWindow=0,this.framesDelivered=0,this.framesAbandoned=0,t}},Eie=class{constructor(t,e){this.config=t,this.seam=e;let r=this.seam.jitterBufferTargetMs??pI;Number.isFinite(r)||(E.warn(`[urun] WT audio jitterBufferTargetMs=${r} is not finite \u2014 using default ${pI}ms`),r=pI),this.targetS=Math.max(0,r)/1e3}config;seam;decoder=null;ctx=null;ownsCtx=!1;resumeAttempts=0;resumeInFlight=!1;notRunningFrames=0;dest=null;trackSurfaced=!1;stopped=!1;playhead=0;targetS;contentBaseS=null;wallBaseS=0;reanchorLogged=!1;lastTsS=null;pendingTs=[];bridgeTrack=null;scheduledCount=0;lastScheduledAt=0;rebuildGen=0;rebuildTimes=[];rebuildBudgetLoggedAt=-1e4;lastRemote=null;assembler=new Sie(t=>this.decodeFrame(t));start(){let t=globalThis.AudioDecoder,e=globalThis.AudioContext;if(typeof t!="function")throw new Error("[urun] WT audio lane engaged without AudioDecoder/AudioContext");if(this.seam.ctx)this.ctx=this.seam.ctx,this.ownsCtx=!1;else{if(typeof e!="function")throw new Error("[urun] WT audio lane engaged without AudioDecoder/AudioContext");this.ctx=new e({sampleRate:this.config.sampleRate}),this.ownsCtx=!0}this.dest=this.ctx.createMediaStreamDestination(),this.armCtxRearm();try{this.initDecoder(t)}catch(s){throw this.ownsCtx&&this.ctx.close().catch(()=>{}),this.ctx=null,this.dest=null,s}this.trackSurfaced=!0,this.resumeLoudly("start");let r=this.dest.stream.getAudioTracks()[0];if(!r)throw new Error("[urun] playout start produced no bridge track");this.surfaceTrack(r)}armCtxRearm(){let t=this.ctx;if(!t)return;let e=()=>{this.ctx&&this.ctx.state!=="running"&&this.resumeLoudly("statechange")},r=t;typeof r.addEventListener=="function"?r.addEventListener("statechange",e):t.onstatechange=e}resumeLoudly(t){let e=this.ctx;if(!e||!e.resume||this.resumeInFlight)return;let r=e.state!=="running"?++this.resumeAttempts:0;this.resumeInFlight=!0,e.resume().catch(s=>{E.warn(`[urun] WT audio playout context ${t}: resume FAILED (state=${e.state}, attempt=${r||"n/a"}): ${s instanceof Error?s.message:String(s)} \u2014 decoded reply audio would be scheduled into a graph that never renders; retrying per frame`)}).finally(()=>{this.resumeInFlight=!1})}stop(){if(!this.stopped){this.stopped=!0;try{this.seam.renderHop?.setSource(null)}catch{}this.trackSurfaced&&(this.trackSurfaced=!1,this.seam.onTrack(null));try{this.decoder?.close()}catch{}this.ownsCtx&&this.ctx?.close().catch(()=>{})}}initDecoder(t){let e=new t({output:r=>this.schedule(r,this.pendingTs.shift()),error:r=>this.onDecoderError(r)});e.configure({codec:this.config.codec,sampleRate:this.config.sampleRate,numberOfChannels:this.config.channels}),this.decoder=e}decodeFrame(t){let e=globalThis.EncodedAudioChunk;if(typeof e!="function"||this.stopped)return;if(!this.decoder){let s=globalThis.AudioDecoder;if(typeof s!="function")return;try{this.initDecoder(s)}catch{return}}let r=this.decoder;r&&(this.pendingTs.push(t.timestamp),r.decode(new e({type:"key",timestamp:Math.round(t.timestamp*(1e6/kl)),data:t.data})))}schedule(t,e){let r=this.ctx,s=this.dest;if(!r||!s||this.stopped){t.close();return}if(r.state!=="running"){t.close(),this.contentBaseS=null,this.lastTsS=null,this.notRunningFrames++,(this.notRunningFrames===1||this.notRunningFrames%50===0)&&E.warn(`[urun] WT audio playout context not RUNNING (state=${r.state}): dropping decoded frames instead of scheduling into a graph that never renders \u2014 resume re-armed per frame (attempts=${this.resumeAttempts}, dropped=${this.notRunningFrames})`),this.resumeLoudly("per-frame");return}let n=t.numberOfFrames,i=Math.max(1,t.numberOfChannels),o=r.createBuffer(i,n,t.sampleRate);for(let u=0;u<i;u++){let l=new Float32Array(n);t.copyTo(l,{planeIndex:u,format:"f32-planar"}),o.copyToChannel(l,u)}let a=n/t.sampleRate;t.close();let c=r.createBufferSource();c.buffer=o,c.connect(s);let d;if(e===void 0)d=Math.max(this.playhead,r.currentTime+this.targetS);else{this.contentBaseS===null&&(this.contentBaseS=e/kl,this.wallBaseS=r.currentTime+this.targetS),d=this.wallBaseS+e/kl-this.contentBaseS;let u=null;this.lastTsS!==null&&(e<this.lastTsS?(d=r.currentTime+this.targetS,u=`backward ts step ${(this.lastTsS-e/kl).toFixed(3)}s (producer clock reset)`):d>r.currentTime+this.targetS+Math.max(a,this.targetS)&&(u=`forward jump ${(d-r.currentTime).toFixed(3)}s out (lead + ${a.toFixed(3)}s tolerance exceeded \u2014 barge flush / producer re-anchor)`),u&&(this.reanchorLogged||(this.reanchorLogged=!0,E.warn(`[urun] WT audio playout re-anchored on a content-timeline discontinuity: ${u} \u2014 the gap is honest silence at rate 1.0, never a stretch`)),this.contentBaseS=e/kl,this.wallBaseS=r.currentTime+this.targetS,d=this.wallBaseS)),d<r.currentTime&&(this.reanchorLogged||(this.reanchorLogged=!0,E.warn(`[urun] WT audio playout re-anchored ${(r.currentTime-d).toFixed(3)}s past its content position (arrival deficit exceeded the lead) \u2014 the gap is honest silence at rate 1.0, never a catch-up stretch`)),this.contentBaseS=e/kl,this.wallBaseS=r.currentTime+this.targetS,d=this.wallBaseS)}c.start(d),this.scheduledCount++,this.lastScheduledAt=performance.now(),e!==void 0&&(this.lastTsS=e/kl),this.playhead=d+a}armBridgeEndedWatch(t){let e=this.rebuildGen;t.addEventListener?.("ended",()=>{if(!this.stopped&&!(e!==this.rebuildGen||this.bridgeTrack!==t)){E.warn("[urun] WT audio bridge track ENDED while the lane is live \u2014 rebuilding the WebAudio playout surface and re-delivering the bridge track");try{this.rebuildSurface()}catch(r){E.error(`[urun] WT audio bridge rebuild failed \u2014 the reply stays silent until the next lane death re-delivers: ${r instanceof Error?r.message:String(r)}`)}}},{once:!0})}playoutProgress(){return{scheduled:this.scheduledCount,lastScheduledAt:this.lastScheduledAt,surfaced:this.trackSurfaced&&this.bridgeTrack?.readyState!=="ended",droppedNotRunning:this.notRunningFrames,ctxState:this.ctx?.state??"closed"}}rebuildSurface(){if(this.stopped)return;let t=performance.now();if(this.rebuildTimes=this.rebuildTimes.filter(s=>t-s<1e4),this.rebuildTimes.length>=gH){t-this.rebuildBudgetLoggedAt>1e4&&(this.rebuildBudgetLoggedAt=t,E.error(`[urun] WT audio bridge rebuild budget spent (${gH} in 10s) \u2014 standing down; the media-dead playout-progress verdict escalates to a re-dial if the surface stays dead`));return}this.rebuildTimes.push(t),this.rebuildGen++;let e=this.ctx;if(!e){let s=globalThis.AudioContext;if(typeof s!="function")throw new Error("[urun] AudioContext unavailable for the playout rebuild");e=new s({sampleRate:this.config.sampleRate}),this.ctx=e,this.ownsCtx=!0,this.armCtxRearm()}e.state!=="running"&&this.resumeLoudly("rebuild"),this.dest=e.createMediaStreamDestination(),this.playhead=0,this.contentBaseS!==null&&this.ctx!==e&&(this.contentBaseS=null,this.lastTsS=null),this.trackSurfaced=!0;let r=this.dest.stream.getAudioTracks()[0];if(!r)throw new Error("[urun] rebuilt playout produced no bridge track");this.surfaceTrack(r)}surfaceTrack(t){this.bridgeTrack=t,this.armBridgeEndedWatch(t),this.lastRemote&&this.lastRemote.readyState==="live"?this.seam.onTrack(this.lastRemote):this.seam.onTrack(t);let e=this.seam.renderHop;e&&(e.onRemote(r=>{if(this.stopped)return;if(r?this.lastRemote=r:this.lastRemote&&this.lastRemote.readyState!=="live"&&(this.lastRemote=null),r){this.seam.onTrack(r);return}if(this.lastRemote&&this.lastRemote.readyState==="live"){this.seam.onTrack(this.lastRemote);return}let s=this.bridgeTrack&&this.bridgeTrack.readyState==="live"?this.bridgeTrack:null;this.seam.onTrack(s)}),e.setSource(t))}onDecoderError(t){if(this.stopped)return;E.warn("[urun] WT audio decoder error \u2014 re-initializing the decoder:",t.message);try{this.decoder?.close()}catch{}this.decoder=null;let e=globalThis.AudioDecoder;if(typeof e=="function")try{this.initDecoder(e)}catch(r){E.error(`[urun] WT audio decoder re-init failed \u2014 lane silent until a later frame re-inits; transport unaffected: ${r instanceof Error?r.message:String(r)}`)}}},QI=1200;function FH(t,e,r,s,n){let i=s-ei;if(i<=0)return null;let o=Math.max(1,Math.ceil(r.byteLength/i));if(o>255)return null;let a=[];for(let c=0;c<o;c++){let d=r.subarray(c*i,Math.min((c+1)*i,r.byteLength)),u=KI({groupId:e>>>0,frameSeq:t>>>0,keyframe:n?.keyframe??!0,fragIndex:c,fragCount:o,lane:n?.lane??$H}),l=new Uint8Array(ei+d.byteLength);l.set(u,0),l.set(d,ei),a.push(l)}return a}var Cie=`
|
|
148
148
|
self.onrtctransform = (event) => {
|
|
149
149
|
const transformer = event.transformer
|
|
150
150
|
if (transformer.options?.role === 'sender') {
|