@urun-sh/core 0.1.38 → 0.1.39

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/index.js CHANGED
@@ -1,7 +1,136 @@
1
- "use strict";var Wi=Object.create;var Pt=Object.defineProperty;var Gi=Object.getOwnPropertyDescriptor;var Ki=Object.getOwnPropertyNames;var Qi=Object.getPrototypeOf,Yi=Object.prototype.hasOwnProperty;var Ji=(s,e,t)=>()=>{if(t)throw t[0];try{return s&&(e=s(s=0)),e}catch(r){throw t=[r],r}};var C=(s,e)=>()=>{try{return e||s((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}},Is=(s,e)=>{for(var t in e)Pt(s,t,{get:e[t],enumerable:!0})},Ls=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Ki(e))!Yi.call(s,n)&&n!==t&&Pt(s,n,{get:()=>e[n],enumerable:!(r=Gi(e,n))||r.enumerable});return s};var Se=(s,e,t)=>(t=s!=null?Wi(Qi(s)):{},Ls(e||!s||!s.__esModule?Pt(t,"default",{value:s,enumerable:!0}):t,s)),Ms=s=>Ls(Pt({},"__esModule",{value:!0}),s);var As=C((Qd,Os)=>{"use strict";var Fe=1e3,qe=Fe*60,$e=qe*60,Ee=$e*24,Xi=Ee*7,Zi=Ee*365.25;Os.exports=function(s,e){e=e||{};var t=typeof s;if(t==="string"&&s.length>0)return eo(s);if(t==="number"&&isFinite(s))return e.long?ro(s):to(s);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(s))};function eo(s){if(s=String(s),!(s.length>100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(s);if(e){var t=parseFloat(e[1]),r=(e[2]||"ms").toLowerCase();switch(r){case"years":case"year":case"yrs":case"yr":case"y":return t*Zi;case"weeks":case"week":case"w":return t*Xi;case"days":case"day":case"d":return t*Ee;case"hours":case"hour":case"hrs":case"hr":case"h":return t*$e;case"minutes":case"minute":case"mins":case"min":case"m":return t*qe;case"seconds":case"second":case"secs":case"sec":case"s":return t*Fe;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function to(s){var e=Math.abs(s);return e>=Ee?Math.round(s/Ee)+"d":e>=$e?Math.round(s/$e)+"h":e>=qe?Math.round(s/qe)+"m":e>=Fe?Math.round(s/Fe)+"s":s+"ms"}function ro(s){var e=Math.abs(s);return e>=Ee?Dt(s,e,Ee,"day"):e>=$e?Dt(s,e,$e,"hour"):e>=qe?Dt(s,e,qe,"minute"):e>=Fe?Dt(s,e,Fe,"second"):s+" ms"}function Dt(s,e,t,r){var n=e>=t*1.5;return Math.round(s/t)+" "+r+(n?"s":"")}});var Sr=C((Yd,Ns)=>{"use strict";function so(s){t.debug=t,t.default=t,t.coerce=c,t.disable=o,t.enable=n,t.enabled=a,t.humanize=As(),t.destroy=d,Object.keys(s).forEach(p=>{t[p]=s[p]}),t.names=[],t.skips=[],t.formatters={};function e(p){let l=0;for(let u=0;u<p.length;u++)l=(l<<5)-l+p.charCodeAt(u),l|=0;return t.colors[Math.abs(l)%t.colors.length]}t.selectColor=e;function t(p){let l,u=null,f,m;function h(...g){if(!h.enabled)return;let _=h,y=Number(new Date),x=y-(l||y);_.diff=x,_.prev=l,_.curr=y,l=y,g[0]=t.coerce(g[0]),typeof g[0]!="string"&&g.unshift("%O");let P=0;g[0]=g[0].replace(/%([a-zA-Z%])/g,(I,Y)=>{if(I==="%%")return"%";P++;let ye=t.formatters[Y];if(typeof ye=="function"){let re=g[P];I=ye.call(_,re),g.splice(P,1),P--}return I}),t.formatArgs.call(_,g),(_.log||t.log).apply(_,g)}return h.namespace=p,h.useColors=t.useColors(),h.color=t.selectColor(p),h.extend=r,h.destroy=t.destroy,Object.defineProperty(h,"enabled",{enumerable:!0,configurable:!1,get:()=>u!==null?u:(f!==t.namespaces&&(f=t.namespaces,m=t.enabled(p)),m),set:g=>{u=g}}),typeof t.init=="function"&&t.init(h),h}function r(p,l){let u=t(this.namespace+(typeof l>"u"?":":l)+p);return u.log=this.log,u}function n(p){t.save(p),t.namespaces=p,t.names=[],t.skips=[];let l=(typeof p=="string"?p:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let u of l)u[0]==="-"?t.skips.push(u.slice(1)):t.names.push(u)}function i(p,l){let u=0,f=0,m=-1,h=0;for(;u<p.length;)if(f<l.length&&(l[f]===p[u]||l[f]==="*"))l[f]==="*"?(m=f,h=u,f++):(u++,f++);else if(m!==-1)f=m+1,h++,u=h;else return!1;for(;f<l.length&&l[f]==="*";)f++;return f===l.length}function o(){let p=[...t.names,...t.skips.map(l=>"-"+l)].join(",");return t.enable(""),p}function a(p){for(let l of t.skips)if(i(p,l))return!1;for(let l of t.names)if(i(p,l))return!0;return!1}function c(p){return p instanceof Error?p.stack||p.message:p}function d(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.enable(t.load()),t}Ns.exports=so});var js=C((W,It)=>{"use strict";W.formatArgs=io;W.save=oo;W.load=ao;W.useColors=no;W.storage=co();W.destroy=(()=>{let s=!1;return()=>{s||(s=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();W.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 no(){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 s;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&&(s=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(s[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function io(s){if(s[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+s[0]+(this.useColors?"%c ":" ")+"+"+It.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;s.splice(1,0,e,"color: inherit");let t=0,r=0;s[0].replace(/%[a-zA-Z%]/g,n=>{n!=="%%"&&(t++,n==="%c"&&(r=t))}),s.splice(r,0,e)}W.log=console.debug||console.log||(()=>{});function oo(s){try{s?W.storage.setItem("debug",s):W.storage.removeItem("debug")}catch{}}function ao(){let s;try{s=W.storage.getItem("debug")||W.storage.getItem("DEBUG")}catch{}return!s&&typeof process<"u"&&"env"in process&&(s=process.env.DEBUG),s}function co(){try{return localStorage}catch{}}It.exports=Sr()(W);var{formatters:po}=It.exports;po.j=function(s){try{return JSON.stringify(s)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var qs={};Is(qs,{createSupportsColor:()=>Cr,default:()=>mo});function J(s,e=globalThis.Deno?globalThis.Deno.args:Mt.default.argv){let t=s.startsWith("-")?"":s.length===1?"-":"--",r=e.indexOf(t+s),n=e.indexOf("--");return r!==-1&&(n===-1||r<n)}function lo(){if(!("FORCE_COLOR"in O))return;if(O.FORCE_COLOR==="true")return 1;if(O.FORCE_COLOR==="false")return 0;if(O.FORCE_COLOR.length===0)return 1;let s=Math.min(Number.parseInt(O.FORCE_COLOR,10),3);if([0,1,2,3].includes(s))return s}function uo(s){return s===0?!1:{level:s,hasBasic:!0,has256:s>=2,has16m:s>=3}}function ho(s,{streamIsTTY:e,sniffFlags:t=!0}={}){let r=lo();r!==void 0&&(Lt=r);let n=t?Lt:r;if(n===0)return 0;if(t){if(J("color=16m")||J("color=full")||J("color=truecolor"))return 3;if(J("color=256"))return 2}if("TF_BUILD"in O&&"AGENT_NAME"in O)return 1;if(s&&!e&&n===void 0)return 0;let i=n||0;if(O.TERM==="dumb")return i;if(Mt.default.platform==="win32"){let o=Fs.default.release().split(".");return Number(o[0])>=10&&Number(o[2])>=10586?Number(o[2])>=14931?3:2:1}if("CI"in O)return["GITHUB_ACTIONS","GITEA_ACTIONS","CIRCLECI"].some(o=>o in O)?3:["TRAVIS","APPVEYOR","GITLAB_CI","BUILDKITE","DRONE"].some(o=>o in O)||O.CI_NAME==="codeship"?1:i;if("TEAMCITY_VERSION"in O)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(O.TEAMCITY_VERSION)?1:0;if(O.COLORTERM==="truecolor"||O.TERM==="xterm-kitty"||O.TERM==="xterm-ghostty"||O.TERM==="wezterm")return 3;if("TERM_PROGRAM"in O){let o=Number.parseInt((O.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(O.TERM_PROGRAM){case"iTerm.app":return o>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(O.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(O.TERM)||"COLORTERM"in O?1:i}function Cr(s,e={}){let t=ho(s,{streamIsTTY:s&&s.isTTY,...e});return uo(t)}var Mt,Fs,Rr,O,Lt,fo,mo,$s=Ji(()=>{"use strict";Mt=Se(require("process"),1),Fs=Se(require("os"),1),Rr=Se(require("tty"),1);({env:O}=Mt.default);J("no-color")||J("no-colors")||J("color=false")||J("color=never")?Lt=0:(J("color")||J("colors")||J("color=true")||J("color=always"))&&(Lt=1);fo={stdout:Cr({isTTY:Rr.default.isatty(1)}),stderr:Cr({isTTY:Rr.default.isatty(2)})},mo=fo});var zs=C((F,At)=>{"use strict";var go=require("tty"),Ot=require("util");F.init=Ro;F.log=yo;F.formatArgs=vo;F.save=bo;F.load=So;F.useColors=_o;F.destroy=Ot.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");F.colors=[6,2,3,4,5,1];try{let s=($s(),Ms(qs));s&&(s.stderr||s).level>=2&&(F.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{}F.inspectOpts=Object.keys(process.env).filter(s=>/^debug_/i.test(s)).reduce((s,e)=>{let t=e.substring(6).toLowerCase().replace(/_([a-z])/g,(n,i)=>i.toUpperCase()),r=process.env[e];return/^(yes|on|true|enabled)$/i.test(r)?r=!0:/^(no|off|false|disabled)$/i.test(r)?r=!1:r==="null"?r=null:r=Number(r),s[t]=r,s},{});function _o(){return"colors"in F.inspectOpts?!!F.inspectOpts.colors:go.isatty(process.stderr.fd)}function vo(s){let{namespace:e,useColors:t}=this;if(t){let r=this.color,n="\x1B[3"+(r<8?r:"8;5;"+r),i=` ${n};1m${e} \x1B[0m`;s[0]=i+s[0].split(`
1
+ "use strict";var aN=Object.create;var n0=Object.defineProperty;var cN=Object.getOwnPropertyDescriptor;var dN=Object.getOwnPropertyNames;var uN=Object.getPrototypeOf,fN=Object.prototype.hasOwnProperty;var T=(r,e,t)=>()=>{if(t)throw t[0];try{return r&&(e=r(r=0)),e}catch(s){throw t=[s],s}};var re=(r,e)=>()=>{try{return e||r((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}},Ef=(r,e)=>{for(var t in e)n0(r,t,{get:e[t],enumerable:!0})},vE=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of dN(e))!fN.call(r,n)&&n!==t&&n0(r,n,{get:()=>e[n],enumerable:!(s=cN(e,n))||s.enumerable});return r};var Ge=(r,e,t)=>(t=r!=null?aN(uN(r)):{},vE(e||!r||!r.__esModule?n0(t,"default",{value:r,enumerable:!0}):t,r)),kx=r=>vE(n0({},"__esModule",{value:!0}),r);var Px=re((WV,wE)=>{"use strict";var md=1e3,gd=md*60,yd=gd*60,Ra=yd*24,lN=Ra*7,hN=Ra*365.25;wE.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return pN(r);if(t==="number"&&isFinite(r))return e.long?gN(r):mN(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function pN(r){if(r=String(r),!(r.length>100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(r);if(e){var t=parseFloat(e[1]),s=(e[2]||"ms").toLowerCase();switch(s){case"years":case"year":case"yrs":case"yr":case"y":return t*hN;case"weeks":case"week":case"w":return t*lN;case"days":case"day":case"d":return t*Ra;case"hours":case"hour":case"hrs":case"hr":case"h":return t*yd;case"minutes":case"minute":case"mins":case"min":case"m":return t*gd;case"seconds":case"second":case"secs":case"sec":case"s":return t*md;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function mN(r){var e=Math.abs(r);return e>=Ra?Math.round(r/Ra)+"d":e>=yd?Math.round(r/yd)+"h":e>=gd?Math.round(r/gd)+"m":e>=md?Math.round(r/md)+"s":r+"ms"}function gN(r){var e=Math.abs(r);return e>=Ra?i0(r,e,Ra,"day"):e>=yd?i0(r,e,yd,"hour"):e>=gd?i0(r,e,gd,"minute"):e>=md?i0(r,e,md,"second"):r+" ms"}function i0(r,e,t,s){var n=e>=t*1.5;return Math.round(r/t)+" "+s+(n?"s":"")}});var Bx=re((GV,SE)=>{"use strict";function yN(r){t.debug=t,t.default=t,t.coerce=c,t.disable=o,t.enable=n,t.enabled=a,t.humanize=Px(),t.destroy=d,Object.keys(r).forEach(u=>{t[u]=r[u]}),t.names=[],t.skips=[],t.formatters={};function e(u){let f=0;for(let h=0;h<u.length;h++)f=(f<<5)-f+u.charCodeAt(h),f|=0;return t.colors[Math.abs(f)%t.colors.length]}t.selectColor=e;function t(u){let f,h=null,y,v;function S(...C){if(!S.enabled)return;let O=S,K=Number(new Date),z=K-(f||K);O.diff=z,O.prev=f,O.curr=K,f=K,C[0]=t.coerce(C[0]),typeof C[0]!="string"&&C.unshift("%O");let Q=0;C[0]=C[0].replace(/%([a-zA-Z%])/g,(se,we)=>{if(se==="%%")return"%";Q++;let me=t.formatters[we];if(typeof me=="function"){let Y=C[Q];se=me.call(O,Y),C.splice(Q,1),Q--}return se}),t.formatArgs.call(O,C),(O.log||t.log).apply(O,C)}return S.namespace=u,S.useColors=t.useColors(),S.color=t.selectColor(u),S.extend=s,S.destroy=t.destroy,Object.defineProperty(S,"enabled",{enumerable:!0,configurable:!1,get:()=>h!==null?h:(y!==t.namespaces&&(y=t.namespaces,v=t.enabled(u)),v),set:C=>{h=C}}),typeof t.init=="function"&&t.init(S),S}function s(u,f){let h=t(this.namespace+(typeof f>"u"?":":f)+u);return h.log=this.log,h}function n(u){t.save(u),t.namespaces=u,t.names=[],t.skips=[];let f=(typeof u=="string"?u:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let h of f)h[0]==="-"?t.skips.push(h.slice(1)):t.names.push(h)}function i(u,f){let h=0,y=0,v=-1,S=0;for(;h<u.length;)if(y<f.length&&(f[y]===u[h]||f[y]==="*"))f[y]==="*"?(v=y,S=h,y++):(h++,y++);else if(v!==-1)y=v+1,S++,h=S;else return!1;for(;y<f.length&&f[y]==="*";)y++;return y===f.length}function o(){let u=[...t.names,...t.skips.map(f=>"-"+f)].join(",");return t.enable(""),u}function a(u){for(let f of t.skips)if(i(u,f))return!1;for(let f of t.names)if(i(u,f))return!0;return!1}function c(u){return u instanceof Error?u.stack||u.message:u}function d(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.enable(t.load()),t}SE.exports=yN});var _E=re((os,o0)=>{"use strict";os.formatArgs=bN;os.save=vN;os.load=wN;os.useColors=xN;os.storage=SN();os.destroy=(()=>{let r=!1;return()=>{r||(r=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();os.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 xN(){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 r;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&&(r=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(r[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function bN(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+o0.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,s=0;r[0].replace(/%[a-zA-Z%]/g,n=>{n!=="%%"&&(t++,n==="%c"&&(s=t))}),r.splice(s,0,e)}os.log=console.debug||console.log||(()=>{});function vN(r){try{r?os.storage.setItem("debug",r):os.storage.removeItem("debug")}catch{}}function wN(){let r;try{r=os.storage.getItem("debug")||os.storage.getItem("DEBUG")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function SN(){try{return localStorage}catch{}}o0.exports=Bx()(os);var{formatters:_N}=o0.exports;_N.j=function(r){try{return JSON.stringify(r)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var Lx={};Ef(Lx,{createSupportsColor:()=>Ox,default:()=>IN});function Os(r,e=globalThis.Deno?globalThis.Deno.args:c0.default.argv){let t=r.startsWith("-")?"":r.length===1?"-":"--",s=e.indexOf(t+r),n=e.indexOf("--");return s!==-1&&(n===-1||s<n)}function EN(){if(!("FORCE_COLOR"in Jt))return;if(Jt.FORCE_COLOR==="true")return 1;if(Jt.FORCE_COLOR==="false")return 0;if(Jt.FORCE_COLOR.length===0)return 1;let r=Math.min(Number.parseInt(Jt.FORCE_COLOR,10),3);if([0,1,2,3].includes(r))return r}function CN(r){return r===0?!1:{level:r,hasBasic:!0,has256:r>=2,has16m:r>=3}}function TN(r,{streamIsTTY:e,sniffFlags:t=!0}={}){let s=EN();s!==void 0&&(a0=s);let n=t?a0:s;if(n===0)return 0;if(t){if(Os("color=16m")||Os("color=full")||Os("color=truecolor"))return 3;if(Os("color=256"))return 2}if("TF_BUILD"in Jt&&"AGENT_NAME"in Jt)return 1;if(r&&!e&&n===void 0)return 0;let i=n||0;if(Jt.TERM==="dumb")return i;if(c0.default.platform==="win32"){let o=EE.default.release().split(".");return Number(o[0])>=10&&Number(o[2])>=10586?Number(o[2])>=14931?3:2:1}if("CI"in Jt)return["GITHUB_ACTIONS","GITEA_ACTIONS","CIRCLECI"].some(o=>o in Jt)?3:["TRAVIS","APPVEYOR","GITLAB_CI","BUILDKITE","DRONE"].some(o=>o in Jt)||Jt.CI_NAME==="codeship"?1:i;if("TEAMCITY_VERSION"in Jt)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(Jt.TEAMCITY_VERSION)?1:0;if(Jt.COLORTERM==="truecolor"||Jt.TERM==="xterm-kitty"||Jt.TERM==="xterm-ghostty"||Jt.TERM==="wezterm")return 3;if("TERM_PROGRAM"in Jt){let o=Number.parseInt((Jt.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(Jt.TERM_PROGRAM){case"iTerm.app":return o>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(Jt.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(Jt.TERM)||"COLORTERM"in Jt?1:i}function Ox(r,e={}){let t=TN(r,{streamIsTTY:r&&r.isTTY,...e});return CN(t)}var c0,EE,Nx,Jt,a0,AN,IN,Dx=T(()=>{"use strict";c0=Ge(require("process"),1),EE=Ge(require("os"),1),Nx=Ge(require("tty"),1);({env:Jt}=c0.default);Os("no-color")||Os("no-colors")||Os("color=false")||Os("color=never")?a0=0:(Os("color")||Os("colors")||Os("color=true")||Os("color=always"))&&(a0=1);AN={stdout:Ox({isTTY:Nx.default.isatty(1)}),stderr:Ox({isTTY:Nx.default.isatty(2)})},IN=AN});var TE=re((Sr,u0)=>{"use strict";var RN=require("tty"),d0=require("util");Sr.init=DN;Sr.log=NN;Sr.formatArgs=PN;Sr.save=ON;Sr.load=LN;Sr.useColors=kN;Sr.destroy=d0.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");Sr.colors=[6,2,3,4,5,1];try{let r=(Dx(),kx(Lx));r&&(r.stderr||r).level>=2&&(Sr.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{}Sr.inspectOpts=Object.keys(process.env).filter(r=>/^debug_/i.test(r)).reduce((r,e)=>{let t=e.substring(6).toLowerCase().replace(/_([a-z])/g,(n,i)=>i.toUpperCase()),s=process.env[e];return/^(yes|on|true|enabled)$/i.test(s)?s=!0:/^(no|off|false|disabled)$/i.test(s)?s=!1:s==="null"?s=null:s=Number(s),r[t]=s,r},{});function kN(){return"colors"in Sr.inspectOpts?!!Sr.inspectOpts.colors:RN.isatty(process.stderr.fd)}function PN(r){let{namespace:e,useColors:t}=this;if(t){let s=this.color,n="\x1B[3"+(s<8?s:"8;5;"+s),i=` ${n};1m${e} \x1B[0m`;r[0]=i+r[0].split(`
2
2
  `).join(`
3
- `+i),s.push(n+"m+"+At.exports.humanize(this.diff)+"\x1B[0m")}else s[0]=wo()+e+" "+s[0]}function wo(){return F.inspectOpts.hideDate?"":new Date().toISOString()+" "}function yo(...s){return process.stderr.write(Ot.formatWithOptions(F.inspectOpts,...s)+`
4
- `)}function bo(s){s?process.env.DEBUG=s:delete process.env.DEBUG}function So(){return process.env.DEBUG}function Ro(s){s.inspectOpts={};let e=Object.keys(F.inspectOpts);for(let t=0;t<e.length;t++)s.inspectOpts[e[t]]=F.inspectOpts[e[t]]}At.exports=Sr()(F);var{formatters:Us}=At.exports;Us.o=function(s){return this.inspectOpts.colors=this.useColors,Ot.inspect(s,this.inspectOpts).split(`
5
- `).map(e=>e.trim()).join(" ")};Us.O=function(s){return this.inspectOpts.colors=this.useColors,Ot.inspect(s,this.inspectOpts)}});var ut=C((Jd,Tr)=>{"use strict";typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?Tr.exports=js():Tr.exports=zs()});var Hs=C(Bs=>{"use strict";Object.defineProperty(Bs,"__esModule",{value:!0})});var z=C(Nt=>{"use strict";Object.defineProperty(Nt,"__esModule",{value:!0});Nt.Logger=void 0;var Ue=ut(),ze="media-client",Er=class{_debug;_warn;_error;constructor(e){e?(this._debug=(0,Ue.default)(`${ze}:${e}`),this._warn=(0,Ue.default)(`${ze}:WARN:${e}`),this._error=(0,Ue.default)(`${ze}:ERROR:${e}`)):(this._debug=(0,Ue.default)(ze),this._warn=(0,Ue.default)(`${ze}:WARN`),this._error=(0,Ue.default)(`${ze}:ERROR`)),this._debug.log=console.info.bind(console),this._warn.log=console.warn.bind(console),this._error.log=console.error.bind(console)}get debug(){return this._debug}get warn(){return this._warn}get error(){return this._error}};Nt.Logger=Er});var tn=C((ep,kr)=>{"use strict";var Be=typeof Reflect=="object"?Reflect:null,Vs=Be&&typeof Be.apply=="function"?Be.apply:function(e,t,r){return Function.prototype.apply.call(e,t,r)},jt;Be&&typeof Be.ownKeys=="function"?jt=Be.ownKeys:Object.getOwnPropertySymbols?jt=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:jt=function(e){return Object.getOwnPropertyNames(e)};function Co(s){console&&console.warn&&console.warn(s)}var Gs=Number.isNaN||function(e){return e!==e};function L(){L.init.call(this)}kr.exports=L;kr.exports.once=xo;L.EventEmitter=L;L.prototype._events=void 0;L.prototype._eventsCount=0;L.prototype._maxListeners=void 0;var Ws=10;function Ft(s){if(typeof s!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof s)}Object.defineProperty(L,"defaultMaxListeners",{enumerable:!0,get:function(){return Ws},set:function(s){if(typeof s!="number"||s<0||Gs(s))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+s+".");Ws=s}});L.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};L.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||Gs(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this};function Ks(s){return s._maxListeners===void 0?L.defaultMaxListeners:s._maxListeners}L.prototype.getMaxListeners=function(){return Ks(this)};L.prototype.emit=function(e){for(var t=[],r=1;r<arguments.length;r++)t.push(arguments[r]);var n=e==="error",i=this._events;if(i!==void 0)n=n&&i.error===void 0;else if(!n)return!1;if(n){var o;if(t.length>0&&(o=t[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var c=i[e];if(c===void 0)return!1;if(typeof c=="function")Vs(c,this,t);else for(var d=c.length,p=Zs(c,d),r=0;r<d;++r)Vs(p[r],this,t);return!0};function Qs(s,e,t,r){var n,i,o;if(Ft(t),i=s._events,i===void 0?(i=s._events=Object.create(null),s._eventsCount=0):(i.newListener!==void 0&&(s.emit("newListener",e,t.listener?t.listener:t),i=s._events),o=i[e]),o===void 0)o=i[e]=t,++s._eventsCount;else if(typeof o=="function"?o=i[e]=r?[t,o]:[o,t]:r?o.unshift(t):o.push(t),n=Ks(s),n>0&&o.length>n&&!o.warned){o.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=s,a.type=e,a.count=o.length,Co(a)}return s}L.prototype.addListener=function(e,t){return Qs(this,e,t,!1)};L.prototype.on=L.prototype.addListener;L.prototype.prependListener=function(e,t){return Qs(this,e,t,!0)};function To(){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 Ys(s,e,t){var r={fired:!1,wrapFn:void 0,target:s,type:e,listener:t},n=To.bind(r);return n.listener=t,r.wrapFn=n,n}L.prototype.once=function(e,t){return Ft(t),this.on(e,Ys(this,e,t)),this};L.prototype.prependOnceListener=function(e,t){return Ft(t),this.prependListener(e,Ys(this,e,t)),this};L.prototype.removeListener=function(e,t){var r,n,i,o,a;if(Ft(t),n=this._events,n===void 0)return this;if(r=n[e],r===void 0)return this;if(r===t||r.listener===t)--this._eventsCount===0?this._events=Object.create(null):(delete n[e],n.removeListener&&this.emit("removeListener",e,r.listener||t));else if(typeof r!="function"){for(i=-1,o=r.length-1;o>=0;o--)if(r[o]===t||r[o].listener===t){a=r[o].listener,i=o;break}if(i<0)return this;i===0?r.shift():Eo(r,i),r.length===1&&(n[e]=r[0]),n.removeListener!==void 0&&this.emit("removeListener",e,a||t)}return this};L.prototype.off=L.prototype.removeListener;L.prototype.removeAllListeners=function(e){var t,r,n;if(r=this._events,r===void 0)return this;if(r.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):r[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete r[e]),this;if(arguments.length===0){var i=Object.keys(r),o;for(n=0;n<i.length;++n)o=i[n],o!=="removeListener"&&this.removeAllListeners(o);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(t=r[e],typeof t=="function")this.removeListener(e,t);else if(t!==void 0)for(n=t.length-1;n>=0;n--)this.removeListener(e,t[n]);return this};function Js(s,e,t){var r=s._events;if(r===void 0)return[];var n=r[e];return n===void 0?[]:typeof n=="function"?t?[n.listener||n]:[n]:t?ko(n):Zs(n,n.length)}L.prototype.listeners=function(e){return Js(this,e,!0)};L.prototype.rawListeners=function(e){return Js(this,e,!1)};L.listenerCount=function(s,e){return typeof s.listenerCount=="function"?s.listenerCount(e):Xs.call(s,e)};L.prototype.listenerCount=Xs;function Xs(s){var e=this._events;if(e!==void 0){var t=e[s];if(typeof t=="function")return 1;if(t!==void 0)return t.length}return 0}L.prototype.eventNames=function(){return this._eventsCount>0?jt(this._events):[]};function Zs(s,e){for(var t=new Array(e),r=0;r<e;++r)t[r]=s[r];return t}function Eo(s,e){for(;e+1<s.length;e++)s[e]=s[e+1];s.pop()}function ko(s){for(var e=new Array(s.length),t=0;t<e.length;++t)e[t]=s[t].listener||s[t];return e}function xo(s,e){return new Promise(function(t,r){function n(o){s.removeListener(e,i),r(o)}function i(){typeof s.removeListener=="function"&&s.removeListener("error",n),t([].slice.call(arguments))}en(s,e,i,{once:!0}),e!=="error"&&Po(s,n,{once:!0})})}function Po(s,e,t){typeof s.on=="function"&&en(s,"error",e,t)}function en(s,e,t,r){if(typeof s.on=="function")r.once?s.once(e,t):s.on(e,t);else if(typeof s.addEventListener=="function")s.addEventListener(e,function n(i){r.once&&s.removeEventListener(e,n),t(i)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof s)}});var G=C(qt=>{"use strict";Object.defineProperty(qt,"__esModule",{value:!0});qt.EnhancedEventEmitter=void 0;var Do=tn(),Io=z(),Lo=new Io.Logger("EnhancedEventEmitter"),xr=class extends Do.EventEmitter{constructor(){super(),this.setMaxListeners(1/0)}close(){super.removeAllListeners()}emit(e,...t){return super.emit(e,...t)}safeEmit(e,...t){try{return super.emit(e,...t)}catch(r){Lo.error("safeEmit() | event listener threw an error [eventName:%s]:%o",e,r);try{super.emit("listenererror",e,r)}catch{}return!!super.listenerCount(e)}}on(e,t){return super.on(e,t),this}off(e,t){return super.off(e,t),this}addListener(e,t){return super.on(e,t),this}prependListener(e,t){return super.prependListener(e,t),this}once(e,t){return super.once(e,t),this}prependOnceListener(e,t){return super.prependOnceListener(e,t),this}removeListener(e,t){return super.off(e,t),this}removeAllListeners(e){return super.removeAllListeners(e),this}listenerCount(e){return super.listenerCount(e)}listeners(e){return super.listeners(e)}rawListeners(e){return super.rawListeners(e)}};qt.EnhancedEventEmitter=xr});var X=C(He=>{"use strict";Object.defineProperty(He,"__esModule",{value:!0});He.InvalidStateError=He.UnsupportedError=void 0;var Pr=class s extends Error{constructor(e){super(e),this.name="UnsupportedError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,s):this.stack=new Error(e).stack}};He.UnsupportedError=Pr;var Dr=class s extends Error{constructor(e){super(e),this.name="InvalidStateError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,s):this.stack=new Error(e).stack}};He.InvalidStateError=Dr});var ke=C(ht=>{"use strict";Object.defineProperty(ht,"__esModule",{value:!0});ht.clone=Mo;ht.generateRandomNumber=Oo;ht.deepFreeze=rn;function Mo(s){if(s!==void 0)return Number.isNaN(s)?NaN:typeof structuredClone=="function"?structuredClone(s):JSON.parse(JSON.stringify(s))}function Oo(){return Math.round(Math.random()*1e7)}function rn(s){let e=Reflect.ownKeys(s);for(let t of e){let r=s[t];(r&&typeof r=="object"||typeof r=="function")&&rn(r)}return Object.freeze(s)}});var sn=C($t=>{"use strict";Object.defineProperty($t,"__esModule",{value:!0});$t.Logger=void 0;var Ve=ut(),We="h264-profile-level-id",Ir=class{_debug;_warn;_error;constructor(e){e?(this._debug=(0,Ve.default)(`${We}:${e}`),this._warn=(0,Ve.default)(`${We}:WARN:${e}`),this._error=(0,Ve.default)(`${We}:ERROR:${e}`)):(this._debug=(0,Ve.default)(We),this._warn=(0,Ve.default)(`${We}:WARN`),this._error=(0,Ve.default)(`${We}:ERROR`)),this._debug.log=console.info.bind(console),this._warn.log=console.warn.bind(console),this._error.log=console.error.bind(console)}get debug(){return this._debug}get warn(){return this._warn}get error(){return this._error}};$t.Logger=Ir});var pn=C(q=>{"use strict";Object.defineProperty(q,"__esModule",{value:!0});q.ProfileLevelId=q.Level=q.Profile=void 0;q.parseProfileLevelId=cn;q.profileLevelIdToString=dn;q.profileToString=Fo;q.levelToString=qo;q.parseSdpProfileLevelId=xe;q.isSameProfile=$o;q.isSameProfileAndLevel=Uo;q.generateProfileLevelIdStringForAnswer=zo;q.supportedLevel=Bo;var Ao=sn(),ie=new Ao.Logger,M;(function(s){s[s.ConstrainedBaseline=1]="ConstrainedBaseline",s[s.Baseline=2]="Baseline",s[s.Main=3]="Main",s[s.ConstrainedHigh=4]="ConstrainedHigh",s[s.High=5]="High",s[s.PredictiveHigh444=6]="PredictiveHigh444"})(M||(q.Profile=M={}));var v;(function(s){s[s.L1_b=0]="L1_b",s[s.L1=10]="L1",s[s.L1_1=11]="L1_1",s[s.L1_2=12]="L1_2",s[s.L1_3=13]="L1_3",s[s.L2=20]="L2",s[s.L2_1=21]="L2_1",s[s.L2_2=22]="L2_2",s[s.L3=30]="L3",s[s.L3_1=31]="L3_1",s[s.L3_2=32]="L3_2",s[s.L4=40]="L4",s[s.L4_1=41]="L4_1",s[s.L4_2=42]="L4_2",s[s.L5=50]="L5",s[s.L5_1=51]="L5_1",s[s.L5_2=52]="L5_2"})(v||(q.Level=v={}));var Ge=class{profile;level;constructor(e,t){this.profile=e,this.level=t}};q.ProfileLevelId=Ge;var No=new Ge(M.ConstrainedBaseline,v.L3_1),se=class{mask;masked_value;constructor(e){this.mask=~on("x",e),this.masked_value=on("1",e)}isMatch(e){return this.masked_value===(e&this.mask)}},ne=class{profile_idc;profile_iop;profile;constructor(e,t,r){this.profile_idc=e,this.profile_iop=t,this.profile=r}},jo=[new ne(66,new se("x1xx0000"),M.ConstrainedBaseline),new ne(77,new se("1xxx0000"),M.ConstrainedBaseline),new ne(88,new se("11xx0000"),M.ConstrainedBaseline),new ne(66,new se("x0xx0000"),M.Baseline),new ne(88,new se("10xx0000"),M.Baseline),new ne(77,new se("0x0x0000"),M.Main),new ne(100,new se("00000000"),M.High),new ne(100,new se("00001100"),M.ConstrainedHigh),new ne(244,new se("00000000"),M.PredictiveHigh444)],nn=[{max_macroblocks_per_second:1485,max_macroblock_frame_size:99,level:v.L1},{max_macroblocks_per_second:1485,max_macroblock_frame_size:99,level:v.L1_b},{max_macroblocks_per_second:3e3,max_macroblock_frame_size:396,level:v.L1_1},{max_macroblocks_per_second:6e3,max_macroblock_frame_size:396,level:v.L1_2},{max_macroblocks_per_second:11880,max_macroblock_frame_size:396,level:v.L1_3},{max_macroblocks_per_second:11880,max_macroblock_frame_size:396,level:v.L2},{max_macroblocks_per_second:19800,max_macroblock_frame_size:792,level:v.L2_1},{max_macroblocks_per_second:20250,max_macroblock_frame_size:1620,level:v.L2_2},{max_macroblocks_per_second:40500,max_macroblock_frame_size:1620,level:v.L3},{max_macroblocks_per_second:108e3,max_macroblock_frame_size:3600,level:v.L3_1},{max_macroblocks_per_second:216e3,max_macroblock_frame_size:5120,level:v.L3_2},{max_macroblocks_per_second:245760,max_macroblock_frame_size:8192,level:v.L4},{max_macroblocks_per_second:245760,max_macroblock_frame_size:8192,level:v.L4_1},{max_macroblocks_per_second:522240,max_macroblock_frame_size:8704,level:v.L4_2},{max_macroblocks_per_second:589824,max_macroblock_frame_size:22080,level:v.L5},{max_macroblocks_per_second:983040,max_macroblock_frame_size:36864,level:v.L5_1},{max_macroblocks_per_second:2073600,max_macroblock_frame_size:36864,level:v.L5_2}];function cn(s){if(typeof s!="string"||s.length!==6)return;let t=parseInt(s,16);if(t===0)return;let r=t&255,n=t>>8&255,i=t>>16&255,o;switch(r){case v.L1_1:{o=(n&16)!==0?v.L1_b:v.L1_1;break}case v.L1:case v.L1_2:case v.L1_3:case v.L2:case v.L2_1:case v.L2_2:case v.L3:case v.L3_1:case v.L3_2:case v.L4:case v.L4_1:case v.L4_2:case v.L5:case v.L5_1:case v.L5_2:{o=r;break}default:{ie.warn(`parseProfileLevelId() | unrecognized level_idc [str:${s}, level_idc:${r}]`);return}}for(let a of jo)if(i===a.profile_idc&&a.profile_iop.isMatch(n))return ie.debug(`parseProfileLevelId() | result [str:${s}, profile:${a.profile}, level:${o}]`),new Ge(a.profile,o);ie.warn(`parseProfileLevelId() | unrecognized profile_idc/profile_iop combination [str:${s}, profile_idc:${i}, profile_iop:${n}]`)}function dn(s){if(s.level==v.L1_b)switch(s.profile){case M.ConstrainedBaseline:return"42f00b";case M.Baseline:return"42100b";case M.Main:return"4d100b";default:{ie.warn(`profileLevelIdToString() | Level 1_b not is allowed for profile ${s.profile}`);return}}let e;switch(s.profile){case M.ConstrainedBaseline:{e="42e0";break}case M.Baseline:{e="4200";break}case M.Main:{e="4d00";break}case M.ConstrainedHigh:{e="640c";break}case M.High:{e="6400";break}case M.PredictiveHigh444:{e="f400";break}default:{ie.warn(`profileLevelIdToString() | unrecognized profile ${s.profile}`);return}}let t=s.level.toString(16);return t.length===1&&(t=`0${t}`),`${e}${t}`}function Fo(s){switch(s){case M.ConstrainedBaseline:return"ConstrainedBaseline";case M.Baseline:return"Baseline";case M.Main:return"Main";case M.ConstrainedHigh:return"ConstrainedHigh";case M.High:return"High";case M.PredictiveHigh444:return"PredictiveHigh444";default:{ie.warn(`profileToString() | unrecognized profile ${s}`);return}}}function qo(s){switch(s){case v.L1_b:return"1b";case v.L1:return"1";case v.L1_1:return"1.1";case v.L1_2:return"1.2";case v.L1_3:return"1.3";case v.L2:return"2";case v.L2_1:return"2.1";case v.L2_2:return"2.2";case v.L3:return"3";case v.L3_1:return"3.1";case v.L3_2:return"3.2";case v.L4:return"4";case v.L4_1:return"4.1";case v.L4_2:return"4.2";case v.L5:return"5";case v.L5_1:return"5.1";case v.L5_2:return"5.2";default:{ie.warn(`levelToString() | unrecognized level ${s}`);return}}}function xe(s={}){let e=s["profile-level-id"];return e?cn(e):No}function $o(s={},e={}){let t=xe(s),r=xe(e);return!!(t&&r&&t.profile===r.profile)}function Uo(s={},e={}){let t=xe(s),r=xe(e);return!!(t&&r&&t.profile===r.profile&&t.level==r.level)}function zo(s={},e={}){if(!s["profile-level-id"]&&!e["profile-level-id"]){ie.warn("generateProfileLevelIdStringForAnswer() | profile-level-id missing in local and remote params");return}let t=xe(s),r=xe(e);if(!t)throw new TypeError("invalid local_profile_level_id");if(!r)throw new TypeError("invalid remote_profile_level_id");if(t.profile!==r.profile)throw new TypeError("H264 Profile mismatch");let n=an(s)&&an(e),i=t.level,o=r.level,a=Vo(i,o),c=n?i:a;return ie.debug(`generateProfileLevelIdStringForAnswer() | result [profile:${t.profile}, level:${c}]`),dn(new Ge(t.profile,c))}function Bo(s,e){for(let r=nn.length-1;r>=0;--r){let n=nn[r];if(n.max_macroblock_frame_size*256<=s&&n.max_macroblocks_per_second<=e*n.max_macroblock_frame_size)return ie.debug(`supportedLevel() | result [max_frame_pixel_count:${s}, max_fps:${e}, level:${n.level}]`),n.level}ie.warn(`supportedLevel() | no level supported [max_frame_pixel_count:${s}, max_fps:${e}]`)}function on(s,e){return+(e[0]===s)<<7|+(e[1]===s)<<6|+(e[2]===s)<<5|+(e[3]===s)<<4|+(e[4]===s)<<3|+(e[5]===s)<<2|+(e[6]===s)<<1|+(e[7]===s)<<0}function Ho(s,e){return s===v.L1_b?e!==v.L1&&e!==v.L1_b:e===v.L1_b?s!==v.L1:s<e}function Vo(s,e){return Ho(s,e)?s:e}function an(s={}){let e=s["level-asymmetry-allowed"];return e===!0||e===1||e==="1"}});var ae=C(B=>{"use strict";Object.defineProperty(B,"__esModule",{value:!0});B.validateAndNormalizeRtpCapabilities=Yo;B.validateAndNormalizeRtpParameters=Mr;B.validateAndNormalizeSctpStreamParameters=Jo;B.validateSctpCapabilities=Xo;B.getExtendedRtpCapabilities=Zo;B.getRecvRtpCapabilities=ea;B.getSendRtpCapabilities=ta;B.getSendingRtpParameters=ra;B.getSendingRemoteRtpParameters=sa;B.reduceCodecs=na;B.generateProbatorRtpParameters=ia;B.canSend=oa;B.canReceive=aa;var ln=pn(),Wo=ke(),Go="probator",Ko=1234,Qo=127;function Yo(s){if(typeof s!="object")throw new TypeError("caps is not an object");if(s.codecs&&!Array.isArray(s.codecs))throw new TypeError("caps.codecs is not an array");s.codecs||(s.codecs=[]);for(let e of s.codecs)ca(e);if(s.headerExtensions&&!Array.isArray(s.headerExtensions))throw new TypeError("caps.headerExtensions is not an array");s.headerExtensions||(s.headerExtensions=[]);for(let e of s.headerExtensions)da(e)}function Mr(s){if(typeof s!="object")throw new TypeError("params is not an object");if(s.mid&&typeof s.mid!="string")throw new TypeError("params.mid is not a string");if(!Array.isArray(s.codecs))throw new TypeError("missing params.codecs");for(let e of s.codecs)pa(e);if(s.headerExtensions&&!Array.isArray(s.headerExtensions))throw new TypeError("params.headerExtensions is not an array");s.headerExtensions||(s.headerExtensions=[]);for(let e of s.headerExtensions)la(e);if(s.encodings&&!Array.isArray(s.encodings))throw new TypeError("params.encodings is not an array");s.encodings||(s.encodings=[]);for(let e of s.encodings)ua(e);if(s.rtcp&&typeof s.rtcp!="object")throw new TypeError("params.rtcp is not an object");s.rtcp||(s.rtcp={}),ha(s.rtcp)}function Jo(s){if(typeof s!="object")throw new TypeError("params is not an object");if(typeof s.streamId!="number")throw new TypeError("missing params.streamId");let e=!1;if(typeof s.ordered=="boolean"?e=!0:s.ordered=!0,s.maxPacketLifeTime&&typeof s.maxPacketLifeTime!="number")throw new TypeError("invalid params.maxPacketLifeTime");if(s.maxRetransmits&&typeof s.maxRetransmits!="number")throw new TypeError("invalid params.maxRetransmits");if(s.maxPacketLifeTime&&s.maxRetransmits)throw new TypeError("cannot provide both maxPacketLifeTime and maxRetransmits");if(e&&s.ordered&&(s.maxPacketLifeTime||s.maxRetransmits))throw new TypeError("cannot be ordered with maxPacketLifeTime or maxRetransmits");if(!e&&(s.maxPacketLifeTime||s.maxRetransmits)&&(s.ordered=!1),s.label&&typeof s.label!="string")throw new TypeError("invalid params.label");if(s.protocol&&typeof s.protocol!="string")throw new TypeError("invalid params.protocol")}function Xo(s){if(typeof s!="object")throw new TypeError("caps is not an object");if(!s.numStreams||typeof s.numStreams!="object")throw new TypeError("missing caps.numStreams");fa(s.numStreams)}function Zo(s,e,t){let r={codecs:[],headerExtensions:[]};if(t)for(let n of s.codecs??[]){if(Ke(n))continue;let i=(e.codecs??[]).find(a=>Lr(a,n,{strict:!0,modify:!0}));if(!i)continue;let o={kind:n.kind,mimeType:n.mimeType,clockRate:n.clockRate,channels:n.channels,localPayloadType:n.preferredPayloadType,localRtxPayloadType:void 0,remotePayloadType:i.preferredPayloadType,remoteRtxPayloadType:void 0,localParameters:n.parameters??{},remoteParameters:i.parameters??{},rtcpFeedback:un(n,i)};r.codecs.push(o)}else for(let n of e.codecs??[]){if(Ke(n))continue;let i=(s.codecs??[]).find(a=>Lr(a,n,{strict:!0,modify:!0}));if(!i)continue;let o={kind:i.kind,mimeType:i.mimeType,clockRate:i.clockRate,channels:i.channels,localPayloadType:i.preferredPayloadType,localRtxPayloadType:void 0,remotePayloadType:n.preferredPayloadType,remoteRtxPayloadType:void 0,localParameters:i.parameters??{},remoteParameters:n.parameters??{},rtcpFeedback:un(i,n)};r.codecs.push(o)}for(let n of r.codecs){let i=s.codecs.find(a=>Ke(a)&&a.parameters?.apt===n.localPayloadType),o=e.codecs.find(a=>Ke(a)&&a.parameters?.apt===n.remotePayloadType);i&&o&&(n.localRtxPayloadType=i.preferredPayloadType,n.remoteRtxPayloadType=o.preferredPayloadType)}for(let n of e.headerExtensions){let i=s.headerExtensions.find(a=>ma(a,n));if(!i)continue;let o={kind:n.kind,uri:n.uri,sendId:i.preferredId,recvId:n.preferredId,encrypt:i.preferredEncrypt??!1,direction:"sendrecv"};switch(n.direction){case"sendrecv":{o.direction="sendrecv";break}case"recvonly":{o.direction="sendonly";break}case"sendonly":{o.direction="recvonly";break}case"inactive":{o.direction="inactive";break}}r.headerExtensions.push(o)}return r}function ea(s){return fn({direction:"recvonly",extendedRtpCapabilities:s})}function ta(s){return fn({direction:"sendonly",extendedRtpCapabilities:s})}function ra(s,e){let t={mid:void 0,codecs:[],headerExtensions:[],encodings:[],rtcp:{}};for(let r of e.codecs){if(r.kind!==s)continue;let n={mimeType:r.mimeType,payloadType:r.localPayloadType,clockRate:r.clockRate,channels:r.channels,parameters:r.localParameters,rtcpFeedback:r.rtcpFeedback};if(t.codecs.push(n),r.localRtxPayloadType){let i={mimeType:`${r.kind}/rtx`,payloadType:r.localRtxPayloadType,clockRate:r.clockRate,parameters:{apt:r.localPayloadType},rtcpFeedback:[]};t.codecs.push(i)}}for(let r of e.headerExtensions){if(r.kind&&r.kind!==s||r.direction!=="sendrecv"&&r.direction!=="sendonly")continue;let n={uri:r.uri,id:r.sendId,encrypt:r.encrypt,parameters:{}};t.headerExtensions.push(n)}return t}function sa(s,e){let t={mid:void 0,codecs:[],headerExtensions:[],encodings:[],rtcp:{}};for(let r of e.codecs){if(r.kind!==s)continue;let n={mimeType:r.mimeType,payloadType:r.localPayloadType,clockRate:r.clockRate,channels:r.channels,parameters:r.remoteParameters,rtcpFeedback:r.rtcpFeedback};if(t.codecs.push(n),r.localRtxPayloadType){let i={mimeType:`${r.kind}/rtx`,payloadType:r.localRtxPayloadType,clockRate:r.clockRate,parameters:{apt:r.localPayloadType},rtcpFeedback:[]};t.codecs.push(i)}}for(let r of e.headerExtensions){if(r.kind&&r.kind!==s||r.direction!=="sendrecv"&&r.direction!=="sendonly")continue;let n={uri:r.uri,id:r.sendId,encrypt:r.encrypt,parameters:{}};t.headerExtensions.push(n)}if(t.headerExtensions.some(r=>r.uri==="http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01"))for(let r of t.codecs)r.rtcpFeedback=(r.rtcpFeedback??[]).filter(n=>n.type!=="goog-remb");else if(t.headerExtensions.some(r=>r.uri==="http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time"))for(let r of t.codecs)r.rtcpFeedback=(r.rtcpFeedback??[]).filter(n=>n.type!=="transport-cc");else for(let r of t.codecs)r.rtcpFeedback=(r.rtcpFeedback??[]).filter(n=>n.type!=="transport-cc"&&n.type!=="goog-remb");return t}function na(s,e){let t=[];if(!e)t.push(s[0]),Ke(s[1])&&t.push(s[1]);else{for(let r=0;r<s.length;++r)if(Lr(s[r],e,{strict:!0})){t.push(s[r]),Ke(s[r+1])&&t.push(s[r+1]);break}if(t.length===0)throw new TypeError("no matching codec found")}return t}function ia(s){s=Wo.clone(s),Mr(s);let e={mid:Go,codecs:[],headerExtensions:[],encodings:[{ssrc:Ko}],rtcp:{cname:"probator"}};return e.codecs.push(s.codecs[0]),e.codecs[0].payloadType=Qo,e.headerExtensions=s.headerExtensions,e}function oa(s,e){return(e.codecs??[]).some(t=>t.kind===s)}function aa(s,e){if(Mr(s),s.codecs.length===0)return!1;let t=s.codecs[0];return(e.codecs??[]).some(r=>r.preferredPayloadType===t.payloadType)}function ca(s){let e=new RegExp("^(audio|video)/(.+)","i");if(typeof s!="object")throw new TypeError("codec is not an object");if(!s.mimeType||typeof s.mimeType!="string")throw new TypeError("missing codec.mimeType");let t=e.exec(s.mimeType);if(!t)throw new TypeError("invalid codec.mimeType");if(s.kind=t[1].toLowerCase(),typeof s.preferredPayloadType!="number")throw new TypeError("missing codec.preferredPayloadType");if(typeof s.clockRate!="number")throw new TypeError("missing codec.clockRate");s.kind==="audio"?typeof s.channels!="number"&&(s.channels=1):delete s.channels,(!s.parameters||typeof s.parameters!="object")&&(s.parameters={});for(let r of Object.keys(s.parameters)){let n=s.parameters[r];if(n===void 0&&(s.parameters[r]="",n=""),typeof n!="string"&&typeof n!="number")throw new TypeError(`invalid codec parameter [key:${r}s, value:${n}]`);if(r==="apt"&&typeof n!="number")throw new TypeError("invalid codec apt parameter")}(!s.rtcpFeedback||!Array.isArray(s.rtcpFeedback))&&(s.rtcpFeedback=[]);for(let r of s.rtcpFeedback)hn(r)}function hn(s){if(typeof s!="object")throw new TypeError("fb is not an object");if(!s.type||typeof s.type!="string")throw new TypeError("missing fb.type");(!s.parameter||typeof s.parameter!="string")&&(s.parameter="")}function da(s){if(typeof s!="object")throw new TypeError("ext is not an object");if(s.kind!=="audio"&&s.kind!=="video")throw new TypeError("invalid ext.kind");if(!s.uri||typeof s.uri!="string")throw new TypeError("missing ext.uri");if(typeof s.preferredId!="number")throw new TypeError("missing ext.preferredId");if(s.preferredEncrypt&&typeof s.preferredEncrypt!="boolean")throw new TypeError("invalid ext.preferredEncrypt");if(s.preferredEncrypt||(s.preferredEncrypt=!1),s.direction&&typeof s.direction!="string")throw new TypeError("invalid ext.direction");s.direction||(s.direction="sendrecv")}function pa(s){let e=new RegExp("^(audio|video)/(.+)","i");if(typeof s!="object")throw new TypeError("codec is not an object");if(!s.mimeType||typeof s.mimeType!="string")throw new TypeError("missing codec.mimeType");let t=e.exec(s.mimeType);if(!t)throw new TypeError("invalid codec.mimeType");if(typeof s.payloadType!="number")throw new TypeError("missing codec.payloadType");if(typeof s.clockRate!="number")throw new TypeError("missing codec.clockRate");t[1].toLowerCase()==="audio"?typeof s.channels!="number"&&(s.channels=1):delete s.channels,(!s.parameters||typeof s.parameters!="object")&&(s.parameters={});for(let n of Object.keys(s.parameters)){let i=s.parameters[n];if(i===void 0&&(s.parameters[n]="",i=""),typeof i!="string"&&typeof i!="number")throw new TypeError(`invalid codec parameter [key:${n}s, value:${i}]`);if(n==="apt"&&typeof i!="number")throw new TypeError("invalid codec apt parameter")}(!s.rtcpFeedback||!Array.isArray(s.rtcpFeedback))&&(s.rtcpFeedback=[]);for(let n of s.rtcpFeedback)hn(n)}function la(s){if(typeof s!="object")throw new TypeError("ext is not an object");if(!s.uri||typeof s.uri!="string")throw new TypeError("missing ext.uri");if(typeof s.id!="number")throw new TypeError("missing ext.id");if(s.encrypt&&typeof s.encrypt!="boolean")throw new TypeError("invalid ext.encrypt");s.encrypt||(s.encrypt=!1),(!s.parameters||typeof s.parameters!="object")&&(s.parameters={});for(let e of Object.keys(s.parameters)){let t=s.parameters[e];if(t===void 0&&(s.parameters[e]="",t=""),typeof t!="string"&&typeof t!="number")throw new TypeError("invalid header extension parameter")}}function ua(s){if(typeof s!="object")throw new TypeError("encoding is not an object");if(s.ssrc&&typeof s.ssrc!="number")throw new TypeError("invalid encoding.ssrc");if(s.rid&&typeof s.rid!="string")throw new TypeError("invalid encoding.rid");if(s.rtx&&typeof s.rtx!="object")throw new TypeError("invalid encoding.rtx");if(s.rtx&&typeof s.rtx.ssrc!="number")throw new TypeError("missing encoding.rtx.ssrc");if((!s.dtx||typeof s.dtx!="boolean")&&(s.dtx=!1),s.scalabilityMode&&typeof s.scalabilityMode!="string")throw new TypeError("invalid encoding.scalabilityMode")}function ha(s){if(typeof s!="object")throw new TypeError("rtcp is not an object");if(s.cname&&typeof s.cname!="string")throw new TypeError("invalid rtcp.cname");(!s.reducedSize||typeof s.reducedSize!="boolean")&&(s.reducedSize=!0)}function fa(s){if(typeof s!="object")throw new TypeError("numStreams is not an object");if(typeof s.OS!="number")throw new TypeError("missing numStreams.OS");if(typeof s.MIS!="number")throw new TypeError("missing numStreams.MIS")}function fn({direction:s,extendedRtpCapabilities:e}){let t={codecs:[],headerExtensions:[]};for(let r of e.codecs){let n={kind:r.kind,mimeType:r.mimeType,preferredPayloadType:r.remotePayloadType,clockRate:r.clockRate,channels:r.channels,parameters:r.localParameters,rtcpFeedback:r.rtcpFeedback};if(t.codecs.push(n),!r.remoteRtxPayloadType)continue;let i={kind:r.kind,mimeType:`${r.kind}/rtx`,preferredPayloadType:r.remoteRtxPayloadType,clockRate:r.clockRate,parameters:{apt:r.remotePayloadType},rtcpFeedback:[]};t.codecs.push(i)}for(let r of e.headerExtensions){if(r.direction!=="sendrecv"&&r.direction!==s)continue;let n={kind:r.kind,uri:r.uri,preferredId:r.recvId,preferredEncrypt:r.encrypt??!1,direction:r.direction};t.headerExtensions.push(n)}return t}function Ke(s){return s?/.+\/rtx$/i.test(s.mimeType):!1}function Lr(s,e,{strict:t=!1,modify:r=!1}={}){let n=s.mimeType.toLowerCase(),i=e.mimeType.toLowerCase();if(n!==i||s.clockRate!==e.clockRate||s.channels!==e.channels)return!1;switch(n){case"video/h264":{if(t){let o=s.parameters["packetization-mode"]??0,a=e.parameters["packetization-mode"]??0;if(o!==a||!ln.isSameProfile(s.parameters,e.parameters))return!1;let c;try{c=ln.generateProfileLevelIdStringForAnswer(s.parameters,e.parameters)}catch{return!1}r&&(c?(s.parameters["profile-level-id"]=c,e.parameters["profile-level-id"]=c):(delete s.parameters["profile-level-id"],delete e.parameters["profile-level-id"]))}break}case"video/vp9":{if(t){let o=s.parameters["profile-id"]??0,a=e.parameters["profile-id"]??0;if(o!==a)return!1}break}}return!0}function ma(s,e){return!(s.kind&&e.kind&&s.kind!==e.kind||s.uri!==e.uri)}function un(s,e){let t=[];for(let r of s.rtcpFeedback??[]){let n=(e.rtcpFeedback??[]).find(i=>i.type===r.type&&(i.parameter===r.parameter||!i.parameter&&!r.parameter));n&&t.push(n)}return t}});var mn=C(Ut=>{"use strict";Object.defineProperty(Ut,"__esModule",{value:!0});Ut.Logger=void 0;var Qe=ut(),Ye="awaitqueue",Or=class{_debug;_warn;_error;constructor(e){e?(this._debug=Qe(`${Ye}:${e}`),this._warn=Qe(`${Ye}:WARN:${e}`),this._error=Qe(`${Ye}:ERROR:${e}`)):(this._debug=Qe(Ye),this._warn=Qe(`${Ye}:WARN`),this._error=Qe(`${Ye}:ERROR`)),this._debug.log=console.info.bind(console),this._warn.log=console.warn.bind(console),this._error.log=console.error.bind(console)}get debug(){return this._debug}get warn(){return this._warn}get error(){return this._error}};Ut.Logger=Or});var jr=C(Je=>{"use strict";Object.defineProperty(Je,"__esModule",{value:!0});Je.AwaitQueueRemovedTaskError=Je.AwaitQueueStoppedError=void 0;var Ar=class s extends Error{constructor(e){super(e??"queue stopped"),this.name="AwaitQueueStoppedError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,s)}};Je.AwaitQueueStoppedError=Ar;var Nr=class s extends Error{constructor(e){super(e??"queue task removed"),this.name="AwaitQueueRemovedTaskError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,s)}};Je.AwaitQueueRemovedTaskError=Nr});var gn=C(zt=>{"use strict";Object.defineProperty(zt,"__esModule",{value:!0});zt.AwaitQueue=void 0;var ga=mn(),Fr=jr(),fe=new ga.Logger("AwaitQueue"),qr=class{pendingTasks=new Map;nextTaskId=0;constructor(){fe.debug("constructor()")}get size(){return this.pendingTasks.size}async push(e,t,r){if(t=t??e.name,fe.debug(`push() [name:${t}, options:%o]`,r),typeof e!="function")throw new TypeError("given task is not a function");if(t)try{Object.defineProperty(e,"name",{value:t})}catch{}return new Promise((n,i)=>{if(t&&r?.removeOngoingTasksWithSameName)for(let a of this.pendingTasks.values())a.name===t&&a.reject(new Fr.AwaitQueueRemovedTaskError,{canExecuteNextTask:!1});let o={id:this.nextTaskId++,task:e,name:t,enqueuedAt:Date.now(),executedAt:void 0,completed:!1,resolve:a=>{if(o.completed)return;o.completed=!0,this.pendingTasks.delete(o.id),fe.debug(`resolving task [name:${o.name}]`),n(a);let[c]=this.pendingTasks.values();c&&!c.executedAt&&this.execute(c)},reject:(a,{canExecuteNextTask:c})=>{if(!o.completed&&(o.completed=!0,this.pendingTasks.delete(o.id),fe.debug(`rejecting task [name:${o.name}]: %s`,String(a)),i(a),c)){let[d]=this.pendingTasks.values();d&&!d.executedAt&&this.execute(d)}}};this.pendingTasks.set(o.id,o),this.pendingTasks.size===1&&this.execute(o)})}stop(){fe.debug("stop()");for(let e of this.pendingTasks.values())fe.debug(`stop() | stopping task [name:${e.name}]`),e.reject(new Fr.AwaitQueueStoppedError,{canExecuteNextTask:!1})}remove(e){fe.debug(`remove() [taskIdx:${e}]`);let t=Array.from(this.pendingTasks.values())[e];if(!t){fe.debug(`stop() | no task with given idx [taskIdx:${e}]`);return}t.reject(new Fr.AwaitQueueRemovedTaskError,{canExecuteNextTask:!0})}dump(){let e=Date.now(),t=0;return Array.from(this.pendingTasks.values()).map(r=>({idx:t++,task:r.task,name:r.name,enqueuedTime:r.executedAt?r.executedAt-r.enqueuedAt:e-r.enqueuedAt,executionTime:r.executedAt?e-r.executedAt:0}))}async execute(e){if(fe.debug(`execute() [name:${e.name}]`),e.executedAt)throw new Error("task already being executed");e.executedAt=Date.now();try{let t=await e.task();e.resolve(t)}catch(t){e.reject(t,{canExecuteNextTask:!0})}}};zt.AwaitQueue=qr});var vn=C(Re=>{"use strict";Object.defineProperty(Re,"__esModule",{value:!0});Re.AwaitQueueRemovedTaskError=Re.AwaitQueueStoppedError=Re.AwaitQueue=void 0;var _a=gn();Object.defineProperty(Re,"AwaitQueue",{enumerable:!0,get:function(){return _a.AwaitQueue}});var _n=jr();Object.defineProperty(Re,"AwaitQueueStoppedError",{enumerable:!0,get:function(){return _n.AwaitQueueStoppedError}});Object.defineProperty(Re,"AwaitQueueRemovedTaskError",{enumerable:!0,get:function(){return _n.AwaitQueueRemovedTaskError}})});var yn=C(Bt=>{"use strict";Object.defineProperty(Bt,"__esModule",{value:!0});Bt.Producer=void 0;var va=z(),wn=G(),Xe=X(),ce=new va.Logger("Producer"),$r=class extends wn.EnhancedEventEmitter{_id;_localId;_closed=!1;_rtpSender;_track;_kind;_rtpParameters;_paused;_maxSpatialLayer;_stopTracks;_disableTrackOnPause;_zeroRtpOnPause;_appData;_observer=new wn.EnhancedEventEmitter;constructor({id:e,localId:t,rtpSender:r,track:n,rtpParameters:i,stopTracks:o,disableTrackOnPause:a,zeroRtpOnPause:c,appData:d}){super(),ce.debug("constructor()"),this._id=e,this._localId=t,this._rtpSender=r,this._track=n,this._kind=n.kind,this._rtpParameters=i,this._paused=a?!n.enabled:!1,this._maxSpatialLayer=void 0,this._stopTracks=o,this._disableTrackOnPause=a,this._zeroRtpOnPause=c,this._appData=d??{},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(e){this._appData=e}get observer(){return this._observer}close(){this._closed||(ce.debug("close()"),this._closed=!0,this.destroyTrack(),this.emit("@close"),this._observer.safeEmit("close"),super.close(),this._observer.close())}transportClosed(){this._closed||(ce.debug("transportClosed()"),this._closed=!0,this.destroyTrack(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}async getStats(){if(this._closed)throw new Xe.InvalidStateError("closed");return new Promise((e,t)=>{this.safeEmit("@getstats",e,t)})}pause(){if(ce.debug("pause()"),this._closed){ce.error("pause() | Producer closed");return}this._paused=!0,this._track&&this._disableTrackOnPause&&(this._track.enabled=!1),this._zeroRtpOnPause&&new Promise((e,t)=>{this.safeEmit("@pause",e,t)}).catch(()=>{}),this._observer.safeEmit("pause")}resume(){if(ce.debug("resume()"),this._closed){ce.error("resume() | Producer closed");return}this._paused=!1,this._track&&this._disableTrackOnPause&&(this._track.enabled=!0),this._zeroRtpOnPause&&new Promise((e,t)=>{this.safeEmit("@resume",e,t)}).catch(()=>{}),this._observer.safeEmit("resume")}async replaceTrack({track:e}){if(ce.debug("replaceTrack() [track:%o]",e),this._closed){if(e&&this._stopTracks)try{e.stop()}catch{}throw new Xe.InvalidStateError("closed")}else if(e?.readyState==="ended")throw new Xe.InvalidStateError("track ended");if(e===this._track){ce.debug("replaceTrack() | same track, ignored");return}await new Promise((t,r)=>{this.safeEmit("@replacetrack",e,t,r)}),this.destroyTrack(),this._track=e,this._track&&this._disableTrackOnPause&&(this._paused?this._paused&&(this._track.enabled=!1):this._track.enabled=!0),this.handleTrack()}async setMaxSpatialLayer(e){if(this._closed)throw new Xe.InvalidStateError("closed");if(this._kind!=="video")throw new Xe.UnsupportedError("not a video Producer");if(typeof e!="number")throw new TypeError("invalid spatialLayer");e!==this._maxSpatialLayer&&(await new Promise((t,r)=>{this.safeEmit("@setmaxspatiallayer",e,t,r)}).catch(()=>{}),this._maxSpatialLayer=e)}async setRtpEncodingParameters(e){if(this._closed)throw new Xe.InvalidStateError("closed");if(typeof e!="object")throw new TypeError("invalid params");await new Promise((t,r)=>{this.safeEmit("@setrtpencodingparameters",e,t,r)})}onTrackEnded(){ce.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{}}};Bt.Producer=$r});var Sn=C(Ht=>{"use strict";Object.defineProperty(Ht,"__esModule",{value:!0});Ht.Consumer=void 0;var wa=z(),bn=G(),ya=X(),de=new wa.Logger("Consumer"),Ur=class extends bn.EnhancedEventEmitter{_id;_localId;_producerId;_closed=!1;_rtpReceiver;_track;_rtpParameters;_paused;_appData;_observer=new bn.EnhancedEventEmitter;constructor({id:e,localId:t,producerId:r,rtpReceiver:n,track:i,rtpParameters:o,appData:a}){super(),de.debug("constructor()"),this._id=e,this._localId=t,this._producerId=r,this._rtpReceiver=n,this._track=i,this._rtpParameters=o,this._paused=!i.enabled,this._appData=a??{},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(e){this._appData=e}get observer(){return this._observer}close(){this._closed||(de.debug("close()"),this._closed=!0,this.destroyTrack(),this.emit("@close"),this._observer.safeEmit("close"),super.close(),this._observer.close())}transportClosed(){this._closed||(de.debug("transportClosed()"),this._closed=!0,this.destroyTrack(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}async getStats(){if(this._closed)throw new ya.InvalidStateError("closed");return new Promise((e,t)=>{this.safeEmit("@getstats",e,t)})}pause(){if(de.debug("pause()"),this._closed){de.error("pause() | Consumer closed");return}if(this._paused){de.debug("pause() | Consumer is already paused");return}this._paused=!0,this._track.enabled=!1,this.emit("@pause"),this._observer.safeEmit("pause")}resume(){if(de.debug("resume()"),this._closed){de.error("resume() | Consumer closed");return}if(!this._paused){de.debug("resume() | Consumer is already resumed");return}this._paused=!1,this._track.enabled=!0,this.emit("@resume"),this._observer.safeEmit("resume")}onTrackEnded(){de.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{}}};Ht.Consumer=Ur});var Cn=C(Vt=>{"use strict";Object.defineProperty(Vt,"__esModule",{value:!0});Vt.DataProducer=void 0;var ba=z(),Rn=G(),Sa=X(),me=new ba.Logger("DataProducer"),zr=class extends Rn.EnhancedEventEmitter{_id;_dataChannel;_closed=!1;_sctpStreamParameters;_appData;_observer=new Rn.EnhancedEventEmitter;constructor({id:e,dataChannel:t,sctpStreamParameters:r,appData:n}){super(),me.debug("constructor()"),this._id=e,this._dataChannel=t,this._sctpStreamParameters=r,this._appData=n??{},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(e){this._dataChannel.bufferedAmountLowThreshold=e}get appData(){return this._appData}set appData(e){this._appData=e}get observer(){return this._observer}close(){this._closed||(me.debug("close()"),this._closed=!0,this._dataChannel.close(),this.emit("@close"),this._observer.safeEmit("close"),super.close(),this._observer.close())}transportClosed(){this._closed||(me.debug("transportClosed()"),this._closed=!0,this._dataChannel.close(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}send(e){if(me.debug("send()"),this._closed)throw new Sa.InvalidStateError("closed");this._dataChannel.send(e)}handleDataChannel(){this._dataChannel.addEventListener("open",()=>{this._closed||(me.debug('DataChannel "open" event'),this.safeEmit("open"))}),this._dataChannel.addEventListener("error",e=>{if(this._closed)return;let t=e.error??new Error("unknown DataChannel error");e.error?.errorDetail==="sctp-failure"?me.error("DataChannel SCTP error [sctpCauseCode:%s]: %s",e.error?.sctpCauseCode,e.error.message):me.error('DataChannel "error" event: %o',t),this.safeEmit("error",t)}),this._dataChannel.addEventListener("close",()=>{this._closed||(me.warn('DataChannel "close" event'),this._closed=!0,this.emit("@close"),this.safeEmit("close"),this._observer.safeEmit("close"))}),this._dataChannel.addEventListener("message",()=>{this._closed||me.warn('DataChannel "message" event in a DataProducer, message discarded')}),this._dataChannel.addEventListener("bufferedamountlow",()=>{this._closed||this.safeEmit("bufferedamountlow")})}};Vt.DataProducer=zr});var En=C(Wt=>{"use strict";Object.defineProperty(Wt,"__esModule",{value:!0});Wt.DataConsumer=void 0;var Ra=z(),Tn=G(),Pe=new Ra.Logger("DataConsumer"),Br=class extends Tn.EnhancedEventEmitter{_id;_dataProducerId;_dataChannel;_closed=!1;_sctpStreamParameters;_appData;_observer=new Tn.EnhancedEventEmitter;constructor({id:e,dataProducerId:t,dataChannel:r,sctpStreamParameters:n,appData:i}){super(),Pe.debug("constructor()"),this._id=e,this._dataProducerId=t,this._dataChannel=r,this._sctpStreamParameters=n,this._appData=i??{},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(e){this._dataChannel.binaryType=e}get appData(){return this._appData}set appData(e){this._appData=e}get observer(){return this._observer}close(){this._closed||(Pe.debug("close()"),this._closed=!0,this._dataChannel.close(),this.emit("@close"),this._observer.safeEmit("close"),super.close(),this._observer.close())}transportClosed(){this._closed||(Pe.debug("transportClosed()"),this._closed=!0,this._dataChannel.close(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}handleDataChannel(){this._dataChannel.addEventListener("open",()=>{this._closed||(Pe.debug('DataChannel "open" event'),this.safeEmit("open"))}),this._dataChannel.addEventListener("error",e=>{if(this._closed)return;let t=e.error??new Error("unknown DataChannel error");e.error?.errorDetail==="sctp-failure"?Pe.error("DataChannel SCTP error [sctpCauseCode:%s]: %s",e.error?.sctpCauseCode,e.error.message):Pe.error('DataChannel "error" event: %o',t),this.safeEmit("error",t)}),this._dataChannel.addEventListener("close",()=>{this._closed||(Pe.warn('DataChannel "close" event'),this._closed=!0,this.emit("@close"),this.safeEmit("close"),this._observer.safeEmit("close"))}),this._dataChannel.addEventListener("message",e=>{this._closed||this.safeEmit("message",e.data)})}};Wt.DataConsumer=Br});var xn=C(Gt=>{"use strict";Object.defineProperty(Gt,"__esModule",{value:!0});Gt.Transport=void 0;var Ca=vn(),Ta=z(),kn=G(),j=X(),Hr=ke(),ft=ae(),Ea=yn(),ka=Sn(),xa=Cn(),Pa=En(),N=new Ta.Logger("Transport"),Vr=class{consumerOptions;promise;resolve;reject;constructor(e){this.consumerOptions=e,this.promise=new Promise((t,r)=>{this.resolve=t,this.reject=r})}},Wr=class extends kn.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 Ca.AwaitQueue;_pendingConsumerTasks=[];_consumerCreationInProgress=!1;_pendingPauseConsumers=new Map;_consumerPauseInProgress=!1;_pendingResumeConsumers=new Map;_consumerResumeInProgress=!1;_pendingCloseConsumers=new Map;_consumerCloseInProgress=!1;_observer=new kn.EnhancedEventEmitter;constructor({direction:e,id:t,iceParameters:r,iceCandidates:n,dtlsParameters:i,sctpParameters:o,iceServers:a,iceTransportPolicy:c,additionalSettings:d,appData:p,handlerFactory:l,getSendExtendedRtpCapabilities:u,recvRtpCapabilities:f,canProduceByKind:m}){super(),N.debug("constructor() [id:%s, direction:%s]",t,e),this._id=t,this._direction=e,this._getSendExtendedRtpCapabilities=u,this._recvRtpCapabilities=f,this._canProduceByKind=m,this._maxSctpMessageSize=o?.maxMessageSize;let h=Hr.clone(d)??{};delete h.iceServers,delete h.iceTransportPolicy,delete h.bundlePolicy,delete h.rtcpMuxPolicy,this._handler=l.factory({direction:e,iceParameters:r,iceCandidates:n,dtlsParameters:i,sctpParameters:o,iceServers:a,iceTransportPolicy:c,additionalSettings:h,getSendExtendedRtpCapabilities:this._getSendExtendedRtpCapabilities}),this._appData=p??{},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(e){this._appData=e}get observer(){return this._observer}close(){if(!this._closed){N.debug("close()"),this._closed=!0,this._awaitQueue.stop(),this._handler.close(),this._connectionState="closed";for(let e of this._producers.values())e.transportClosed();this._producers.clear();for(let e of this._consumers.values())e.transportClosed();this._consumers.clear();for(let e of this._dataProducers.values())e.transportClosed();this._dataProducers.clear();for(let e of this._dataConsumers.values())e.transportClosed();this._dataConsumers.clear(),this._observer.safeEmit("close"),super.close(),this._observer.close()}}async getStats(){if(this._closed)throw new j.InvalidStateError("closed");return this._handler.getTransportStats()}async restartIce({iceParameters:e}){if(N.debug("restartIce()"),this._closed)throw new j.InvalidStateError("closed");if(!e)throw new TypeError("missing iceParameters");return this._awaitQueue.push(async()=>await this._handler.restartIce(e),"transport.restartIce()")}async updateIceServers({iceServers:e}={}){if(N.debug("updateIceServers()"),this._closed)throw new j.InvalidStateError("closed");if(!Array.isArray(e))throw new TypeError("missing iceServers");return this._awaitQueue.push(async()=>this._handler.updateIceServers(e),"transport.updateIceServers()")}async produce({track:e,streamId:t,encodings:r,codecOptions:n,headerExtensionOptions:i,codec:o,stopTracks:a=!0,disableTrackOnPause:c=!0,zeroRtpOnPause:d=!1,onRtpSender:p,appData:l={}}={}){if(N.debug("produce() [track:%o]",e),this._closed)throw new j.InvalidStateError("closed");if(e){if(this._direction!=="send")throw new j.UnsupportedError("not a sending Transport");if(this._canProduceByKind[e.kind]){if(e.readyState==="ended")throw new j.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(l&&typeof l!="object")throw new TypeError("if given, appData must be an object")}else throw new j.UnsupportedError(`cannot produce ${e.kind}`)}else throw new TypeError("missing track");return this._awaitQueue.push(async()=>{let u;if(r&&!Array.isArray(r))throw TypeError("encodings must be an array");r?.length===0?u=void 0:r&&(u=r.map(g=>{let _={active:!0};return g.active===!1&&(_.active=!1),typeof g.dtx=="boolean"&&(_.dtx=g.dtx),typeof g.scalabilityMode=="string"&&(_.scalabilityMode=g.scalabilityMode),typeof g.scaleResolutionDownBy=="number"&&(_.scaleResolutionDownBy=g.scaleResolutionDownBy),typeof g.maxBitrate=="number"&&(_.maxBitrate=g.maxBitrate),typeof g.maxFramerate=="number"&&(_.maxFramerate=g.maxFramerate),typeof g.adaptivePtime=="boolean"&&(_.adaptivePtime=g.adaptivePtime),typeof g.priority=="string"&&(_.priority=g.priority),typeof g.networkPriority=="string"&&(_.networkPriority=g.networkPriority),_}));let{localId:f,rtpParameters:m,rtpSender:h}=await this._handler.send({track:e,streamId:t,encodings:u,codecOptions:n,headerExtensionOptions:i,codec:o,onRtpSender:p});try{ft.validateAndNormalizeRtpParameters(m);let{id:g}=await new Promise((y,x)=>{this.safeEmit("produce",{kind:e.kind,rtpParameters:m,appData:l},y,x)}),_=new Ea.Producer({id:g,localId:f,rtpSender:h,track:e,rtpParameters:m,stopTracks:a,disableTrackOnPause:c,zeroRtpOnPause:d,appData:l});return this._producers.set(_.id,_),this.handleProducer(_),this._observer.safeEmit("newproducer",_),_}catch(g){throw this._handler.stopSending(f).catch(()=>{}),g}},"transport.produce()").catch(u=>{if(a)try{e.stop()}catch{}throw u})}async consume({id:e,producerId:t,kind:r,rtpParameters:n,streamId:i,onRtpReceiver:o,appData:a={}}){if(N.debug("consume()"),this._closed)throw new j.InvalidStateError("closed");if(this._direction!=="recv")throw new j.UnsupportedError("not a receiving Transport");if(typeof e!="string")throw new TypeError("missing id");if(typeof t!="string")throw new TypeError("missing producerId");if(r!=="audio"&&r!=="video")throw new TypeError(`invalid kind '${r}'`);if(this.listenerCount("connect")===0&&this._connectionState==="new")throw new TypeError('no "connect" listener set into this transport');if(a&&typeof a!="object")throw new TypeError("if given, appData must be an object");let c=Hr.clone(n);if(!ft.canReceive(c,this._recvRtpCapabilities))throw new j.UnsupportedError("cannot consume this Producer");let p=new Vr({id:e,producerId:t,kind:r,rtpParameters:c,streamId:i,onRtpReceiver:o,appData:a});return this._pendingConsumerTasks.push(p),queueMicrotask(()=>{this._closed||this._consumerCreationInProgress===!1&&this.createPendingConsumers()}),p.promise}async produceData({ordered:e=!0,maxPacketLifeTime:t,maxRetransmits:r,label:n="",protocol:i="",appData:o={}}={}){if(N.debug("produceData()"),this._closed)throw new j.InvalidStateError("closed");if(this._direction!=="send")throw new j.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(o&&typeof o!="object")throw new TypeError("if given, appData must be an object")}else throw new j.UnsupportedError("SCTP not enabled by remote Transport");return(t||r)&&(e=!1),this._awaitQueue.push(async()=>{let{dataChannel:a,sctpStreamParameters:c}=await this._handler.sendDataChannel({sctpStreamParameters:{ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:n,protocol:i}});ft.validateAndNormalizeSctpStreamParameters(c);let{id:d}=await new Promise((l,u)=>{this.safeEmit("producedata",{sctpStreamParameters:c,label:n,protocol:i,appData:o},l,u)}),p=new xa.DataProducer({id:d,dataChannel:a,sctpStreamParameters:c,appData:o});return this._dataProducers.set(p.id,p),this.handleDataProducer(p),this._observer.safeEmit("newdataproducer",p),p},"transport.produceData()")}async consumeData({id:e,dataProducerId:t,sctpStreamParameters:r,label:n="",protocol:i="",appData:o={}}){if(N.debug("consumeData()"),this._closed)throw new j.InvalidStateError("closed");if(this._direction!=="recv")throw new j.UnsupportedError("not a receiving Transport");if(this._maxSctpMessageSize){if(typeof e!="string")throw new TypeError("missing id");if(typeof t!="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(o&&typeof o!="object")throw new TypeError("if given, appData must be an object")}else throw new j.UnsupportedError("SCTP not enabled by remote Transport");let a=Hr.clone(r);return ft.validateAndNormalizeSctpStreamParameters(a),this._awaitQueue.push(async()=>{let{dataChannel:c}=await this._handler.receiveDataChannel({maxMessageSize:this._maxSctpMessageSize,sctpStreamParameters:a,label:n,protocol:i}),d=new Pa.DataConsumer({id:e,dataProducerId:t,dataChannel:c,sctpStreamParameters:a,appData:o});return this._dataConsumers.set(d.id,d),this.handleDataConsumer(d),this._observer.safeEmit("newdataconsumer",d),d},"transport.consumeData()")}getDataChannelMaxMessageSize(){return this._handler.getDataChannelMaxMessageSize()}createPendingConsumers(){this._consumerCreationInProgress=!0,this._awaitQueue.push(async()=>{if(this._pendingConsumerTasks.length===0){N.debug("createPendingConsumers() | there is no Consumer to be created");return}let e=[...this._pendingConsumerTasks];this._pendingConsumerTasks=[];let t,r=[];for(let n of e){let{id:i,kind:o,rtpParameters:a,streamId:c,onRtpReceiver:d}=n.consumerOptions;r.push({trackId:i,kind:o,rtpParameters:a,streamId:c,onRtpReceiver:d})}try{let n=await this._handler.receive(r);for(let i=0;i<n.length;++i){let o=e[i],a=n[i],{id:c,producerId:d,kind:p,rtpParameters:l,appData:u}=o.consumerOptions,{localId:f,rtpReceiver:m,track:h}=a,g=new ka.Consumer({id:c,localId:f,producerId:d,rtpReceiver:m,track:h,rtpParameters:l,appData:u});this._consumers.set(g.id,g),this.handleConsumer(g),!this._probatorConsumerCreated&&!t&&p==="video"&&(t=g),this._observer.safeEmit("newconsumer",g),o.resolve(g)}}catch(n){for(let i of e)i.reject(n)}if(t)try{let n=ft.generateProbatorRtpParameters(t.rtpParameters);await this._handler.receive([{trackId:"probator",kind:"video",rtpParameters:n}]),N.debug("createPendingConsumers() | Consumer for RTP probation created"),this._probatorConsumerCreated=!0}catch(n){N.error("createPendingConsumers() | failed to create Consumer for RTP probation:%o",n)}},"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){N.debug("pausePendingConsumers() | there is no Consumer to be paused");return}let e=Array.from(this._pendingPauseConsumers.values());this._pendingPauseConsumers.clear();try{let t=e.map(r=>r.localId);await this._handler.pauseReceiving(t)}catch(t){N.error("pausePendingConsumers() | failed to pause Consumers:",t)}},"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){N.debug("resumePendingConsumers() | there is no Consumer to be resumed");return}let e=Array.from(this._pendingResumeConsumers.values());this._pendingResumeConsumers.clear();try{let t=e.map(r=>r.localId);await this._handler.resumeReceiving(t)}catch(t){N.error("resumePendingConsumers() | failed to resume Consumers:",t)}},"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){N.debug("closePendingConsumers() | there is no Consumer to be closed");return}let e=Array.from(this._pendingCloseConsumers.values());this._pendingCloseConsumers.clear();try{await this._handler.stopReceiving(e.map(t=>t.localId))}catch(t){N.error("closePendingConsumers() | failed to close Consumers:",t)}},"transport.closePendingConsumers()").then(()=>{this._consumerCloseInProgress=!1,this._pendingCloseConsumers.size>0&&this.closePendingConsumers()}).catch(()=>{})}handleHandler(){let e=this._handler;e.on("@connect",({dtlsParameters:t},r,n)=>{if(this._closed){n(new j.InvalidStateError("closed"));return}this.safeEmit("connect",{dtlsParameters:t},r,n)}),e.on("@icegatheringstatechange",t=>{t!==this._iceGatheringState&&(N.debug("ICE gathering state changed to %s",t),this._iceGatheringState=t,this._closed||this.safeEmit("icegatheringstatechange",t))}),e.on("@icecandidateerror",t=>{N.warn(`ICE candidate error [url:${t.url}, localAddress:${t.address}, localPort:${t.port}]: ${t.errorCode} "${t.errorText}"`),this.safeEmit("icecandidateerror",t)}),e.on("@connectionstatechange",t=>{t!==this._connectionState&&(N.debug("connection state changed to %s",t),this._connectionState=t,this._closed||this.safeEmit("connectionstatechange",t))})}handleProducer(e){e.on("@close",()=>{this._producers.delete(e.id),!this._closed&&this._awaitQueue.push(async()=>await this._handler.stopSending(e.localId),"producer @close event").catch(t=>N.warn("producer.close() failed:%o",t))}),e.on("@pause",(t,r)=>{this._awaitQueue.push(async()=>await this._handler.pauseSending(e.localId),"producer @pause event").then(t).catch(r)}),e.on("@resume",(t,r)=>{this._awaitQueue.push(async()=>await this._handler.resumeSending(e.localId),"producer @resume event").then(t).catch(r)}),e.on("@replacetrack",(t,r,n)=>{this._awaitQueue.push(async()=>await this._handler.replaceTrack(e.localId,t),"producer @replacetrack event").then(r).catch(n)}),e.on("@setmaxspatiallayer",(t,r,n)=>{this._awaitQueue.push(async()=>await this._handler.setMaxSpatialLayer(e.localId,t),"producer @setmaxspatiallayer event").then(r).catch(n)}),e.on("@setrtpencodingparameters",(t,r,n)=>{this._awaitQueue.push(async()=>await this._handler.setRtpEncodingParameters(e.localId,t),"producer @setrtpencodingparameters event").then(r).catch(n)}),e.on("@getstats",(t,r)=>{if(this._closed)return r(new j.InvalidStateError("closed"));this._handler.getSenderStats(e.localId).then(t).catch(r)})}handleConsumer(e){e.on("@close",()=>{this._consumers.delete(e.id),this._pendingPauseConsumers.delete(e.id),this._pendingResumeConsumers.delete(e.id),!this._closed&&(this._pendingCloseConsumers.set(e.id,e),this._consumerCloseInProgress===!1&&this.closePendingConsumers())}),e.on("@pause",()=>{this._pendingResumeConsumers.has(e.id)&&this._pendingResumeConsumers.delete(e.id),this._pendingPauseConsumers.set(e.id,e),queueMicrotask(()=>{this._closed||this._consumerPauseInProgress===!1&&this.pausePendingConsumers()})}),e.on("@resume",()=>{this._pendingPauseConsumers.has(e.id)&&this._pendingPauseConsumers.delete(e.id),this._pendingResumeConsumers.set(e.id,e),queueMicrotask(()=>{this._closed||this._consumerResumeInProgress===!1&&this.resumePendingConsumers()})}),e.on("@getstats",(t,r)=>{if(this._closed)return r(new j.InvalidStateError("closed"));this._handler.getReceiverStats(e.localId).then(t).catch(r)})}handleDataProducer(e){e.on("@close",()=>{this._dataProducers.delete(e.id)})}handleDataConsumer(e){e.on("@close",()=>{this._dataConsumers.delete(e.id)})}};Gt.Transport=Wr});var Kt=C((gp,Dn)=>{"use strict";var Pn=Dn.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 e="candidate:%s %d %s %d %s %d typ %s";return e+=s.raddr!=null?" raddr %s rport %d":"%v%v",e+=s.tcptype!=null?" tcptype %s":"%v",s.generation!=null&&(e+=" generation %d"),e+=s["network-id"]!=null?" network-id %d":"%v",e+=s["network-cost"]!=null?" network-cost %d":"%v",e}},{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 e="ssrc:%d";return s.attribute!=null&&(e+=" %s",s.value!=null&&(e+=":%s")),e}},{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 e="mediaclk:";return e+=s.id!=null?"id=%s %s":"%v%s",e+=s.mediaClockValue!=null?"=%s":"",e+=s.rateNumerator!=null?" rate=%s":"",e+=s.rateDenominator!=null?"/%s":"",e}},{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(Pn).forEach(function(s){var e=Pn[s];e.forEach(function(t){t.reg||(t.reg=/(.*)/),t.format||(t.format="%s")})})});var Mn=C(ge=>{"use strict";var Ze=function(s){return String(Number(s))===s?Number(s):s},Da=function(s,e,t,r){if(r&&!t)e[r]=Ze(s[1]);else for(var n=0;n<t.length;n+=1)s[n+1]!=null&&(e[t[n]]=Ze(s[n+1]))},Ia=function(s,e,t){var r=s.name&&s.names;s.push&&!e[s.push]?e[s.push]=[]:r&&!e[s.name]&&(e[s.name]={});var n=s.push?{}:r?e[s.name]:e;Da(t.match(s.reg),n,s.names,s.name),s.push&&e[s.push].push(n)},In=Kt(),La=RegExp.prototype.test.bind(/^([a-z])=(.*)/);ge.parse=function(s){var e={},t=[],r=e;return s.split(/(\r\n|\r|\n)/).filter(La).forEach(function(n){var i=n[0],o=n.slice(2);i==="m"&&(t.push({rtp:[],fmtp:[]}),r=t[t.length-1]);for(var a=0;a<(In[i]||[]).length;a+=1){var c=In[i][a];if(c.reg.test(o))return Ia(c,r,o)}}),e.media=t,e};var Ln=function(s,e){var t=e.split(/=(.+)/,2);return t.length===2?s[t[0]]=Ze(t[1]):t.length===1&&e.length>1&&(s[t[0]]=void 0),s};ge.parseParams=function(s){return s.split(/;\s?/).reduce(Ln,{})};ge.parseFmtpConfig=ge.parseParams;ge.parsePayloads=function(s){return s.toString().split(" ").map(Number)};ge.parseRemoteCandidates=function(s){for(var e=[],t=s.split(" ").map(Ze),r=0;r<t.length;r+=3)e.push({component:t[r],ip:t[r+1],port:t[r+2]});return e};ge.parseImageAttributes=function(s){return s.split(" ").map(function(e){return e.substring(1,e.length-1).split(",").reduce(Ln,{})})};ge.parseSimulcastStreamList=function(s){return s.split(";").map(function(e){return e.split(",").map(function(t){var r,n=!1;return t[0]!=="~"?r=Ze(t):(r=Ze(t.substring(1,t.length)),n=!0),{scid:r,paused:n}})})}});var An=C((vp,On)=>{"use strict";var Gr=Kt(),Ma=/%[sdv%]/g,Oa=function(s){var e=1,t=arguments,r=t.length;return s.replace(Ma,function(n){if(e>=r)return n;var i=t[e];switch(e+=1,n){case"%%":return"%";case"%s":return String(i);case"%d":return Number(i);case"%v":return""}})},mt=function(s,e,t){var r=e.format instanceof Function?e.format(e.push?t:t[e.name]):e.format,n=[s+"="+r];if(e.names)for(var i=0;i<e.names.length;i+=1){var o=e.names[i];e.name?n.push(t[e.name][o]):n.push(t[e.names[i]])}else n.push(t[e.name]);return Oa.apply(null,n)},Aa=["v","o","s","i","u","e","p","c","b","t","r","z","a"],Na=["i","c","b","a"];On.exports=function(s,e){e=e||{},s.version==null&&(s.version=0),s.name==null&&(s.name=" "),s.media.forEach(function(i){i.payloads==null&&(i.payloads="")});var t=e.outerOrder||Aa,r=e.innerOrder||Na,n=[];return t.forEach(function(i){Gr[i].forEach(function(o){o.name in s&&s[o.name]!=null?n.push(mt(i,o,s)):o.push in s&&s[o.push]!=null&&s[o.push].forEach(function(a){n.push(mt(i,o,a))})})}),s.media.forEach(function(i){n.push(mt("m",Gr.m[0],i)),r.forEach(function(o){Gr[o].forEach(function(a){a.name in i&&i[a.name]!=null?n.push(mt(o,a,i)):a.push in i&&i[a.push]!=null&&i[a.push].forEach(function(c){n.push(mt(o,a,c))})})})}),n.join(`\r
3
+ `+i),r.push(n+"m+"+u0.exports.humanize(this.diff)+"\x1B[0m")}else r[0]=BN()+e+" "+r[0]}function BN(){return Sr.inspectOpts.hideDate?"":new Date().toISOString()+" "}function NN(...r){return process.stderr.write(d0.formatWithOptions(Sr.inspectOpts,...r)+`
4
+ `)}function ON(r){r?process.env.DEBUG=r:delete process.env.DEBUG}function LN(){return process.env.DEBUG}function DN(r){r.inspectOpts={};let e=Object.keys(Sr.inspectOpts);for(let t=0;t<e.length;t++)r.inspectOpts[e[t]]=Sr.inspectOpts[e[t]]}u0.exports=Bx()(Sr);var{formatters:CE}=u0.exports;CE.o=function(r){return this.inspectOpts.colors=this.useColors,d0.inspect(r,this.inspectOpts).split(`
5
+ `).map(e=>e.trim()).join(" ")};CE.O=function(r){return this.inspectOpts.colors=this.useColors,d0.inspect(r,this.inspectOpts)}});var Cf=re((XV,Mx)=>{"use strict";typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?Mx.exports=_E():Mx.exports=TE()});var IE=re(AE=>{"use strict";Object.defineProperty(AE,"__esModule",{value:!0})});var Yr=re(f0=>{"use strict";Object.defineProperty(f0,"__esModule",{value:!0});f0.Logger=void 0;var xd=Cf(),bd="media-client",Ux=class{_debug;_warn;_error;constructor(e){e?(this._debug=(0,xd.default)(`${bd}:${e}`),this._warn=(0,xd.default)(`${bd}:WARN:${e}`),this._error=(0,xd.default)(`${bd}:ERROR:${e}`)):(this._debug=(0,xd.default)(bd),this._warn=(0,xd.default)(`${bd}:WARN`),this._error=(0,xd.default)(`${bd}:ERROR`)),this._debug.log=console.info.bind(console),this._warn.log=console.warn.bind(console),this._error.log=console.error.bind(console)}get debug(){return this._debug}get warn(){return this._warn}get error(){return this._error}};f0.Logger=Ux});var jE=re((QV,jx)=>{"use strict";var vd=typeof Reflect=="object"?Reflect:null,RE=vd&&typeof vd.apply=="function"?vd.apply:function(e,t,s){return Function.prototype.apply.call(e,t,s)},l0;vd&&typeof vd.ownKeys=="function"?l0=vd.ownKeys:Object.getOwnPropertySymbols?l0=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:l0=function(e){return Object.getOwnPropertyNames(e)};function MN(r){console&&console.warn&&console.warn(r)}var PE=Number.isNaN||function(e){return e!==e};function Ht(){Ht.init.call(this)}jx.exports=Ht;jx.exports.once=FN;Ht.EventEmitter=Ht;Ht.prototype._events=void 0;Ht.prototype._eventsCount=0;Ht.prototype._maxListeners=void 0;var kE=10;function h0(r){if(typeof r!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof r)}Object.defineProperty(Ht,"defaultMaxListeners",{enumerable:!0,get:function(){return kE},set:function(r){if(typeof r!="number"||r<0||PE(r))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+r+".");kE=r}});Ht.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};Ht.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||PE(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this};function BE(r){return r._maxListeners===void 0?Ht.defaultMaxListeners:r._maxListeners}Ht.prototype.getMaxListeners=function(){return BE(this)};Ht.prototype.emit=function(e){for(var t=[],s=1;s<arguments.length;s++)t.push(arguments[s]);var n=e==="error",i=this._events;if(i!==void 0)n=n&&i.error===void 0;else if(!n)return!1;if(n){var o;if(t.length>0&&(o=t[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var c=i[e];if(c===void 0)return!1;if(typeof c=="function")RE(c,this,t);else for(var d=c.length,u=ME(c,d),s=0;s<d;++s)RE(u[s],this,t);return!0};function NE(r,e,t,s){var n,i,o;if(h0(t),i=r._events,i===void 0?(i=r._events=Object.create(null),r._eventsCount=0):(i.newListener!==void 0&&(r.emit("newListener",e,t.listener?t.listener:t),i=r._events),o=i[e]),o===void 0)o=i[e]=t,++r._eventsCount;else if(typeof o=="function"?o=i[e]=s?[t,o]:[o,t]:s?o.unshift(t):o.push(t),n=BE(r),n>0&&o.length>n&&!o.warned){o.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=r,a.type=e,a.count=o.length,MN(a)}return r}Ht.prototype.addListener=function(e,t){return NE(this,e,t,!1)};Ht.prototype.on=Ht.prototype.addListener;Ht.prototype.prependListener=function(e,t){return NE(this,e,t,!0)};function UN(){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 OE(r,e,t){var s={fired:!1,wrapFn:void 0,target:r,type:e,listener:t},n=UN.bind(s);return n.listener=t,s.wrapFn=n,n}Ht.prototype.once=function(e,t){return h0(t),this.on(e,OE(this,e,t)),this};Ht.prototype.prependOnceListener=function(e,t){return h0(t),this.prependListener(e,OE(this,e,t)),this};Ht.prototype.removeListener=function(e,t){var s,n,i,o,a;if(h0(t),n=this._events,n===void 0)return this;if(s=n[e],s===void 0)return this;if(s===t||s.listener===t)--this._eventsCount===0?this._events=Object.create(null):(delete n[e],n.removeListener&&this.emit("removeListener",e,s.listener||t));else if(typeof s!="function"){for(i=-1,o=s.length-1;o>=0;o--)if(s[o]===t||s[o].listener===t){a=s[o].listener,i=o;break}if(i<0)return this;i===0?s.shift():jN(s,i),s.length===1&&(n[e]=s[0]),n.removeListener!==void 0&&this.emit("removeListener",e,a||t)}return this};Ht.prototype.off=Ht.prototype.removeListener;Ht.prototype.removeAllListeners=function(e){var t,s,n;if(s=this._events,s===void 0)return this;if(s.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):s[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete s[e]),this;if(arguments.length===0){var i=Object.keys(s),o;for(n=0;n<i.length;++n)o=i[n],o!=="removeListener"&&this.removeAllListeners(o);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(t=s[e],typeof t=="function")this.removeListener(e,t);else if(t!==void 0)for(n=t.length-1;n>=0;n--)this.removeListener(e,t[n]);return this};function LE(r,e,t){var s=r._events;if(s===void 0)return[];var n=s[e];return n===void 0?[]:typeof n=="function"?t?[n.listener||n]:[n]:t?HN(n):ME(n,n.length)}Ht.prototype.listeners=function(e){return LE(this,e,!0)};Ht.prototype.rawListeners=function(e){return LE(this,e,!1)};Ht.listenerCount=function(r,e){return typeof r.listenerCount=="function"?r.listenerCount(e):DE.call(r,e)};Ht.prototype.listenerCount=DE;function DE(r){var e=this._events;if(e!==void 0){var t=e[r];if(typeof t=="function")return 1;if(t!==void 0)return t.length}return 0}Ht.prototype.eventNames=function(){return this._eventsCount>0?l0(this._events):[]};function ME(r,e){for(var t=new Array(e),s=0;s<e;++s)t[s]=r[s];return t}function jN(r,e){for(;e+1<r.length;e++)r[e]=r[e+1];r.pop()}function HN(r){for(var e=new Array(r.length),t=0;t<e.length;++t)e[t]=r[t].listener||r[t];return e}function FN(r,e){return new Promise(function(t,s){function n(o){r.removeListener(e,i),s(o)}function i(){typeof r.removeListener=="function"&&r.removeListener("error",n),t([].slice.call(arguments))}UE(r,e,i,{once:!0}),e!=="error"&&qN(r,n,{once:!0})})}function qN(r,e,t){typeof r.on=="function"&&UE(r,"error",e,t)}function UE(r,e,t,s){if(typeof r.on=="function")s.once?r.once(e,t):r.on(e,t);else if(typeof r.addEventListener=="function")r.addEventListener(e,function n(i){s.once&&r.removeEventListener(e,n),t(i)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof r)}});var as=re(p0=>{"use strict";Object.defineProperty(p0,"__esModule",{value:!0});p0.EnhancedEventEmitter=void 0;var zN=jE(),$N=Yr(),VN=new $N.Logger("EnhancedEventEmitter"),Hx=class extends zN.EventEmitter{constructor(){super(),this.setMaxListeners(1/0)}close(){super.removeAllListeners()}emit(e,...t){return super.emit(e,...t)}safeEmit(e,...t){try{return super.emit(e,...t)}catch(s){VN.error("safeEmit() | event listener threw an error [eventName:%s]:%o",e,s);try{super.emit("listenererror",e,s)}catch{}return!!super.listenerCount(e)}}on(e,t){return super.on(e,t),this}off(e,t){return super.off(e,t),this}addListener(e,t){return super.on(e,t),this}prependListener(e,t){return super.prependListener(e,t),this}once(e,t){return super.once(e,t),this}prependOnceListener(e,t){return super.prependOnceListener(e,t),this}removeListener(e,t){return super.off(e,t),this}removeAllListeners(e){return super.removeAllListeners(e),this}listenerCount(e){return super.listenerCount(e)}listeners(e){return super.listeners(e)}rawListeners(e){return super.rawListeners(e)}};p0.EnhancedEventEmitter=Hx});var Ls=re(wd=>{"use strict";Object.defineProperty(wd,"__esModule",{value:!0});wd.InvalidStateError=wd.UnsupportedError=void 0;var Fx=class r extends Error{constructor(e){super(e),this.name="UnsupportedError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,r):this.stack=new Error(e).stack}};wd.UnsupportedError=Fx;var qx=class r extends Error{constructor(e){super(e),this.name="InvalidStateError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,r):this.stack=new Error(e).stack}};wd.InvalidStateError=qx});var ka=re(Tf=>{"use strict";Object.defineProperty(Tf,"__esModule",{value:!0});Tf.clone=KN;Tf.generateRandomNumber=WN;Tf.deepFreeze=HE;function KN(r){if(r!==void 0)return Number.isNaN(r)?NaN:typeof structuredClone=="function"?structuredClone(r):JSON.parse(JSON.stringify(r))}function WN(){return Math.round(Math.random()*1e7)}function HE(r){let e=Reflect.ownKeys(r);for(let t of e){let s=r[t];(s&&typeof s=="object"||typeof s=="function")&&HE(s)}return Object.freeze(r)}});var FE=re(m0=>{"use strict";Object.defineProperty(m0,"__esModule",{value:!0});m0.Logger=void 0;var Sd=Cf(),_d="h264-profile-level-id",zx=class{_debug;_warn;_error;constructor(e){e?(this._debug=(0,Sd.default)(`${_d}:${e}`),this._warn=(0,Sd.default)(`${_d}:WARN:${e}`),this._error=(0,Sd.default)(`${_d}:ERROR:${e}`)):(this._debug=(0,Sd.default)(_d),this._warn=(0,Sd.default)(`${_d}:WARN`),this._error=(0,Sd.default)(`${_d}:ERROR`)),this._debug.log=console.info.bind(console),this._warn.log=console.warn.bind(console),this._error.log=console.error.bind(console)}get debug(){return this._debug}get warn(){return this._warn}get error(){return this._error}};m0.Logger=zx});var WE=re(Tr=>{"use strict";Object.defineProperty(Tr,"__esModule",{value:!0});Tr.ProfileLevelId=Tr.Level=Tr.Profile=void 0;Tr.parseProfileLevelId=VE;Tr.profileLevelIdToString=KE;Tr.profileToString=JN;Tr.levelToString=QN;Tr.parseSdpProfileLevelId=Pa;Tr.isSameProfile=ZN;Tr.isSameProfileAndLevel=eO;Tr.generateProfileLevelIdStringForAnswer=tO;Tr.supportedLevel=rO;var GN=FE(),rn=new GN.Logger,zt;(function(r){r[r.ConstrainedBaseline=1]="ConstrainedBaseline",r[r.Baseline=2]="Baseline",r[r.Main=3]="Main",r[r.ConstrainedHigh=4]="ConstrainedHigh",r[r.High=5]="High",r[r.PredictiveHigh444=6]="PredictiveHigh444"})(zt||(Tr.Profile=zt={}));var De;(function(r){r[r.L1_b=0]="L1_b",r[r.L1=10]="L1",r[r.L1_1=11]="L1_1",r[r.L1_2=12]="L1_2",r[r.L1_3=13]="L1_3",r[r.L2=20]="L2",r[r.L2_1=21]="L2_1",r[r.L2_2=22]="L2_2",r[r.L3=30]="L3",r[r.L3_1=31]="L3_1",r[r.L3_2=32]="L3_2",r[r.L4=40]="L4",r[r.L4_1=41]="L4_1",r[r.L4_2=42]="L4_2",r[r.L5=50]="L5",r[r.L5_1=51]="L5_1",r[r.L5_2=52]="L5_2"})(De||(Tr.Level=De={}));var Ed=class{profile;level;constructor(e,t){this.profile=e,this.level=t}};Tr.ProfileLevelId=Ed;var XN=new Ed(zt.ConstrainedBaseline,De.L3_1),en=class{mask;masked_value;constructor(e){this.mask=~zE("x",e),this.masked_value=zE("1",e)}isMatch(e){return this.masked_value===(e&this.mask)}},tn=class{profile_idc;profile_iop;profile;constructor(e,t,s){this.profile_idc=e,this.profile_iop=t,this.profile=s}},YN=[new tn(66,new en("x1xx0000"),zt.ConstrainedBaseline),new tn(77,new en("1xxx0000"),zt.ConstrainedBaseline),new tn(88,new en("11xx0000"),zt.ConstrainedBaseline),new tn(66,new en("x0xx0000"),zt.Baseline),new tn(88,new en("10xx0000"),zt.Baseline),new tn(77,new en("0x0x0000"),zt.Main),new tn(100,new en("00000000"),zt.High),new tn(100,new en("00001100"),zt.ConstrainedHigh),new tn(244,new en("00000000"),zt.PredictiveHigh444)],qE=[{max_macroblocks_per_second:1485,max_macroblock_frame_size:99,level:De.L1},{max_macroblocks_per_second:1485,max_macroblock_frame_size:99,level:De.L1_b},{max_macroblocks_per_second:3e3,max_macroblock_frame_size:396,level:De.L1_1},{max_macroblocks_per_second:6e3,max_macroblock_frame_size:396,level:De.L1_2},{max_macroblocks_per_second:11880,max_macroblock_frame_size:396,level:De.L1_3},{max_macroblocks_per_second:11880,max_macroblock_frame_size:396,level:De.L2},{max_macroblocks_per_second:19800,max_macroblock_frame_size:792,level:De.L2_1},{max_macroblocks_per_second:20250,max_macroblock_frame_size:1620,level:De.L2_2},{max_macroblocks_per_second:40500,max_macroblock_frame_size:1620,level:De.L3},{max_macroblocks_per_second:108e3,max_macroblock_frame_size:3600,level:De.L3_1},{max_macroblocks_per_second:216e3,max_macroblock_frame_size:5120,level:De.L3_2},{max_macroblocks_per_second:245760,max_macroblock_frame_size:8192,level:De.L4},{max_macroblocks_per_second:245760,max_macroblock_frame_size:8192,level:De.L4_1},{max_macroblocks_per_second:522240,max_macroblock_frame_size:8704,level:De.L4_2},{max_macroblocks_per_second:589824,max_macroblock_frame_size:22080,level:De.L5},{max_macroblocks_per_second:983040,max_macroblock_frame_size:36864,level:De.L5_1},{max_macroblocks_per_second:2073600,max_macroblock_frame_size:36864,level:De.L5_2}];function VE(r){if(typeof r!="string"||r.length!==6)return;let t=parseInt(r,16);if(t===0)return;let s=t&255,n=t>>8&255,i=t>>16&255,o;switch(s){case De.L1_1:{o=(n&16)!==0?De.L1_b:De.L1_1;break}case De.L1:case De.L1_2:case De.L1_3:case De.L2:case De.L2_1:case De.L2_2:case De.L3:case De.L3_1:case De.L3_2:case De.L4:case De.L4_1:case De.L4_2:case De.L5:case De.L5_1:case De.L5_2:{o=s;break}default:{rn.warn(`parseProfileLevelId() | unrecognized level_idc [str:${r}, level_idc:${s}]`);return}}for(let a of YN)if(i===a.profile_idc&&a.profile_iop.isMatch(n))return rn.debug(`parseProfileLevelId() | result [str:${r}, profile:${a.profile}, level:${o}]`),new Ed(a.profile,o);rn.warn(`parseProfileLevelId() | unrecognized profile_idc/profile_iop combination [str:${r}, profile_idc:${i}, profile_iop:${n}]`)}function KE(r){if(r.level==De.L1_b)switch(r.profile){case zt.ConstrainedBaseline:return"42f00b";case zt.Baseline:return"42100b";case zt.Main:return"4d100b";default:{rn.warn(`profileLevelIdToString() | Level 1_b not is allowed for profile ${r.profile}`);return}}let e;switch(r.profile){case zt.ConstrainedBaseline:{e="42e0";break}case zt.Baseline:{e="4200";break}case zt.Main:{e="4d00";break}case zt.ConstrainedHigh:{e="640c";break}case zt.High:{e="6400";break}case zt.PredictiveHigh444:{e="f400";break}default:{rn.warn(`profileLevelIdToString() | unrecognized profile ${r.profile}`);return}}let t=r.level.toString(16);return t.length===1&&(t=`0${t}`),`${e}${t}`}function JN(r){switch(r){case zt.ConstrainedBaseline:return"ConstrainedBaseline";case zt.Baseline:return"Baseline";case zt.Main:return"Main";case zt.ConstrainedHigh:return"ConstrainedHigh";case zt.High:return"High";case zt.PredictiveHigh444:return"PredictiveHigh444";default:{rn.warn(`profileToString() | unrecognized profile ${r}`);return}}}function QN(r){switch(r){case De.L1_b:return"1b";case De.L1:return"1";case De.L1_1:return"1.1";case De.L1_2:return"1.2";case De.L1_3:return"1.3";case De.L2:return"2";case De.L2_1:return"2.1";case De.L2_2:return"2.2";case De.L3:return"3";case De.L3_1:return"3.1";case De.L3_2:return"3.2";case De.L4:return"4";case De.L4_1:return"4.1";case De.L4_2:return"4.2";case De.L5:return"5";case De.L5_1:return"5.1";case De.L5_2:return"5.2";default:{rn.warn(`levelToString() | unrecognized level ${r}`);return}}}function Pa(r={}){let e=r["profile-level-id"];return e?VE(e):XN}function ZN(r={},e={}){let t=Pa(r),s=Pa(e);return!!(t&&s&&t.profile===s.profile)}function eO(r={},e={}){let t=Pa(r),s=Pa(e);return!!(t&&s&&t.profile===s.profile&&t.level==s.level)}function tO(r={},e={}){if(!r["profile-level-id"]&&!e["profile-level-id"]){rn.warn("generateProfileLevelIdStringForAnswer() | profile-level-id missing in local and remote params");return}let t=Pa(r),s=Pa(e);if(!t)throw new TypeError("invalid local_profile_level_id");if(!s)throw new TypeError("invalid remote_profile_level_id");if(t.profile!==s.profile)throw new TypeError("H264 Profile mismatch");let n=$E(r)&&$E(e),i=t.level,o=s.level,a=nO(i,o),c=n?i:a;return rn.debug(`generateProfileLevelIdStringForAnswer() | result [profile:${t.profile}, level:${c}]`),KE(new Ed(t.profile,c))}function rO(r,e){for(let s=qE.length-1;s>=0;--s){let n=qE[s];if(n.max_macroblock_frame_size*256<=r&&n.max_macroblocks_per_second<=e*n.max_macroblock_frame_size)return rn.debug(`supportedLevel() | result [max_frame_pixel_count:${r}, max_fps:${e}, level:${n.level}]`),n.level}rn.warn(`supportedLevel() | no level supported [max_frame_pixel_count:${r}, max_fps:${e}]`)}function zE(r,e){return+(e[0]===r)<<7|+(e[1]===r)<<6|+(e[2]===r)<<5|+(e[3]===r)<<4|+(e[4]===r)<<3|+(e[5]===r)<<2|+(e[6]===r)<<1|+(e[7]===r)<<0}function sO(r,e){return r===De.L1_b?e!==De.L1&&e!==De.L1_b:e===De.L1_b?r!==De.L1:r<e}function nO(r,e){return sO(r,e)?r:e}function $E(r={}){let e=r["level-asymmetry-allowed"];return e===!0||e===1||e==="1"}});var Rn=re(Jr=>{"use strict";Object.defineProperty(Jr,"__esModule",{value:!0});Jr.validateAndNormalizeRtpCapabilities=dO;Jr.validateAndNormalizeRtpParameters=Vx;Jr.validateAndNormalizeSctpStreamParameters=uO;Jr.validateSctpCapabilities=fO;Jr.getExtendedRtpCapabilities=lO;Jr.getRecvRtpCapabilities=hO;Jr.getSendRtpCapabilities=pO;Jr.getSendingRtpParameters=mO;Jr.getSendingRemoteRtpParameters=gO;Jr.reduceCodecs=yO;Jr.generateProbatorRtpParameters=xO;Jr.canSend=bO;Jr.canReceive=vO;var GE=WE(),iO=ka(),oO="probator",aO=1234,cO=127;function dO(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 e of r.codecs)wO(e);if(r.headerExtensions&&!Array.isArray(r.headerExtensions))throw new TypeError("caps.headerExtensions is not an array");r.headerExtensions||(r.headerExtensions=[]);for(let e of r.headerExtensions)SO(e)}function Vx(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 e of r.codecs)_O(e);if(r.headerExtensions&&!Array.isArray(r.headerExtensions))throw new TypeError("params.headerExtensions is not an array");r.headerExtensions||(r.headerExtensions=[]);for(let e of r.headerExtensions)EO(e);if(r.encodings&&!Array.isArray(r.encodings))throw new TypeError("params.encodings is not an array");r.encodings||(r.encodings=[]);for(let e of r.encodings)CO(e);if(r.rtcp&&typeof r.rtcp!="object")throw new TypeError("params.rtcp is not an object");r.rtcp||(r.rtcp={}),TO(r.rtcp)}function uO(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 e=!1;if(typeof r.ordered=="boolean"?e=!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(e&&r.ordered&&(r.maxPacketLifeTime||r.maxRetransmits))throw new TypeError("cannot be ordered with maxPacketLifeTime or maxRetransmits");if(!e&&(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 fO(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");AO(r.numStreams)}function lO(r,e,t){let s={codecs:[],headerExtensions:[]};if(t)for(let n of r.codecs??[]){if(Cd(n))continue;let i=(e.codecs??[]).find(a=>$x(a,n,{strict:!0,modify:!0}));if(!i)continue;let o={kind:n.kind,mimeType:n.mimeType,clockRate:n.clockRate,channels:n.channels,localPayloadType:n.preferredPayloadType,localRtxPayloadType:void 0,remotePayloadType:i.preferredPayloadType,remoteRtxPayloadType:void 0,localParameters:n.parameters??{},remoteParameters:i.parameters??{},rtcpFeedback:XE(n,i)};s.codecs.push(o)}else for(let n of e.codecs??[]){if(Cd(n))continue;let i=(r.codecs??[]).find(a=>$x(a,n,{strict:!0,modify:!0}));if(!i)continue;let o={kind:i.kind,mimeType:i.mimeType,clockRate:i.clockRate,channels:i.channels,localPayloadType:i.preferredPayloadType,localRtxPayloadType:void 0,remotePayloadType:n.preferredPayloadType,remoteRtxPayloadType:void 0,localParameters:i.parameters??{},remoteParameters:n.parameters??{},rtcpFeedback:XE(i,n)};s.codecs.push(o)}for(let n of s.codecs){let i=r.codecs.find(a=>Cd(a)&&a.parameters?.apt===n.localPayloadType),o=e.codecs.find(a=>Cd(a)&&a.parameters?.apt===n.remotePayloadType);i&&o&&(n.localRtxPayloadType=i.preferredPayloadType,n.remoteRtxPayloadType=o.preferredPayloadType)}for(let n of e.headerExtensions){let i=r.headerExtensions.find(a=>IO(a,n));if(!i)continue;let o={kind:n.kind,uri:n.uri,sendId:i.preferredId,recvId:n.preferredId,encrypt:i.preferredEncrypt??!1,direction:"sendrecv"};switch(n.direction){case"sendrecv":{o.direction="sendrecv";break}case"recvonly":{o.direction="sendonly";break}case"sendonly":{o.direction="recvonly";break}case"inactive":{o.direction="inactive";break}}s.headerExtensions.push(o)}return s}function hO(r){return JE({direction:"recvonly",extendedRtpCapabilities:r})}function pO(r){return JE({direction:"sendonly",extendedRtpCapabilities:r})}function mO(r,e){let t={mid:void 0,codecs:[],headerExtensions:[],encodings:[],rtcp:{}};for(let s of e.codecs){if(s.kind!==r)continue;let n={mimeType:s.mimeType,payloadType:s.localPayloadType,clockRate:s.clockRate,channels:s.channels,parameters:s.localParameters,rtcpFeedback:s.rtcpFeedback};if(t.codecs.push(n),s.localRtxPayloadType){let i={mimeType:`${s.kind}/rtx`,payloadType:s.localRtxPayloadType,clockRate:s.clockRate,parameters:{apt:s.localPayloadType},rtcpFeedback:[]};t.codecs.push(i)}}for(let s of e.headerExtensions){if(s.kind&&s.kind!==r||s.direction!=="sendrecv"&&s.direction!=="sendonly")continue;let n={uri:s.uri,id:s.sendId,encrypt:s.encrypt,parameters:{}};t.headerExtensions.push(n)}return t}function gO(r,e){let t={mid:void 0,codecs:[],headerExtensions:[],encodings:[],rtcp:{}};for(let s of e.codecs){if(s.kind!==r)continue;let n={mimeType:s.mimeType,payloadType:s.localPayloadType,clockRate:s.clockRate,channels:s.channels,parameters:s.remoteParameters,rtcpFeedback:s.rtcpFeedback};if(t.codecs.push(n),s.localRtxPayloadType){let i={mimeType:`${s.kind}/rtx`,payloadType:s.localRtxPayloadType,clockRate:s.clockRate,parameters:{apt:s.localPayloadType},rtcpFeedback:[]};t.codecs.push(i)}}for(let s of e.headerExtensions){if(s.kind&&s.kind!==r||s.direction!=="sendrecv"&&s.direction!=="sendonly")continue;let n={uri:s.uri,id:s.sendId,encrypt:s.encrypt,parameters:{}};t.headerExtensions.push(n)}if(t.headerExtensions.some(s=>s.uri==="http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01"))for(let s of t.codecs)s.rtcpFeedback=(s.rtcpFeedback??[]).filter(n=>n.type!=="goog-remb");else if(t.headerExtensions.some(s=>s.uri==="http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time"))for(let s of t.codecs)s.rtcpFeedback=(s.rtcpFeedback??[]).filter(n=>n.type!=="transport-cc");else for(let s of t.codecs)s.rtcpFeedback=(s.rtcpFeedback??[]).filter(n=>n.type!=="transport-cc"&&n.type!=="goog-remb");return t}function yO(r,e){let t=[];if(!e)t.push(r[0]),Cd(r[1])&&t.push(r[1]);else{for(let s=0;s<r.length;++s)if($x(r[s],e,{strict:!0})){t.push(r[s]),Cd(r[s+1])&&t.push(r[s+1]);break}if(t.length===0)throw new TypeError("no matching codec found")}return t}function xO(r){r=iO.clone(r),Vx(r);let e={mid:oO,codecs:[],headerExtensions:[],encodings:[{ssrc:aO}],rtcp:{cname:"probator"}};return e.codecs.push(r.codecs[0]),e.codecs[0].payloadType=cO,e.headerExtensions=r.headerExtensions,e}function bO(r,e){return(e.codecs??[]).some(t=>t.kind===r)}function vO(r,e){if(Vx(r),r.codecs.length===0)return!1;let t=r.codecs[0];return(e.codecs??[]).some(s=>s.preferredPayloadType===t.payloadType)}function wO(r){let e=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 t=e.exec(r.mimeType);if(!t)throw new TypeError("invalid codec.mimeType");if(r.kind=t[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 s of Object.keys(r.parameters)){let n=r.parameters[s];if(n===void 0&&(r.parameters[s]="",n=""),typeof n!="string"&&typeof n!="number")throw new TypeError(`invalid codec parameter [key:${s}s, value:${n}]`);if(s==="apt"&&typeof n!="number")throw new TypeError("invalid codec apt parameter")}(!r.rtcpFeedback||!Array.isArray(r.rtcpFeedback))&&(r.rtcpFeedback=[]);for(let s of r.rtcpFeedback)YE(s)}function YE(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 SO(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 _O(r){let e=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 t=e.exec(r.mimeType);if(!t)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");t[1].toLowerCase()==="audio"?typeof r.channels!="number"&&(r.channels=1):delete r.channels,(!r.parameters||typeof r.parameters!="object")&&(r.parameters={});for(let n of Object.keys(r.parameters)){let i=r.parameters[n];if(i===void 0&&(r.parameters[n]="",i=""),typeof i!="string"&&typeof i!="number")throw new TypeError(`invalid codec parameter [key:${n}s, value:${i}]`);if(n==="apt"&&typeof i!="number")throw new TypeError("invalid codec apt parameter")}(!r.rtcpFeedback||!Array.isArray(r.rtcpFeedback))&&(r.rtcpFeedback=[]);for(let n of r.rtcpFeedback)YE(n)}function EO(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 e of Object.keys(r.parameters)){let t=r.parameters[e];if(t===void 0&&(r.parameters[e]="",t=""),typeof t!="string"&&typeof t!="number")throw new TypeError("invalid header extension parameter")}}function CO(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 TO(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 AO(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 JE({direction:r,extendedRtpCapabilities:e}){let t={codecs:[],headerExtensions:[]};for(let s of e.codecs){let n={kind:s.kind,mimeType:s.mimeType,preferredPayloadType:s.remotePayloadType,clockRate:s.clockRate,channels:s.channels,parameters:s.localParameters,rtcpFeedback:s.rtcpFeedback};if(t.codecs.push(n),!s.remoteRtxPayloadType)continue;let i={kind:s.kind,mimeType:`${s.kind}/rtx`,preferredPayloadType:s.remoteRtxPayloadType,clockRate:s.clockRate,parameters:{apt:s.remotePayloadType},rtcpFeedback:[]};t.codecs.push(i)}for(let s of e.headerExtensions){if(s.direction!=="sendrecv"&&s.direction!==r)continue;let n={kind:s.kind,uri:s.uri,preferredId:s.recvId,preferredEncrypt:s.encrypt??!1,direction:s.direction};t.headerExtensions.push(n)}return t}function Cd(r){return r?/.+\/rtx$/i.test(r.mimeType):!1}function $x(r,e,{strict:t=!1,modify:s=!1}={}){let n=r.mimeType.toLowerCase(),i=e.mimeType.toLowerCase();if(n!==i||r.clockRate!==e.clockRate||r.channels!==e.channels)return!1;switch(n){case"video/h264":{if(t){let o=r.parameters["packetization-mode"]??0,a=e.parameters["packetization-mode"]??0;if(o!==a||!GE.isSameProfile(r.parameters,e.parameters))return!1;let c;try{c=GE.generateProfileLevelIdStringForAnswer(r.parameters,e.parameters)}catch{return!1}s&&(c?(r.parameters["profile-level-id"]=c,e.parameters["profile-level-id"]=c):(delete r.parameters["profile-level-id"],delete e.parameters["profile-level-id"]))}break}case"video/vp9":{if(t){let o=r.parameters["profile-id"]??0,a=e.parameters["profile-id"]??0;if(o!==a)return!1}break}}return!0}function IO(r,e){return!(r.kind&&e.kind&&r.kind!==e.kind||r.uri!==e.uri)}function XE(r,e){let t=[];for(let s of r.rtcpFeedback??[]){let n=(e.rtcpFeedback??[]).find(i=>i.type===s.type&&(i.parameter===s.parameter||!i.parameter&&!s.parameter));n&&t.push(n)}return t}});var QE=re(g0=>{"use strict";Object.defineProperty(g0,"__esModule",{value:!0});g0.Logger=void 0;var Td=Cf(),Ad="awaitqueue",Kx=class{_debug;_warn;_error;constructor(e){e?(this._debug=Td(`${Ad}:${e}`),this._warn=Td(`${Ad}:WARN:${e}`),this._error=Td(`${Ad}:ERROR:${e}`)):(this._debug=Td(Ad),this._warn=Td(`${Ad}:WARN`),this._error=Td(`${Ad}:ERROR`)),this._debug.log=console.info.bind(console),this._warn.log=console.warn.bind(console),this._error.log=console.error.bind(console)}get debug(){return this._debug}get warn(){return this._warn}get error(){return this._error}};g0.Logger=Kx});var Xx=re(Id=>{"use strict";Object.defineProperty(Id,"__esModule",{value:!0});Id.AwaitQueueRemovedTaskError=Id.AwaitQueueStoppedError=void 0;var Wx=class r extends Error{constructor(e){super(e??"queue stopped"),this.name="AwaitQueueStoppedError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,r)}};Id.AwaitQueueStoppedError=Wx;var Gx=class r extends Error{constructor(e){super(e??"queue task removed"),this.name="AwaitQueueRemovedTaskError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,r)}};Id.AwaitQueueRemovedTaskError=Gx});var ZE=re(y0=>{"use strict";Object.defineProperty(y0,"__esModule",{value:!0});y0.AwaitQueue=void 0;var RO=QE(),Yx=Xx(),bi=new RO.Logger("AwaitQueue"),Jx=class{pendingTasks=new Map;nextTaskId=0;constructor(){bi.debug("constructor()")}get size(){return this.pendingTasks.size}async push(e,t,s){if(t=t??e.name,bi.debug(`push() [name:${t}, options:%o]`,s),typeof e!="function")throw new TypeError("given task is not a function");if(t)try{Object.defineProperty(e,"name",{value:t})}catch{}return new Promise((n,i)=>{if(t&&s?.removeOngoingTasksWithSameName)for(let a of this.pendingTasks.values())a.name===t&&a.reject(new Yx.AwaitQueueRemovedTaskError,{canExecuteNextTask:!1});let o={id:this.nextTaskId++,task:e,name:t,enqueuedAt:Date.now(),executedAt:void 0,completed:!1,resolve:a=>{if(o.completed)return;o.completed=!0,this.pendingTasks.delete(o.id),bi.debug(`resolving task [name:${o.name}]`),n(a);let[c]=this.pendingTasks.values();c&&!c.executedAt&&this.execute(c)},reject:(a,{canExecuteNextTask:c})=>{if(!o.completed&&(o.completed=!0,this.pendingTasks.delete(o.id),bi.debug(`rejecting task [name:${o.name}]: %s`,String(a)),i(a),c)){let[d]=this.pendingTasks.values();d&&!d.executedAt&&this.execute(d)}}};this.pendingTasks.set(o.id,o),this.pendingTasks.size===1&&this.execute(o)})}stop(){bi.debug("stop()");for(let e of this.pendingTasks.values())bi.debug(`stop() | stopping task [name:${e.name}]`),e.reject(new Yx.AwaitQueueStoppedError,{canExecuteNextTask:!1})}remove(e){bi.debug(`remove() [taskIdx:${e}]`);let t=Array.from(this.pendingTasks.values())[e];if(!t){bi.debug(`stop() | no task with given idx [taskIdx:${e}]`);return}t.reject(new Yx.AwaitQueueRemovedTaskError,{canExecuteNextTask:!0})}dump(){let e=Date.now(),t=0;return Array.from(this.pendingTasks.values()).map(s=>({idx:t++,task:s.task,name:s.name,enqueuedTime:s.executedAt?s.executedAt-s.enqueuedAt:e-s.enqueuedAt,executionTime:s.executedAt?e-s.executedAt:0}))}async execute(e){if(bi.debug(`execute() [name:${e.name}]`),e.executedAt)throw new Error("task already being executed");e.executedAt=Date.now();try{let t=await e.task();e.resolve(t)}catch(t){e.reject(t,{canExecuteNextTask:!0})}}};y0.AwaitQueue=Jx});var tC=re(xo=>{"use strict";Object.defineProperty(xo,"__esModule",{value:!0});xo.AwaitQueueRemovedTaskError=xo.AwaitQueueStoppedError=xo.AwaitQueue=void 0;var kO=ZE();Object.defineProperty(xo,"AwaitQueue",{enumerable:!0,get:function(){return kO.AwaitQueue}});var eC=Xx();Object.defineProperty(xo,"AwaitQueueStoppedError",{enumerable:!0,get:function(){return eC.AwaitQueueStoppedError}});Object.defineProperty(xo,"AwaitQueueRemovedTaskError",{enumerable:!0,get:function(){return eC.AwaitQueueRemovedTaskError}})});var sC=re(x0=>{"use strict";Object.defineProperty(x0,"__esModule",{value:!0});x0.Producer=void 0;var PO=Yr(),rC=as(),Rd=Ls(),kn=new PO.Logger("Producer"),Qx=class extends rC.EnhancedEventEmitter{_id;_localId;_closed=!1;_rtpSender;_track;_kind;_rtpParameters;_paused;_maxSpatialLayer;_stopTracks;_disableTrackOnPause;_zeroRtpOnPause;_appData;_observer=new rC.EnhancedEventEmitter;constructor({id:e,localId:t,rtpSender:s,track:n,rtpParameters:i,stopTracks:o,disableTrackOnPause:a,zeroRtpOnPause:c,appData:d}){super(),kn.debug("constructor()"),this._id=e,this._localId=t,this._rtpSender=s,this._track=n,this._kind=n.kind,this._rtpParameters=i,this._paused=a?!n.enabled:!1,this._maxSpatialLayer=void 0,this._stopTracks=o,this._disableTrackOnPause=a,this._zeroRtpOnPause=c,this._appData=d??{},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(e){this._appData=e}get observer(){return this._observer}close(){this._closed||(kn.debug("close()"),this._closed=!0,this.destroyTrack(),this.emit("@close"),this._observer.safeEmit("close"),super.close(),this._observer.close())}transportClosed(){this._closed||(kn.debug("transportClosed()"),this._closed=!0,this.destroyTrack(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}async getStats(){if(this._closed)throw new Rd.InvalidStateError("closed");return new Promise((e,t)=>{this.safeEmit("@getstats",e,t)})}pause(){if(kn.debug("pause()"),this._closed){kn.error("pause() | Producer closed");return}this._paused=!0,this._track&&this._disableTrackOnPause&&(this._track.enabled=!1),this._zeroRtpOnPause&&new Promise((e,t)=>{this.safeEmit("@pause",e,t)}).catch(()=>{}),this._observer.safeEmit("pause")}resume(){if(kn.debug("resume()"),this._closed){kn.error("resume() | Producer closed");return}this._paused=!1,this._track&&this._disableTrackOnPause&&(this._track.enabled=!0),this._zeroRtpOnPause&&new Promise((e,t)=>{this.safeEmit("@resume",e,t)}).catch(()=>{}),this._observer.safeEmit("resume")}async replaceTrack({track:e}){if(kn.debug("replaceTrack() [track:%o]",e),this._closed){if(e&&this._stopTracks)try{e.stop()}catch{}throw new Rd.InvalidStateError("closed")}else if(e?.readyState==="ended")throw new Rd.InvalidStateError("track ended");if(e===this._track){kn.debug("replaceTrack() | same track, ignored");return}await new Promise((t,s)=>{this.safeEmit("@replacetrack",e,t,s)}),this.destroyTrack(),this._track=e,this._track&&this._disableTrackOnPause&&(this._paused?this._paused&&(this._track.enabled=!1):this._track.enabled=!0),this.handleTrack()}async setMaxSpatialLayer(e){if(this._closed)throw new Rd.InvalidStateError("closed");if(this._kind!=="video")throw new Rd.UnsupportedError("not a video Producer");if(typeof e!="number")throw new TypeError("invalid spatialLayer");e!==this._maxSpatialLayer&&(await new Promise((t,s)=>{this.safeEmit("@setmaxspatiallayer",e,t,s)}).catch(()=>{}),this._maxSpatialLayer=e)}async setRtpEncodingParameters(e){if(this._closed)throw new Rd.InvalidStateError("closed");if(typeof e!="object")throw new TypeError("invalid params");await new Promise((t,s)=>{this.safeEmit("@setrtpencodingparameters",e,t,s)})}onTrackEnded(){kn.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{}}};x0.Producer=Qx});var iC=re(b0=>{"use strict";Object.defineProperty(b0,"__esModule",{value:!0});b0.Consumer=void 0;var BO=Yr(),nC=as(),NO=Ls(),Pn=new BO.Logger("Consumer"),Zx=class extends nC.EnhancedEventEmitter{_id;_localId;_producerId;_closed=!1;_rtpReceiver;_track;_rtpParameters;_paused;_appData;_observer=new nC.EnhancedEventEmitter;constructor({id:e,localId:t,producerId:s,rtpReceiver:n,track:i,rtpParameters:o,appData:a}){super(),Pn.debug("constructor()"),this._id=e,this._localId=t,this._producerId=s,this._rtpReceiver=n,this._track=i,this._rtpParameters=o,this._paused=!i.enabled,this._appData=a??{},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(e){this._appData=e}get observer(){return this._observer}close(){this._closed||(Pn.debug("close()"),this._closed=!0,this.destroyTrack(),this.emit("@close"),this._observer.safeEmit("close"),super.close(),this._observer.close())}transportClosed(){this._closed||(Pn.debug("transportClosed()"),this._closed=!0,this.destroyTrack(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}async getStats(){if(this._closed)throw new NO.InvalidStateError("closed");return new Promise((e,t)=>{this.safeEmit("@getstats",e,t)})}pause(){if(Pn.debug("pause()"),this._closed){Pn.error("pause() | Consumer closed");return}if(this._paused){Pn.debug("pause() | Consumer is already paused");return}this._paused=!0,this._track.enabled=!1,this.emit("@pause"),this._observer.safeEmit("pause")}resume(){if(Pn.debug("resume()"),this._closed){Pn.error("resume() | Consumer closed");return}if(!this._paused){Pn.debug("resume() | Consumer is already resumed");return}this._paused=!1,this._track.enabled=!0,this.emit("@resume"),this._observer.safeEmit("resume")}onTrackEnded(){Pn.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{}}};b0.Consumer=Zx});var aC=re(v0=>{"use strict";Object.defineProperty(v0,"__esModule",{value:!0});v0.DataProducer=void 0;var OO=Yr(),oC=as(),LO=Ls(),vi=new OO.Logger("DataProducer"),eb=class extends oC.EnhancedEventEmitter{_id;_dataChannel;_closed=!1;_sctpStreamParameters;_appData;_observer=new oC.EnhancedEventEmitter;constructor({id:e,dataChannel:t,sctpStreamParameters:s,appData:n}){super(),vi.debug("constructor()"),this._id=e,this._dataChannel=t,this._sctpStreamParameters=s,this._appData=n??{},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(e){this._dataChannel.bufferedAmountLowThreshold=e}get appData(){return this._appData}set appData(e){this._appData=e}get observer(){return this._observer}close(){this._closed||(vi.debug("close()"),this._closed=!0,this._dataChannel.close(),this.emit("@close"),this._observer.safeEmit("close"),super.close(),this._observer.close())}transportClosed(){this._closed||(vi.debug("transportClosed()"),this._closed=!0,this._dataChannel.close(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}send(e){if(vi.debug("send()"),this._closed)throw new LO.InvalidStateError("closed");this._dataChannel.send(e)}handleDataChannel(){this._dataChannel.addEventListener("open",()=>{this._closed||(vi.debug('DataChannel "open" event'),this.safeEmit("open"))}),this._dataChannel.addEventListener("error",e=>{if(this._closed)return;let t=e.error??new Error("unknown DataChannel error");e.error?.errorDetail==="sctp-failure"?vi.error("DataChannel SCTP error [sctpCauseCode:%s]: %s",e.error?.sctpCauseCode,e.error.message):vi.error('DataChannel "error" event: %o',t),this.safeEmit("error",t)}),this._dataChannel.addEventListener("close",()=>{this._closed||(vi.warn('DataChannel "close" event'),this._closed=!0,this.emit("@close"),this.safeEmit("close"),this._observer.safeEmit("close"))}),this._dataChannel.addEventListener("message",()=>{this._closed||vi.warn('DataChannel "message" event in a DataProducer, message discarded')}),this._dataChannel.addEventListener("bufferedamountlow",()=>{this._closed||this.safeEmit("bufferedamountlow")})}};v0.DataProducer=eb});var dC=re(w0=>{"use strict";Object.defineProperty(w0,"__esModule",{value:!0});w0.DataConsumer=void 0;var DO=Yr(),cC=as(),Ba=new DO.Logger("DataConsumer"),tb=class extends cC.EnhancedEventEmitter{_id;_dataProducerId;_dataChannel;_closed=!1;_sctpStreamParameters;_appData;_observer=new cC.EnhancedEventEmitter;constructor({id:e,dataProducerId:t,dataChannel:s,sctpStreamParameters:n,appData:i}){super(),Ba.debug("constructor()"),this._id=e,this._dataProducerId=t,this._dataChannel=s,this._sctpStreamParameters=n,this._appData=i??{},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(e){this._dataChannel.binaryType=e}get appData(){return this._appData}set appData(e){this._appData=e}get observer(){return this._observer}close(){this._closed||(Ba.debug("close()"),this._closed=!0,this._dataChannel.close(),this.emit("@close"),this._observer.safeEmit("close"),super.close(),this._observer.close())}transportClosed(){this._closed||(Ba.debug("transportClosed()"),this._closed=!0,this._dataChannel.close(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}handleDataChannel(){this._dataChannel.addEventListener("open",()=>{this._closed||(Ba.debug('DataChannel "open" event'),this.safeEmit("open"))}),this._dataChannel.addEventListener("error",e=>{if(this._closed)return;let t=e.error??new Error("unknown DataChannel error");e.error?.errorDetail==="sctp-failure"?Ba.error("DataChannel SCTP error [sctpCauseCode:%s]: %s",e.error?.sctpCauseCode,e.error.message):Ba.error('DataChannel "error" event: %o',t),this.safeEmit("error",t)}),this._dataChannel.addEventListener("close",()=>{this._closed||(Ba.warn('DataChannel "close" event'),this._closed=!0,this.emit("@close"),this.safeEmit("close"),this._observer.safeEmit("close"))}),this._dataChannel.addEventListener("message",e=>{this._closed||this.safeEmit("message",e.data)})}};w0.DataConsumer=tb});var fC=re(S0=>{"use strict";Object.defineProperty(S0,"__esModule",{value:!0});S0.Transport=void 0;var MO=tC(),UO=Yr(),uC=as(),yr=Ls(),rb=ka(),Af=Rn(),jO=sC(),HO=iC(),FO=aC(),qO=dC(),dr=new UO.Logger("Transport"),sb=class{consumerOptions;promise;resolve;reject;constructor(e){this.consumerOptions=e,this.promise=new Promise((t,s)=>{this.resolve=t,this.reject=s})}},nb=class extends uC.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 MO.AwaitQueue;_pendingConsumerTasks=[];_consumerCreationInProgress=!1;_pendingPauseConsumers=new Map;_consumerPauseInProgress=!1;_pendingResumeConsumers=new Map;_consumerResumeInProgress=!1;_pendingCloseConsumers=new Map;_consumerCloseInProgress=!1;_observer=new uC.EnhancedEventEmitter;constructor({direction:e,id:t,iceParameters:s,iceCandidates:n,dtlsParameters:i,sctpParameters:o,iceServers:a,iceTransportPolicy:c,additionalSettings:d,appData:u,handlerFactory:f,getSendExtendedRtpCapabilities:h,recvRtpCapabilities:y,canProduceByKind:v}){super(),dr.debug("constructor() [id:%s, direction:%s]",t,e),this._id=t,this._direction=e,this._getSendExtendedRtpCapabilities=h,this._recvRtpCapabilities=y,this._canProduceByKind=v,this._maxSctpMessageSize=o?.maxMessageSize;let S=rb.clone(d)??{};delete S.iceServers,delete S.iceTransportPolicy,delete S.bundlePolicy,delete S.rtcpMuxPolicy,this._handler=f.factory({direction:e,iceParameters:s,iceCandidates:n,dtlsParameters:i,sctpParameters:o,iceServers:a,iceTransportPolicy:c,additionalSettings:S,getSendExtendedRtpCapabilities:this._getSendExtendedRtpCapabilities}),this._appData=u??{},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(e){this._appData=e}get observer(){return this._observer}close(){if(!this._closed){dr.debug("close()"),this._closed=!0,this._awaitQueue.stop(),this._handler.close(),this._connectionState="closed";for(let e of this._producers.values())e.transportClosed();this._producers.clear();for(let e of this._consumers.values())e.transportClosed();this._consumers.clear();for(let e of this._dataProducers.values())e.transportClosed();this._dataProducers.clear();for(let e of this._dataConsumers.values())e.transportClosed();this._dataConsumers.clear(),this._observer.safeEmit("close"),super.close(),this._observer.close()}}async getStats(){if(this._closed)throw new yr.InvalidStateError("closed");return this._handler.getTransportStats()}async restartIce({iceParameters:e}){if(dr.debug("restartIce()"),this._closed)throw new yr.InvalidStateError("closed");if(!e)throw new TypeError("missing iceParameters");return this._awaitQueue.push(async()=>await this._handler.restartIce(e),"transport.restartIce()")}async updateIceServers({iceServers:e}={}){if(dr.debug("updateIceServers()"),this._closed)throw new yr.InvalidStateError("closed");if(!Array.isArray(e))throw new TypeError("missing iceServers");return this._awaitQueue.push(async()=>this._handler.updateIceServers(e),"transport.updateIceServers()")}async produce({track:e,streamId:t,encodings:s,codecOptions:n,headerExtensionOptions:i,codec:o,stopTracks:a=!0,disableTrackOnPause:c=!0,zeroRtpOnPause:d=!1,onRtpSender:u,appData:f={}}={}){if(dr.debug("produce() [track:%o]",e),this._closed)throw new yr.InvalidStateError("closed");if(e){if(this._direction!=="send")throw new yr.UnsupportedError("not a sending Transport");if(this._canProduceByKind[e.kind]){if(e.readyState==="ended")throw new yr.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(f&&typeof f!="object")throw new TypeError("if given, appData must be an object")}else throw new yr.UnsupportedError(`cannot produce ${e.kind}`)}else throw new TypeError("missing track");return this._awaitQueue.push(async()=>{let h;if(s&&!Array.isArray(s))throw TypeError("encodings must be an array");s?.length===0?h=void 0:s&&(h=s.map(C=>{let O={active:!0};return C.active===!1&&(O.active=!1),typeof C.dtx=="boolean"&&(O.dtx=C.dtx),typeof C.scalabilityMode=="string"&&(O.scalabilityMode=C.scalabilityMode),typeof C.scaleResolutionDownBy=="number"&&(O.scaleResolutionDownBy=C.scaleResolutionDownBy),typeof C.maxBitrate=="number"&&(O.maxBitrate=C.maxBitrate),typeof C.maxFramerate=="number"&&(O.maxFramerate=C.maxFramerate),typeof C.adaptivePtime=="boolean"&&(O.adaptivePtime=C.adaptivePtime),typeof C.priority=="string"&&(O.priority=C.priority),typeof C.networkPriority=="string"&&(O.networkPriority=C.networkPriority),O}));let{localId:y,rtpParameters:v,rtpSender:S}=await this._handler.send({track:e,streamId:t,encodings:h,codecOptions:n,headerExtensionOptions:i,codec:o,onRtpSender:u});try{Af.validateAndNormalizeRtpParameters(v);let{id:C}=await new Promise((K,z)=>{this.safeEmit("produce",{kind:e.kind,rtpParameters:v,appData:f},K,z)}),O=new jO.Producer({id:C,localId:y,rtpSender:S,track:e,rtpParameters:v,stopTracks:a,disableTrackOnPause:c,zeroRtpOnPause:d,appData:f});return this._producers.set(O.id,O),this.handleProducer(O),this._observer.safeEmit("newproducer",O),O}catch(C){throw this._handler.stopSending(y).catch(()=>{}),C}},"transport.produce()").catch(h=>{if(a)try{e.stop()}catch{}throw h})}async consume({id:e,producerId:t,kind:s,rtpParameters:n,streamId:i,onRtpReceiver:o,appData:a={}}){if(dr.debug("consume()"),this._closed)throw new yr.InvalidStateError("closed");if(this._direction!=="recv")throw new yr.UnsupportedError("not a receiving Transport");if(typeof e!="string")throw new TypeError("missing id");if(typeof t!="string")throw new TypeError("missing producerId");if(s!=="audio"&&s!=="video")throw new TypeError(`invalid kind '${s}'`);if(this.listenerCount("connect")===0&&this._connectionState==="new")throw new TypeError('no "connect" listener set into this transport');if(a&&typeof a!="object")throw new TypeError("if given, appData must be an object");let c=rb.clone(n);if(!Af.canReceive(c,this._recvRtpCapabilities))throw new yr.UnsupportedError("cannot consume this Producer");let u=new sb({id:e,producerId:t,kind:s,rtpParameters:c,streamId:i,onRtpReceiver:o,appData:a});return this._pendingConsumerTasks.push(u),queueMicrotask(()=>{this._closed||this._consumerCreationInProgress===!1&&this.createPendingConsumers()}),u.promise}async produceData({ordered:e=!0,maxPacketLifeTime:t,maxRetransmits:s,label:n="",protocol:i="",appData:o={}}={}){if(dr.debug("produceData()"),this._closed)throw new yr.InvalidStateError("closed");if(this._direction!=="send")throw new yr.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(o&&typeof o!="object")throw new TypeError("if given, appData must be an object")}else throw new yr.UnsupportedError("SCTP not enabled by remote Transport");return(t||s)&&(e=!1),this._awaitQueue.push(async()=>{let{dataChannel:a,sctpStreamParameters:c}=await this._handler.sendDataChannel({sctpStreamParameters:{ordered:e,maxPacketLifeTime:t,maxRetransmits:s,label:n,protocol:i}});Af.validateAndNormalizeSctpStreamParameters(c);let{id:d}=await new Promise((f,h)=>{this.safeEmit("producedata",{sctpStreamParameters:c,label:n,protocol:i,appData:o},f,h)}),u=new FO.DataProducer({id:d,dataChannel:a,sctpStreamParameters:c,appData:o});return this._dataProducers.set(u.id,u),this.handleDataProducer(u),this._observer.safeEmit("newdataproducer",u),u},"transport.produceData()")}async consumeData({id:e,dataProducerId:t,sctpStreamParameters:s,label:n="",protocol:i="",appData:o={}}){if(dr.debug("consumeData()"),this._closed)throw new yr.InvalidStateError("closed");if(this._direction!=="recv")throw new yr.UnsupportedError("not a receiving Transport");if(this._maxSctpMessageSize){if(typeof e!="string")throw new TypeError("missing id");if(typeof t!="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(o&&typeof o!="object")throw new TypeError("if given, appData must be an object")}else throw new yr.UnsupportedError("SCTP not enabled by remote Transport");let a=rb.clone(s);return Af.validateAndNormalizeSctpStreamParameters(a),this._awaitQueue.push(async()=>{let{dataChannel:c}=await this._handler.receiveDataChannel({maxMessageSize:this._maxSctpMessageSize,sctpStreamParameters:a,label:n,protocol:i}),d=new qO.DataConsumer({id:e,dataProducerId:t,dataChannel:c,sctpStreamParameters:a,appData:o});return this._dataConsumers.set(d.id,d),this.handleDataConsumer(d),this._observer.safeEmit("newdataconsumer",d),d},"transport.consumeData()")}getDataChannelMaxMessageSize(){return this._handler.getDataChannelMaxMessageSize()}createPendingConsumers(){this._consumerCreationInProgress=!0,this._awaitQueue.push(async()=>{if(this._pendingConsumerTasks.length===0){dr.debug("createPendingConsumers() | there is no Consumer to be created");return}let e=[...this._pendingConsumerTasks];this._pendingConsumerTasks=[];let t,s=[];for(let n of e){let{id:i,kind:o,rtpParameters:a,streamId:c,onRtpReceiver:d}=n.consumerOptions;s.push({trackId:i,kind:o,rtpParameters:a,streamId:c,onRtpReceiver:d})}try{let n=await this._handler.receive(s);for(let i=0;i<n.length;++i){let o=e[i],a=n[i],{id:c,producerId:d,kind:u,rtpParameters:f,appData:h}=o.consumerOptions,{localId:y,rtpReceiver:v,track:S}=a,C=new HO.Consumer({id:c,localId:y,producerId:d,rtpReceiver:v,track:S,rtpParameters:f,appData:h});this._consumers.set(C.id,C),this.handleConsumer(C),!this._probatorConsumerCreated&&!t&&u==="video"&&(t=C),this._observer.safeEmit("newconsumer",C),o.resolve(C)}}catch(n){for(let i of e)i.reject(n)}if(t)try{let n=Af.generateProbatorRtpParameters(t.rtpParameters);await this._handler.receive([{trackId:"probator",kind:"video",rtpParameters:n}]),dr.debug("createPendingConsumers() | Consumer for RTP probation created"),this._probatorConsumerCreated=!0}catch(n){dr.error("createPendingConsumers() | failed to create Consumer for RTP probation:%o",n)}},"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){dr.debug("pausePendingConsumers() | there is no Consumer to be paused");return}let e=Array.from(this._pendingPauseConsumers.values());this._pendingPauseConsumers.clear();try{let t=e.map(s=>s.localId);await this._handler.pauseReceiving(t)}catch(t){dr.error("pausePendingConsumers() | failed to pause Consumers:",t)}},"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){dr.debug("resumePendingConsumers() | there is no Consumer to be resumed");return}let e=Array.from(this._pendingResumeConsumers.values());this._pendingResumeConsumers.clear();try{let t=e.map(s=>s.localId);await this._handler.resumeReceiving(t)}catch(t){dr.error("resumePendingConsumers() | failed to resume Consumers:",t)}},"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){dr.debug("closePendingConsumers() | there is no Consumer to be closed");return}let e=Array.from(this._pendingCloseConsumers.values());this._pendingCloseConsumers.clear();try{await this._handler.stopReceiving(e.map(t=>t.localId))}catch(t){dr.error("closePendingConsumers() | failed to close Consumers:",t)}},"transport.closePendingConsumers()").then(()=>{this._consumerCloseInProgress=!1,this._pendingCloseConsumers.size>0&&this.closePendingConsumers()}).catch(()=>{})}handleHandler(){let e=this._handler;e.on("@connect",({dtlsParameters:t},s,n)=>{if(this._closed){n(new yr.InvalidStateError("closed"));return}this.safeEmit("connect",{dtlsParameters:t},s,n)}),e.on("@icegatheringstatechange",t=>{t!==this._iceGatheringState&&(dr.debug("ICE gathering state changed to %s",t),this._iceGatheringState=t,this._closed||this.safeEmit("icegatheringstatechange",t))}),e.on("@icecandidateerror",t=>{dr.warn(`ICE candidate error [url:${t.url}, localAddress:${t.address}, localPort:${t.port}]: ${t.errorCode} "${t.errorText}"`),this.safeEmit("icecandidateerror",t)}),e.on("@connectionstatechange",t=>{t!==this._connectionState&&(dr.debug("connection state changed to %s",t),this._connectionState=t,this._closed||this.safeEmit("connectionstatechange",t))})}handleProducer(e){e.on("@close",()=>{this._producers.delete(e.id),!this._closed&&this._awaitQueue.push(async()=>await this._handler.stopSending(e.localId),"producer @close event").catch(t=>dr.warn("producer.close() failed:%o",t))}),e.on("@pause",(t,s)=>{this._awaitQueue.push(async()=>await this._handler.pauseSending(e.localId),"producer @pause event").then(t).catch(s)}),e.on("@resume",(t,s)=>{this._awaitQueue.push(async()=>await this._handler.resumeSending(e.localId),"producer @resume event").then(t).catch(s)}),e.on("@replacetrack",(t,s,n)=>{this._awaitQueue.push(async()=>await this._handler.replaceTrack(e.localId,t),"producer @replacetrack event").then(s).catch(n)}),e.on("@setmaxspatiallayer",(t,s,n)=>{this._awaitQueue.push(async()=>await this._handler.setMaxSpatialLayer(e.localId,t),"producer @setmaxspatiallayer event").then(s).catch(n)}),e.on("@setrtpencodingparameters",(t,s,n)=>{this._awaitQueue.push(async()=>await this._handler.setRtpEncodingParameters(e.localId,t),"producer @setrtpencodingparameters event").then(s).catch(n)}),e.on("@getstats",(t,s)=>{if(this._closed)return s(new yr.InvalidStateError("closed"));this._handler.getSenderStats(e.localId).then(t).catch(s)})}handleConsumer(e){e.on("@close",()=>{this._consumers.delete(e.id),this._pendingPauseConsumers.delete(e.id),this._pendingResumeConsumers.delete(e.id),!this._closed&&(this._pendingCloseConsumers.set(e.id,e),this._consumerCloseInProgress===!1&&this.closePendingConsumers())}),e.on("@pause",()=>{this._pendingResumeConsumers.has(e.id)&&this._pendingResumeConsumers.delete(e.id),this._pendingPauseConsumers.set(e.id,e),queueMicrotask(()=>{this._closed||this._consumerPauseInProgress===!1&&this.pausePendingConsumers()})}),e.on("@resume",()=>{this._pendingPauseConsumers.has(e.id)&&this._pendingPauseConsumers.delete(e.id),this._pendingResumeConsumers.set(e.id,e),queueMicrotask(()=>{this._closed||this._consumerResumeInProgress===!1&&this.resumePendingConsumers()})}),e.on("@getstats",(t,s)=>{if(this._closed)return s(new yr.InvalidStateError("closed"));this._handler.getReceiverStats(e.localId).then(t).catch(s)})}handleDataProducer(e){e.on("@close",()=>{this._dataProducers.delete(e.id)})}handleDataConsumer(e){e.on("@close",()=>{this._dataConsumers.delete(e.id)})}};S0.Transport=nb});var _0=re((pK,hC)=>{"use strict";var lC=hC.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(r){return r.encoding?"rtpmap:%d %s/%s/%s":r.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(r){return r.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(r){return r.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(r){return"extmap:%d"+(r.direction?"/%s":"%v")+(r["encrypt-uri"]?" %s":"%v")+" %s"+(r.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(r){return r.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(r){var e="candidate:%s %d %s %d %s %d typ %s";return e+=r.raddr!=null?" raddr %s rport %d":"%v%v",e+=r.tcptype!=null?" tcptype %s":"%v",r.generation!=null&&(e+=" generation %d"),e+=r["network-id"]!=null?" network-id %d":"%v",e+=r["network-cost"]!=null?" network-cost %d":"%v",e}},{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(r){var e="ssrc:%d";return r.attribute!=null&&(e+=" %s",r.value!=null&&(e+=":%s")),e}},{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(r){return r.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(r){return r.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(r){return"imageattr:%s %s %s"+(r.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(r){return"simulcast:%s %s"+(r.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(r){return"ts-refclk:%s"+(r.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(r){var e="mediaclk:";return e+=r.id!=null?"id=%s %s":"%v%s",e+=r.mediaClockValue!=null?"=%s":"",e+=r.rateNumerator!=null?" rate=%s":"",e+=r.rateDenominator!=null?"/%s":"",e}},{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(lC).forEach(function(r){var e=lC[r];e.forEach(function(t){t.reg||(t.reg=/(.*)/),t.format||(t.format="%s")})})});var gC=re(wi=>{"use strict";var kd=function(r){return String(Number(r))===r?Number(r):r},zO=function(r,e,t,s){if(s&&!t)e[s]=kd(r[1]);else for(var n=0;n<t.length;n+=1)r[n+1]!=null&&(e[t[n]]=kd(r[n+1]))},$O=function(r,e,t){var s=r.name&&r.names;r.push&&!e[r.push]?e[r.push]=[]:s&&!e[r.name]&&(e[r.name]={});var n=r.push?{}:s?e[r.name]:e;zO(t.match(r.reg),n,r.names,r.name),r.push&&e[r.push].push(n)},pC=_0(),VO=RegExp.prototype.test.bind(/^([a-z])=(.*)/);wi.parse=function(r){var e={},t=[],s=e;return r.split(/(\r\n|\r|\n)/).filter(VO).forEach(function(n){var i=n[0],o=n.slice(2);i==="m"&&(t.push({rtp:[],fmtp:[]}),s=t[t.length-1]);for(var a=0;a<(pC[i]||[]).length;a+=1){var c=pC[i][a];if(c.reg.test(o))return $O(c,s,o)}}),e.media=t,e};var mC=function(r,e){var t=e.split(/=(.+)/,2);return t.length===2?r[t[0]]=kd(t[1]):t.length===1&&e.length>1&&(r[t[0]]=void 0),r};wi.parseParams=function(r){return r.split(/;\s?/).reduce(mC,{})};wi.parseFmtpConfig=wi.parseParams;wi.parsePayloads=function(r){return r.toString().split(" ").map(Number)};wi.parseRemoteCandidates=function(r){for(var e=[],t=r.split(" ").map(kd),s=0;s<t.length;s+=3)e.push({component:t[s],ip:t[s+1],port:t[s+2]});return e};wi.parseImageAttributes=function(r){return r.split(" ").map(function(e){return e.substring(1,e.length-1).split(",").reduce(mC,{})})};wi.parseSimulcastStreamList=function(r){return r.split(";").map(function(e){return e.split(",").map(function(t){var s,n=!1;return t[0]!=="~"?s=kd(t):(s=kd(t.substring(1,t.length)),n=!0),{scid:s,paused:n}})})}});var xC=re((gK,yC)=>{"use strict";var ib=_0(),KO=/%[sdv%]/g,WO=function(r){var e=1,t=arguments,s=t.length;return r.replace(KO,function(n){if(e>=s)return n;var i=t[e];switch(e+=1,n){case"%%":return"%";case"%s":return String(i);case"%d":return Number(i);case"%v":return""}})},If=function(r,e,t){var s=e.format instanceof Function?e.format(e.push?t:t[e.name]):e.format,n=[r+"="+s];if(e.names)for(var i=0;i<e.names.length;i+=1){var o=e.names[i];e.name?n.push(t[e.name][o]):n.push(t[e.names[i]])}else n.push(t[e.name]);return WO.apply(null,n)},GO=["v","o","s","i","u","e","p","c","b","t","r","z","a"],XO=["i","c","b","a"];yC.exports=function(r,e){e=e||{},r.version==null&&(r.version=0),r.name==null&&(r.name=" "),r.media.forEach(function(i){i.payloads==null&&(i.payloads="")});var t=e.outerOrder||GO,s=e.innerOrder||XO,n=[];return t.forEach(function(i){ib[i].forEach(function(o){o.name in r&&r[o.name]!=null?n.push(If(i,o,r)):o.push in r&&r[o.push]!=null&&r[o.push].forEach(function(a){n.push(If(i,o,a))})})}),r.media.forEach(function(i){n.push(If("m",ib.m[0],i)),s.forEach(function(o){ib[o].forEach(function(a){a.name in i&&i[a.name]!=null?n.push(If(o,a,i)):a.push in i&&i[a.push]!=null&&i[a.push].forEach(function(c){n.push(If(o,a,c))})})})}),n.join(`\r
6
6
  `)+`\r
7
- `}});var _e=C(pe=>{"use strict";var De=Mn(),ja=An(),Fa=Kt();pe.grammar=Fa;pe.write=ja;pe.parse=De.parse;pe.parseParams=De.parseParams;pe.parseFmtpConfig=De.parseFmtpConfig;pe.parsePayloads=De.parsePayloads;pe.parseRemoteCandidates=De.parseRemoteCandidates;pe.parseImageAttributes=De.parseImageAttributes;pe.parseSimulcastStreamList=De.parseSimulcastStreamList});var Ie=C(Kr=>{"use strict";Object.defineProperty(Kr,"__esModule",{value:!0});Kr.parse=$a;var qa=new RegExp("^[LS]([1-9]\\d{0,1})T([1-9]\\d{0,1})");function $a(s){let e=qa.exec(s??"");return e?{spatialLayers:Number(e[1]),temporalLayers:Number(e[2])}:{spatialLayers:1,temporalLayers:1}}});var Fn=C(Ce=>{"use strict";Object.defineProperty(Ce,"__esModule",{value:!0});Ce.OfferMediaSection=Ce.AnswerMediaSection=Ce.MediaSection=void 0;var Ua=_e(),Nn=ke(),gt=class{_mediaObject;constructor({iceParameters:e,iceCandidates:t,dtlsParameters:r}){if(this._mediaObject={type:"",port:0,protocol:"",payloads:"",rtp:[],fmtp:[]},e&&this.setIceParameters(e),t){this._mediaObject.candidates=[];for(let n of t){let i={foundation:n.foundation,component:1,ip:n.address??n.ip,port:n.port,priority:n.priority,transport:n.protocol,type:n.type};n.tcpType&&(i.tcptype=n.tcpType),this._mediaObject.candidates.push(i)}this._mediaObject.endOfCandidates="end-of-candidates",this._mediaObject.iceOptions="renomination"}r&&this.setDtlsRole(r.role)}get mid(){return String(this._mediaObject.mid)}get closed(){return this._mediaObject.port===0}getObject(){return this._mediaObject}setIceParameters(e){this._mediaObject.iceUfrag=e.usernameFragment,this._mediaObject.icePwd=e.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}};Ce.MediaSection=gt;var Qr=class extends gt{constructor({iceParameters:e,iceCandidates:t,dtlsParameters:r,sctpParameters:n,plainRtpParameters:i,offerMediaObject:o,offerRtpParameters:a,answerRtpParameters:c,codecOptions:d}){switch(super({iceParameters:e,iceCandidates:t,dtlsParameters:r}),this._mediaObject.mid=String(o.mid),this._mediaObject.type=o.type,this._mediaObject.protocol=o.protocol,i?(this._mediaObject.connection={ip:i.ip,version:i.ipVersion},this._mediaObject.port=i.port):(this._mediaObject.connection={ip:"127.0.0.1",version:4},this._mediaObject.port=7),o.type){case"audio":case"video":{this._mediaObject.direction="recvonly",this._mediaObject.rtp=[],this._mediaObject.rtcpFb=[],this._mediaObject.fmtp=[];for(let p of c.codecs){let l={payload:p.payloadType,codec:jn(p),rate:p.clockRate};p.channels>1&&(l.encoding=p.channels),this._mediaObject.rtp.push(l);let u=Nn.clone(p.parameters)??{},f=Nn.clone(p.rtcpFeedback)??[];if(d){let{opusStereo:h,opusFec:g,opusDtx:_,opusMaxPlaybackRate:y,opusMaxAverageBitrate:x,opusPtime:P,opusNack:k,videoGoogleStartBitrate:I,videoGoogleMaxBitrate:Y,videoGoogleMinBitrate:ye}=d,re=a.codecs.find(he=>he.payloadType===p.payloadType);switch(p.mimeType.toLowerCase()){case"audio/opus":case"audio/multiopus":{h!==void 0&&(re.parameters["sprop-stereo"]=h?1:0,u.stereo=h?1:0),g!==void 0&&(re.parameters.useinbandfec=g?1:0,u.useinbandfec=g?1:0),_!==void 0&&(re.parameters.usedtx=_?1:0,u.usedtx=_?1:0),y!==void 0&&(u.maxplaybackrate=y),x!==void 0&&(u.maxaveragebitrate=x),P!==void 0&&(re.parameters.ptime=P,u.ptime=P),k||(re.rtcpFeedback=re.rtcpFeedback.filter(he=>he.type!=="nack"||he.parameter),f=f.filter(he=>he.type!=="nack"||he.parameter));break}case"video/vp8":case"video/vp9":case"video/h264":case"video/h265":case"video/av1":{I!==void 0&&(u["x-google-start-bitrate"]=I),Y!==void 0&&(u["x-google-max-bitrate"]=Y),ye!==void 0&&(u["x-google-min-bitrate"]=ye);break}}}let m={payload:p.payloadType,config:""};for(let h of Object.keys(u))m.config&&(m.config+=";"),m.config+=`${h}=${u[h]}`;m.config&&this._mediaObject.fmtp.push(m);for(let h of f)this._mediaObject.rtcpFb.push({payload:p.payloadType,type:h.type,subtype:h.parameter})}this._mediaObject.payloads=c.codecs.map(p=>p.payloadType).join(" "),this._mediaObject.ext=[];for(let p of c.headerExtensions)(o.ext??[]).some(u=>u.uri===p.uri)&&this._mediaObject.ext.push({uri:p.uri,value:p.id});if(o.extmapAllowMixed==="extmap-allow-mixed"&&(this._mediaObject.extmapAllowMixed="extmap-allow-mixed"),o.simulcast){this._mediaObject.simulcast={dir1:"recv",list1:o.simulcast.list1},this._mediaObject.rids=[];for(let p of o.rids??[])p.direction==="send"&&this._mediaObject.rids.push({id:p.id,direction:"recv"})}else if(o.simulcast_03){this._mediaObject.simulcast_03={value:o.simulcast_03.value.replace(/send/g,"recv")},this._mediaObject.rids=[];for(let p of o.rids??[])p.direction==="send"&&this._mediaObject.rids.push({id:p.id,direction:"recv"})}this._mediaObject.rtcpMux="rtcp-mux",this._mediaObject.rtcpRsize="rtcp-rsize";break}case"application":{typeof o.sctpPort=="number"?(this._mediaObject.payloads="webrtc-datachannel",this._mediaObject.sctpPort=n.port,this._mediaObject.maxMessageSize=n.maxMessageSize):o.sctpmap&&(this._mediaObject.payloads=String(n.port),this._mediaObject.sctpmap={app:"webrtc-datachannel",sctpmapNumber:n.port,maxMessageSize:n.maxMessageSize});break}}}setDtlsRole(e){switch(e){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(e){if(!this._mediaObject.simulcast?.list1)return;let t={};for(let i of e)i.rid&&(t[i.rid]=i);let r=this._mediaObject.simulcast.list1,n=Ua.parseSimulcastStreamList(r);for(let i of n)for(let o of i)o.paused=!t[o.scid]?.active;this._mediaObject.simulcast.list1=n.map(i=>i.map(o=>`${o.paused?"~":""}${o.scid}`).join(",")).join(";")}};Ce.AnswerMediaSection=Qr;var Yr=class extends gt{constructor({iceParameters:e,iceCandidates:t,dtlsParameters:r,sctpParameters:n,plainRtpParameters:i,mid:o,kind:a,offerRtpParameters:c,streamId:d,trackId:p}){switch(super({iceParameters:e,iceCandidates:t,dtlsParameters:r}),this._mediaObject.mid=String(o),this._mediaObject.type=a,i?(this._mediaObject.connection={ip:i.ip,version:i.ipVersion},this._mediaObject.protocol="RTP/AVP",this._mediaObject.port=i.port):(this._mediaObject.connection={ip:"127.0.0.1",version:4},n?this._mediaObject.protocol="UDP/DTLS/SCTP":this._mediaObject.protocol="UDP/TLS/RTP/SAVPF",this._mediaObject.port=7),this._mediaObject.extmapAllowMixed="extmap-allow-mixed",a){case"audio":case"video":{this._mediaObject.direction="sendonly",this._mediaObject.rtp=[],this._mediaObject.rtcpFb=[],this._mediaObject.fmtp=[],this._mediaObject.msid=[{id:d,appdata:p}];for(let m of c.codecs){let h={payload:m.payloadType,codec:jn(m),rate:m.clockRate};m.channels>1&&(h.encoding=m.channels),this._mediaObject.rtp.push(h);let g={payload:m.payloadType,config:""};for(let _ of Object.keys(m.parameters??{}))g.config&&(g.config+=";"),g.config+=`${_}=${m.parameters[_]}`;g.config&&this._mediaObject.fmtp.push(g);for(let _ of m.rtcpFeedback)this._mediaObject.rtcpFb.push({payload:m.payloadType,type:_.type,subtype:_.parameter})}this._mediaObject.payloads=c.codecs.map(m=>m.payloadType).join(" "),this._mediaObject.ext=[];for(let m of c.headerExtensions)this._mediaObject.ext.push({uri:m.uri,value:m.id});this._mediaObject.rtcpMux="rtcp-mux",this._mediaObject.rtcpRsize="rtcp-rsize";let l=c.encodings[0],u=l.ssrc,f=l.rtx?.ssrc;this._mediaObject.ssrcs=[],this._mediaObject.ssrcGroups=[],u&&c.rtcp.cname&&this._mediaObject.ssrcs.push({id:u,attribute:"cname",value:c.rtcp.cname}),f&&(c.rtcp.cname&&this._mediaObject.ssrcs.push({id:f,attribute:"cname",value:c.rtcp.cname}),u&&this._mediaObject.ssrcGroups.push({semantics:"FID",ssrcs:`${u} ${f}`}));break}case"application":{this._mediaObject.payloads="webrtc-datachannel",this._mediaObject.sctpPort=n.port,this._mediaObject.maxMessageSize=n.maxMessageSize;break}}}setDtlsRole(e){this._mediaObject.setup="actpass"}resume(){this._mediaObject.direction="sendonly"}};Ce.OfferMediaSection=Yr;function jn(s){let t=new RegExp("^(audio|video)/(.+)","i").exec(s.mimeType);if(!t)throw new TypeError("invalid codec.mimeType");return t[2]}});var et=C(Jt=>{"use strict";Object.defineProperty(Jt,"__esModule",{value:!0});Jt.RemoteSdp=void 0;var za=_e(),Ba=z(),Qt=Fn(),Ha=Xr(),Va=["av1","h264"],Yt=new Ba.Logger("RemoteSdp"),Jr=class{_iceParameters;_iceCandidates;_dtlsParameters;_sctpParameters;_plainRtpParameters;_mediaSections=[];_midToIndex=new Map;_firstMid;_sdpObject;constructor({iceParameters:e,iceCandidates:t,dtlsParameters:r,sctpParameters:n,plainRtpParameters:i}){if(this._iceParameters=e,this._iceCandidates=t,this._dtlsParameters=r,this._sctpParameters=n,this._plainRtpParameters=i,this._sdpObject={version:0,origin:{address:"0.0.0.0",ipVer:4,netType:"IN",sessionId:"10000",sessionVersion:0,username:`media-client-v${Ha.version}`},name:"-",timing:{start:0,stop:0},media:[]},this._sdpObject.iceOptions="ice2",e?.iceLite&&(this._sdpObject.icelite="ice-lite"),r){this._sdpObject.msidSemantic={semantic:"WMS",token:"*"};let o=this._dtlsParameters.fingerprints.length;this._sdpObject.fingerprint={type:r.fingerprints[o-1].algorithm,hash:r.fingerprints[o-1].value},this._sdpObject.groups=[{type:"BUNDLE",mids:""}]}i&&(this._sdpObject.origin.address=i.ip,this._sdpObject.origin.ipVer=i.ipVersion)}updateIceParameters(e){Yt.debug("updateIceParameters() [iceParameters:%o]",e),this._iceParameters=e,this._sdpObject.icelite=e.iceLite?"ice-lite":void 0;for(let t of this._mediaSections)t.setIceParameters(e)}updateDtlsRole(e){Yt.debug("updateDtlsRole() [role:%s]",e),this._dtlsParameters.role=e;for(let t of this._mediaSections)t.setDtlsRole(e)}setSessionExtmapAllowMixed(){Yt.debug("setSessionExtmapAllowMixed()"),this._sdpObject.extmapAllowMixed="extmap-allow-mixed"}getNextMediaSectionIdx(){for(let e=0;e<this._mediaSections.length;++e){let t=this._mediaSections[e];if(t.closed)return{idx:e,reuseMid:t.mid}}return{idx:this._mediaSections.length}}send({offerMediaObject:e,reuseMid:t,offerRtpParameters:r,answerRtpParameters:n,codecOptions:i}){let o=new Qt.AnswerMediaSection({iceParameters:this._iceParameters,iceCandidates:this._iceCandidates,dtlsParameters:this._dtlsParameters,plainRtpParameters:this._plainRtpParameters,offerMediaObject:e,offerRtpParameters:r,answerRtpParameters:n,codecOptions:i}),a=o.getObject();a.rtp.find(d=>Va.includes(d.codec.toLowerCase()))||(a.ext=a.ext?.filter(d=>d.uri!=="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension")),t?this.replaceMediaSection(o,t):this._midToIndex.has(o.mid)?this.replaceMediaSection(o):this.addMediaSection(o)}receive({mid:e,kind:t,offerRtpParameters:r,streamId:n,trackId:i}){this.setSessionExtmapAllowMixed();let o=new Qt.OfferMediaSection({iceParameters:this._iceParameters,iceCandidates:this._iceCandidates,dtlsParameters:this._dtlsParameters,plainRtpParameters:this._plainRtpParameters,mid:e,kind:t,offerRtpParameters:r,streamId:n,trackId:i}),a=this._mediaSections.find(c=>c.closed&&c.getObject().type===t);a?this.replaceMediaSection(o,a.mid):this.addMediaSection(o)}pauseMediaSection(e){this.findMediaSection(e).pause()}resumeSendingMediaSection(e){this.findMediaSection(e).resume()}resumeReceivingMediaSection(e){this.findMediaSection(e).resume()}disableMediaSection(e){this.findMediaSection(e).disable()}closeMediaSection(e){let t=this.findMediaSection(e);return e===this._firstMid?(Yt.debug("closeMediaSection() | cannot close first media section, disabling it instead [mid:%s]",e),this.disableMediaSection(e),!1):(t.close(),this.regenerateBundleMids(),!0)}muxMediaSectionSimulcast(e,t){let r=this.findMediaSection(e);r.muxSimulcastStreams(t),this.replaceMediaSection(r)}sendSctpAssociation({offerMediaObject:e}){let t=new Qt.AnswerMediaSection({iceParameters:this._iceParameters,iceCandidates:this._iceCandidates,dtlsParameters:this._dtlsParameters,sctpParameters:this._sctpParameters,plainRtpParameters:this._plainRtpParameters,offerMediaObject:e});this.addMediaSection(t)}receiveSctpAssociation(){let e=new Qt.OfferMediaSection({iceParameters:this._iceParameters,iceCandidates:this._iceCandidates,dtlsParameters:this._dtlsParameters,sctpParameters:this._sctpParameters,plainRtpParameters:this._plainRtpParameters,mid:"datachannel",kind:"application"});this.addMediaSection(e)}getSdp(){return this._sdpObject.origin.sessionVersion++,za.write(this._sdpObject)}addMediaSection(e){this._firstMid||(this._firstMid=e.mid),this._mediaSections.push(e),this._midToIndex.set(e.mid,this._mediaSections.length-1),this._sdpObject.media.push(e.getObject()),this.regenerateBundleMids()}replaceMediaSection(e,t){if(typeof t=="string"){let r=this._midToIndex.get(t);if(r===void 0)throw new Error(`no media section found for reuseMid '${t}'`);let n=this._mediaSections[r];this._mediaSections[r]=e,this._midToIndex.delete(n.mid),this._midToIndex.set(e.mid,r),this._sdpObject.media[r]=e.getObject(),this.regenerateBundleMids()}else{let r=this._midToIndex.get(e.mid);if(r===void 0)throw new Error(`no media section found with mid '${e.mid}'`);this._mediaSections[r]=e,this._sdpObject.media[r]=e.getObject()}}findMediaSection(e){let t=this._midToIndex.get(e);if(t===void 0)throw new Error(`no media section found with mid '${e}'`);return this._mediaSections[t]}regenerateBundleMids(){this._dtlsParameters&&(this._sdpObject.groups[0].mids=this._mediaSections.filter(e=>!e.closed).map(e=>e.mid).join(" "))}};Jt.RemoteSdp=Jr});var tt=C(Le=>{"use strict";Object.defineProperty(Le,"__esModule",{value:!0});Le.extractRtpCapabilities=Wa;Le.extractDtlsParameters=Ga;Le.getCname=Ka;Le.applyCodecParameters=Qa;Le.addHeaderExtension=Ya;var qn=_e();function Wa({sdpObject:s}){let e=new Map,t=new Map;for(let n of s.media){let i=n.type;switch(i){case"audio":case"video":break;default:continue}for(let o of n.rtp){let a={kind:i,mimeType:`${i}/${o.codec}`,preferredPayloadType:o.payload,clockRate:o.rate,channels:o.encoding,parameters:{},rtcpFeedback:[]};e.set(a.preferredPayloadType,a)}for(let o of n.fmtp??[]){let a=qn.parseParams(o.config),c=e.get(o.payload);c&&(a?.hasOwnProperty("profile-level-id")&&(a["profile-level-id"]=String(a["profile-level-id"])),c.parameters=a)}for(let o of n.rtcpFb??[]){let a={type:o.type,parameter:o.subtype};if(a.parameter||delete a.parameter,o.payload!=="*"){let c=e.get(Number(o.payload));if(!c)continue;c.rtcpFeedback.push(a)}else for(let c of e.values())c.kind===i&&!/.+\/rtx$/i.test(c.mimeType)&&c.rtcpFeedback.push(a)}for(let o of n.ext??[]){if(o["encrypt-uri"])continue;let a={kind:i,uri:o.uri,preferredId:o.value};t.set(a.preferredId,a)}}return{codecs:Array.from(e.values()),headerExtensions:Array.from(t.values())}}function Ga({sdpObject:s}){let e=s.setup,t=s.fingerprint;if(!e||!t){let i=(s.media??[]).find(o=>o.port!==0);i&&(e=e??i.setup,t=t??i.fingerprint)}if(e){if(!t)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 r;switch(e){case"active":{r="client";break}case"passive":{r="server";break}case"actpass":{r="auto";break}}return{role:r,fingerprints:[{algorithm:t.type,value:t.hash}]}}function Ka({offerMediaObject:s}){let e=(s.ssrcs??[]).find(t=>t.attribute==="cname");return e?e.value:""}function Qa({offerRtpParameters:s,answerMediaObject:e}){for(let t of s.codecs){let r=t.mimeType.toLowerCase();if(r!=="audio/opus"||!(e.rtp??[]).find(a=>a.payload===t.payloadType))continue;e.fmtp=e.fmtp??[];let i=e.fmtp.find(a=>a.payload===t.payloadType);i||(i={payload:t.payloadType,config:""},e.fmtp.push(i));let o=qn.parseParams(i.config);if(r==="audio/opus"){let a=t.parameters?.["sprop-stereo"];a!==void 0&&(o.stereo=Number(a)?1:0)}i.config="";for(let a of Object.keys(o))i.config&&(i.config+=";"),i.config+=`${a}=${o[a]}`}}function Ya({offerMediaObject:s,headerExtensionUri:e,headerExtensionId:t}){s.ext||(s.ext=[]),s.ext.push({uri:e,value:t})}});var rt=C(Xt=>{"use strict";Object.defineProperty(Xt,"__esModule",{value:!0});Xt.getRtpEncodings=Ja;Xt.addLegacySimulcast=Xa;function Ja({offerMediaObject:s,codecs:e}){let t=new Set;for(let i of s.ssrcs??[]){let o=i.id;o&&t.add(o)}if(t.size===0)throw new Error("no a=ssrc lines found");let r=new Map;for(let i of s.ssrcGroups??[]){if(i.semantics!=="FID")continue;let o=i.ssrcs.split(/\s+/),a=Number(o[0]),c=Number(o[1]);t.has(a)&&(t.delete(a),t.delete(c),r.set(a,c))}for(let i of t)r.set(i,void 0);let n=[];for(let[i,o]of r){let a={ssrc:i};o&&e.length>1&&(a.rtx={ssrc:o}),n.push(a)}return n}function Xa({offerMediaObject:s,numStreams:e}){if(e<=1)throw new TypeError("numStreams must be greater than 1");let t=(s.ssrcs??[]).find(l=>l.attribute==="msid");if(!t)throw new Error("a=ssrc line with msid information not found");let[r,n]=t.value.split(" "),i=Number(t.id),o;(s.ssrcGroups??[]).some(l=>{if(l.semantics!=="FID")return!1;let u=l.ssrcs.split(/\s+/);return Number(u[0])===i?(o=Number(u[1]),!0):!1});let a=(s.ssrcs??[]).find(l=>l.attribute==="cname");if(!a)throw new Error("a=ssrc line with cname information not found");let c=a.value,d=[],p=[];for(let l=0;l<e;++l)d.push(i+l),o&&p.push(o+l);s.ssrcGroups=[],s.ssrcs=[],s.ssrcGroups.push({semantics:"SIM",ssrcs:d.join(" ")});for(let l of d)s.ssrcs.push({id:l,attribute:"cname",value:c}),s.ssrcs.push({id:l,attribute:"msid",value:`${r} ${n}`});for(let l=0;l<p.length;++l){let u=d[l],f=p[l];s.ssrcs.push({id:f,attribute:"cname",value:c}),s.ssrcs.push({id:f,attribute:"msid",value:`${r} ${n}`}),s.ssrcGroups.push({semantics:"FID",ssrcs:`${u} ${f}`})}}});var st=C(_t=>{"use strict";Object.defineProperty(_t,"__esModule",{value:!0});_t.addNackSupportForOpus=Za;_t.addHeaderExtensionSupport=ec;_t.getMsidStreamIdAndTrackId=tc;function Za(s){for(let e of s.codecs??[])(e.mimeType.toLowerCase()==="audio/opus"||e.mimeType.toLowerCase()==="audio/multiopus")&&!e.rtcpFeedback?.some(t=>t.type==="nack"&&!t.parameter)&&(e.rtcpFeedback||(e.rtcpFeedback=[]),e.rtcpFeedback.push({type:"nack"}))}function ec(s,e){let t,r=s.headerExtensions?.find(i=>i.uri===e.uri);if(r){if(r.kind===e.kind)return;t=r.preferredId}if(s.headerExtensions||(s.headerExtensions=[]),t===void 0){t=1;let i=new Set(s.headerExtensions.map(o=>o.preferredId));for(;i.has(t);)++t}let n={kind:e.kind,uri:e.uri,preferredId:t,preferredEncrypt:!1,direction:e.direction};s.headerExtensions.push(n)}function tc(s){if(!s||typeof s!="string")return{msidStreamId:void 0,msidTrackId:void 0};let[e,t]=s.trim().split(/\s+/);return e?{msidStreamId:e,msidTrackId:t}:{msidStreamId:void 0,msidTrackId:void 0}}});var Bn=C(Zt=>{"use strict";Object.defineProperty(Zt,"__esModule",{value:!0});Zt.Chrome111=void 0;var le=_e(),rc=G(),sc=z(),vt=ae(),nc=X(),ic=Ie(),oc=et(),wt=tt(),$n=rt(),Zr=st(),T=new sc.Logger("Chrome111"),Un="Chrome111",zn={OS:65535,MIS:65535},es=class s extends rc.EnhancedEventEmitter{_closed=!1;_direction;_remoteSdp;_getSendExtendedRtpCapabilities;_forcedLocalDtlsRole;_pc;_mapMidTransceiver=new Map;_sendStream=new MediaStream;_hasDataChannelMediaSection=!1;_nextSendSctpStreamId=0;_transportReady=!1;static createFactory(){return{name:Un,factory:e=>new s(e),getNativeRtpCapabilities:async({direction:e})=>{T.debug("getNativeRtpCapabilities() [direction:%o]",e);let t=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{t.addTransceiver("audio",{direction:e}),t.addTransceiver("video",{direction:e,sendEncodings:[{scalabilityMode:"L3T3"}]});let r=await t.createOffer();try{t.close()}catch{}t=void 0;let n=le.parse(r.sdp);return s.getLocalRtpCapabilities(n)}catch(r){try{t?.close()}catch{}throw t=void 0,r}},getNativeSctpCapabilities:async()=>(T.debug("getNativeSctpCapabilities()"),{numStreams:zn})}}static getLocalRtpCapabilities(e,t=[]){let r=wt.extractRtpCapabilities({sdpObject:e});vt.validateAndNormalizeRtpCapabilities(r),Zr.addNackSupportForOpus(r);for(let n of t)Zr.addHeaderExtensionSupport(r,n);return r}constructor({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:c,getSendExtendedRtpCapabilities:d}){super(),T.debug("constructor()"),this._direction=e,this._remoteSdp=new oc.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i}),this._getSendExtendedRtpCapabilities=d,n.role&&n.role!=="auto"&&(this._forcedLocalDtlsRole=n.role==="server"?"client":"server"),this._pc=new RTCPeerConnection({iceServers:o??[],iceTransportPolicy:a??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...c}),this._pc.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.addEventListener("icecandidateerror",this.onIceCandidateError),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",this.onConnectionStateChange):(T.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return Un}close(){if(T.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(e){this.assertNotClosed(),T.debug("updateIceServers()");let t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),T.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),!!this._transportReady)if(this._direction==="send"){let t=await this._pc.createOffer({iceRestart:!0});T.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",t),await this._pc.setLocalDescription(t);let r={type:"answer",sdp:this._remoteSdp.getSdp()};T.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",r),await this._pc.setRemoteDescription(r)}else{let t={type:"offer",sdp:this._remoteSdp.getSdp()};T.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let r=await this._pc.createAnswer();T.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,streamId:t,encodings:r,codecOptions:n,headerExtensionOptions:i,codec:o,onRtpSender:a}){if(this.assertNotClosed(),this.assertSendDirection(),T.debug("send() [kind:%s, track.id:%s, streamId:%s]",e.kind,e.id,t),r&&r.length>1){let P=1;for(let k of r){let I=k.scalabilityMode?(0,ic.parse)(k.scalabilityMode).temporalLayers:3;I>P&&(P=I)}r.forEach((k,I)=>{k.rid=`r${I}`,k.scalabilityMode=`L1T${P}`})}let c=this._remoteSdp.getNextMediaSectionIdx(),d=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:r});a&&a(d.sender);let p=await this._pc.createOffer(),l=le.parse(p.sdp);l.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();let u=[];u.push({uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",kind:e.kind,direction:"sendonly"});let f=s.getLocalRtpCapabilities(l,u),m=this._getSendExtendedRtpCapabilities(f),h=vt.getSendingRtpParameters(e.kind,m);h.codecs=vt.reduceCodecs(h.codecs,o);let g=vt.getSendingRemoteRtpParameters(e.kind,m);if(g.codecs=vt.reduceCodecs(g.codecs,o),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:l}),i?.absCaptureTime){let P=l.media[c.idx];wt.addHeaderExtension({offerMediaObject:P,headerExtensionUri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",headerExtensionId:g.headerExtensions.find(k=>k.uri==="http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time").id}),p={type:"offer",sdp:le.write(l)}}T.debug("send() | calling pc.setLocalDescription() [offer:%o]",p),await this._pc.setLocalDescription(p);let _=d.mid;h.mid=_,l=le.parse(this._pc.localDescription.sdp);let y=l.media[c.idx];if(h.rtcp.cname=wt.getCname({offerMediaObject:y}),h.msid=`${t??this._sendStream.id} ${e.id}`,!r)h.encodings=$n.getRtpEncodings({offerMediaObject:y,codecs:h.codecs});else if(r.length===1){let P=$n.getRtpEncodings({offerMediaObject:y,codecs:h.codecs});Object.assign(P[0],r[0]),h.encodings=P}else h.encodings=r;this._remoteSdp.send({offerMediaObject:y,reuseMid:c.reuseMid,offerRtpParameters:h,answerRtpParameters:g,codecOptions:n});let x={type:"answer",sdp:this._remoteSdp.getSdp()};return T.debug("send() | calling pc.setRemoteDescription() [answer:%o]",x),await this._pc.setRemoteDescription(x),this._mapMidTransceiver.set(_,d),{localId:_,rtpParameters:h,rtpSender:d.sender}}async stopSending(e){if(this.assertSendDirection(),T.debug("stopSending() [localId:%s]",e),this._closed)return;let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");if(t.sender.replaceTrack(null),this._pc.removeTrack(t.sender),this._remoteSdp.closeMediaSection(t.mid))try{t.stop()}catch{}let n=await this._pc.createOffer();T.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);let i={type:"answer",sdp:this._remoteSdp.getSdp()};T.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),T.debug("pauseSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);let r=await this._pc.createOffer();T.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);let n={type:"answer",sdp:this._remoteSdp.getSdp()};T.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),T.debug("resumeSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(this._remoteSdp.resumeSendingMediaSection(e),!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly";let r=await this._pc.createOffer();T.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);let n={type:"answer",sdp:this._remoteSdp.getSdp()};T.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?T.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):T.debug("replaceTrack() [localId:%s, no track]",e);let r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");await r.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),this.assertSendDirection(),T.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);let r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");let n=r.sender.getParameters();n.encodings.forEach((a,c)=>{c<=t?a.active=!0:a.active=!1}),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);let i=await this._pc.createOffer();T.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);let o={type:"answer",sdp:this._remoteSdp.getSdp()};T.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),T.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);let r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");let n=r.sender.getParameters();n.encodings.forEach((a,c)=>{n.encodings[c]={...a,...t}}),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);let i=await this._pc.createOffer();T.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);let o={type:"answer",sdp:this._remoteSdp.getSdp()};T.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({sctpStreamParameters:e}){this.assertNotClosed(),this.assertSendDirection();let t={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e.ordered,maxPacketLifeTime:e.maxPacketLifeTime,maxRetransmits:e.maxRetransmits,protocol:e.protocol};T.debug("sendDataChannel() [options:%o]",t);let r=this._pc.createDataChannel(e.label,t);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%zn.MIS,!this._hasDataChannelMediaSection){let i=await this._pc.createOffer(),o=le.parse(i.sdp),a=o.media.find(d=>d.type==="application");this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),T.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i),this._remoteSdp.sendSctpAssociation({offerMediaObject:a});let c={type:"answer",sdp:this._remoteSdp.getSdp()};T.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",c),await this._pc.setRemoteDescription(c),this._hasDataChannelMediaSection=!0}let n={streamId:t.id,ordered:t.ordered,maxPacketLifeTime:t.maxPacketLifeTime,maxRetransmits:t.maxRetransmits};return{dataChannel:r,sctpStreamParameters:n}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();let t=[],r=new Map;for(let a of e){let{trackId:c,kind:d,rtpParameters:p,streamId:l}=a;T.debug("receive() [trackId:%s, kind:%s]",c,d);let u=p.mid??String(this._mapMidTransceiver.size);r.set(c,u);let{msidStreamId:f}=Zr.getMsidStreamIdAndTrackId(p.msid);this._remoteSdp.receive({mid:u,kind:d,offerRtpParameters:p,streamId:l??f??p.rtcp?.cname??"-",trackId:c})}let n={type:"offer",sdp:this._remoteSdp.getSdp()};T.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",n),await this._pc.setRemoteDescription(n);for(let a of e){let{trackId:c,onRtpReceiver:d}=a;if(d){let p=r.get(c),l=this._pc.getTransceivers().find(u=>u.mid===p);if(!l)throw new Error("transceiver not found");d(l.receiver)}}let i=await this._pc.createAnswer(),o=le.parse(i.sdp);for(let a of e){let{trackId:c,rtpParameters:d}=a,p=r.get(c),l=o.media.find(u=>String(u.mid)===p);wt.applyCodecParameters({offerRtpParameters:d,answerMediaObject:l})}i={type:"answer",sdp:le.write(o)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),T.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(let a of e){let{trackId:c}=a,d=r.get(c),p=this._pc.getTransceivers().find(l=>l.mid===d);if(p)this._mapMidTransceiver.set(d,p),t.push({localId:d,track:p.receiver.track,rtpReceiver:p.receiver});else throw new Error("new RTCRtpTransceiver not found")}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(let n of e){T.debug("stopReceiving() [localId:%s]",n);let i=this._mapMidTransceiver.get(n);if(!i)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(i.mid)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};T.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let r=await this._pc.createAnswer();T.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r);for(let n of e)this._mapMidTransceiver.delete(n)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(let n of e){T.debug("pauseReceiving() [localId:%s]",n);let i=this._mapMidTransceiver.get(n);if(!i)throw new Error("associated RTCRtpTransceiver not found");i.direction="inactive",this._remoteSdp.pauseMediaSection(n)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};T.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let r=await this._pc.createAnswer();T.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(let n of e){T.debug("resumeReceiving() [localId:%s]",n);let i=this._mapMidTransceiver.get(n);if(!i)throw new Error("associated RTCRtpTransceiver not found");i.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(n)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};T.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let r=await this._pc.createAnswer();T.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async getReceiverStats(e){this.assertNotClosed(),this.assertRecvDirection();let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({maxMessageSize:e,sctpStreamParameters:t,label:r,protocol:n}){this.assertNotClosed(),this.assertRecvDirection();let{streamId:i,ordered:o,maxPacketLifeTime:a,maxRetransmits:c}=t,d={negotiated:!0,id:i,ordered:o,maxPacketLifeTime:a,maxRetransmits:c,protocol:n};T.debug("receiveDataChannel() [options:%o]",d);let p=this._pc.createDataChannel(r,d);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();let l={type:"offer",sdp:this._remoteSdp.getSdp()};T.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",l),await this._pc.setRemoteDescription(l);let u=await this._pc.createAnswer(),f=le.parse(u.sdp),m=f.media.find(h=>h.type==="application");m.maxMessageSize=e,this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:f}),u={type:"answer",sdp:le.write(f)},T.debug("receiveDataChannel() | calling pc.setLocalDescription() [answer:%o]",u),await this._pc.setLocalDescription(u),this._hasDataChannelMediaSection=!0}return{dataChannel:p}}getDataChannelMaxMessageSize(){return this._pc.sctp?.maxMessageSize}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=le.parse(this._pc.localDescription.sdp));let r=wt.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole(e==="client"?"server":"client"),await new Promise((n,i)=>{this.safeEmit("@connect",{dtlsParameters:r},n,i)}),this._transportReady=!0}onIceGatheringStateChange=()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)};onIceCandidateError=e=>{this.emit("@icecandidateerror",e)};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 nc.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')}};Zt.Chrome111=es});var Wn=C(er=>{"use strict";Object.defineProperty(er,"__esModule",{value:!0});er.Chrome74=void 0;var Z=_e(),ac=z(),cc=G(),yt=ae(),dc=X(),pc=Ie(),lc=et(),bt=tt(),ts=rt(),rs=st(),S=new ac.Logger("Chrome74"),Hn="Chrome74",Vn={OS:1024,MIS:1024},ss=class s extends cc.EnhancedEventEmitter{_closed=!1;_direction;_remoteSdp;_getSendExtendedRtpCapabilities;_forcedLocalDtlsRole;_pc;_mapMidTransceiver=new Map;_sendStream=new MediaStream;_hasDataChannelMediaSection=!1;_nextSendSctpStreamId=0;_transportReady=!1;static createFactory(){return{name:Hn,factory:e=>new s(e),getNativeRtpCapabilities:async({direction:e})=>{S.debug("getNativeRtpCapabilities() [direction:%o]",e);let t=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{t.addTransceiver("audio",{direction:e}),t.addTransceiver("video",{direction:e});let r=await t.createOffer();try{t.close()}catch{}t=void 0;let n=Z.parse(r.sdp);return s.getLocalRtpCapabilities(n)}catch(r){try{t?.close()}catch{}throw t=void 0,r}},getNativeSctpCapabilities:async()=>(S.debug("getNativeSctpCapabilities()"),{numStreams:Vn})}}static getLocalRtpCapabilities(e,t=[]){let r=bt.extractRtpCapabilities({sdpObject:e});yt.validateAndNormalizeRtpCapabilities(r),rs.addNackSupportForOpus(r);for(let n of t)rs.addHeaderExtensionSupport(r,n);return r}constructor({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:c,getSendExtendedRtpCapabilities:d}){super(),S.debug("constructor()"),this._direction=e,this._remoteSdp=new lc.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i}),this._getSendExtendedRtpCapabilities=d,n.role&&n.role!=="auto"&&(this._forcedLocalDtlsRole=n.role==="server"?"client":"server"),this._pc=new RTCPeerConnection({iceServers:o??[],iceTransportPolicy:a??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...c}),this._pc.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.addEventListener("icecandidateerror",this.onIceCandidateError),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",this.onConnectionStateChange):(S.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return Hn}close(){if(S.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(e){this.assertNotClosed(),S.debug("updateIceServers()");let t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),S.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),!!this._transportReady)if(this._direction==="send"){let t=await this._pc.createOffer({iceRestart:!0});S.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",t),await this._pc.setLocalDescription(t);let r={type:"answer",sdp:this._remoteSdp.getSdp()};S.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",r),await this._pc.setRemoteDescription(r)}else{let t={type:"offer",sdp:this._remoteSdp.getSdp()};S.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let r=await this._pc.createAnswer();S.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,streamId:t,encodings:r,codecOptions:n,headerExtensionOptions:i,codec:o}){this.assertNotClosed(),this.assertSendDirection(),S.debug("send() [kind:%s, track.id:%s, streamId:%s]",e.kind,e.id,t),r&&r.length>1&&r.forEach((k,I)=>{k.rid=`r${I}`});let a=this._remoteSdp.getNextMediaSectionIdx(),c=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:r}),d=await this._pc.createOffer(),p=Z.parse(d.sdp);p.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();let l=[];l.push({uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",kind:e.kind,direction:"sendonly"});let u=s.getLocalRtpCapabilities(p,l),f=this._getSendExtendedRtpCapabilities(u),m=yt.getSendingRtpParameters(e.kind,f);m.codecs=yt.reduceCodecs(m.codecs,o);let h=yt.getSendingRemoteRtpParameters(e.kind,f);h.codecs=yt.reduceCodecs(h.codecs,o),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:p});let g=!1,_=(0,pc.parse)((r??[{}])[0].scalabilityMode),y;r?.length===1&&_.spatialLayers>1&&m.codecs[0].mimeType.toLowerCase()==="video/vp9"&&(S.debug("send() | enabling legacy simulcast for VP9 SVC"),g=!0,p=Z.parse(d.sdp),y=p.media[a.idx],ts.addLegacySimulcast({offerMediaObject:y,numStreams:_.spatialLayers}),d={type:"offer",sdp:Z.write(p)}),S.debug("send() | calling pc.setLocalDescription() [offer:%o]",d),i?.absCaptureTime&&(y=p.media[a.idx],bt.addHeaderExtension({offerMediaObject:y,headerExtensionUri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",headerExtensionId:h.headerExtensions.find(k=>k.uri==="http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time").id}),d={type:"offer",sdp:Z.write(p)}),await this._pc.setLocalDescription(d);let x=c.mid;if(m.mid=x,p=Z.parse(this._pc.localDescription.sdp),y=p.media[a.idx],m.rtcp.cname=bt.getCname({offerMediaObject:y}),m.msid=`${t??this._sendStream.id} ${e.id}`,!r)m.encodings=ts.getRtpEncodings({offerMediaObject:y,codecs:m.codecs});else if(r.length===1){let k=ts.getRtpEncodings({offerMediaObject:y,codecs:m.codecs});Object.assign(k[0],r[0]),g&&(k=[k[0]]),m.encodings=k}else m.encodings=r;if(m.encodings.length>1&&(m.codecs[0].mimeType.toLowerCase()==="video/vp8"||m.codecs[0].mimeType.toLowerCase()==="video/h264"))for(let k of m.encodings)k.scalabilityMode?k.scalabilityMode=`L1T${_.temporalLayers}`:k.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:y,reuseMid:a.reuseMid,offerRtpParameters:m,answerRtpParameters:h,codecOptions:n});let P={type:"answer",sdp:this._remoteSdp.getSdp()};return S.debug("send() | calling pc.setRemoteDescription() [answer:%o]",P),await this._pc.setRemoteDescription(P),this._mapMidTransceiver.set(x,c),{localId:x,rtpParameters:m,rtpSender:c.sender}}async stopSending(e){if(this.assertSendDirection(),S.debug("stopSending() [localId:%s]",e),this._closed)return;let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");if(t.sender.replaceTrack(null),this._pc.removeTrack(t.sender),this._remoteSdp.closeMediaSection(t.mid))try{t.stop()}catch{}let n=await this._pc.createOffer();S.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);let i={type:"answer",sdp:this._remoteSdp.getSdp()};S.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),S.debug("pauseSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);let r=await this._pc.createOffer();S.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);let n={type:"answer",sdp:this._remoteSdp.getSdp()};S.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),S.debug("resumeSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(this._remoteSdp.resumeSendingMediaSection(e),!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly";let r=await this._pc.createOffer();S.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);let n={type:"answer",sdp:this._remoteSdp.getSdp()};S.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?S.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):S.debug("replaceTrack() [localId:%s, no track]",e);let r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");await r.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),this.assertSendDirection(),S.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);let r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");let n=r.sender.getParameters();n.encodings.forEach((a,c)=>{c<=t?a.active=!0:a.active=!1}),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);let i=await this._pc.createOffer();S.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);let o={type:"answer",sdp:this._remoteSdp.getSdp()};S.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),S.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);let r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");let n=r.sender.getParameters();n.encodings.forEach((a,c)=>{n.encodings[c]={...a,...t}}),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);let i=await this._pc.createOffer();S.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);let o={type:"answer",sdp:this._remoteSdp.getSdp()};S.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({sctpStreamParameters:e}){this.assertNotClosed(),this.assertSendDirection();let t={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e.ordered,maxPacketLifeTime:e.maxPacketLifeTime,maxRetransmits:e.maxRetransmits,protocol:e.protocol};S.debug("sendDataChannel() [options:%o]",t);let r=this._pc.createDataChannel(e.label,t);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%Vn.MIS,!this._hasDataChannelMediaSection){let i=await this._pc.createOffer(),o=Z.parse(i.sdp),a=o.media.find(d=>d.type==="application");this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),S.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i),this._remoteSdp.sendSctpAssociation({offerMediaObject:a});let c={type:"answer",sdp:this._remoteSdp.getSdp()};S.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",c),await this._pc.setRemoteDescription(c),this._hasDataChannelMediaSection=!0}let n={streamId:t.id,ordered:t.ordered,maxPacketLifeTime:t.maxPacketLifeTime,maxRetransmits:t.maxRetransmits};return{dataChannel:r,sctpStreamParameters:n}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();let t=[],r=new Map;for(let a of e){let{trackId:c,kind:d,rtpParameters:p,streamId:l}=a;S.debug("receive() [trackId:%s, kind:%s]",c,d);let u=p.mid??String(this._mapMidTransceiver.size);r.set(c,u);let{msidStreamId:f}=rs.getMsidStreamIdAndTrackId(p.msid);this._remoteSdp.receive({mid:u,kind:d,offerRtpParameters:p,streamId:l??f??p.rtcp?.cname??"-",trackId:c})}let n={type:"offer",sdp:this._remoteSdp.getSdp()};S.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",n),await this._pc.setRemoteDescription(n);let i=await this._pc.createAnswer(),o=Z.parse(i.sdp);for(let a of e){let{trackId:c,rtpParameters:d}=a,p=r.get(c),l=o.media.find(u=>String(u.mid)===p);bt.applyCodecParameters({offerRtpParameters:d,answerMediaObject:l})}i={type:"answer",sdp:Z.write(o)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),S.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(let a of e){let{trackId:c}=a,d=r.get(c),p=this._pc.getTransceivers().find(l=>l.mid===d);if(p)this._mapMidTransceiver.set(d,p),t.push({localId:d,track:p.receiver.track,rtpReceiver:p.receiver});else throw new Error("new RTCRtpTransceiver not found")}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(let n of e){S.debug("stopReceiving() [localId:%s]",n);let i=this._mapMidTransceiver.get(n);if(!i)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(i.mid)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};S.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let r=await this._pc.createAnswer();S.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r);for(let n of e)this._mapMidTransceiver.delete(n)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(let n of e){S.debug("pauseReceiving() [localId:%s]",n);let i=this._mapMidTransceiver.get(n);if(!i)throw new Error("associated RTCRtpTransceiver not found");i.direction="inactive",this._remoteSdp.pauseMediaSection(n)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};S.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let r=await this._pc.createAnswer();S.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(let n of e){S.debug("resumeReceiving() [localId:%s]",n);let i=this._mapMidTransceiver.get(n);if(!i)throw new Error("associated RTCRtpTransceiver not found");i.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(n)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};S.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let r=await this._pc.createAnswer();S.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async getReceiverStats(e){this.assertNotClosed(),this.assertRecvDirection();let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({maxMessageSize:e,sctpStreamParameters:t,label:r,protocol:n}){this.assertNotClosed(),this.assertRecvDirection();let{streamId:i,ordered:o,maxPacketLifeTime:a,maxRetransmits:c}=t,d={negotiated:!0,id:i,ordered:o,maxPacketLifeTime:a,maxRetransmits:c,protocol:n};S.debug("receiveDataChannel() [options:%o]",d);let p=this._pc.createDataChannel(r,d);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();let l={type:"offer",sdp:this._remoteSdp.getSdp()};S.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",l),await this._pc.setRemoteDescription(l);let u=await this._pc.createAnswer(),f=Z.parse(u.sdp),m=f.media.find(h=>h.type==="application");m.maxMessageSize=e,this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:f}),u={type:"answer",sdp:Z.write(f)},S.debug("receiveDataChannel() | calling pc.setLocalDescription() [answer:%o]",u),await this._pc.setLocalDescription(u),this._hasDataChannelMediaSection=!0}return{dataChannel:p}}getDataChannelMaxMessageSize(){return this._pc.sctp?.maxMessageSize}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=Z.parse(this._pc.localDescription.sdp));let r=bt.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole(e==="client"?"server":"client"),await new Promise((n,i)=>{this.safeEmit("@connect",{dtlsParameters:r},n,i)}),this._transportReady=!0}onIceGatheringStateChange=()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)};onIceCandidateError=e=>{this.emit("@icecandidateerror",e)};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 dc.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')}};er.Chrome74=ss});var Jn=C(rr=>{"use strict";Object.defineProperty(rr,"__esModule",{value:!0});rr.Firefox120=void 0;var ve=_e(),uc=G(),hc=z(),Gn=X(),St=ae(),fc=Ie(),mc=et(),tr=tt(),Kn=rt(),gc=st(),E=new hc.Logger("Firefox120"),Qn="Firefox120",Yn={OS:16,MIS:2048},ns=class s extends uc.EnhancedEventEmitter{_closed=!1;_direction;_remoteSdp;_getSendExtendedRtpCapabilities;_pc;_mapMidTransceiver=new Map;_sendStream=new MediaStream;_hasDataChannelMediaSection=!1;_nextSendSctpStreamId=0;_transportReady=!1;static createFactory(){return{name:Qn,factory:e=>new s(e),getNativeRtpCapabilities:async({direction:e})=>{E.debug("getNativeRtpCapabilities() [direction:%o]",e);let t=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"}),r=document.createElement("canvas");r.getContext("2d");let i=r.captureStream().getVideoTracks()[0];try{t.addTransceiver("audio",{direction:e}),t.addTransceiver(i,{direction:e,sendEncodings:[{rid:"r0",maxBitrate:1e5},{rid:"r1",maxBitrate:5e5}]});let o=await t.createOffer();try{r.remove()}catch{}try{i.stop()}catch{}try{t.close()}catch{}t=void 0;let a=ve.parse(o.sdp);return s.getLocalRtpCapabilities(a)}catch(o){try{r.remove()}catch{}try{i.stop()}catch{}try{t?.close()}catch{}throw t=void 0,o}},getNativeSctpCapabilities:async()=>(E.debug("getNativeSctpCapabilities()"),{numStreams:Yn})}}static getLocalRtpCapabilities(e){let t=tr.extractRtpCapabilities({sdpObject:e});return St.validateAndNormalizeRtpCapabilities(t),t}constructor({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:c,getSendExtendedRtpCapabilities:d}){super(),E.debug("constructor()"),this._direction=e,this._remoteSdp=new mc.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i}),this._getSendExtendedRtpCapabilities=d,this._pc=new RTCPeerConnection({iceServers:o??[],iceTransportPolicy:a??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...c}),this._pc.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.addEventListener("icecandidateerror",this.onIceCandidateError),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",this.onConnectionStateChange):(E.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return Qn}close(){if(E.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(e){throw this.assertNotClosed(),new Gn.UnsupportedError("not supported")}async restartIce(e){if(this.assertNotClosed(),E.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),!!this._transportReady)if(this._direction==="send"){let t=await this._pc.createOffer({iceRestart:!0});E.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",t),await this._pc.setLocalDescription(t);let r={type:"answer",sdp:this._remoteSdp.getSdp()};E.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",r),await this._pc.setRemoteDescription(r)}else{let t={type:"offer",sdp:this._remoteSdp.getSdp()};E.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let r=await this._pc.createAnswer();E.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,streamId:t,encodings:r,codecOptions:n,codec:i,onRtpSender:o}){this.assertNotClosed(),this.assertSendDirection(),E.debug("send() [kind:%s, track.id:%s, streamId:%s]",e.kind,e.id,t),r&&r.length>1&&r.forEach((y,x)=>{y.rid=`r${x}`});let a=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:r});o&&o(a.sender);let c=await this._pc.createOffer(),d=ve.parse(c.sdp);d.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();let p=s.getLocalRtpCapabilities(d),l=this._getSendExtendedRtpCapabilities(p),u=St.getSendingRtpParameters(e.kind,l);u.codecs=St.reduceCodecs(u.codecs,i);let f=St.getSendingRemoteRtpParameters(e.kind,l);f.codecs=St.reduceCodecs(f.codecs,i),this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:d});let m=(0,fc.parse)((r??[{}])[0].scalabilityMode);E.debug("send() | calling pc.setLocalDescription() [offer:%o]",c),await this._pc.setLocalDescription(c);let h=a.mid;u.mid=h,d=ve.parse(this._pc.localDescription.sdp);let g=d.media[d.media.length-1];if(u.rtcp.cname=tr.getCname({offerMediaObject:g}),u.msid=`${t??this._sendStream.id} ${e.id}`,!r)u.encodings=Kn.getRtpEncodings({offerMediaObject:g,codecs:u.codecs});else if(r.length===1){let y=Kn.getRtpEncodings({offerMediaObject:g,codecs:u.codecs});Object.assign(y[0],r[0]),u.encodings=y}else u.encodings=r;if(u.encodings.length>1&&(u.codecs[0].mimeType.toLowerCase()==="video/vp8"||u.codecs[0].mimeType.toLowerCase()==="video/h264"))for(let y of u.encodings)y.scalabilityMode?y.scalabilityMode=`L1T${m.temporalLayers}`:y.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:g,offerRtpParameters:u,answerRtpParameters:f,codecOptions:n});let _={type:"answer",sdp:this._remoteSdp.getSdp()};return E.debug("send() | calling pc.setRemoteDescription() [answer:%o]",_),await this._pc.setRemoteDescription(_),this._mapMidTransceiver.set(h,a),{localId:h,rtpParameters:u,rtpSender:a.sender}}async stopSending(e){if(this.assertSendDirection(),E.debug("stopSending() [localId:%s]",e),this._closed)return;let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated transceiver not found");t.sender.replaceTrack(null),this._pc.removeTrack(t.sender),this._remoteSdp.disableMediaSection(t.mid);let r=await this._pc.createOffer();E.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);let n={type:"answer",sdp:this._remoteSdp.getSdp()};E.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),E.debug("pauseSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);let r=await this._pc.createOffer();E.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);let n={type:"answer",sdp:this._remoteSdp.getSdp()};E.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),E.debug("resumeSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly",this._remoteSdp.resumeSendingMediaSection(e);let r=await this._pc.createOffer();E.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);let n={type:"answer",sdp:this._remoteSdp.getSdp()};E.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?E.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):E.debug("replaceTrack() [localId:%s, no track]",e);let r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");await r.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),this.assertSendDirection(),E.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);let r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated transceiver not found");let n=r.sender.getParameters();n.encodings.forEach((a,c)=>{c<=t?a.active=!0:a.active=!1}),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);let i=await this._pc.createOffer();E.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);let o={type:"answer",sdp:this._remoteSdp.getSdp()};E.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),E.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);let r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");let n=r.sender.getParameters();n.encodings.forEach((a,c)=>{n.encodings[c]={...a,...t}}),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);let i=await this._pc.createOffer();E.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);let o={type:"answer",sdp:this._remoteSdp.getSdp()};E.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({sctpStreamParameters:e}){this.assertNotClosed(),this.assertSendDirection();let t={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e.ordered,maxPacketLifeTime:e.maxPacketLifeTime,maxRetransmits:e.maxRetransmits,protocol:e.protocol};E.debug("sendDataChannel() [options:%o]",t);let r=this._pc.createDataChannel(e.label,t);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%Yn.MIS,!this._hasDataChannelMediaSection){let i=await this._pc.createOffer(),o=ve.parse(i.sdp),a=o.media.find(d=>d.type==="application");this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:o}),E.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i),this._remoteSdp.sendSctpAssociation({offerMediaObject:a});let c={type:"answer",sdp:this._remoteSdp.getSdp()};E.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",c),await this._pc.setRemoteDescription(c),this._hasDataChannelMediaSection=!0}let n={streamId:t.id,ordered:t.ordered,maxPacketLifeTime:t.maxPacketLifeTime,maxRetransmits:t.maxRetransmits};return{dataChannel:r,sctpStreamParameters:n}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();let t=[],r=new Map;for(let a of e){let{trackId:c,kind:d,rtpParameters:p,streamId:l}=a;E.debug("receive() [trackId:%s, kind:%s]",c,d);let u=p.mid??String(this._mapMidTransceiver.size);r.set(c,u);let{msidStreamId:f}=gc.getMsidStreamIdAndTrackId(p.msid);this._remoteSdp.receive({mid:u,kind:d,offerRtpParameters:p,streamId:l??f??p.rtcp?.cname??"-",trackId:c})}let n={type:"offer",sdp:this._remoteSdp.getSdp()};E.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",n),await this._pc.setRemoteDescription(n);for(let a of e){let{trackId:c,onRtpReceiver:d}=a;if(d){let p=r.get(c),l=this._pc.getTransceivers().find(u=>u.mid===p);if(!l)throw new Error("transceiver not found");d(l.receiver)}}let i=await this._pc.createAnswer(),o=ve.parse(i.sdp);for(let a of e){let{trackId:c,rtpParameters:d}=a,p=r.get(c),l=o.media.find(u=>String(u.mid)===p);tr.applyCodecParameters({offerRtpParameters:d,answerMediaObject:l}),i={type:"answer",sdp:ve.write(o)}}this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:o}),E.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(let a of e){let{trackId:c}=a,d=r.get(c),p=this._pc.getTransceivers().find(l=>l.mid===d);if(!p)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(d,p),t.push({localId:d,track:p.receiver.track,rtpReceiver:p.receiver})}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(let n of e){E.debug("stopReceiving() [localId:%s]",n);let i=this._mapMidTransceiver.get(n);if(!i)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(i.mid)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};E.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let r=await this._pc.createAnswer();E.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r);for(let n of e)this._mapMidTransceiver.delete(n)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(let n of e){E.debug("pauseReceiving() [localId:%s]",n);let i=this._mapMidTransceiver.get(n);if(!i)throw new Error("associated RTCRtpTransceiver not found");i.direction="inactive",this._remoteSdp.pauseMediaSection(n)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};E.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let r=await this._pc.createAnswer();E.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(let n of e){E.debug("resumeReceiving() [localId:%s]",n);let i=this._mapMidTransceiver.get(n);if(!i)throw new Error("associated RTCRtpTransceiver not found");i.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(n)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};E.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let r=await this._pc.createAnswer();E.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async getReceiverStats(e){this.assertRecvDirection();let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({maxMessageSize:e,sctpStreamParameters:t,label:r,protocol:n}){this.assertNotClosed(),this.assertRecvDirection();let{streamId:i,ordered:o,maxPacketLifeTime:a,maxRetransmits:c}=t,d={negotiated:!0,id:i,ordered:o,maxPacketLifeTime:a,maxRetransmits:c,protocol:n};E.debug("receiveDataChannel() [options:%o]",d);let p=this._pc.createDataChannel(r,d);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();let l={type:"offer",sdp:this._remoteSdp.getSdp()};E.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",l),await this._pc.setRemoteDescription(l);let u=await this._pc.createAnswer(),f=ve.parse(u.sdp),m=f.media.find(h=>h.type==="application");m.maxMessageSize=e,this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:f}),u={type:"answer",sdp:ve.write(f)},E.debug("receiveDataChannel() | calling pc.setLocalDescription() [answer:%o]",u),await this._pc.setLocalDescription(u),this._hasDataChannelMediaSection=!0}return{dataChannel:p}}getDataChannelMaxMessageSize(){return this._pc.sctp?.maxMessageSize}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=ve.parse(this._pc.localDescription.sdp));let r=tr.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole(e==="client"?"server":"client"),await new Promise((n,i)=>{this.safeEmit("@connect",{dtlsParameters:r},n,i)}),this._transportReady=!0}onIceGatheringStateChange=()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)};onIceCandidateError=e=>{this.emit("@icecandidateerror",e)};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 Gn.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')}};rr.Firefox120=ns});var ti=C(sr=>{"use strict";Object.defineProperty(sr,"__esModule",{value:!0});sr.Safari12=void 0;var ee=_e(),_c=G(),vc=z(),Rt=ae(),wc=X(),yc=Ie(),bc=et(),Ct=tt(),Xn=rt(),is=st(),R=new vc.Logger("Safari12"),Zn="Safari12",ei={OS:65535,MIS:65535},os=class s extends _c.EnhancedEventEmitter{_closed=!1;_direction;_remoteSdp;_getSendExtendedRtpCapabilities;_forcedLocalDtlsRole;_pc;_mapMidTransceiver=new Map;_sendStream=new MediaStream;_hasDataChannelMediaSection=!1;_nextSendSctpStreamId=0;_transportReady=!1;static createFactory(){return{name:Zn,factory:e=>new s(e),getNativeRtpCapabilities:async({direction:e})=>{R.debug("getNativeRtpCapabilities() [direction:%o]",e);let t=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{t.addTransceiver("audio",{direction:e}),t.addTransceiver("video",{direction:e});let r=await t.createOffer();try{t.close()}catch{}t=void 0;let n=ee.parse(r.sdp);return s.getLocalRtpCapabilities(n)}catch(r){try{t?.close()}catch{}throw t=void 0,r}},getNativeSctpCapabilities:async()=>(R.debug("getNativeSctpCapabilities()"),{numStreams:ei})}}static getLocalRtpCapabilities(e,t=[]){let r=Ct.extractRtpCapabilities({sdpObject:e});Rt.validateAndNormalizeRtpCapabilities(r),is.addNackSupportForOpus(r);for(let n of t)is.addHeaderExtensionSupport(r,n);return r}constructor({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:c,getSendExtendedRtpCapabilities:d}){super(),R.debug("constructor()"),this._direction=e,this._remoteSdp=new bc.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i}),this._getSendExtendedRtpCapabilities=d,n.role&&n.role!=="auto"&&(this._forcedLocalDtlsRole=n.role==="server"?"client":"server"),this._pc=new RTCPeerConnection({iceServers:o??[],iceTransportPolicy:a??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...c}),this._pc.addEventListener("icegatheringstatechange",()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)}),this._pc.addEventListener("icecandidateerror",p=>{this.emit("@icecandidateerror",p)}),this._pc.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.addEventListener("icecandidateerror",this.onIceCandidateError),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",this.onConnectionStateChange):(R.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return Zn}close(){if(R.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(e){this.assertNotClosed(),R.debug("updateIceServers()");let t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),R.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),!!this._transportReady)if(this._direction==="send"){let t=await this._pc.createOffer({iceRestart:!0});R.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",t),await this._pc.setLocalDescription(t);let r={type:"answer",sdp:this._remoteSdp.getSdp()};R.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",r),await this._pc.setRemoteDescription(r)}else{let t={type:"offer",sdp:this._remoteSdp.getSdp()};R.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let r=await this._pc.createAnswer();R.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,streamId:t,encodings:r,codecOptions:n,headerExtensionOptions:i,codec:o,onRtpSender:a}){this.assertNotClosed(),this.assertSendDirection(),R.debug("send() [kind:%s, track.id:%s, streamId:%s]",e.kind,e.id,t);let c=this._remoteSdp.getNextMediaSectionIdx(),d=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream]});a&&a(d.sender);let p=await this._pc.createOffer(),l=ee.parse(p.sdp);l.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();let u=[];u.push({uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",kind:e.kind,direction:"sendonly"});let f=s.getLocalRtpCapabilities(l,u),m=this._getSendExtendedRtpCapabilities(f),h=Rt.getSendingRtpParameters(e.kind,m);h.codecs=Rt.reduceCodecs(h.codecs,o);let g=Rt.getSendingRemoteRtpParameters(e.kind,m);g.codecs=Rt.reduceCodecs(g.codecs,o);let _;this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:l});let y=(0,yc.parse)((r??[{}])[0].scalabilityMode);r&&r.length>1&&(R.debug("send() | enabling legacy simulcast"),l=ee.parse(p.sdp),_=l.media[c.idx],Xn.addLegacySimulcast({offerMediaObject:_,numStreams:r.length}),p={type:"offer",sdp:ee.write(l)}),i?.absCaptureTime&&(_=l.media[c.idx],Ct.addHeaderExtension({offerMediaObject:_,headerExtensionUri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",headerExtensionId:g.headerExtensions.find(k=>k.uri==="http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time").id}),p={type:"offer",sdp:ee.write(l)}),R.debug("send() | calling pc.setLocalDescription() [offer:%o]",p),await this._pc.setLocalDescription(p);let x=d.mid;if(h.mid=x,l=ee.parse(this._pc.localDescription.sdp),_=l.media[c.idx],h.rtcp.cname=Ct.getCname({offerMediaObject:_}),h.msid=`${t??this._sendStream.id} ${e.id}`,h.encodings=Xn.getRtpEncodings({offerMediaObject:_,codecs:h.codecs}),r)for(let k=0;k<h.encodings.length;++k)r[k]&&Object.assign(h.encodings[k],r[k]);if(h.encodings.length>1&&(h.codecs[0].mimeType.toLowerCase()==="video/vp8"||h.codecs[0].mimeType.toLowerCase()==="video/h264"))for(let k of h.encodings)k.scalabilityMode?k.scalabilityMode=`L1T${y.temporalLayers}`:k.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:_,reuseMid:c.reuseMid,offerRtpParameters:h,answerRtpParameters:g,codecOptions:n});let P={type:"answer",sdp:this._remoteSdp.getSdp()};return R.debug("send() | calling pc.setRemoteDescription() [answer:%o]",P),await this._pc.setRemoteDescription(P),this._mapMidTransceiver.set(x,d),{localId:x,rtpParameters:h,rtpSender:d.sender}}async stopSending(e){if(this.assertSendDirection(),this._closed)return;R.debug("stopSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");if(t.sender.replaceTrack(null),this._pc.removeTrack(t.sender),this._remoteSdp.closeMediaSection(t.mid))try{t.stop()}catch{}let n=await this._pc.createOffer();R.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);let i={type:"answer",sdp:this._remoteSdp.getSdp()};R.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),R.debug("pauseSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);let r=await this._pc.createOffer();R.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);let n={type:"answer",sdp:this._remoteSdp.getSdp()};R.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),R.debug("resumeSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly",this._remoteSdp.resumeSendingMediaSection(e);let r=await this._pc.createOffer();R.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);let n={type:"answer",sdp:this._remoteSdp.getSdp()};R.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?R.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):R.debug("replaceTrack() [localId:%s, no track]",e);let r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");await r.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),this.assertSendDirection(),R.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);let r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");let n=r.sender.getParameters();n.encodings.forEach((a,c)=>{c<=t?a.active=!0:a.active=!1}),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);let i=await this._pc.createOffer();R.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);let o={type:"answer",sdp:this._remoteSdp.getSdp()};R.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),R.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);let r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");let n=r.sender.getParameters();n.encodings.forEach((a,c)=>{n.encodings[c]={...a,...t}}),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);let i=await this._pc.createOffer();R.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);let o={type:"answer",sdp:this._remoteSdp.getSdp()};R.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({sctpStreamParameters:e}){this.assertNotClosed(),this.assertSendDirection();let t={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e.ordered,maxPacketLifeTime:e.maxPacketLifeTime,maxRetransmits:e.maxRetransmits,protocol:e.protocol};R.debug("sendDataChannel() [options:%o]",t);let r=this._pc.createDataChannel(e.label,t);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%ei.MIS,!this._hasDataChannelMediaSection){let i=await this._pc.createOffer(),o=ee.parse(i.sdp),a=o.media.find(d=>d.type==="application");this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),R.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i),this._remoteSdp.sendSctpAssociation({offerMediaObject:a});let c={type:"answer",sdp:this._remoteSdp.getSdp()};R.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",c),await this._pc.setRemoteDescription(c),this._hasDataChannelMediaSection=!0}let n={streamId:t.id,ordered:t.ordered,maxPacketLifeTime:t.maxPacketLifeTime,maxRetransmits:t.maxRetransmits};return{dataChannel:r,sctpStreamParameters:n}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();let t=[],r=new Map;for(let a of e){let{trackId:c,kind:d,rtpParameters:p,streamId:l}=a;R.debug("receive() [trackId:%s, kind:%s]",c,d);let u=p.mid??String(this._mapMidTransceiver.size);r.set(c,u);let{msidStreamId:f}=is.getMsidStreamIdAndTrackId(p.msid);this._remoteSdp.receive({mid:u,kind:d,offerRtpParameters:p,streamId:l??f??p.rtcp?.cname??"-",trackId:c})}let n={type:"offer",sdp:this._remoteSdp.getSdp()};R.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",n),await this._pc.setRemoteDescription(n);for(let a of e){let{trackId:c,onRtpReceiver:d}=a;if(d){let p=r.get(c),l=this._pc.getTransceivers().find(u=>u.mid===p);if(!l)throw new Error("transceiver not found");d(l.receiver)}}let i=await this._pc.createAnswer(),o=ee.parse(i.sdp);for(let a of e){let{trackId:c,rtpParameters:d}=a,p=r.get(c),l=o.media.find(u=>String(u.mid)===p);Ct.applyCodecParameters({offerRtpParameters:d,answerMediaObject:l})}i={type:"answer",sdp:ee.write(o)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),R.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(let a of e){let{trackId:c}=a,d=r.get(c),p=this._pc.getTransceivers().find(l=>l.mid===d);if(!p)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(d,p),t.push({localId:d,track:p.receiver.track,rtpReceiver:p.receiver})}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(let n of e){R.debug("stopReceiving() [localId:%s]",n);let i=this._mapMidTransceiver.get(n);if(!i)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(i.mid)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};R.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let r=await this._pc.createAnswer();R.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r);for(let n of e)this._mapMidTransceiver.delete(n)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(let n of e){R.debug("pauseReceiving() [localId:%s]",n);let i=this._mapMidTransceiver.get(n);if(!i)throw new Error("associated RTCRtpTransceiver not found");i.direction="inactive",this._remoteSdp.pauseMediaSection(n)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};R.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let r=await this._pc.createAnswer();R.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(let n of e){R.debug("resumeReceiving() [localId:%s]",n);let i=this._mapMidTransceiver.get(n);if(!i)throw new Error("associated RTCRtpTransceiver not found");i.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(n)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};R.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let r=await this._pc.createAnswer();R.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async getReceiverStats(e){this.assertNotClosed(),this.assertRecvDirection();let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({maxMessageSize:e,sctpStreamParameters:t,label:r,protocol:n}){this.assertNotClosed(),this.assertRecvDirection();let{streamId:i,ordered:o,maxPacketLifeTime:a,maxRetransmits:c}=t,d={negotiated:!0,id:i,ordered:o,maxPacketLifeTime:a,maxRetransmits:c,protocol:n};R.debug("receiveDataChannel() [options:%o]",d);let p=this._pc.createDataChannel(r,d);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();let l={type:"offer",sdp:this._remoteSdp.getSdp()};R.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",l),await this._pc.setRemoteDescription(l);let u=await this._pc.createAnswer(),f=ee.parse(u.sdp),m=f.media.find(h=>h.type==="application");m.maxMessageSize=e,this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:f}),u={type:"answer",sdp:ee.write(f)},R.debug("receiveDataChannel() | calling pc.setLocalDescription() [answer:%o]",u),await this._pc.setLocalDescription(u),this._hasDataChannelMediaSection=!0}return{dataChannel:p}}getDataChannelMaxMessageSize(){return this._pc.sctp?.maxMessageSize}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=ee.parse(this._pc.localDescription.sdp));let r=Ct.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole(e==="client"?"server":"client"),await new Promise((n,i)=>{this.safeEmit("@connect",{dtlsParameters:r},n,i)}),this._transportReady=!0}onIceGatheringStateChange=()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)};onIceCandidateError=e=>{this.emit("@icecandidateerror",e)};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 wc.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')}};sr.Safari12=os});var ni=C(nr=>{"use strict";Object.defineProperty(nr,"__esModule",{value:!0});nr.ReactNative106=void 0;var te=_e(),Sc=G(),Rc=z(),Tt=ae(),Cc=X(),Tc=Ie(),Ec=et(),Et=tt(),as=rt(),cs=st(),b=new Rc.Logger("ReactNative106"),ri="ReactNative106",si={OS:65535,MIS:65535},ds=class s extends Sc.EnhancedEventEmitter{_closed=!1;_direction;_remoteSdp;_getSendExtendedRtpCapabilities;_forcedLocalDtlsRole;_pc;_mapMidTransceiver=new Map;_sendStream=new MediaStream;_hasDataChannelMediaSection=!1;_nextSendSctpStreamId=0;_transportReady=!1;static createFactory(){return{name:ri,factory:e=>new s(e),getNativeRtpCapabilities:async({direction:e})=>{b.debug("getNativeRtpCapabilities() [direction:%o]",e);let t=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{t.addTransceiver("audio",{direction:e}),t.addTransceiver("video",{direction:e});let r=await t.createOffer();try{t.close()}catch{}t=void 0;let n=te.parse(r.sdp);return s.getLocalRtpCapabilities(n)}catch(r){try{t?.close()}catch{}throw t=void 0,r}},getNativeSctpCapabilities:async()=>(b.debug("getNativeSctpCapabilities()"),{numStreams:si})}}static getLocalRtpCapabilities(e,t=[]){let r=Et.extractRtpCapabilities({sdpObject:e});Tt.validateAndNormalizeRtpCapabilities(r),cs.addNackSupportForOpus(r);for(let n of t)cs.addHeaderExtensionSupport(r,n);return r}constructor({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:c,getSendExtendedRtpCapabilities:d}){super(),b.debug("constructor()"),this._direction=e,this._remoteSdp=new Ec.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i}),this._getSendExtendedRtpCapabilities=d,n.role&&n.role!=="auto"&&(this._forcedLocalDtlsRole=n.role==="server"?"client":"server"),this._pc=new RTCPeerConnection({iceServers:o??[],iceTransportPolicy:a??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...c}),this._pc.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.addEventListener("icecandidateerror",this.onIceCandidateError),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",this.onConnectionStateChange):(b.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return ri}close(){if(b.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(e){this.assertNotClosed(),b.debug("updateIceServers()");let t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),b.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),!!this._transportReady)if(this._direction==="send"){let t=await this._pc.createOffer({iceRestart:!0});b.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",t),await this._pc.setLocalDescription(t);let r={type:"answer",sdp:this._remoteSdp.getSdp()};b.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",r),await this._pc.setRemoteDescription(r)}else{let t={type:"offer",sdp:this._remoteSdp.getSdp()};b.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let r=await this._pc.createAnswer();b.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,streamId:t,encodings:r,codecOptions:n,headerExtensionOptions:i,codec:o,onRtpSender:a}){this.assertNotClosed(),this.assertSendDirection(),b.debug("send() [kind:%s, track.id:%s, streamId:%s]",e.kind,e.id,t),r&&r.length>1&&r.forEach((I,Y)=>{I.rid=`r${Y}`});let c=this._remoteSdp.getNextMediaSectionIdx(),d=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:r});a&&a(d.sender);let p=await this._pc.createOffer(),l=te.parse(p.sdp);l.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();let u=[];u.push({uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",kind:e.kind,direction:"sendonly"});let f=s.getLocalRtpCapabilities(l,u),m=this._getSendExtendedRtpCapabilities(f),h=Tt.getSendingRtpParameters(e.kind,m);h.codecs=Tt.reduceCodecs(h.codecs,o);let g=Tt.getSendingRemoteRtpParameters(e.kind,m);g.codecs=Tt.reduceCodecs(g.codecs,o),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:l});let _=!1,y=(0,Tc.parse)((r??[{}])[0].scalabilityMode),x;r?.length===1&&y.spatialLayers>1&&h.codecs[0].mimeType.toLowerCase()==="video/vp9"&&(b.debug("send() | enabling legacy simulcast for VP9 SVC"),_=!0,l=te.parse(p.sdp),x=l.media[c.idx],as.addLegacySimulcast({offerMediaObject:x,numStreams:y.spatialLayers}),p={type:"offer",sdp:te.write(l)}),i?.absCaptureTime&&(x=l.media[c.idx],Et.addHeaderExtension({offerMediaObject:x,headerExtensionUri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",headerExtensionId:g.headerExtensions.find(I=>I.uri==="http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time").id}),p={type:"offer",sdp:te.write(l)}),b.debug("send() | calling pc.setLocalDescription() [offer:%o]",p),await this._pc.setLocalDescription(p);let P=d.mid??void 0;if(P||b.warn("send() | missing transceiver.mid (bug in react-native-webrtc, using a workaround"),h.mid=P,l=te.parse(this._pc.localDescription.sdp),x=l.media[c.idx],h.rtcp.cname=Et.getCname({offerMediaObject:x}),h.msid=`${t??this._sendStream.id} ${e.id}`,!r)h.encodings=as.getRtpEncodings({offerMediaObject:x,codecs:h.codecs});else if(r.length===1){let I=as.getRtpEncodings({offerMediaObject:x,codecs:h.codecs});Object.assign(I[0],r[0]),_&&(I=[I[0]]),h.encodings=I}else h.encodings=r;if(h.encodings.length>1&&(h.codecs[0].mimeType.toLowerCase()==="video/vp8"||h.codecs[0].mimeType.toLowerCase()==="video/h264"))for(let I of h.encodings)I.scalabilityMode?I.scalabilityMode=`L1T${y.temporalLayers}`:I.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:x,reuseMid:c.reuseMid,offerRtpParameters:h,answerRtpParameters:g,codecOptions:n});let k={type:"answer",sdp:this._remoteSdp.getSdp()};return b.debug("send() | calling pc.setRemoteDescription() [answer:%o]",k),await this._pc.setRemoteDescription(k),P||(P=d.mid,h.mid=P),this._mapMidTransceiver.set(P,d),{localId:P,rtpParameters:h,rtpSender:d.sender}}async stopSending(e){if(this.assertSendDirection(),this._closed)return;b.debug("stopSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");if(t.sender.replaceTrack(null),this._pc.removeTrack(t.sender),this._remoteSdp.closeMediaSection(t.mid))try{t.stop()}catch{}let n=await this._pc.createOffer();b.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);let i={type:"answer",sdp:this._remoteSdp.getSdp()};b.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),b.debug("pauseSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);let r=await this._pc.createOffer();b.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);let n={type:"answer",sdp:this._remoteSdp.getSdp()};b.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),b.debug("resumeSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(this._remoteSdp.resumeSendingMediaSection(e),!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly";let r=await this._pc.createOffer();b.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);let n={type:"answer",sdp:this._remoteSdp.getSdp()};b.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?b.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):b.debug("replaceTrack() [localId:%s, no track]",e);let r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");await r.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),this.assertSendDirection(),b.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);let r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");let n=r.sender.getParameters();n.encodings.forEach((a,c)=>{c<=t?a.active=!0:a.active=!1}),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);let i=await this._pc.createOffer();b.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);let o={type:"answer",sdp:this._remoteSdp.getSdp()};b.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),b.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);let r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");let n=r.sender.getParameters();n.encodings.forEach((a,c)=>{n.encodings[c]={...a,...t}}),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);let i=await this._pc.createOffer();b.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);let o={type:"answer",sdp:this._remoteSdp.getSdp()};b.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({sctpStreamParameters:e}){this.assertNotClosed(),this.assertSendDirection();let t={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e.ordered,maxPacketLifeTime:e.maxPacketLifeTime,maxRetransmits:e.maxRetransmits,protocol:e.protocol};b.debug("sendDataChannel() [options:%o]",t);let r=this._pc.createDataChannel(e.label,t);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%si.MIS,!this._hasDataChannelMediaSection){let i=await this._pc.createOffer(),o=te.parse(i.sdp),a=o.media.find(d=>d.type==="application");this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),b.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i),this._remoteSdp.sendSctpAssociation({offerMediaObject:a});let c={type:"answer",sdp:this._remoteSdp.getSdp()};b.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",c),await this._pc.setRemoteDescription(c),this._hasDataChannelMediaSection=!0}let n={streamId:t.id,ordered:t.ordered,maxPacketLifeTime:t.maxPacketLifeTime,maxRetransmits:t.maxRetransmits};return{dataChannel:r,sctpStreamParameters:n}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();let t=[],r=new Map;for(let a of e){let{trackId:c,kind:d,rtpParameters:p,streamId:l}=a;b.debug("receive() [trackId:%s, kind:%s]",c,d);let u=p.mid??String(this._mapMidTransceiver.size);r.set(c,u);let{msidStreamId:f}=cs.getMsidStreamIdAndTrackId(p.msid);this._remoteSdp.receive({mid:u,kind:d,offerRtpParameters:p,streamId:l??f??p.rtcp?.cname??"-",trackId:c})}let n={type:"offer",sdp:this._remoteSdp.getSdp()};b.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",n),await this._pc.setRemoteDescription(n);for(let a of e){let{trackId:c,onRtpReceiver:d}=a;if(d){let p=r.get(c),l=this._pc.getTransceivers().find(u=>u.mid===p);if(!l)throw new Error("transceiver not found");d(l.receiver)}}let i=await this._pc.createAnswer(),o=te.parse(i.sdp);for(let a of e){let{trackId:c,rtpParameters:d}=a,p=r.get(c),l=o.media.find(u=>String(u.mid)===p);Et.applyCodecParameters({offerRtpParameters:d,answerMediaObject:l})}i={type:"answer",sdp:te.write(o)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),b.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(let a of e){let{trackId:c}=a,d=r.get(c),p=this._pc.getTransceivers().find(l=>l.mid===d);if(p)this._mapMidTransceiver.set(d,p),t.push({localId:d,track:p.receiver.track,rtpReceiver:p.receiver});else throw new Error("new RTCRtpTransceiver not found")}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(let n of e){b.debug("stopReceiving() [localId:%s]",n);let i=this._mapMidTransceiver.get(n);if(!i)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(i.mid)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};b.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let r=await this._pc.createAnswer();b.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r);for(let n of e)this._mapMidTransceiver.delete(n)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(let n of e){b.debug("pauseReceiving() [localId:%s]",n);let i=this._mapMidTransceiver.get(n);if(!i)throw new Error("associated RTCRtpTransceiver not found");i.direction="inactive",this._remoteSdp.pauseMediaSection(n)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};b.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let r=await this._pc.createAnswer();b.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(let n of e){b.debug("resumeReceiving() [localId:%s]",n);let i=this._mapMidTransceiver.get(n);if(!i)throw new Error("associated RTCRtpTransceiver not found");i.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(n)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};b.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let r=await this._pc.createAnswer();b.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async getReceiverStats(e){this.assertNotClosed(),this.assertRecvDirection();let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({maxMessageSize:e,sctpStreamParameters:t,label:r,protocol:n}){this.assertNotClosed(),this.assertRecvDirection();let{streamId:i,ordered:o,maxPacketLifeTime:a,maxRetransmits:c}=t,d={negotiated:!0,id:i,ordered:o,maxPacketLifeTime:a,maxRetransmits:c,protocol:n};b.debug("receiveDataChannel() [options:%o]",d);let p=this._pc.createDataChannel(r,d);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();let l={type:"offer",sdp:this._remoteSdp.getSdp()};b.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",l),await this._pc.setRemoteDescription(l);let u=await this._pc.createAnswer(),f=te.parse(u.sdp),m=f.media.find(h=>h.type==="application");m.maxMessageSize=e,this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:f}),u={type:"answer",sdp:te.write(f)},b.debug("receiveDataChannel() | calling pc.setLocalDescription() [answer:%o]",u),await this._pc.setLocalDescription(u),this._hasDataChannelMediaSection=!0}return{dataChannel:p}}getDataChannelMaxMessageSize(){return this._pc.sctp?.maxMessageSize}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=te.parse(this._pc.localDescription.sdp));let r=Et.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole(e==="client"?"server":"client"),await new Promise((n,i)=>{this.safeEmit("@connect",{dtlsParameters:r},n,i)}),this._transportReady=!0}onIceGatheringStateChange=()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)};onIceCandidateError=e=>{this.emit("@icecandidateerror",e)};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 Cc.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')}};nr.ReactNative106=ds});var ci=C(nt=>{"use strict";Object.defineProperty(nt,"__esModule",{value:!0});nt.Device=void 0;nt.detectDevice=ii;nt.detectDeviceAsync=oi;var kc=z(),xc=G(),Te=X(),ir=ke(),K=ae(),Pc=xn(),Dc=Bn(),Ic=Wn(),Lc=Jn(),Mc=ti(),Oc=ni(),w=new kc.Logger("Device");function ii(s,e){return w.debug("detectDevice()"),!s&&typeof navigator=="object"&&(s=navigator.userAgent),!e&&typeof navigator=="object"&&(e=navigator.userAgentData),ai(s,e)}async function oi(s,e){return w.debug("detectDeviceAsync()"),!s&&typeof navigator=="object"&&(s=navigator.userAgent),!e&&typeof navigator=="object"&&(e=navigator.userAgentData),ai(s,e)}var ps=class s{_handlerFactory;_handlerName;_loaded=!1;_getSendExtendedRtpCapabilities;_recvRtpCapabilities;_sendRtpCapabilities;_canProduceByKind={audio:!1,video:!1};_sctpCapabilities;_observer=new xc.EnhancedEventEmitter;static async factory({handlerName:e,handlerFactory:t}={}){if(w.debug("factory()"),e&&t)throw new TypeError("just one of handlerName or handlerInterface can be given");if(!e&&!t&&(e=await oi(),!e))throw new Te.UnsupportedError("device not supported");return new s({handlerName:e,handlerFactory:t})}constructor({handlerName:e,handlerFactory:t}={}){if(w.debug("constructor()"),e&&t)throw new TypeError("just one of handlerName or handlerInterface can be given");if(t)this._handlerFactory=t;else{if(e)w.debug("constructor() | handler given: %s",e);else if(e=ii(),e)w.debug("constructor() | detected handler: %s",e);else throw new Te.UnsupportedError("device not supported");switch(e){case"Chrome111":{this._handlerFactory=Dc.Chrome111.createFactory();break}case"Chrome74":{this._handlerFactory=Ic.Chrome74.createFactory();break}case"Firefox120":{this._handlerFactory=Lc.Firefox120.createFactory();break}case"Safari12":{this._handlerFactory=Mc.Safari12.createFactory();break}case"ReactNative106":{this._handlerFactory=Oc.ReactNative106.createFactory();break}default:throw new TypeError(`unknown handlerName "${e}"`)}}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 Te.InvalidStateError("not loaded");return this._recvRtpCapabilities}get sendRtpCapabilities(){if(!this._loaded)throw new Te.InvalidStateError("not loaded");return this._sendRtpCapabilities}get sctpCapabilities(){if(!this._loaded)throw new Te.InvalidStateError("not loaded");return this._sctpCapabilities}get observer(){return this._observer}async load({routerRtpCapabilities:e,preferLocalCodecsOrder:t=!1}){if(w.debug("load() [routerRtpCapabilities:%o]",e),this._loaded)throw new Te.InvalidStateError("already loaded");let r=ir.clone(e);K.validateAndNormalizeRtpCapabilities(r);let{getNativeRtpCapabilities:n,getNativeSctpCapabilities:i}=this._handlerFactory,o=ir.clone(await n({direction:"recvonly"}));w.debug("load() | got native receiving RTP capabilities:%o",o),K.validateAndNormalizeRtpCapabilities(o);let a=ir.clone(await n({direction:"sendonly"}));w.debug("load() | got native sending RTP capabilities:%o",a),K.validateAndNormalizeRtpCapabilities(a),this._getSendExtendedRtpCapabilities=p=>ir.clone(K.getExtendedRtpCapabilities(p,r,t));let c=K.getExtendedRtpCapabilities(o,r,!1);this._recvRtpCapabilities=K.getRecvRtpCapabilities(c),w.debug("load() | got receiving RTP capabilities:%o",this._recvRtpCapabilities),K.validateAndNormalizeRtpCapabilities(this._recvRtpCapabilities);let d=K.getExtendedRtpCapabilities(a,r,t);this._sendRtpCapabilities=K.getSendRtpCapabilities(d),w.debug("load() | got sending RTP capabilities:%o",this._sendRtpCapabilities),K.validateAndNormalizeRtpCapabilities(this._sendRtpCapabilities),this._canProduceByKind.audio=K.canSend("audio",this._sendRtpCapabilities),this._canProduceByKind.video=K.canSend("video",this._sendRtpCapabilities),this._sctpCapabilities=await i(),K.validateSctpCapabilities(this._sctpCapabilities),w.debug("load() | got native SCTP capabilities:%o",this._sctpCapabilities),w.debug("load() succeeded"),this._loaded=!0}canProduce(e){if(this._loaded){if(e!=="audio"&&e!=="video")throw new TypeError(`invalid kind "${e}"`)}else throw new Te.InvalidStateError("not loaded");return this._canProduceByKind[e]}createSendTransport({id:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:c,appData:d}){return w.debug("createSendTransport()"),this.createTransport({direction:"send",id:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:c,appData:d})}createRecvTransport({id:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:c,appData:d}){return w.debug("createRecvTransport()"),this.createTransport({direction:"recv",id:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:c,appData:d})}createTransport({direction:e,id:t,iceParameters:r,iceCandidates:n,dtlsParameters:i,sctpParameters:o,iceServers:a,iceTransportPolicy:c,additionalSettings:d,appData:p}){if(this._loaded){if(typeof t!="string")throw new TypeError("missing id");if(typeof r!="object")throw new TypeError("missing iceParameters");if(Array.isArray(n)){if(typeof i!="object")throw new TypeError("missing dtlsParameters");if(o&&typeof o!="object")throw new TypeError("wrong sctpParameters");if(p&&typeof p!="object")throw new TypeError("if given, appData must be an object")}else throw new TypeError("missing iceCandidates")}else throw new Te.InvalidStateError("not loaded");let l=new Pc.Transport({direction:e,id:t,iceParameters:r,iceCandidates:n,dtlsParameters:i,sctpParameters:o,iceServers:a,iceTransportPolicy:c,additionalSettings:d,appData:p,handlerFactory:this._handlerFactory,getSendExtendedRtpCapabilities:this._getSendExtendedRtpCapabilities,recvRtpCapabilities:this._recvRtpCapabilities,canProduceByKind:this._canProduceByKind});return this._observer.safeEmit("newtransport",l),l}};nt.Device=ps;function ai(s,e){w.debug('detectDeviceImpl() [userAgent:"%s", userAgentData:%o]',s,e);let t=Ac(s,e);if(t){if(t>=111)return w.debug("detectDeviceImpl() | using Chrome111 handler"),"Chrome111";if(t>=74)return w.debug("detectDeviceImpl() | using Chrome74 handler"),"Chrome74";w.warn("detectDeviceImpl() | unsupported Chromium based browser/version");return}let r=Nc(s);if(r){if(r>=120)return w.debug("detectDeviceImpl() | using Firefox120 handler"),"Firefox120";w.warn("detectDeviceImpl() | unsupported Firefox browser/version");return}let n=jc(s);if(n){if(n>=605)return w.debug("detectDeviceImpl() | using Safari12 handler"),"Safari12";w.warn("detectDeviceImpl() | unsupported desktop Safari browser/version");return}let i=Fc(s);if(i){if(i>=605)return w.debug("detectDeviceImpl() | using Safari12 handler"),"Safari12";w.warn("detectDeviceImpl() | unsupported iOS Safari based browser/version");return}if(kt()){if(typeof RTCPeerConnection<"u"&&typeof RTCRtpTransceiver<"u")return w.debug("detectDeviceImpl() | using ReactNative106 handler"),"ReactNative106";w.warn("detectDeviceImpl() | unsupported react-native-webrtc version without RTCPeerConnection or RTCRtpTransceiver, forgot to call registerGlobals() on it?");return}w.warn('detectDeviceImpl() | device not supported [userAgent:"%s", userAgentData:%o]',s,e)}function Ac(s,e){if(w.debug("getChromiumMajorVersion()"),or(s,e)){w.debug("getChromiumMajorVersion() | this is iOS => undefined");return}if(kt()){w.debug("getChromiumMajorVersion() | this is React-Native => undefined");return}if(e){let n=(Array.isArray(e.brands)?e.brands:[]).find(i=>i.brand==="Chromium");if(n){let i=Number(n.version);return w.debug(`getChromiumMajorVersion() | Chromium major version based on NavigatorUAData => ${i}`),i}}let t=s?.match(/\b(?:Chrome|Chromium)\/(\w+)/i);if(t?.[1]){let r=Number(t[1]);return w.debug(`getChromiumMajorVersion() | Chromium major version based on User-Agent => ${r}`),r}w.debug("getChromiumMajorVersion() | this is not Chromium => undefined")}function Nc(s){if(w.debug("getFirefoxMajorVersion()"),or(s)){w.debug("getFirefoxMajorVersion() | this is iOS => undefined");return}if(kt()){w.debug("getFirefoxMajorVersion() | this is React-Native => undefined");return}let e=s?.match(/\bFirefox\/(\w+)/i);if(e?.[1]){let t=Number(e[1]);return w.debug(`getFirefoxMajorVersion() | Firefox major version based on User-Agent => ${t}`),t}w.debug("getFirefoxMajorVersion() | this is not Firefox => undefined")}function jc(s){if(w.debug("getMacOSWebKitMajorVersion()"),or(s)){w.debug("getMacOSWebKitMajorVersion() | this is iOS => undefined");return}if(kt()){w.debug("getMacOSWebKitMajorVersion() | this is React-Native => undefined");return}if(!(s&&/\bSafari\b/i.test(s)&&!/\bChrome\b/i.test(s)&&!/\bChromium\b/i.test(s)&&!/\bFirefox\b/i.test(s))){w.debug("getMacOSWebKitMajorVersion() | this is not Safari => undefined");return}let t=s.match(/AppleWebKit\/(\w+)/i);if(t?.[1]){let r=Number(t[1]);return w.debug(`getMacOSWebKitMajorVersion() | WebKit major version based on User-Agent => ${r}`),r}w.debug("getMacOSWebKitMajorVersion() | this is not WebKit => undefined")}function Fc(s){if(w.debug("getIOSWebKitMajorVersion()"),!or(s)){w.debug("getIOSWebKitMajorVersion() | this is not iOS => undefined");return}if(kt()){w.debug("getIOSWebKitMajorVersion() | this is React-Native => undefined");return}let e=s?.match(/AppleWebKit\/(\w+)/i);if(e?.[1]){let t=Number(e[1]);return w.debug(`getIOSWebKitMajorVersion() | WebKit major version based on User-Agent => ${t}`),t}w.debug("getIOSWebKitMajorVersion() | this is not WebKit => undefined")}function or(s,e){return w.debug("isIOS()"),e?.platform==="iOS"?(w.debug("isIOS() | this is iOS based on NavigatorUAData.platform => true"),!0):e?.platform?(w.debug("isIOS() | this is not iOS based on NavigatorUAData.platform => false"),!1):s&&/iPad|iPhone|iPod/.test(s)?(w.debug("isIOS() | this is iOS based on User-Agent => true"),!0):typeof navigator=="object"&&navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1?(w.debug("isIOS() | this is iPadOS 13+ based on User-Agent => true"),!0):(w.debug("isIOS() | this is not iOS => false"),!1)}function kt(){return w.debug("isReactNative()"),typeof navigator=="object"&&navigator.product==="ReactNative"?(w.debug("isReactNative() | this is React-Native based on navigator.product"),!0):(w.debug("isReactNative() | this is not React-Native => false"),!1)}});var pi=C(di=>{"use strict";var Me=256,cr=[],ar;for(;Me--;)cr[Me]=(Me+256).toString(16).substring(1);function qc(){var s=0,e,t="";if(!ar||Me+16>256){for(ar=Array(s=256);s--;)ar[s]=256*Math.random()|0;s=Me=0}for(;s<16;s++)e=ar[Me+s],s==6?t+=cr[e&15|64]:s==8?t+=cr[e&63|128]:t+=cr[e],s&1&&s>1&&s<11&&(t+="-");return Me++,t}di.v4=qc});var li=C(dr=>{"use strict";Object.defineProperty(dr,"__esModule",{value:!0});dr.FakeEventTarget=void 0;var ls=class{listeners={};addEventListener(e,t,r){t&&(this.listeners[e]=this.listeners[e]??[],this.listeners[e].push({callback:typeof t=="function"?t:t.handleEvent,once:typeof r=="object"&&r.once===!0}))}removeEventListener(e,t,r){this.listeners[e]&&t&&(this.listeners[e]=this.listeners[e].filter(n=>n.callback!==(typeof t=="function"?t:t.handleEvent)))}dispatchEvent(e){if(!e||typeof e.type!="string")throw new Error("invalid event object");let t=this.listeners[e.type];if(!t)return!0;for(let r of[...t]){try{r.callback.call(this,e)}catch(n){setTimeout(()=>{throw n},0)}r.once&&this.removeEventListener(e.type,r.callback)}return!e.defaultPrevented}};dr.FakeEventTarget=ls});var ui=C(pr=>{"use strict";Object.defineProperty(pr,"__esModule",{value:!0});pr.FakeEvent=void 0;var us=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(e,t={}){this.type=e,this.bubbles=t.bubbles??!1,this.cancelable=t.cancelable??!1}preventDefault(){this.cancelable&&(this.defaultPrevented=!0)}stopPropagation(){}stopImmediatePropagation(){}composedPath(){return[]}initEvent(e,t,r){}};pr.FakeEvent=us});var hi=C(hs=>{"use strict";Object.defineProperty(hs,"__esModule",{value:!0});hs.clone=$c;function $c(s){if(s!==void 0)return Number.isNaN(s)?NaN:typeof structuredClone=="function"?structuredClone(s):JSON.parse(JSON.stringify(s))}});var mi=C(ur=>{"use strict";Object.defineProperty(ur,"__esModule",{value:!0});ur.FakeMediaStreamTrack=void 0;var fi=pi(),Uc=li(),it=ui(),lr=hi(),fs=class s extends Uc.FakeEventTarget{#m;#l;#u;#e;#r;#t;#s;#h;#n;#f;#i;#o=null;#a=null;#c=null;#d=null;#p=null;constructor({kind:e,id:t,label:r,contentHint:n,enabled:i,muted:o,readyState:a,capabilities:c,constraints:d,settings:p,data:l}){super(),this.#m=t??(0,fi.v4)(),this.#l=e,this.#u=r??"",this.#s=n??"",this.#r=i??!0,this.#t=o??!1,this.#e=a??"live",this.#h=c??{},this.#n=d??{},this.#f=p??{},this.#i=l??{}}get id(){return this.#m}get kind(){return this.#l}get label(){return this.#u}get contentHint(){return this.#s}set contentHint(e){this.#s=e}get enabled(){return this.#r}set enabled(e){let t=this.#r!==e;this.#r=e,t&&this.dispatchEvent(new it.FakeEvent("enabledchange"))}get muted(){return this.#t}get readyState(){return this.#e}get data(){return this.#i}set data(e){this.#i=e}get onmute(){return this.#o}set onmute(e){this.#o&&this.removeEventListener("mute",this.#o),this.#o=e,e&&this.addEventListener("mute",e)}get onunmute(){return this.#a}set onunmute(e){this.#a&&this.removeEventListener("unmute",this.#a),this.#a=e,e&&this.addEventListener("unmute",e)}get onended(){return this.#c}set onended(e){this.#c&&this.removeEventListener("ended",this.#c),this.#c=e,e&&this.addEventListener("ended",e)}get onenabledchange(){return this.#d}set onenabledchange(e){this.#d&&this.removeEventListener("enabledchange",this.#d),this.#d=e,e&&this.addEventListener("enabledchange",e)}get onstopped(){return this.#p}set onstopped(e){this.#p&&this.removeEventListener("stopped",this.#p),this.#p=e,e&&this.addEventListener("stopped",e)}addEventListener(e,t,r){super.addEventListener(e,t,r)}removeEventListener(e,t,r){super.removeEventListener(e,t,r)}stop(){this.#e!=="ended"&&(this.#e="ended",this.dispatchEvent(new it.FakeEvent("stopped")))}clone({id:e,data:t}={}){return new s({id:e??(0,fi.v4)(),kind:this.#l,label:this.#u,contentHint:this.#s,enabled:this.#r,muted:this.#t,readyState:this.#e,capabilities:(0,lr.clone)(this.#h),constraints:(0,lr.clone)(this.#n),settings:(0,lr.clone)(this.#f),data:t??(0,lr.clone)(this.#i)})}getCapabilities(){return this.#h}getConstraints(){return this.#n}async applyConstraints(e={}){return this.#n=e,Promise.resolve()}getSettings(){return this.#f}remoteStop(){this.#e!=="ended"&&(this.#e="ended",this.dispatchEvent(new it.FakeEvent("stopped")),this.dispatchEvent(new it.FakeEvent("ended")))}remoteMute(){this.#t||(this.#t=!0,this.dispatchEvent(new it.FakeEvent("mute")))}remoteUnmute(){this.#t&&(this.#t=!1,this.dispatchEvent(new it.FakeEvent("unmute")))}};ur.FakeMediaStreamTrack=fs});var gi=C(hr=>{"use strict";Object.defineProperty(hr,"__esModule",{value:!0});hr.FakeEventTarget=void 0;var ms=class{listeners={};addEventListener(e,t,r){t&&(this.listeners[e]=this.listeners[e]??[],this.listeners[e].push({callback:typeof t=="function"?t:t.handleEvent,once:typeof r=="object"&&r.once===!0}))}removeEventListener(e,t,r){this.listeners[e]&&t&&(this.listeners[e]=this.listeners[e].filter(n=>n.callback!==(typeof t=="function"?t:t.handleEvent)))}dispatchEvent(e){if(!e||typeof e.type!="string")throw new Error("invalid event object");let t=this.listeners[e.type];if(!t)return!0;for(let r of[...t]){try{r.callback.call(this,e)}catch(n){setTimeout(()=>{throw n},0)}r.once&&this.removeEventListener(e.type,r.callback)}return!e.defaultPrevented}};hr.FakeEventTarget=ms});var wi=C(mr=>{"use strict";Object.defineProperty(mr,"__esModule",{value:!0});mr.FakeHandler=void 0;var zc=mi(),Bc=G(),Hc=z(),ot=ke(),gs=ae(),vi=X(),Vc=gi(),$=new Hc.Logger("FakeHandler"),_i="FakeHandler",_s=class s extends Bc.EnhancedEventEmitter{_closed=!1;_fakeParameters;_getSendExtendedRtpCapabilities;_cname=`CNAME-${ot.generateRandomNumber()}`;_defaultSendStreamId=`${ot.generateRandomNumber()}`;_transportReady=!1;_nextLocalId=1;_tracks=new Map;_nextSctpStreamId=0;static createFactory(e){return{name:_i,factory:t=>new s(t,e),getNativeRtpCapabilities:async({direction:t})=>($.debug("getNativeRtpCapabilities() [direction:%o]",t),s.getLocalRtpCapabilities(e)),getNativeSctpCapabilities:async()=>($.debug("getNativeSctpCapabilities()"),e.generateNativeSctpCapabilities())}}static getLocalRtpCapabilities(e){let t=e.generateNativeRtpCapabilities();return gs.validateAndNormalizeRtpCapabilities(t),t}constructor({getSendExtendedRtpCapabilities:e},t){super(),$.debug("constructor()"),this._getSendExtendedRtpCapabilities=e,this._fakeParameters=t}get name(){return _i}close(){$.debug("close()"),!this._closed&&(this._closed=!0,super.close())}setIceGatheringState(e){this.emit("@icegatheringstatechange",e)}setConnectionState(e){this.emit("@connectionstatechange",e)}async updateIceServers(e){this.assertNotClosed(),$.debug("updateIceServers()")}async restartIce(e){this.assertNotClosed(),$.debug("restartIce()")}async getTransportStats(){return this.assertNotClosed(),new Map}async send({track:e,streamId:t,encodings:r,codecOptions:n,codec:i}){this.assertNotClosed(),$.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),this._transportReady||await this.setupTransport({localDtlsRole:"server"});let o=s.getLocalRtpCapabilities(this._fakeParameters),a=this._getSendExtendedRtpCapabilities(o),c=gs.getSendingRtpParameters(e.kind,a);c.codecs=gs.reduceCodecs(c.codecs,i);let d=c.codecs.some(l=>/.+\/rtx$/i.test(l.mimeType));c.mid=`mid-${ot.generateRandomNumber()}`,c.msid=`${t??"-"} ${e.id}`,r||(r=[{}]);for(let l of r)l.ssrc=ot.generateRandomNumber(),d&&(l.rtx={ssrc:ot.generateRandomNumber()});c.encodings=r,c.rtcp={cname:this._cname,reducedSize:!0,mux:!0},c.msid=`${t??this._defaultSendStreamId} ${e.id}`;let p=this._nextLocalId++;return this._tracks.set(p,e),{localId:String(p),rtpParameters:c}}async stopSending(e){if($.debug("stopSending() [localId:%s]",e),!this._closed){if(!this._tracks.has(Number(e)))throw new Error("local track not found");this._tracks.delete(Number(e))}}async pauseSending(e){this.assertNotClosed()}async resumeSending(e){this.assertNotClosed()}async replaceTrack(e,t){this.assertNotClosed(),t?$.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):$.debug("replaceTrack() [localId:%s, no track]",e),this._tracks.delete(Number(e)),this._tracks.set(Number(e),t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),$.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),$.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t)}async getSenderStats(e){return this.assertNotClosed(),new Map}async sendDataChannel({sctpStreamParameters:e}){this.assertNotClosed(),this._transportReady||await this.setupTransport({localDtlsRole:"server"}),$.debug("sendDataChannel()");let t=new fr({id:this._nextSctpStreamId++,ordered:e.ordered,maxPacketLifeTime:e.maxPacketLifeTime,maxRetransmits:e.maxRetransmits,label:e.label,protocol:e.protocol}),r={streamId:this._nextSctpStreamId,ordered:e.ordered,maxPacketLifeTime:e.maxPacketLifeTime,maxRetransmits:e.maxRetransmits};return{dataChannel:t,sctpStreamParameters:r}}async receive(e){this.assertNotClosed();let t=[];for(let r of e){let{trackId:n,kind:i}=r;this._transportReady||await this.setupTransport({localDtlsRole:"client"}),$.debug("receive() [trackId:%s, kind:%s]",n,i);let o=this._nextLocalId++,a=new zc.FakeMediaStreamTrack({kind:i});this._tracks.set(o,a),t.push({localId:String(o),track:a})}return t}async stopReceiving(e){if(!this._closed)for(let t of e)$.debug("stopReceiving() [localId:%s]",t),this._tracks.delete(Number(t))}async pauseReceiving(e){this.assertNotClosed()}async resumeReceiving(e){this.assertNotClosed()}async getReceiverStats(e){return this.assertNotClosed(),new Map}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:r}){return this.assertNotClosed(),this._transportReady||await this.setupTransport({localDtlsRole:"client"}),$.debug("receiveDataChannel()"),{dataChannel:new fr({id:e.streamId,ordered:e.ordered,maxPacketLifeTime:e.maxPacketLifeTime,maxRetransmits:e.maxRetransmits,label:t,protocol:r})}}getDataChannelMaxMessageSize(){return 5e5}async setupTransport({localDtlsRole:e,localSdpObject:t}){let r=ot.clone(this._fakeParameters.generateLocalDtlsParameters());e&&(r.role=e),this.emit("@connectionstatechange","connecting"),await new Promise((n,i)=>this.emit("@connect",{dtlsParameters:r},n,i)),this._transportReady=!0}assertNotClosed(){if(this._closed)throw new vi.InvalidStateError("method called in a closed handler")}};mr.FakeHandler=_s;var fr=class extends Vc.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:e,ordered:t=!0,maxPacketLifeTime:r=null,maxRetransmits:n=null,label:i="",protocol:o=""}){super(),$.debug(`constructor() [id:${e}, ordered:${t}, maxPacketLifeTime:${r}, maxRetransmits:${n}, label:${i}, protocol:${o}`),this._id=e,this._ordered=t,this._maxPacketLifeTime=r,this._maxRetransmits=n,this._label=i,this._protocol=o}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(e){this._bufferedAmountLowThreshold=e}get binaryType(){return this._binaryType}set binaryType(e){this._binaryType=e}get onopen(){return this._onopen}set onopen(e){this._onopen&&this.removeEventListener("open",this._onopen),this._onopen=e,e&&this.addEventListener("open",e)}get onclosing(){return this._onclosing}set onclosing(e){this._onclosing&&this.removeEventListener("closing",this._onclosing),this._onclosing=e,e&&this.addEventListener("closing",e)}get onclose(){return this._onclose}set onclose(e){this._onclose&&this.removeEventListener("close",this._onclose),this._onclose=e,e&&this.addEventListener("close",e)}get onmessage(){return this._onmessage}set onmessage(e){this._onmessage&&this.removeEventListener("message",this._onmessage),this._onmessage=e,e&&this.addEventListener("message",e)}get onbufferedamountlow(){return this._onbufferedamountlow}set onbufferedamountlow(e){this._onbufferedamountlow&&this.removeEventListener("bufferedamountlow",this._onbufferedamountlow),this._onbufferedamountlow=e,e&&this.addEventListener("bufferedamountlow",e)}get onerror(){return this._onerror}set onerror(e){this._onerror&&this.removeEventListener("error",this._onerror),this._onerror=e,e&&this.addEventListener("error",e)}addEventListener(e,t,r){super.addEventListener(e,t,r)}removeEventListener(e,t,r){super.removeEventListener(e,t,r)}close(){["closing","closed"].includes(this._readyState)||(this._readyState="closed")}send(e){if(this._readyState!=="open")throw new vi.InvalidStateError("not open")}}});var yi=C(oe=>{"use strict";Object.defineProperty(oe,"__esModule",{value:!0});oe.generateRouterRtpCapabilities=Wc;oe.generateNativeRtpCapabilities=Gc;oe.generateNativeSctpCapabilities=Kc;oe.generateLocalDtlsParameters=Qc;oe.generateTransportRemoteParameters=Yc;oe.generateProducerRemoteParameters=Jc;oe.generateConsumerRemoteParameters=Xc;oe.generateDataProducerRemoteParameters=Zc;oe.generateDataConsumerRemoteParameters=ed;var H=ke();function Q(){return String(H.generateRandomNumber())}function Wc(){return H.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 Gc(){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 Kc(){return H.deepFreeze({numStreams:{OS:2048,MIS:2048}})}function Qc(){return H.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 Yc(){return{id:Q(),iceParameters:H.deepFreeze({iceLite:!0,password:"yku5ej8nvfaor28lvtrabcx0wkrpkztz",usernameFragment:"h3hk1iz6qqlnqlne"}),iceCandidates:H.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:H.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:H.deepFreeze({port:5e3,OS:2048,MIS:2048,maxMessageSize:2e6})}}function Jc(){return H.deepFreeze({id:Q()})}function Xc({id:s,codecMimeType:e}={}){switch(e){case"audio/opus":return{id:s??Q(),producerId:Q(),kind:"audio",rtpParameters:H.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:s??Q(),producerId:Q(),kind:"audio",rtpParameters:H.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:s??Q(),producerId:Q(),kind:"video",rtpParameters:H.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:s??Q(),producerId:Q(),kind:"video",rtpParameters:H.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 '${e}'`)}}function Zc(){return H.deepFreeze({id:Q()})}function ed({id:s}={}){return{id:s??Q(),dataProducerId:Q(),sctpStreamParameters:H.deepFreeze({streamId:666,maxPacketLifeTime:5e3,maxRetransmits:void 0})}}});var Xr=C(A=>{"use strict";Object.defineProperty(A,"__esModule",{value:!0});A.debug=A.testFakeParameters=A.FakeHandler=A.enhancedEvents=A.ortc=A.parseScalabilityMode=A.detectDeviceAsync=A.detectDevice=A.Device=A.version=A.types=void 0;var td=ut();A.debug=td.default;A.types=Hs();A.version="3.20.0";var vs=ci();Object.defineProperty(A,"Device",{enumerable:!0,get:function(){return vs.Device}});Object.defineProperty(A,"detectDevice",{enumerable:!0,get:function(){return vs.detectDevice}});Object.defineProperty(A,"detectDeviceAsync",{enumerable:!0,get:function(){return vs.detectDeviceAsync}});var rd=Ie();Object.defineProperty(A,"parseScalabilityMode",{enumerable:!0,get:function(){return rd.parse}});A.ortc=ae();A.enhancedEvents=G();var sd=wi();Object.defineProperty(A,"FakeHandler",{enumerable:!0,get:function(){return sd.FakeHandler}});A.testFakeParameters=yi()});var Si=C((Up,ws)=>{"use strict";var nd=Object.prototype.hasOwnProperty,V="~";function xt(){}Object.create&&(xt.prototype=Object.create(null),new xt().__proto__||(V=!1));function id(s,e,t){this.fn=s,this.context=e,this.once=t||!1}function bi(s,e,t,r,n){if(typeof t!="function")throw new TypeError("The listener must be a function");var i=new id(t,r||s,n),o=V?V+e:e;return s._events[o]?s._events[o].fn?s._events[o]=[s._events[o],i]:s._events[o].push(i):(s._events[o]=i,s._eventsCount++),s}function gr(s,e){--s._eventsCount===0?s._events=new xt:delete s._events[e]}function U(){this._events=new xt,this._eventsCount=0}U.prototype.eventNames=function(){var e=[],t,r;if(this._eventsCount===0)return e;for(r in t=this._events)nd.call(t,r)&&e.push(V?r.slice(1):r);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};U.prototype.listeners=function(e){var t=V?V+e:e,r=this._events[t];if(!r)return[];if(r.fn)return[r.fn];for(var n=0,i=r.length,o=new Array(i);n<i;n++)o[n]=r[n].fn;return o};U.prototype.listenerCount=function(e){var t=V?V+e:e,r=this._events[t];return r?r.fn?1:r.length:0};U.prototype.emit=function(e,t,r,n,i,o){var a=V?V+e:e;if(!this._events[a])return!1;var c=this._events[a],d=arguments.length,p,l;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),d){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,r),!0;case 4:return c.fn.call(c.context,t,r,n),!0;case 5:return c.fn.call(c.context,t,r,n,i),!0;case 6:return c.fn.call(c.context,t,r,n,i,o),!0}for(l=1,p=new Array(d-1);l<d;l++)p[l-1]=arguments[l];c.fn.apply(c.context,p)}else{var u=c.length,f;for(l=0;l<u;l++)switch(c[l].once&&this.removeListener(e,c[l].fn,void 0,!0),d){case 1:c[l].fn.call(c[l].context);break;case 2:c[l].fn.call(c[l].context,t);break;case 3:c[l].fn.call(c[l].context,t,r);break;case 4:c[l].fn.call(c[l].context,t,r,n);break;default:if(!p)for(f=1,p=new Array(d-1);f<d;f++)p[f-1]=arguments[f];c[l].fn.apply(c[l].context,p)}}return!0};U.prototype.on=function(e,t,r){return bi(this,e,t,r,!1)};U.prototype.once=function(e,t,r){return bi(this,e,t,r,!0)};U.prototype.removeListener=function(e,t,r,n){var i=V?V+e:e;if(!this._events[i])return this;if(!t)return gr(this,i),this;var o=this._events[i];if(o.fn)o.fn===t&&(!n||o.once)&&(!r||o.context===r)&&gr(this,i);else{for(var a=0,c=[],d=o.length;a<d;a++)(o[a].fn!==t||n&&!o[a].once||r&&o[a].context!==r)&&c.push(o[a]);c.length?this._events[i]=c.length===1?c[0]:c:gr(this,i)}return this};U.prototype.removeAllListeners=function(e){var t;return e?(t=V?V+e:e,this._events[t]&&gr(this,t)):(this._events=new xt,this._eventsCount=0),this};U.prototype.off=U.prototype.removeListener;U.prototype.addListener=U.prototype.on;U.prefixed=V;U.EventEmitter=U;typeof ws<"u"&&(ws.exports=U)});var Vd={};Is(Vd,{App:()=>$i,RequestAbortError:()=>we,RequestCancelledError:()=>pt,RequestError:()=>ue,RequestTimeoutError:()=>dt,Session:()=>lt,createStore:()=>Bi,videoStream:()=>Hi});module.exports=Ms(Vd);var Ne=class{_handlers=new Map;_ws;_onMessage;_onOpen;_listeningForOpen=!1;_pendingSends=[];_disposed=!1;constructor(e){this._ws=e,this._onMessage=t=>{if(typeof t.data!="string")return;let r;try{r=JSON.parse(t.data)}catch{console.warn("[ChannelMultiplexer] Failed to parse WebSocket message as JSON");return}if(!r.channel)return;let n=this._handlers.get(r.channel);if(n)for(let i of n)i(r)},this._ws.addEventListener("message",this._onMessage),this._onOpen=()=>{this.flushPendingSends()}}on(e,t){let r=this._handlers.get(e);return r||(r=new Set,this._handlers.set(e,r)),r.add(t),()=>{r.delete(t),r.size===0&&this._handlers.delete(e)}}emit(e,t){if(this._disposed)return;let r=JSON.stringify({channel:e,...t});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 e=this._pendingSends;this._pendingSends=[];for(let t of e)this._ws.send(t)}listenForOpen(){this._listeningForOpen||(this._listeningForOpen=!0,this._ws.addEventListener("open",this._onOpen))}},je=class{_handlers=new Map;_pendingSends=[];_target=null;_targetUnsubscribes=[];_disposed=!1;setTarget(e){if(this._disposed)return;this.detachTarget(),this._target=e;for(let[r,n]of this._handlers)for(let i of n)this._targetUnsubscribes.push(e.on(r,i));let t=this._pendingSends;this._pendingSends=[];for(let r of t)e.emit(r.channel,r.data)}rewriteSessionChannels(e,t){if(e===t)return;let r=`session:${e}:`,n=`session:${t}:`,i=new Map;for(let[o,a]of this._handlers)i.set(o.startsWith(r)?n+o.slice(r.length):o,a);this._handlers=i,this._pendingSends=this._pendingSends.map(o=>({...o,channel:o.channel.startsWith(r)?n+o.channel.slice(r.length):o.channel}))}on(e,t){if(this._disposed)return()=>{};let r=this._handlers.get(e);r||(r=new Set,this._handlers.set(e,r)),r.add(t);let n=this._target?.on(e,t);return n&&this._targetUnsubscribes.push(n),()=>{r?.delete(t),r?.size===0&&this._handlers.delete(e),n?.(),n&&(this._targetUnsubscribes=this._targetUnsubscribes.filter(i=>i!==n))}}emit(e,t){if(!this._disposed){if(this._target){this._target.emit(e,t);return}this._pendingSends.push({channel:e,data:t})}}dispose(){this._disposed=!0,this._pendingSends=[],this._handlers.clear(),this.detachTarget()}detachTarget(){for(let e of this._targetUnsubscribes)e();this._targetUnsubscribes=[],this._target=null}};var Di=Se(Xr());var ys=Se(Si(),1);function vr(){return typeof window>"u"&&typeof process<"u"&&process.versions!=null&&process.versions.node!=null}function Ci(){return vr()?"Chrome111":void 0}var od=["RTCPeerConnection","RTCSessionDescription","RTCIceCandidate","RTCRtpSender","RTCRtpReceiver","RTCRtpTransceiver","RTCDataChannel","RTCDtlsTransport","RTCIceTransport","RTCCertificate","MediaStream","MediaStreamTrack"],_r=null;function Ti(){return vr()?_r||(_r=ad(),_r):Promise.resolve()}async function ad(){let s=globalThis;if(typeof s.WebSocket>"u")try{let e=await import("ws"),t=e.default??e;s.WebSocket=t}catch(e){Ri("WebSocket",e)}if(typeof s.RTCPeerConnection>"u")try{let e=await import("@roamhq/wrtc"),t=e.default??e;for(let r of od)t[r]!=null&&typeof s[r]>"u"&&(s[r]=t[r])}catch(e){Ri("@roamhq/wrtc",e)}}function Ri(s,e){let t=e instanceof Error?e.message:String(e);console.warn(`[urun-sh/core] Node WebRTC support: optional dependency "${s}" unavailable (${t}). Realtime media will not work in this Node process; install "${s}" to enable it. Doc/KV transport over WebSocket is unaffected.`)}var Ei=[1e3,2e3,4e3,8e3,3e4],ki=5,cd=15e3,dd=2e3,pd=6e3,ld=2,ud=750,hd=3,xi=[1e3,2e3,4e3],fd=15e3,bs="control",Ii=0,Li=1,Ss=64;function md(s,e){if(s===bs){let n=new Uint8Array(1+e.length);return n[0]=Ii,n.set(e,1),n}let t=new TextEncoder().encode(s);if(t.length<1||t.length>Ss)throw new Error(`[urun] doc key length out of range (1..${Ss}): ${t.length}`);let r=new Uint8Array(3+t.length+e.length);return r[0]=Li,r[1]=t.length>>>8&255,r[2]=t.length&255,r.set(t,3),r.set(e,3+t.length),r}function gd(s){if(s.length===0)return{docKey:bs,payload:s.slice()};let e=s[0];if(e===Ii)return{docKey:bs,payload:s.slice(1)};if(e===Li){if(s.length<3)return null;let t=s[1]<<8|s[2];if(t<1||t>Ss||s.length<3+t)return null;let r=new TextDecoder().decode(s.subarray(3,3+t)),n=s.slice(3+t);return{docKey:r,payload:n}}return null}var _d={queued:"queued",pending:"provisioning",allocating:"provisioning",provisioning:"provisioning",allocated:"connecting",connecting:"connecting",live:"live",running:"live",failed:"error",rejected:"error",expired:"error",cancelled:"ended",canceled:"ended",closed:"ended"},vd=8e3,at=class{_state="disconnected";_sessionId=null;_tracks=new Map;_tracksByName=new Map;_options;_emitter=new ys.default;_ws=null;_device=null;_recvTransport=null;_sendTransport=null;_consumers=new Map;_audioProducer=null;_pendingProduce=null;_multiplexer=null;_reconnectAttempts=0;_intentionalDisconnect=!1;_reconnectTimer=null;_stableResetTimer=null;_generation=0;_lastStartOptions;_resolveConnection=null;_recvTransportMsg=null;_lastConsumeMsg=null;_recvConnectWatchdog=null;_recvTcpFailoverDone=!1;_phase={name:"idle"};_requestId;_liveReached=!1;_mediaMonitorTimer=null;_lastInboundTotal=0;_mediaEverFlowed=!1;_lastInboundAdvanceAt=0;_mediaDeathHandled=!1;_currentEpoch=0;_consumerId=null;_pendingStreamSubscribes=new Set;get consumerId(){return this._consumerId===null&&(this._consumerId=wd()),this._consumerId}get state(){return this._state}get currentIncarnation(){return this._currentEpoch}get phase(){return this._phase}get sessionId(){return this._sessionId}get tracks(){return this._tracks}get multiplexer(){return this._multiplexer}get isOpen(){return this._ws?.readyState===WebSocket.OPEN}getTrackByName(e){let t=this._tracksByName.get(e);if(t&&t.readyState!=="ended")return t;for(let r of this._tracks.values())if(r.kind===e&&r.readyState!=="ended")return r;return t}setAuth(e){this._options={...this._options,...e},this.isOpen&&this._send({type:"auth",orgId:this._options.orgId,jwt:this._options.jwt,authProvider:this._options.authProvider})}constructor(e){this._options=e??{url:""},e?.sessionId&&(this._sessionId=e.sessionId)}setConnection(e){if(this.isOpen)throw new Error("TransportSession: cannot change connection while connected");this._options={...this._options,...e},e.sessionId&&(this._sessionId=e.sessionId)}setConnectionResolver(e){this._resolveConnection=e}applyControlDocState(e){let t=e&&typeof e=="object"?e.session:void 0,r=bd(t);r!==void 0&&this.setIncarnation(r)}setIncarnation(e){if(!Number.isFinite(e)||e<=this._currentEpoch)return;let t=this._currentEpoch>0,r=this._state==="connected";this._currentEpoch=e,t&&r&&!this._intentionalDisconnect&&this._renegotiate()}isStaleIncarnation(e){return Number.isFinite(e)?e<this._currentEpoch:!1}isStaleClosedMarker(e){if(!e)return!1;let t=typeof e.status=="string"?e.status:void 0;if(t!=="closed"&&t!=="ended")return!1;let r=e.status_epoch??e.statusEpoch,n=typeof r=="number"?r:Number(r);return Number.isFinite(n)?n<this._currentEpoch:!1}async connect(e){this._lastStartOptions=e,this._intentionalDisconnect=!1;let t=++this._generation;this._state!=="reconnecting"&&this._state!=="renegotiating"&&this._setState("connecting");let r=null,n=()=>t!==this._generation||this._intentionalDisconnect,i=()=>{if(n())throw new Error("TransportSession: connect cancelled")},o=async()=>{for(let c of this._connectUrls()){i();try{return await this._connectOnce(c,t,e),!0}catch(d){r=d instanceof Error?d:new Error(String(d)),this._cleanupSocket()}}return!1},a=this._resolveConnection?ld:1;for(let c=0;c<a;c++)if(c>0&&(await Pi(ud),i()),await o())return;if(this._resolveConnection)for(let c=0;c<hd;c++){this._setState("reconnecting"),await Pi(xi[Math.min(c,xi.length-1)]),i();try{let d=await this._resolveConnection();i(),this.setAuth({jwt:d.jwt??this._options.jwt,authProvider:this._options.authProvider,orgId:this._options.orgId}),this.setConnection({url:d.url,sessionId:d.sessionId})}catch(d){if(n())throw new Error("TransportSession: connect cancelled");r=d instanceof Error?d:new Error(String(d));continue}if(await o())return}throw this._setState("failed"),r??new Error("TransportSession: connect failed")}disconnect(){if(this._generation+=1,this._intentionalDisconnect=!0,this._stopMediaMonitor(),this._reconnectTimer&&(clearTimeout(this._reconnectTimer),this._reconnectTimer=null),this._clearReconnectBudgetReset(),this._reconnectAttempts=0,this._audioProducer){this._send({type:"stopAudio"});try{this._audioProducer.close()}catch{}this._audioProducer=null}for(let e of this._consumers.values())try{e.close()}catch{}if(this._consumers.clear(),this._sendTransport){try{this._sendTransport.close()}catch{}this._sendTransport=null}if(this._recvTransport){this._clearRecvWatchdog();try{this._recvTransport.close()}catch{}this._recvTransport=null}if(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._ws){let e=this._ws;this._ws=null;try{e.close(1e3,"intentional disconnect")}catch{}}this._tracks.clear(),this._tracksByName.clear(),this._setState("disconnected"),this._liveReached=!1,this._setPhase("ended"),this._emitter.emit("disconnected")}on(e,t){return this._emitter.on(e,t),()=>{this._emitter.off(e,t)}}sendInput(e,t){this._send({type:"input",data:e,sequence:t})}sendDocSync(e,t){!this._ws||this._ws.readyState!==WebSocket.OPEN||this._ws.send(md(e,t))}onDocSync(e,t){let r=(n,i)=>{n===e&&t(i)};return this.on("docSync",r)}onDocSyncReady(e){return this.on("docSyncReady",e)}_emitDocSyncFrame(e){let t=gd(e);if(!t){console.warn("[urun] doc-sync: unknown/malformed typed-v1 frame; dropped");return}this._emitter.emit("docSync",t.docKey,t.payload)}async addTrack(e){if(!this._sendTransport)throw new Error("TransportSession: send transport not ready");this._audioProducer=await this._sendTransport.produce({track:e,codecOptions:{opusStereo:!1,opusDtx:!1,opusFec:!1}})}removeTrack(){this._audioProducer&&(this._send({type:"stopAudio"}),this._audioProducer.close(),this._audioProducer=null)}requestDiagnostics(){this._send({type:"diagnostics"})}seekStream(e,t){this._send({type:"stream.seek",stream:e,target:t})}subscribeStream(e){this._pendingStreamSubscribes.add(e),this._sendStreamSubscribe(e)}unsubscribeStream(e){this._pendingStreamSubscribes.delete(e),this._send({t:"stream.unsubscribe",name:e,consumerId:this.consumerId})}_sendStreamSubscribe(e){this._send({t:"stream.subscribe",name:e,consumerId:this.consumerId})}_flushStreamSubscribes(){for(let e of this._pendingStreamSubscribes)this._sendStreamSubscribe(e)}async _handleMessage(e){switch(e.type){case"routerRtpCapabilities":await this._onRouterCapabilities(e.rtpCapabilities);break;case"createWebRtcTransport":await this._onCreateRecvTransport(e);break;case"createSendTransport":await this._onCreateSendTransport(e);break;case"consume":await this._onConsume(e);break;case"produced":if(this._pendingProduce){let t=this._pendingProduce;this._pendingProduce=null,clearTimeout(t.timeoutId),t.resolve(e.id)}break;case"started":this._emitter.emit("started");break;case"status":this._onStatus(e);break}}_onStatus(e){let t=e.request_id??e.requestId;if(t&&(this._requestId=t),this._liveReached)return;let r=typeof e.status=="string"?e.status:void 0,n=(r&&_d[r])??"provisioning",i=e.queue_position??e.queuePosition,o=e.queue_depth??e.queueDepth,a=typeof i=="number"&&typeof o=="number";if(n==="error"){this._setPhase("error",{error:{reason:r??"admission failed",code:r}});return}if(n==="ended"){this._setPhase("ended");return}if(n==="queued"){this._setPhase("queued",a?{queue:{position:i,depth:o}}:void 0);return}if(n==="connecting"){this._setPhase("connecting");return}this._setPhase("provisioning")}async _onRouterCapabilities(e){vr()&&await Ti();let t=Ci(),r=new Di.Device(t?{handlerName:t}:void 0);await r.load({routerRtpCapabilities:e}),this._device=r,this._send({type:"rtpCapabilities",rtpCapabilities:r.rtpCapabilities})}async _onCreateRecvTransport(e){this._device&&(this._recvTransportMsg=e,this._recvTcpFailoverDone=!1,this._buildRecvTransport(e,!1))}_buildRecvTransport(e,t){if(!this._device)return;let r=e.iceCandidates,n=t?r.filter(a=>a.protocol==="tcp"):r,i=this._device.createRecvTransport({id:e.id,iceParameters:e.iceParameters,iceCandidates:n,dtlsParameters:e.dtlsParameters,iceServers:[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun1.l.google.com:19302"}]}),o=this._generation;i.on("connect",({dtlsParameters:a},c,d)=>{try{this._send({type:"connectTransport",transportId:i.id,dtlsParameters:a}),c()}catch(p){d(p)}}),i.on("connectionstatechange",a=>{if(o===this._generation){if(a==="connected"){this._clearRecvWatchdog();return}if(!(this._intentionalDisconnect&&a==="closed")&&(a==="failed"||a==="disconnected")){if(!t&&!this._recvTcpFailoverDone){this._failoverRecvToTcp(`state:${a}`);return}a==="failed"&&this._emitError(new Error(`media transport ${a}`),a)}}}),this._recvTransport=i,this._clearRecvWatchdog(),t||(this._recvConnectWatchdog=setTimeout(()=>{o===this._generation&&this._recvTransport?.connectionState!=="connected"&&this._failoverRecvToTcp("timeout")},vd))}_clearRecvWatchdog(){this._recvConnectWatchdog&&(clearTimeout(this._recvConnectWatchdog),this._recvConnectWatchdog=null)}_failoverRecvToTcp(e){if(this._recvTcpFailoverDone||this._intentionalDisconnect)return;let t=this._recvTransportMsg;if(!this._device||!t)return;if(!t.iceCandidates.some(n=>n.protocol==="tcp")){this._emitter.emit("error",new Error(`media transport failed (${e}); no TCP candidate`));return}if(this._recvTcpFailoverDone=!0,this._clearRecvWatchdog(),this._recvTransport)try{this._recvTransport.close()}catch{}this._buildRecvTransport(t,!0),this._lastConsumeMsg&&this._onConsume(this._lastConsumeMsg)}async _onCreateSendTransport(e){if(!this._device)return;let t=this._device.createSendTransport({id:e.id,iceParameters:e.iceParameters,iceCandidates:e.iceCandidates,dtlsParameters:e.dtlsParameters,iceServers:[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun1.l.google.com:19302"}]}),r=this._generation;t.on("connect",({dtlsParameters:n},i,o)=>{try{this._send({type:"connectSendTransport",transportId:t.id,dtlsParameters:n}),i()}catch(a){o(a)}}),t.on("produce",({kind:n,rtpParameters:i},o,a)=>{if(this._pendingProduce){a(new Error("produce already pending"));return}let c=setTimeout(()=>{let d=this._pendingProduce;!d||d.timeoutId!==c||(this._pendingProduce=null,d.reject(new Error("Produce timed out")))},15e3);this._pendingProduce={timeoutId:c,resolve:d=>{o({id:d})},reject:a};try{this._send({type:"produce",kind:n,rtpParameters:i})}catch(d){this._pendingProduce?.timeoutId===c&&(this._pendingProduce=null,clearTimeout(c)),a(d)}}),t.on("connectionstatechange",n=>{r===this._generation&&(this._intentionalDisconnect&&n==="closed"||(n==="failed"||n==="closed")&&this._emitError(new Error(`media send transport ${n}`),n))}),this._sendTransport=t,this._emitter.emit("audioTransportReady")}async _onConsume(e){if(!this._recvTransport)return;this._lastConsumeMsg=e;let t=this._generation,r=await this._recvTransport.consume({id:e.id,producerId:e.producerId,kind:e.kind,rtpParameters:e.rtpParameters});this._consumers.set(r.id,r),this._tracks.set(r.track.id,r.track);let n=e.streamName??e.label;n&&this._tracksByName.set(n,r.track),this._liveReached||this._setPhase("live"),this._emitter.emit("track",r.track),r.track.addEventListener("ended",()=>{t!==this._generation||this._intentionalDisconnect||this._renegotiate()},{once:!0}),this._send({type:"resumeConsumer",consumerId:r.id}),this._startMediaMonitor()}_mediaPollMs(){let e=this._options.mediaLiveness?.pollMs;return e===void 0?dd:e}_mediaStallTimeoutMs(){let e=this._options.mediaLiveness?.stallTimeoutMs;return e===void 0?pd:e}_startMediaMonitor(){let e=this._mediaPollMs();if(e<=0||this._mediaMonitorTimer)return;this._lastInboundTotal=0,this._mediaEverFlowed=!1,this._lastInboundAdvanceAt=Date.now(),this._mediaDeathHandled=!1;let t=this._generation;this._mediaMonitorTimer=setInterval(()=>{t!==this._generation||this._intentionalDisconnect||this._sampleMediaLiveness(t)},e)}_stopMediaMonitor(){this._mediaMonitorTimer&&(clearInterval(this._mediaMonitorTimer),this._mediaMonitorTimer=null)}async _sampleMediaLiveness(e){if(this._consumers.size===0)return;let t=0;for(let n of this._consumers.values())t+=await yd(n);if(e!==this._generation||this._intentionalDisconnect)return;let r=Date.now();if(t>this._lastInboundTotal){this._lastInboundTotal=t,this._lastInboundAdvanceAt=r,t>0&&(this._mediaEverFlowed=!0);return}this._mediaEverFlowed&&(this._mediaDeathHandled||r-this._lastInboundAdvanceAt>=this._mediaStallTimeoutMs()&&(this._mediaDeathHandled=!0,this._renegotiate()))}_renegotiate(){this._intentionalDisconnect||this._reconnectTimer||(this._stopMediaMonitor(),this._setState("renegotiating"),this._attemptReconnect())}_attemptReconnect(e){if(this._intentionalDisconnect||this._reconnectTimer)return;if(this._reconnectAttempts>=ki){this._setState("failed"),this._emitError(new Error(`Failed after ${ki} attempts`));return}let t=Ei[Math.min(this._reconnectAttempts,Ei.length-1)];this._reconnectAttempts++,this._state!=="renegotiating"&&this._setState("reconnecting"),this._reconnectTimer=setTimeout(async()=>{this._reconnectTimer=null,this._cleanupMedia();try{await this.connect(e??this._lastStartOptions)}catch(r){if(r instanceof Error&&r.message==="TransportSession: connect cancelled")return;this._attemptReconnect(e)}},t)}_connectUrls(){let e=[],t=r=>{if(!r)return;let n=/\/ws\/rtc\/[^/?#]+/.test(r),i=this._sessionId&&!n?`${r}${r.includes("?")?"&":"?"}sessionId=${encodeURIComponent(this._sessionId)}`:r;e.includes(i)||e.push(i)};t(this._options.url);for(let r of this._options.fallbackUrls??[])t(r);return e}_connectOnce(e,t,r){return new Promise((n,i)=>{let o=!1,a=!1,c=null,d=new WebSocket(e);d.binaryType="arraybuffer",this._ws=d;let p=l=>{a||this._ws!==d||t!==this._generation||(a=!0,c&&clearTimeout(c),i(l))};c=setTimeout(()=>{try{d.close()}catch{}p(new Error("TransportSession: connect timed out"))},cd),d.onopen=()=>{a||t!==this._generation||(o=!0,c&&clearTimeout(c),this._multiplexer=new Ne(d),d.send(JSON.stringify(this._startMessage(r))),this._emitter.emit("docSyncReady"),this._flushStreamSubscribes(),this._scheduleReconnectBudgetReset(),this._setState("connected"),this._liveReached||this._setPhase("connecting"),this._emitter.emit("connected"),a=!0,n())},d.onerror=()=>{o||p(new Error("WebSocket connection error"))},d.onclose=()=>{if(!(this._ws!==d||t!==this._generation)){if(this._clearReconnectBudgetReset(),!o){p(new Error("WebSocket closed before connecting"));return}c&&clearTimeout(c),this._setState("disconnected"),this._intentionalDisconnect||(this._emitter.emit("disconnected"),this._attemptReconnect(r))}},d.onmessage=l=>{if(!(this._ws!==d||t!==this._generation)){if(typeof l.data=="string")try{this._handleMessage(JSON.parse(l.data))}catch(u){this._emitter.emit("error",u instanceof Error?u:new Error(String(u)))}else if(l.data instanceof ArrayBuffer)this._emitDocSyncFrame(new Uint8Array(l.data));else if(ArrayBuffer.isView(l.data)){let u=l.data;this._emitDocSyncFrame(new Uint8Array(u.buffer,u.byteOffset,u.byteLength))}}}})}_startMessage(e){let t={type:"start",docFraming:"typed-v1",video:e?.video??{width:854,height:480,frameRate:16}};return e?.prompt&&(t.prompt=e.prompt),e?.cameraControl&&(t.camera_control=e.cameraControl),e?.args&&(t.args=e.args),e?.app&&(t.app=e.app),e?.functionName&&(t.function=e.functionName),e?.role&&(t.role=e.role),this._options.orgId&&(t.orgId=this._options.orgId),this._options.jwt&&(t.jwt=this._options.jwt),this._options.authProvider&&(t.authProvider=this._options.authProvider),t}_cleanupSocket(){if(this._clearReconnectBudgetReset(),!this._ws)return;let e=this._ws;this._ws=null;try{e.close()}catch{}}_scheduleReconnectBudgetReset(){this._clearReconnectBudgetReset(),this._reconnectAttempts!==0&&(this._stableResetTimer=setTimeout(()=>{this._stableResetTimer=null,this._reconnectAttempts=0},fd))}_clearReconnectBudgetReset(){this._stableResetTimer&&(clearTimeout(this._stableResetTimer),this._stableResetTimer=null)}_cleanupMedia(){this._stopMediaMonitor();for(let e of this._consumers.values())try{e.close()}catch{}if(this._consumers.clear(),this._audioProducer){try{this._audioProducer.close()}catch{}this._audioProducer=null}if(this._clearRecvWatchdog(),this._recvTransport){try{this._recvTransport.close()}catch{}this._recvTransport=null}if(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(e){!this._ws||this._ws.readyState!==WebSocket.OPEN||this._ws.send(JSON.stringify(e))}_setState(e){this._state!==e&&(this._state=e,this._emitter.emit("stateChange",e))}_setPhase(e,t){e==="live"&&(this._liveReached=!0);let r={name:e};t?.queue&&(r.queue=t.queue),this._requestId&&(r.requestId=this._requestId),this._sessionId&&(r.sessionId=this._sessionId),t?.error&&(r.error=t.error),this._phase=r,this._emitter.emit("phase",r)}_emitError(e,t){this._setPhase("error",{error:{reason:e.message,code:t}}),this._emitter.emit("error",e)}};function Pi(s){return new Promise(e=>setTimeout(e,s))}function wd(){let s=globalThis.crypto;return s?.randomUUID?s.randomUUID():`cons_${Date.now().toString(36)}_${Math.random().toString(36).slice(2)}`}async function yd(s){if(typeof s.getStats!="function")return 0;let e;try{e=await s.getStats()}catch{return 0}let t=0,r=n=>{if(!n||typeof n!="object")return;let i=n;if(i.type==="inbound-rtp"){let o=typeof i.bytesReceived=="number"?i.bytesReceived:0,a=typeof i.packetsReceived=="number"?i.packetsReceived:0;t+=o+a}};if(e instanceof Map)for(let n of e.values())r(n);else if(Array.isArray(e))for(let n of e)r(n);else e&&typeof e.forEach=="function"&&e.forEach(r);return t}function bd(s){if(!s||typeof s!="object")return;let e=s.epoch,t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?t:void 0}var Sd="session-api.prod.cloud.urun.sh",Rd=["https://session-api.use2.prod.cloud.urun.sh","https://session-api.usw2.prod.cloud.urun.sh"];function wr(s){return s.trim().replace(/\/+$/,"")}function Mi(s,e){let t=[],r=n=>{if(!n)return;let i=wr(n);i&&!t.includes(i)&&t.push(i)};r(s);for(let n of e??[])r(n);for(let n of Ld(s))r(n);return t}var Cd=120,Td=1e3,Ed=3;function kd(s){if(!s)return null;try{let e=new URL(s),t=e.pathname.replace(/\/api\/sessions\/create\/?$/,"");return wr(`${e.origin}${t}`)}catch{return null}}async function Oi(s){let e=Mi(s.baseUrl,s.fallbackUrls),t=null,r=e.length>1;for(let n of e)try{return await xd(n,s,{pollAttempts:Cd,retryAfterLimitMs:r?Td:void 0})}catch(i){if(t=i instanceof Error?i:new Error(String(i)),t instanceof Oe)throw t}throw t??new Error("[urun] session allocation failed")}async function xd(s,e,t){let r,n,i,o=s,a=0,c=new Set;for(let d=0;d<t.pollAttempts;d++){n=i??await Cs(e),i=void 0;let p=r?await fetch(`${o}/api/session-requests/${encodeURIComponent(r)}`,{headers:Rs(e,n)}):await fetch(`${o}/api/sessions/create`,{method:"POST",redirect:"manual",headers:{...Rs(e,n),"Content-Type":"application/json","Idempotency-Key":e.idempotencyKey},body:JSON.stringify(Pd(e))});if(!r&&(p.status===307||p.status===308)){let m=kd(p.headers.get("location"));if(m&&m!==o&&a<Ed){a+=1,o=m;continue}throw new Error(`[urun] session create redirected from ${o} without a usable target`)}let l=await Ni(p);if(p.ok&&(l.status==="allocated"||!l.status&&!!l.session_id)&&!!l.session_id){let m=l.session_id;if(!l.ws_url)throw new Oe(`[urun] gateway allocated session ${m} without ws_url`);if(!ji(l.ws_url))throw new Oe(`[urun] gateway allocated session ${m} with non-absolute ws_url`);return{baseUrl:o,sessionId:m,wsUrl:l.ws_url,response:l}}if(p.status===202||l.status==="pending"||l.status==="queued"||l.queued){if(r=l.request_id||r,!r)throw new Error("[urun] gateway queued session without request_id");await Id(Dd(p,l,t.retryAfterLimitMs));continue}if((p.status===401||p.status===403)&&e.getAccessToken){let m=n??"";c.add(m);let h=await Cs(e,{forceRefresh:!0,reason:"unauthorized"});if(h&&!c.has(h)){i=h,r=void 0;continue}}let f=l.error_message||l.error_code||`HTTP ${p.status}`;throw new Error(`[urun] session allocation failed at ${o}: ${f}`)}throw new Error(`[urun] timed out waiting for session allocation at ${o}`)}function Rs(s,e){let t={"X-Tenant-Id":s.orgId,"X-Auth-Provider":s.authProvider||"default","X-User-Id":"anonymous"};return e&&(t.Authorization=`Bearer ${e}`),t}async function Cs(s,e){return s.getAccessToken?await s.getAccessToken(e)??void 0:s.jwt}function Pd(s){return{app:s.app,function:s.functionName,gpus:1,idempotency_key:s.idempotencyKey}}async function Ai(s){let e=Mi(s.baseUrl,s.fallbackUrls),t=null;for(let r of e)try{let n={baseUrl:r,app:"",functionName:"",orgId:s.orgId,jwt:s.jwt,getAccessToken:s.getAccessToken,authProvider:s.authProvider,idempotencyKey:""},i=await Cs(n),o=await fetch(`${wr(r)}/api/sessions/${encodeURIComponent(s.sessionId)}/viewer-connect`,{headers:Rs(n,i)});if(!o.ok)throw new Error(`[urun] viewer-connect for ${s.sessionId} failed: HTTP ${o.status}`);let a=await Ni(o);if(!a.ws_url||!ji(a.ws_url))throw new Oe(`[urun] viewer-connect returned no usable ws_url for ${s.sessionId}`);return{baseUrl:wr(r),sessionId:s.sessionId,wsUrl:a.ws_url,response:a}}catch(n){if(t=n instanceof Error?n:new Error(String(n)),t instanceof Oe)throw t}throw t??new Error("[urun] viewer-connect failed")}async function Ni(s){try{let e=await s.json();return e&&typeof e=="object"?e:{}}catch{return{}}}function Dd(s,e,t){let r=Number(s.headers.get("Retry-After")||""),n=Number(e.retry_after_seconds??r),i=t??1e4;return Number.isFinite(n)&&n>0?Math.min(n*1e3,i):1e3}function Id(s){return new Promise(e=>setTimeout(e,s))}var Oe=class extends Error{};function ji(s){try{let e=new URL(s);return e.protocol==="ws:"||e.protocol==="wss:"}catch{return!1}}function Ld(s){try{return new URL(s).hostname!==Sd?[]:Rd}catch{return[]}}var ct=Se(require("yjs")),Fi=Symbol("urun:doc:remote"),Md=Symbol("urun:doc:local");function yr(s){return s!==null&&typeof s=="object"&&!Array.isArray(s)}function Ts(s,e){let t={...s};for(let r of Object.keys(e)){let n=e[r],i=t[r];yr(n)&&yr(i)?t[r]=Ts(i,n):t[r]=n}return t}function Od(s,e){let t=e.split("."),r=s;for(let n of t){if(r==null||typeof r!="object")return;r=r[n]}return r}function qi(s){return s===void 0?s:JSON.parse(JSON.stringify(s))}var br=class{_doc=new ct.Doc;_root=this._doc.getMap("session");_listeners=new Set;_key;_sessionId;_transport;_transportUnsubs=[];_synced;_pendingPatches=[];_texts=new Map;_observer=()=>this.notify();_updateHandler=(e,t)=>{t!==Fi&&this._transport?.sendDocSync(this._key,e)};constructor(e,t,r){this._key=e,this._sessionId=t,this._transport=r??null,this._synced=this._transport===null,this._root.observeDeep(this._observer),this._doc.on("update",this._updateHandler),this._transport&&(this._transportUnsubs.push(this._transport.onDocSync(this._key,n=>this.applyRemote(n)),this._transport.onDocSyncReady(()=>this.sendHello())),this._transport.isOpen&&this.sendHello())}setSessionId(e){this._sessionId=e}set(e){if(!this._synced){this._pendingPatches.push(qi(e)),this.notify();return}this.applyPatch(e)}get(e,t){let r=this.snapshot();return e?Od(r,e)??t:r}on(e,t){return this._listeners.add(t),()=>this._listeners.delete(t)}text(e){let t=this._texts.get(e);return t||(t=new Es(this._doc.getText(`text:${e}`)),this._texts.set(e,t)),t}dispose(){this._root.unobserveDeep(this._observer),this._doc.off("update",this._updateHandler);for(let e of this._transportUnsubs)e();this._transportUnsubs=[],this._transport=null,this._listeners.clear();for(let e of this._texts.values())e.dispose();this._texts.clear(),this._doc.destroy()}sendHello(){this._transport&&this._transport.sendDocSync(this._key,ct.encodeStateAsUpdate(this._doc))}applyRemote(e){if(ct.applyUpdate(this._doc,e,Fi),!this._synced){this._synced=!0;let t=this._pendingPatches.splice(0);for(let r of t)this.applyPatch(r)}}applyPatch(e){this._doc.transact(()=>{let t=this._root.toJSON();for(let[r,n]of Object.entries(e)){let i=t[r],o=yr(n)&&yr(i)?Ts(i,n):qi(n);JSON.stringify(o)!==JSON.stringify(i)&&this._root.set(r,o)}},Md)}snapshot(){let e=this._root.toJSON();for(let t of this._pendingPatches)e=Ts(e,t);return e}notify(){let e=this.snapshot();for(let t of this._listeners)t(e)}},Es=class{constructor(e){this._ytext=e;this._observer=t=>{for(let r of t.delta)if(typeof r.insert=="string"&&r.insert.length>0){let n=r.insert;for(let i of this._delta)i(n)}},this._ytext.observe(this._observer)}_ytext;_delta=new Set;_observer;append(e){e.length!==0&&this._ytext.insert(this._ytext.length,e)}toString(){return this._ytext.toString()}get length(){return this._ytext.length}on(e,t){return this._delta.add(t),()=>this._delta.delete(t)}dispose(){this._ytext.unobserve(this._observer),this._delta.clear()}};var ue=class extends Error{requestId;code;constructor(e,t){super(e),this.name="RequestError",this.requestId=t?.requestId,this.code=t?.code,t?.cause!==void 0&&(this.cause=t.cause),Object.setPrototypeOf(this,new.target.prototype)}},dt=class extends ue{timeoutMs;constructor(e,t){super(`[urun] request timed out after ${e}ms`,{requestId:t}),this.name="RequestTimeoutError",this.timeoutMs=e,Object.setPrototypeOf(this,new.target.prototype)}},we=class extends ue{constructor(e){super("[urun] request aborted",{requestId:e}),this.name="RequestAbortError",Object.setPrototypeOf(this,new.target.prototype)}},pt=class extends ue{constructor(e){super("[urun] request cancelled: session disconnected",{requestId:e}),this.name="RequestCancelledError",Object.setPrototypeOf(this,new.target.prototype)}};var Ad=new Set,Nd="rpc",jd="llm",Fd="llm-resp";function qd(s){return`${Fd}:${s}`}function ks(){let s=globalThis.crypto;return s?.randomUUID?s.randomUUID():`req_${Date.now().toString(36)}_${Math.random().toString(36).slice(2)}`}function $d(s){if(s&&typeof s=="object"){let e=s.error;if(e&&typeof e=="object"){let{message:t,code:r}=e;return{message:typeof t=="string"?t:JSON.stringify(e),code:typeof r=="string"?r:void 0}}if(typeof e=="string")return{message:e}}return{message:typeof s=="string"?s:JSON.stringify(s)}}function Ud(s,e,t,r,n,i,o,a){let c=[],d=null,p=!1,l=null,u=!1,f,m,h=new Promise((D,be)=>{f=D,m=be});h.catch(()=>{});let g=i(),_=null,y=null,x=!0,P=()=>{x=!1,_?.(),_=null,y?.(),y=null,o?.removeEventListener("abort",re),g.dispose(),u&&s.set({requests:{[e]:null}})},k=()=>{if(d){if(c.length>0){let D=d;d=null,D.resolve({value:c.shift(),done:!1})}else if(l!==null){let D=d;d=null,D.reject(l)}else if(p){let D=d;d=null,D.resolve({value:void 0,done:!0})}}},I=D=>{p||(c.push(D),k())},Y=D=>{p||(l=D,p=!0,m(D),P(),k())},ye=D=>{p||(p=!0,f(D),P(),k())},re=()=>Y(new we(e)),he=D=>{if(!(p||!D||typeof D!="object"))switch(D.t){case"delta":typeof D.delta=="string"&&I(D.delta);break;case"response":ye(D.body);break;case"error":{let{message:be,code:Ae}=$d(D.body);Y(new ue(be,{requestId:e,code:D.code??Ae}));break}}},Vi=()=>{let D=g.messages()[Symbol.asyncIterator]();_=()=>{D.return?.(void 0)};let be=()=>{x&&D.next().then(Ae=>{if(x){if(Ae.done){p||ye(void 0);return}he(Ae.value),be()}},Ae=>{x&&Y(Ae)})};be()},Ds=()=>{if(!u){if(u=!0,o){if(o.aborted){Y(new we(e));return}o.addEventListener("abort",re,{once:!0})}y=a?.(D=>Y(D))??null,Vi(),s.set({requests:{[e]:{payload:t,consumer_id:r,stream:n}}})}};return{deltas:{[Symbol.asyncIterator](){return{next(){if(Ds(),c.length>0)return Promise.resolve({value:c.shift(),done:!1});if(l!==null){let D=l;return l=null,Promise.reject(D)}return p?Promise.resolve({value:void 0,done:!0}):new Promise((D,be)=>{d={resolve:D,reject:be}})},return(){return p||(p=!0,f(void 0),P()),Promise.resolve({value:void 0,done:!0})},throw(D){return p||(p=!0,m(D),P()),Promise.reject(D)}}}},body:h,start:Ds}}function zd(s,e){return[`streams/${s}/${e}`,`streams/${s}/*`]}var xs=class{constructor(e,t,r){this._name=e;this._transport=t;this._laneDoc=r;this._track=this._transport.getTrackByName(this._name)??null,this._unsubscribeTransport=this._transport.on("track",()=>{let n=this._transport.getTrackByName(this._name)??null;n!==this._track&&this._setTrack(n)})}_name;_transport;_laneDoc;_track=null;_handlers=new Map;_unsubscribeTransport=null;_subscribed=!1;_messageConsumers=new Set;_laneUnsubs=[];_laneSeen=new Map;_disposed=!1;messages(){this._ensureSubscribed();let e=this;return{[Symbol.asyncIterator](){let t=[],r=null,n=!1,i={push(a){if(!n)if(r){let c=r;r=null,c({value:a,done:!1})}else t.push(a)},end(){if(n=!0,r){let a=r;r=null,a({value:void 0,done:!0})}}};e._messageConsumers.add(i);let o=()=>{n=!0,e._messageConsumers.delete(i)};return{next(){return t.length>0?Promise.resolve({value:t.shift(),done:!1}):n?Promise.resolve({value:void 0,done:!0}):new Promise(a=>{r=a})},return(){return o(),Promise.resolve({value:void 0,done:!0})}}}}}_ensureSubscribed(){if(!(this._subscribed||this._disposed)&&(this._subscribed=!0,this._transport.subscribeStream(this._name),!!this._laneDoc))for(let e of zd(this._name,this._transport.consumerId)){let t=this._laneDoc(e);this._laneSeen.set(e,0);let r=n=>this._drainLane(e,n);r(t.get()),this._laneUnsubs.push(t.on("change",r))}}_drainLane(e,t){let r=t.messages;if(!Array.isArray(r))return;let n=this._laneSeen.get(e)??0;for(;n<r.length;n++){let i=r[n];for(let o of this._messageConsumers)o.push(i)}this._laneSeen.set(e,n)}get track(){let e=this._transport.getTrackByName(this._name)??this._track;return e!==this._track&&this._setTrack(e),this._track}async attach(e){await this._transport.addTrack(e)}async detach(){this._transport.removeTrack()}async seek(e){if(e!=="live"&&(!Number.isFinite(e)||e<0))throw new Error('[urun] stream.seek target must be "live" or a non-negative number of seconds');this._transport.seekStream(this._name,e)}on(e,t){let r=this._handlers.get(e);return r||(r=new Set,this._handlers.set(e,r)),r.add(t),()=>{r?.delete(t),r?.size===0&&this._handlers.delete(e)}}dispose(){this._disposed=!0,this._unsubscribeTransport?.(),this._unsubscribeTransport=null,this._handlers.clear(),this._subscribed&&this._transport.unsubscribeStream(this._name);for(let e of this._laneUnsubs)e();this._laneUnsubs=[];for(let e of this._messageConsumers)e.end();this._messageConsumers.clear()}_setTrack(e){this._track=e,e&&e.addEventListener("ended",()=>{this._track===e&&this._setTrack(null)},{once:!0});let t=this._handlers.get("track");if(t)for(let r of t)r(e)}},lt=class s{_sessionId;_multiplexer;_transport;_docs=new Map;_streams=new Map;_activeRequests=new Set;constructor(e,t,r){this._sessionId=e,this._multiplexer=t,this._transport=r,this._wireControlDocIncarnation()}_wireControlDocIncarnation(){let e=this.doc("control");this._transport.applyControlDocState(e.get()),e.on("change",t=>{this._transport.applyControlDocState(t)})}static async attach(e,t){let r=await Ai({baseUrl:t.baseUrl,fallbackUrls:t.fallbackUrls,sessionId:e,orgId:t.orgId,jwt:t.jwt,getAccessToken:t.getAccessToken,authProvider:t.authProvider}),n=t.getAccessToken?await t.getAccessToken()??void 0:t.jwt,i=new je,o=new at({url:r.wsUrl,orgId:t.orgId,jwt:n,authProvider:t.authProvider,sessionId:e}),a=new s(e,i,o);return o.on("connected",()=>{o.multiplexer&&i.setTarget(o.multiplexer)}),o.setConnection({url:r.wsUrl,sessionId:e}),await o.connect({role:"viewer"}),a}get id(){return this._sessionId}get phase(){return this._transport.phase}onPhase(e){return e(this._transport.phase),this._transport.on("phase",e)}setSessionId(e){if(e===this._sessionId)return;this._multiplexer.rewriteSessionChannels?.call(this._multiplexer,this._sessionId,e),this._sessionId=e;for(let r of this._docs.values())r.setSessionId(e)}stream(e){let t=this._streams.get(e);return t||(t=new xs(e,this._transport,r=>this.doc(r)),this._streams.set(e,t)),t}doc(e){let t=this._docs.get(e);return t||(t=new br(e,this._sessionId,Ad.has(e)?null:this._transport),this._docs.set(e,t)),t}request(e,t={}){let r=this.doc(Nd),n=ks();return new Promise((i,o)=>{let a=!1,c=null,d=null,p=null,l=()=>{d&&(clearTimeout(d),d=null),c&&(c(),c=null),p&&(this._activeRequests.delete(p),p=null),t.signal?.removeEventListener("abort",f),r.set({requests:{[n]:null}})},u=h=>{a||(a=!0,l(),h())},f=()=>u(()=>o(new we(n)));if(t.signal){if(t.signal.aborted){a=!0,o(new we(n));return}t.signal.addEventListener("abort",f,{once:!0})}let m=h=>{let _=h.responses?.[n];if(_==null)return;let y=_;if(y.error!==void 0&&y.error!==null){let x=typeof y.error=="string"?y.error:JSON.stringify(y.error);u(()=>o(new ue(x,{requestId:n,code:y.code})))}else u(()=>i(y.result))};c=r.on("change",m),p=h=>u(()=>o(h)),this._activeRequests.add(p),typeof t.timeout=="number"&&t.timeout>=0&&(d=setTimeout(()=>u(()=>o(new dt(t.timeout,n))),t.timeout)),r.set({requests:{[n]:{payload:e}}}),m(r.get())})}_consumeResponse(e,t,r,n){let i=this.doc(jd);return Ud(i,e,t,this._transport.consumerId,r,()=>this.stream(qd(e)),n,o=>(this._activeRequests.add(o),()=>this._activeRequests.delete(o)))}requestStream(e,t={}){let r=ks();return this._consumeResponse(r,e,!0,t.signal).deltas}complete(e,t={}){let r=ks(),n=this._consumeResponse(r,e,!1,t.signal);return n.start(),n.body}disconnect(){let e=Array.from(this._activeRequests);this._activeRequests.clear();for(let t of e)try{t(new pt)}catch{}for(let t of this._docs.values())t.dispose();this._docs.clear();for(let t of this._streams.values())t.dispose();this._streams.clear(),this._transport.disconnect()}};var Bd=new Set(["then","catch","finally","toJSON",Symbol.toPrimitive]);function $i(s,e){return new Proxy({},{get(t,r){if(!(Bd.has(r)||typeof r!="string"))return n=>{let i=n??{},o=()=>`s_${Date.now()}_${Math.random().toString(36).slice(2)}`,a=o(),c=new je,d=new at({url:"",orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionId:a}),p=new lt(a,c,d),l=async u=>{let f=await Oi({baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,app:s,functionName:r,orgId:e.orgId,jwt:e.jwt,getAccessToken:e.getAccessToken,authProvider:e.authProvider,idempotencyKey:u}),m=e.getAccessToken?await e.getAccessToken()??void 0:e.jwt;return p.setSessionId(f.sessionId),{url:f.wsUrl,sessionId:f.sessionId,jwt:m}};return d.setConnectionResolver(()=>l(o())),d.on("connected",()=>{d.multiplexer&&c.setTarget(d.multiplexer)}),(async()=>{let u=await l(a);d.setAuth({jwt:u.jwt,authProvider:e.authProvider,orgId:e.orgId}),d.setConnection({url:u.url,sessionId:u.sessionId}),await d.connect({app:s,functionName:r,args:i})})().catch(u=>{console.error(`[urun] Failed to connect session for ${r}:`,u)}),p}}})}var Ui=3e4,zi="stream:",Ps=class{_ws;_multiplexer;_pendingRpc=new Map;_rpcId=0;constructor(e,t){this._ws=e,this._multiplexer=t,this._ws.addEventListener("message",r=>{let n;try{n=JSON.parse(typeof r.data=="string"?r.data:"")}catch{return}if(n.rpcId&&this._pendingRpc.has(n.rpcId)){let i=this._pendingRpc.get(n.rpcId);this._pendingRpc.delete(n.rpcId),clearTimeout(i.timer),n.error?i.reject(new Error(n.error)):i.resolve(n.result)}})}async get(e){return this._sendRpc("store.get",{key:e})}async has(e){return await this._sendRpc("store.has",{key:e})}on(e,t){let r=`${zi}${e}`;return this._multiplexer.on(r,n=>{t(n)})}emit(e,t){let r=`${zi}${e}`,n=typeof t=="object"&&t!==null&&!Array.isArray(t)?t:{data:t};this._multiplexer.emit(r,n)}_getInternals(){return{multiplexer:this._multiplexer,ws:this._ws}}_sendRpc(e,t){return new Promise((r,n)=>{if(!this._ws||this._ws.readyState!==WebSocket.OPEN){n(new Error("WebSocket not open"));return}let i=String(++this._rpcId),o=setTimeout(()=>{this._pendingRpc.has(i)&&(this._pendingRpc.delete(i),n(new Error(`RPC request "${e}" timed out after ${Ui}ms`)))},Ui);this._pendingRpc.set(i,{resolve:r,reject:n,timer:o}),this._ws.send(JSON.stringify({rpcId:i,type:e,...t}))})}};function Bi(s){let r=`${s.baseUrl.replace(/\/$/,"").replace(/^http/,"ws")}/store/${encodeURIComponent(s.orgId)}`,n=new WebSocket(r);(s.jwt||s.apiKey)&&n.addEventListener("open",()=>{n.send(JSON.stringify({type:"auth",orgId:s.orgId,jwt:s.jwt,authProvider:s.authProvider,apiKey:s.apiKey}))});let i=new Ne(n);return new Ps(n,i)}var Hd='video/mp4; codecs="avc1.42E01E"';function Hi(s,e){let t=e?.codec??Hd,r=document.createElement("video");r.muted=!0,r.playsInline=!0;let n=new MediaSource,i=URL.createObjectURL(n);r.src=i,n.addEventListener("sourceopen",()=>{let u;try{u=n.addSourceBuffer(t)}catch(g){throw g instanceof DOMException&&g.name==="NotSupportedError"?new Error(`Codec not supported: "${t}". Ensure the codec string matches the fMP4 container format. Common values: video/mp4; codecs="avc1.42E01E" (H.264 Baseline), video/mp4; codecs="avc1.4D401F" (H.264 Main).`):g}let f=s.getReader();function m(){return u.updating?new Promise(g=>{u.addEventListener("updateend",()=>g(),{once:!0})}):Promise.resolve()}async function h(){try{for(;;){let{done:g,value:_}=await f.read();if(g){await m(),n.readyState==="open"&&n.endOfStream();return}await m();try{u.appendBuffer(_)}catch(y){if(y instanceof DOMException&&y.name==="QuotaExceededError"){let x=u.buffered;if(x.length>0){let P=x.start(x.length-1);u.remove(0,P),await m(),u.appendBuffer(_)}else throw y}else throw y}}}catch{if(n.readyState==="open")try{n.endOfStream("decode")}catch{}}}h()}),r.play().catch(()=>{});let o=r,a=o.captureStream??o.mozCaptureStream;if(!a)throw new Error("captureStream() is not supported in this browser. videoStream() requires HTMLMediaElement.captureStream() support.");let c=a.call(r),d=c.getTracks(),p=0,l=d.length;if(l===0)r.addEventListener("emptied",()=>{URL.revokeObjectURL(i)},{once:!0});else for(let u of d)u.addEventListener("ended",()=>{p++,p>=l&&URL.revokeObjectURL(i)});return c}0&&(module.exports={App,RequestAbortError,RequestCancelledError,RequestError,RequestTimeoutError,Session,createStore,videoStream});
7
+ `}});var Si=re(Bn=>{"use strict";var Na=gC(),YO=xC(),JO=_0();Bn.grammar=JO;Bn.write=YO;Bn.parse=Na.parse;Bn.parseParams=Na.parseParams;Bn.parseFmtpConfig=Na.parseFmtpConfig;Bn.parsePayloads=Na.parsePayloads;Bn.parseRemoteCandidates=Na.parseRemoteCandidates;Bn.parseImageAttributes=Na.parseImageAttributes;Bn.parseSimulcastStreamList=Na.parseSimulcastStreamList});var Oa=re(ob=>{"use strict";Object.defineProperty(ob,"__esModule",{value:!0});ob.parse=ZO;var QO=new RegExp("^[LS]([1-9]\\d{0,1})T([1-9]\\d{0,1})");function ZO(r){let e=QO.exec(r??"");return e?{spatialLayers:Number(e[1]),temporalLayers:Number(e[2])}:{spatialLayers:1,temporalLayers:1}}});var wC=re(bo=>{"use strict";Object.defineProperty(bo,"__esModule",{value:!0});bo.OfferMediaSection=bo.AnswerMediaSection=bo.MediaSection=void 0;var eL=Si(),bC=ka(),Rf=class{_mediaObject;constructor({iceParameters:e,iceCandidates:t,dtlsParameters:s}){if(this._mediaObject={type:"",port:0,protocol:"",payloads:"",rtp:[],fmtp:[]},e&&this.setIceParameters(e),t){this._mediaObject.candidates=[];for(let n of t){let i={foundation:n.foundation,component:1,ip:n.address??n.ip,port:n.port,priority:n.priority,transport:n.protocol,type:n.type};n.tcpType&&(i.tcptype=n.tcpType),this._mediaObject.candidates.push(i)}this._mediaObject.endOfCandidates="end-of-candidates",this._mediaObject.iceOptions="renomination"}s&&this.setDtlsRole(s.role)}get mid(){return String(this._mediaObject.mid)}get closed(){return this._mediaObject.port===0}getObject(){return this._mediaObject}setIceParameters(e){this._mediaObject.iceUfrag=e.usernameFragment,this._mediaObject.icePwd=e.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}};bo.MediaSection=Rf;var ab=class extends Rf{constructor({iceParameters:e,iceCandidates:t,dtlsParameters:s,sctpParameters:n,plainRtpParameters:i,offerMediaObject:o,offerRtpParameters:a,answerRtpParameters:c,codecOptions:d}){switch(super({iceParameters:e,iceCandidates:t,dtlsParameters:s}),this._mediaObject.mid=String(o.mid),this._mediaObject.type=o.type,this._mediaObject.protocol=o.protocol,i?(this._mediaObject.connection={ip:i.ip,version:i.ipVersion},this._mediaObject.port=i.port):(this._mediaObject.connection={ip:"127.0.0.1",version:4},this._mediaObject.port=7),o.type){case"audio":case"video":{this._mediaObject.direction="recvonly",this._mediaObject.rtp=[],this._mediaObject.rtcpFb=[],this._mediaObject.fmtp=[];for(let u of c.codecs){let f={payload:u.payloadType,codec:vC(u),rate:u.clockRate};u.channels>1&&(f.encoding=u.channels),this._mediaObject.rtp.push(f);let h=bC.clone(u.parameters)??{},y=bC.clone(u.rtcpFeedback)??[];if(d){let{opusStereo:S,opusFec:C,opusDtx:O,opusMaxPlaybackRate:K,opusMaxAverageBitrate:z,opusPtime:Q,opusNack:oe,videoGoogleStartBitrate:se,videoGoogleMaxBitrate:we,videoGoogleMinBitrate:me}=d,Y=a.codecs.find(Ze=>Ze.payloadType===u.payloadType);switch(u.mimeType.toLowerCase()){case"audio/opus":case"audio/multiopus":{S!==void 0&&(Y.parameters["sprop-stereo"]=S?1:0,h.stereo=S?1:0),C!==void 0&&(Y.parameters.useinbandfec=C?1:0,h.useinbandfec=C?1:0),O!==void 0&&(Y.parameters.usedtx=O?1:0,h.usedtx=O?1:0),K!==void 0&&(h.maxplaybackrate=K),z!==void 0&&(h.maxaveragebitrate=z),Q!==void 0&&(Y.parameters.ptime=Q,h.ptime=Q),oe||(Y.rtcpFeedback=Y.rtcpFeedback.filter(Ze=>Ze.type!=="nack"||Ze.parameter),y=y.filter(Ze=>Ze.type!=="nack"||Ze.parameter));break}case"video/vp8":case"video/vp9":case"video/h264":case"video/h265":case"video/av1":{se!==void 0&&(h["x-google-start-bitrate"]=se),we!==void 0&&(h["x-google-max-bitrate"]=we),me!==void 0&&(h["x-google-min-bitrate"]=me);break}}}let v={payload:u.payloadType,config:""};for(let S of Object.keys(h))v.config&&(v.config+=";"),v.config+=`${S}=${h[S]}`;v.config&&this._mediaObject.fmtp.push(v);for(let S of y)this._mediaObject.rtcpFb.push({payload:u.payloadType,type:S.type,subtype:S.parameter})}this._mediaObject.payloads=c.codecs.map(u=>u.payloadType).join(" "),this._mediaObject.ext=[];for(let u of c.headerExtensions)(o.ext??[]).some(h=>h.uri===u.uri)&&this._mediaObject.ext.push({uri:u.uri,value:u.id});if(o.extmapAllowMixed==="extmap-allow-mixed"&&(this._mediaObject.extmapAllowMixed="extmap-allow-mixed"),o.simulcast){this._mediaObject.simulcast={dir1:"recv",list1:o.simulcast.list1},this._mediaObject.rids=[];for(let u of o.rids??[])u.direction==="send"&&this._mediaObject.rids.push({id:u.id,direction:"recv"})}else if(o.simulcast_03){this._mediaObject.simulcast_03={value:o.simulcast_03.value.replace(/send/g,"recv")},this._mediaObject.rids=[];for(let u of o.rids??[])u.direction==="send"&&this._mediaObject.rids.push({id:u.id,direction:"recv"})}this._mediaObject.rtcpMux="rtcp-mux",this._mediaObject.rtcpRsize="rtcp-rsize";break}case"application":{typeof o.sctpPort=="number"?(this._mediaObject.payloads="webrtc-datachannel",this._mediaObject.sctpPort=n.port,this._mediaObject.maxMessageSize=n.maxMessageSize):o.sctpmap&&(this._mediaObject.payloads=String(n.port),this._mediaObject.sctpmap={app:"webrtc-datachannel",sctpmapNumber:n.port,maxMessageSize:n.maxMessageSize});break}}}setDtlsRole(e){switch(e){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(e){if(!this._mediaObject.simulcast?.list1)return;let t={};for(let i of e)i.rid&&(t[i.rid]=i);let s=this._mediaObject.simulcast.list1,n=eL.parseSimulcastStreamList(s);for(let i of n)for(let o of i)o.paused=!t[o.scid]?.active;this._mediaObject.simulcast.list1=n.map(i=>i.map(o=>`${o.paused?"~":""}${o.scid}`).join(",")).join(";")}};bo.AnswerMediaSection=ab;var cb=class extends Rf{constructor({iceParameters:e,iceCandidates:t,dtlsParameters:s,sctpParameters:n,plainRtpParameters:i,mid:o,kind:a,offerRtpParameters:c,streamId:d,trackId:u}){switch(super({iceParameters:e,iceCandidates:t,dtlsParameters:s}),this._mediaObject.mid=String(o),this._mediaObject.type=a,i?(this._mediaObject.connection={ip:i.ip,version:i.ipVersion},this._mediaObject.protocol="RTP/AVP",this._mediaObject.port=i.port):(this._mediaObject.connection={ip:"127.0.0.1",version:4},n?this._mediaObject.protocol="UDP/DTLS/SCTP":this._mediaObject.protocol="UDP/TLS/RTP/SAVPF",this._mediaObject.port=7),this._mediaObject.extmapAllowMixed="extmap-allow-mixed",a){case"audio":case"video":{this._mediaObject.direction="sendonly",this._mediaObject.rtp=[],this._mediaObject.rtcpFb=[],this._mediaObject.fmtp=[],this._mediaObject.msid=[{id:d,appdata:u}];for(let v of c.codecs){let S={payload:v.payloadType,codec:vC(v),rate:v.clockRate};v.channels>1&&(S.encoding=v.channels),this._mediaObject.rtp.push(S);let C={payload:v.payloadType,config:""};for(let O of Object.keys(v.parameters??{}))C.config&&(C.config+=";"),C.config+=`${O}=${v.parameters[O]}`;C.config&&this._mediaObject.fmtp.push(C);for(let O of v.rtcpFeedback)this._mediaObject.rtcpFb.push({payload:v.payloadType,type:O.type,subtype:O.parameter})}this._mediaObject.payloads=c.codecs.map(v=>v.payloadType).join(" "),this._mediaObject.ext=[];for(let v of c.headerExtensions)this._mediaObject.ext.push({uri:v.uri,value:v.id});this._mediaObject.rtcpMux="rtcp-mux",this._mediaObject.rtcpRsize="rtcp-rsize";let f=c.encodings[0],h=f.ssrc,y=f.rtx?.ssrc;this._mediaObject.ssrcs=[],this._mediaObject.ssrcGroups=[],h&&c.rtcp.cname&&this._mediaObject.ssrcs.push({id:h,attribute:"cname",value:c.rtcp.cname}),y&&(c.rtcp.cname&&this._mediaObject.ssrcs.push({id:y,attribute:"cname",value:c.rtcp.cname}),h&&this._mediaObject.ssrcGroups.push({semantics:"FID",ssrcs:`${h} ${y}`}));break}case"application":{this._mediaObject.payloads="webrtc-datachannel",this._mediaObject.sctpPort=n.port,this._mediaObject.maxMessageSize=n.maxMessageSize;break}}}setDtlsRole(e){this._mediaObject.setup="actpass"}resume(){this._mediaObject.direction="sendonly"}};bo.OfferMediaSection=cb;function vC(r){let t=new RegExp("^(audio|video)/(.+)","i").exec(r.mimeType);if(!t)throw new TypeError("invalid codec.mimeType");return t[2]}});var Pd=re(T0=>{"use strict";Object.defineProperty(T0,"__esModule",{value:!0});T0.RemoteSdp=void 0;var tL=Si(),rL=Yr(),E0=wC(),sL=ub(),nL=["av1","h264"],C0=new rL.Logger("RemoteSdp"),db=class{_iceParameters;_iceCandidates;_dtlsParameters;_sctpParameters;_plainRtpParameters;_mediaSections=[];_midToIndex=new Map;_firstMid;_sdpObject;constructor({iceParameters:e,iceCandidates:t,dtlsParameters:s,sctpParameters:n,plainRtpParameters:i}){if(this._iceParameters=e,this._iceCandidates=t,this._dtlsParameters=s,this._sctpParameters=n,this._plainRtpParameters=i,this._sdpObject={version:0,origin:{address:"0.0.0.0",ipVer:4,netType:"IN",sessionId:"10000",sessionVersion:0,username:`media-client-v${sL.version}`},name:"-",timing:{start:0,stop:0},media:[]},this._sdpObject.iceOptions="ice2",e?.iceLite&&(this._sdpObject.icelite="ice-lite"),s){this._sdpObject.msidSemantic={semantic:"WMS",token:"*"};let o=this._dtlsParameters.fingerprints.length;this._sdpObject.fingerprint={type:s.fingerprints[o-1].algorithm,hash:s.fingerprints[o-1].value},this._sdpObject.groups=[{type:"BUNDLE",mids:""}]}i&&(this._sdpObject.origin.address=i.ip,this._sdpObject.origin.ipVer=i.ipVersion)}updateIceParameters(e){C0.debug("updateIceParameters() [iceParameters:%o]",e),this._iceParameters=e,this._sdpObject.icelite=e.iceLite?"ice-lite":void 0;for(let t of this._mediaSections)t.setIceParameters(e)}updateDtlsRole(e){C0.debug("updateDtlsRole() [role:%s]",e),this._dtlsParameters.role=e;for(let t of this._mediaSections)t.setDtlsRole(e)}setSessionExtmapAllowMixed(){C0.debug("setSessionExtmapAllowMixed()"),this._sdpObject.extmapAllowMixed="extmap-allow-mixed"}getNextMediaSectionIdx(){for(let e=0;e<this._mediaSections.length;++e){let t=this._mediaSections[e];if(t.closed)return{idx:e,reuseMid:t.mid}}return{idx:this._mediaSections.length}}send({offerMediaObject:e,reuseMid:t,offerRtpParameters:s,answerRtpParameters:n,codecOptions:i}){let o=new E0.AnswerMediaSection({iceParameters:this._iceParameters,iceCandidates:this._iceCandidates,dtlsParameters:this._dtlsParameters,plainRtpParameters:this._plainRtpParameters,offerMediaObject:e,offerRtpParameters:s,answerRtpParameters:n,codecOptions:i}),a=o.getObject();a.rtp.find(d=>nL.includes(d.codec.toLowerCase()))||(a.ext=a.ext?.filter(d=>d.uri!=="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension")),t?this.replaceMediaSection(o,t):this._midToIndex.has(o.mid)?this.replaceMediaSection(o):this.addMediaSection(o)}receive({mid:e,kind:t,offerRtpParameters:s,streamId:n,trackId:i}){this.setSessionExtmapAllowMixed();let o=new E0.OfferMediaSection({iceParameters:this._iceParameters,iceCandidates:this._iceCandidates,dtlsParameters:this._dtlsParameters,plainRtpParameters:this._plainRtpParameters,mid:e,kind:t,offerRtpParameters:s,streamId:n,trackId:i}),a=this._mediaSections.find(c=>c.closed&&c.getObject().type===t);a?this.replaceMediaSection(o,a.mid):this.addMediaSection(o)}pauseMediaSection(e){this.findMediaSection(e).pause()}resumeSendingMediaSection(e){this.findMediaSection(e).resume()}resumeReceivingMediaSection(e){this.findMediaSection(e).resume()}disableMediaSection(e){this.findMediaSection(e).disable()}closeMediaSection(e){let t=this.findMediaSection(e);return e===this._firstMid?(C0.debug("closeMediaSection() | cannot close first media section, disabling it instead [mid:%s]",e),this.disableMediaSection(e),!1):(t.close(),this.regenerateBundleMids(),!0)}muxMediaSectionSimulcast(e,t){let s=this.findMediaSection(e);s.muxSimulcastStreams(t),this.replaceMediaSection(s)}sendSctpAssociation({offerMediaObject:e}){let t=new E0.AnswerMediaSection({iceParameters:this._iceParameters,iceCandidates:this._iceCandidates,dtlsParameters:this._dtlsParameters,sctpParameters:this._sctpParameters,plainRtpParameters:this._plainRtpParameters,offerMediaObject:e});this.addMediaSection(t)}receiveSctpAssociation(){let e=new E0.OfferMediaSection({iceParameters:this._iceParameters,iceCandidates:this._iceCandidates,dtlsParameters:this._dtlsParameters,sctpParameters:this._sctpParameters,plainRtpParameters:this._plainRtpParameters,mid:"datachannel",kind:"application"});this.addMediaSection(e)}getSdp(){return this._sdpObject.origin.sessionVersion++,tL.write(this._sdpObject)}addMediaSection(e){this._firstMid||(this._firstMid=e.mid),this._mediaSections.push(e),this._midToIndex.set(e.mid,this._mediaSections.length-1),this._sdpObject.media.push(e.getObject()),this.regenerateBundleMids()}replaceMediaSection(e,t){if(typeof t=="string"){let s=this._midToIndex.get(t);if(s===void 0)throw new Error(`no media section found for reuseMid '${t}'`);let n=this._mediaSections[s];this._mediaSections[s]=e,this._midToIndex.delete(n.mid),this._midToIndex.set(e.mid,s),this._sdpObject.media[s]=e.getObject(),this.regenerateBundleMids()}else{let s=this._midToIndex.get(e.mid);if(s===void 0)throw new Error(`no media section found with mid '${e.mid}'`);this._mediaSections[s]=e,this._sdpObject.media[s]=e.getObject()}}findMediaSection(e){let t=this._midToIndex.get(e);if(t===void 0)throw new Error(`no media section found with mid '${e}'`);return this._mediaSections[t]}regenerateBundleMids(){this._dtlsParameters&&(this._sdpObject.groups[0].mids=this._mediaSections.filter(e=>!e.closed).map(e=>e.mid).join(" "))}};T0.RemoteSdp=db});var Bd=re(La=>{"use strict";Object.defineProperty(La,"__esModule",{value:!0});La.extractRtpCapabilities=iL;La.extractDtlsParameters=oL;La.getCname=aL;La.applyCodecParameters=cL;La.addHeaderExtension=dL;var SC=Si();function iL({sdpObject:r}){let e=new Map,t=new Map;for(let n of r.media){let i=n.type;switch(i){case"audio":case"video":break;default:continue}for(let o of n.rtp){let a={kind:i,mimeType:`${i}/${o.codec}`,preferredPayloadType:o.payload,clockRate:o.rate,channels:o.encoding,parameters:{},rtcpFeedback:[]};e.set(a.preferredPayloadType,a)}for(let o of n.fmtp??[]){let a=SC.parseParams(o.config),c=e.get(o.payload);c&&(a?.hasOwnProperty("profile-level-id")&&(a["profile-level-id"]=String(a["profile-level-id"])),c.parameters=a)}for(let o of n.rtcpFb??[]){let a={type:o.type,parameter:o.subtype};if(a.parameter||delete a.parameter,o.payload!=="*"){let c=e.get(Number(o.payload));if(!c)continue;c.rtcpFeedback.push(a)}else for(let c of e.values())c.kind===i&&!/.+\/rtx$/i.test(c.mimeType)&&c.rtcpFeedback.push(a)}for(let o of n.ext??[]){if(o["encrypt-uri"])continue;let a={kind:i,uri:o.uri,preferredId:o.value};t.set(a.preferredId,a)}}return{codecs:Array.from(e.values()),headerExtensions:Array.from(t.values())}}function oL({sdpObject:r}){let e=r.setup,t=r.fingerprint;if(!e||!t){let i=(r.media??[]).find(o=>o.port!==0);i&&(e=e??i.setup,t=t??i.fingerprint)}if(e){if(!t)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 s;switch(e){case"active":{s="client";break}case"passive":{s="server";break}case"actpass":{s="auto";break}}return{role:s,fingerprints:[{algorithm:t.type,value:t.hash}]}}function aL({offerMediaObject:r}){let e=(r.ssrcs??[]).find(t=>t.attribute==="cname");return e?e.value:""}function cL({offerRtpParameters:r,answerMediaObject:e}){for(let t of r.codecs){let s=t.mimeType.toLowerCase();if(s!=="audio/opus"||!(e.rtp??[]).find(a=>a.payload===t.payloadType))continue;e.fmtp=e.fmtp??[];let i=e.fmtp.find(a=>a.payload===t.payloadType);i||(i={payload:t.payloadType,config:""},e.fmtp.push(i));let o=SC.parseParams(i.config);if(s==="audio/opus"){let a=t.parameters?.["sprop-stereo"];a!==void 0&&(o.stereo=Number(a)?1:0)}i.config="";for(let a of Object.keys(o))i.config&&(i.config+=";"),i.config+=`${a}=${o[a]}`}}function dL({offerMediaObject:r,headerExtensionUri:e,headerExtensionId:t}){r.ext||(r.ext=[]),r.ext.push({uri:e,value:t})}});var Nd=re(A0=>{"use strict";Object.defineProperty(A0,"__esModule",{value:!0});A0.getRtpEncodings=uL;A0.addLegacySimulcast=fL;function uL({offerMediaObject:r,codecs:e}){let t=new Set;for(let i of r.ssrcs??[]){let o=i.id;o&&t.add(o)}if(t.size===0)throw new Error("no a=ssrc lines found");let s=new Map;for(let i of r.ssrcGroups??[]){if(i.semantics!=="FID")continue;let o=i.ssrcs.split(/\s+/),a=Number(o[0]),c=Number(o[1]);t.has(a)&&(t.delete(a),t.delete(c),s.set(a,c))}for(let i of t)s.set(i,void 0);let n=[];for(let[i,o]of s){let a={ssrc:i};o&&e.length>1&&(a.rtx={ssrc:o}),n.push(a)}return n}function fL({offerMediaObject:r,numStreams:e}){if(e<=1)throw new TypeError("numStreams must be greater than 1");let t=(r.ssrcs??[]).find(f=>f.attribute==="msid");if(!t)throw new Error("a=ssrc line with msid information not found");let[s,n]=t.value.split(" "),i=Number(t.id),o;(r.ssrcGroups??[]).some(f=>{if(f.semantics!=="FID")return!1;let h=f.ssrcs.split(/\s+/);return Number(h[0])===i?(o=Number(h[1]),!0):!1});let a=(r.ssrcs??[]).find(f=>f.attribute==="cname");if(!a)throw new Error("a=ssrc line with cname information not found");let c=a.value,d=[],u=[];for(let f=0;f<e;++f)d.push(i+f),o&&u.push(o+f);r.ssrcGroups=[],r.ssrcs=[],r.ssrcGroups.push({semantics:"SIM",ssrcs:d.join(" ")});for(let f of d)r.ssrcs.push({id:f,attribute:"cname",value:c}),r.ssrcs.push({id:f,attribute:"msid",value:`${s} ${n}`});for(let f=0;f<u.length;++f){let h=d[f],y=u[f];r.ssrcs.push({id:y,attribute:"cname",value:c}),r.ssrcs.push({id:y,attribute:"msid",value:`${s} ${n}`}),r.ssrcGroups.push({semantics:"FID",ssrcs:`${h} ${y}`})}}});var Od=re(kf=>{"use strict";Object.defineProperty(kf,"__esModule",{value:!0});kf.addNackSupportForOpus=lL;kf.addHeaderExtensionSupport=hL;kf.getMsidStreamIdAndTrackId=pL;function lL(r){for(let e of r.codecs??[])(e.mimeType.toLowerCase()==="audio/opus"||e.mimeType.toLowerCase()==="audio/multiopus")&&!e.rtcpFeedback?.some(t=>t.type==="nack"&&!t.parameter)&&(e.rtcpFeedback||(e.rtcpFeedback=[]),e.rtcpFeedback.push({type:"nack"}))}function hL(r,e){let t,s=r.headerExtensions?.find(i=>i.uri===e.uri);if(s){if(s.kind===e.kind)return;t=s.preferredId}if(r.headerExtensions||(r.headerExtensions=[]),t===void 0){t=1;let i=new Set(r.headerExtensions.map(o=>o.preferredId));for(;i.has(t);)++t}let n={kind:e.kind,uri:e.uri,preferredId:t,preferredEncrypt:!1,direction:e.direction};r.headerExtensions.push(n)}function pL(r){if(!r||typeof r!="string")return{msidStreamId:void 0,msidTrackId:void 0};let[e,t]=r.trim().split(/\s+/);return e?{msidStreamId:e,msidTrackId:t}:{msidStreamId:void 0,msidTrackId:void 0}}});var TC=re(I0=>{"use strict";Object.defineProperty(I0,"__esModule",{value:!0});I0.Chrome111=void 0;var Nn=Si(),mL=as(),gL=Yr(),Pf=Rn(),yL=Ls(),xL=Oa(),bL=Pd(),Bf=Bd(),_C=Nd(),fb=Od(),et=new gL.Logger("Chrome111"),EC="Chrome111",CC={OS:65535,MIS:65535},lb=class r extends mL.EnhancedEventEmitter{_closed=!1;_direction;_remoteSdp;_getSendExtendedRtpCapabilities;_forcedLocalDtlsRole;_pc;_mapMidTransceiver=new Map;_sendStream=new MediaStream;_hasDataChannelMediaSection=!1;_nextSendSctpStreamId=0;_transportReady=!1;static createFactory(){return{name:EC,factory:e=>new r(e),getNativeRtpCapabilities:async({direction:e})=>{et.debug("getNativeRtpCapabilities() [direction:%o]",e);let t=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{t.addTransceiver("audio",{direction:e}),t.addTransceiver("video",{direction:e,sendEncodings:[{scalabilityMode:"L3T3"}]});let s=await t.createOffer();try{t.close()}catch{}t=void 0;let n=Nn.parse(s.sdp);return r.getLocalRtpCapabilities(n)}catch(s){try{t?.close()}catch{}throw t=void 0,s}},getNativeSctpCapabilities:async()=>(et.debug("getNativeSctpCapabilities()"),{numStreams:CC})}}static getLocalRtpCapabilities(e,t=[]){let s=Bf.extractRtpCapabilities({sdpObject:e});Pf.validateAndNormalizeRtpCapabilities(s),fb.addNackSupportForOpus(s);for(let n of t)fb.addHeaderExtensionSupport(s,n);return s}constructor({direction:e,iceParameters:t,iceCandidates:s,dtlsParameters:n,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:c,getSendExtendedRtpCapabilities:d}){super(),et.debug("constructor()"),this._direction=e,this._remoteSdp=new bL.RemoteSdp({iceParameters:t,iceCandidates:s,dtlsParameters:n,sctpParameters:i}),this._getSendExtendedRtpCapabilities=d,n.role&&n.role!=="auto"&&(this._forcedLocalDtlsRole=n.role==="server"?"client":"server"),this._pc=new RTCPeerConnection({iceServers:o??[],iceTransportPolicy:a??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...c}),this._pc.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.addEventListener("icecandidateerror",this.onIceCandidateError),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",this.onConnectionStateChange):(et.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return EC}close(){if(et.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(e){this.assertNotClosed(),et.debug("updateIceServers()");let t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),et.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),!!this._transportReady)if(this._direction==="send"){let t=await this._pc.createOffer({iceRestart:!0});et.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",t),await this._pc.setLocalDescription(t);let s={type:"answer",sdp:this._remoteSdp.getSdp()};et.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}else{let t={type:"offer",sdp:this._remoteSdp.getSdp()};et.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let s=await this._pc.createAnswer();et.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",s),await this._pc.setLocalDescription(s)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,streamId:t,encodings:s,codecOptions:n,headerExtensionOptions:i,codec:o,onRtpSender:a}){if(this.assertNotClosed(),this.assertSendDirection(),et.debug("send() [kind:%s, track.id:%s, streamId:%s]",e.kind,e.id,t),s&&s.length>1){let Q=1;for(let oe of s){let se=oe.scalabilityMode?(0,xL.parse)(oe.scalabilityMode).temporalLayers:3;se>Q&&(Q=se)}s.forEach((oe,se)=>{oe.rid=`r${se}`,oe.scalabilityMode=`L1T${Q}`})}let c=this._remoteSdp.getNextMediaSectionIdx(),d=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:s});a&&a(d.sender);let u=await this._pc.createOffer(),f=Nn.parse(u.sdp);f.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();let h=[];h.push({uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",kind:e.kind,direction:"sendonly"});let y=r.getLocalRtpCapabilities(f,h),v=this._getSendExtendedRtpCapabilities(y),S=Pf.getSendingRtpParameters(e.kind,v);S.codecs=Pf.reduceCodecs(S.codecs,o);let C=Pf.getSendingRemoteRtpParameters(e.kind,v);if(C.codecs=Pf.reduceCodecs(C.codecs,o),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:f}),i?.absCaptureTime){let Q=f.media[c.idx];Bf.addHeaderExtension({offerMediaObject:Q,headerExtensionUri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",headerExtensionId:C.headerExtensions.find(oe=>oe.uri==="http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time").id}),u={type:"offer",sdp:Nn.write(f)}}et.debug("send() | calling pc.setLocalDescription() [offer:%o]",u),await this._pc.setLocalDescription(u);let O=d.mid;S.mid=O,f=Nn.parse(this._pc.localDescription.sdp);let K=f.media[c.idx];if(S.rtcp.cname=Bf.getCname({offerMediaObject:K}),S.msid=`${t??this._sendStream.id} ${e.id}`,!s)S.encodings=_C.getRtpEncodings({offerMediaObject:K,codecs:S.codecs});else if(s.length===1){let Q=_C.getRtpEncodings({offerMediaObject:K,codecs:S.codecs});Object.assign(Q[0],s[0]),S.encodings=Q}else S.encodings=s;this._remoteSdp.send({offerMediaObject:K,reuseMid:c.reuseMid,offerRtpParameters:S,answerRtpParameters:C,codecOptions:n});let z={type:"answer",sdp:this._remoteSdp.getSdp()};return et.debug("send() | calling pc.setRemoteDescription() [answer:%o]",z),await this._pc.setRemoteDescription(z),this._mapMidTransceiver.set(O,d),{localId:O,rtpParameters:S,rtpSender:d.sender}}async stopSending(e){if(this.assertSendDirection(),et.debug("stopSending() [localId:%s]",e),this._closed)return;let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");if(t.sender.replaceTrack(null),this._pc.removeTrack(t.sender),this._remoteSdp.closeMediaSection(t.mid))try{t.stop()}catch{}let n=await this._pc.createOffer();et.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);let i={type:"answer",sdp:this._remoteSdp.getSdp()};et.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),et.debug("pauseSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);let s=await this._pc.createOffer();et.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",s),await this._pc.setLocalDescription(s);let n={type:"answer",sdp:this._remoteSdp.getSdp()};et.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),et.debug("resumeSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(this._remoteSdp.resumeSendingMediaSection(e),!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly";let s=await this._pc.createOffer();et.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",s),await this._pc.setLocalDescription(s);let n={type:"answer",sdp:this._remoteSdp.getSdp()};et.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?et.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):et.debug("replaceTrack() [localId:%s, no track]",e);let s=this._mapMidTransceiver.get(e);if(!s)throw new Error("associated RTCRtpTransceiver not found");await s.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),this.assertSendDirection(),et.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);let s=this._mapMidTransceiver.get(e);if(!s)throw new Error("associated RTCRtpTransceiver not found");let n=s.sender.getParameters();n.encodings.forEach((a,c)=>{c<=t?a.active=!0:a.active=!1}),await s.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);let i=await this._pc.createOffer();et.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);let o={type:"answer",sdp:this._remoteSdp.getSdp()};et.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),et.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);let s=this._mapMidTransceiver.get(e);if(!s)throw new Error("associated RTCRtpTransceiver not found");let n=s.sender.getParameters();n.encodings.forEach((a,c)=>{n.encodings[c]={...a,...t}}),await s.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);let i=await this._pc.createOffer();et.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);let o={type:"answer",sdp:this._remoteSdp.getSdp()};et.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({sctpStreamParameters:e}){this.assertNotClosed(),this.assertSendDirection();let t={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e.ordered,maxPacketLifeTime:e.maxPacketLifeTime,maxRetransmits:e.maxRetransmits,protocol:e.protocol};et.debug("sendDataChannel() [options:%o]",t);let s=this._pc.createDataChannel(e.label,t);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%CC.MIS,!this._hasDataChannelMediaSection){let i=await this._pc.createOffer(),o=Nn.parse(i.sdp),a=o.media.find(d=>d.type==="application");this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),et.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i),this._remoteSdp.sendSctpAssociation({offerMediaObject:a});let c={type:"answer",sdp:this._remoteSdp.getSdp()};et.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",c),await this._pc.setRemoteDescription(c),this._hasDataChannelMediaSection=!0}let n={streamId:t.id,ordered:t.ordered,maxPacketLifeTime:t.maxPacketLifeTime,maxRetransmits:t.maxRetransmits};return{dataChannel:s,sctpStreamParameters:n}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();let t=[],s=new Map;for(let a of e){let{trackId:c,kind:d,rtpParameters:u,streamId:f}=a;et.debug("receive() [trackId:%s, kind:%s]",c,d);let h=u.mid??String(this._mapMidTransceiver.size);s.set(c,h);let{msidStreamId:y}=fb.getMsidStreamIdAndTrackId(u.msid);this._remoteSdp.receive({mid:h,kind:d,offerRtpParameters:u,streamId:f??y??u.rtcp?.cname??"-",trackId:c})}let n={type:"offer",sdp:this._remoteSdp.getSdp()};et.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",n),await this._pc.setRemoteDescription(n);for(let a of e){let{trackId:c,onRtpReceiver:d}=a;if(d){let u=s.get(c),f=this._pc.getTransceivers().find(h=>h.mid===u);if(!f)throw new Error("transceiver not found");d(f.receiver)}}let i=await this._pc.createAnswer(),o=Nn.parse(i.sdp);for(let a of e){let{trackId:c,rtpParameters:d}=a,u=s.get(c),f=o.media.find(h=>String(h.mid)===u);Bf.applyCodecParameters({offerRtpParameters:d,answerMediaObject:f})}i={type:"answer",sdp:Nn.write(o)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),et.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(let a of e){let{trackId:c}=a,d=s.get(c),u=this._pc.getTransceivers().find(f=>f.mid===d);if(u)this._mapMidTransceiver.set(d,u),t.push({localId:d,track:u.receiver.track,rtpReceiver:u.receiver});else throw new Error("new RTCRtpTransceiver not found")}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(let n of e){et.debug("stopReceiving() [localId:%s]",n);let i=this._mapMidTransceiver.get(n);if(!i)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(i.mid)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};et.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let s=await this._pc.createAnswer();et.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",s),await this._pc.setLocalDescription(s);for(let n of e)this._mapMidTransceiver.delete(n)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(let n of e){et.debug("pauseReceiving() [localId:%s]",n);let i=this._mapMidTransceiver.get(n);if(!i)throw new Error("associated RTCRtpTransceiver not found");i.direction="inactive",this._remoteSdp.pauseMediaSection(n)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};et.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let s=await this._pc.createAnswer();et.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",s),await this._pc.setLocalDescription(s)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(let n of e){et.debug("resumeReceiving() [localId:%s]",n);let i=this._mapMidTransceiver.get(n);if(!i)throw new Error("associated RTCRtpTransceiver not found");i.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(n)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};et.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let s=await this._pc.createAnswer();et.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",s),await this._pc.setLocalDescription(s)}async getReceiverStats(e){this.assertNotClosed(),this.assertRecvDirection();let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({maxMessageSize:e,sctpStreamParameters:t,label:s,protocol:n}){this.assertNotClosed(),this.assertRecvDirection();let{streamId:i,ordered:o,maxPacketLifeTime:a,maxRetransmits:c}=t,d={negotiated:!0,id:i,ordered:o,maxPacketLifeTime:a,maxRetransmits:c,protocol:n};et.debug("receiveDataChannel() [options:%o]",d);let u=this._pc.createDataChannel(s,d);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();let f={type:"offer",sdp:this._remoteSdp.getSdp()};et.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",f),await this._pc.setRemoteDescription(f);let h=await this._pc.createAnswer(),y=Nn.parse(h.sdp),v=y.media.find(S=>S.type==="application");v.maxMessageSize=e,this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:y}),h={type:"answer",sdp:Nn.write(y)},et.debug("receiveDataChannel() | calling pc.setLocalDescription() [answer:%o]",h),await this._pc.setLocalDescription(h),this._hasDataChannelMediaSection=!0}return{dataChannel:u}}getDataChannelMaxMessageSize(){return this._pc.sctp?.maxMessageSize}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=Nn.parse(this._pc.localDescription.sdp));let s=Bf.extractDtlsParameters({sdpObject:t});s.role=e,this._remoteSdp.updateDtlsRole(e==="client"?"server":"client"),await new Promise((n,i)=>{this.safeEmit("@connect",{dtlsParameters:s},n,i)}),this._transportReady=!0}onIceGatheringStateChange=()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)};onIceCandidateError=e=>{this.emit("@icecandidateerror",e)};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 yL.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')}};I0.Chrome111=lb});var RC=re(R0=>{"use strict";Object.defineProperty(R0,"__esModule",{value:!0});R0.Chrome74=void 0;var Ds=Si(),vL=Yr(),wL=as(),Nf=Rn(),SL=Ls(),_L=Oa(),EL=Pd(),Of=Bd(),hb=Nd(),pb=Od(),Je=new vL.Logger("Chrome74"),AC="Chrome74",IC={OS:1024,MIS:1024},mb=class r extends wL.EnhancedEventEmitter{_closed=!1;_direction;_remoteSdp;_getSendExtendedRtpCapabilities;_forcedLocalDtlsRole;_pc;_mapMidTransceiver=new Map;_sendStream=new MediaStream;_hasDataChannelMediaSection=!1;_nextSendSctpStreamId=0;_transportReady=!1;static createFactory(){return{name:AC,factory:e=>new r(e),getNativeRtpCapabilities:async({direction:e})=>{Je.debug("getNativeRtpCapabilities() [direction:%o]",e);let t=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{t.addTransceiver("audio",{direction:e}),t.addTransceiver("video",{direction:e});let s=await t.createOffer();try{t.close()}catch{}t=void 0;let n=Ds.parse(s.sdp);return r.getLocalRtpCapabilities(n)}catch(s){try{t?.close()}catch{}throw t=void 0,s}},getNativeSctpCapabilities:async()=>(Je.debug("getNativeSctpCapabilities()"),{numStreams:IC})}}static getLocalRtpCapabilities(e,t=[]){let s=Of.extractRtpCapabilities({sdpObject:e});Nf.validateAndNormalizeRtpCapabilities(s),pb.addNackSupportForOpus(s);for(let n of t)pb.addHeaderExtensionSupport(s,n);return s}constructor({direction:e,iceParameters:t,iceCandidates:s,dtlsParameters:n,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:c,getSendExtendedRtpCapabilities:d}){super(),Je.debug("constructor()"),this._direction=e,this._remoteSdp=new EL.RemoteSdp({iceParameters:t,iceCandidates:s,dtlsParameters:n,sctpParameters:i}),this._getSendExtendedRtpCapabilities=d,n.role&&n.role!=="auto"&&(this._forcedLocalDtlsRole=n.role==="server"?"client":"server"),this._pc=new RTCPeerConnection({iceServers:o??[],iceTransportPolicy:a??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...c}),this._pc.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.addEventListener("icecandidateerror",this.onIceCandidateError),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",this.onConnectionStateChange):(Je.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return AC}close(){if(Je.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(e){this.assertNotClosed(),Je.debug("updateIceServers()");let t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),Je.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),!!this._transportReady)if(this._direction==="send"){let t=await this._pc.createOffer({iceRestart:!0});Je.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",t),await this._pc.setLocalDescription(t);let s={type:"answer",sdp:this._remoteSdp.getSdp()};Je.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}else{let t={type:"offer",sdp:this._remoteSdp.getSdp()};Je.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let s=await this._pc.createAnswer();Je.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",s),await this._pc.setLocalDescription(s)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,streamId:t,encodings:s,codecOptions:n,headerExtensionOptions:i,codec:o}){this.assertNotClosed(),this.assertSendDirection(),Je.debug("send() [kind:%s, track.id:%s, streamId:%s]",e.kind,e.id,t),s&&s.length>1&&s.forEach((oe,se)=>{oe.rid=`r${se}`});let a=this._remoteSdp.getNextMediaSectionIdx(),c=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:s}),d=await this._pc.createOffer(),u=Ds.parse(d.sdp);u.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();let f=[];f.push({uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",kind:e.kind,direction:"sendonly"});let h=r.getLocalRtpCapabilities(u,f),y=this._getSendExtendedRtpCapabilities(h),v=Nf.getSendingRtpParameters(e.kind,y);v.codecs=Nf.reduceCodecs(v.codecs,o);let S=Nf.getSendingRemoteRtpParameters(e.kind,y);S.codecs=Nf.reduceCodecs(S.codecs,o),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:u});let C=!1,O=(0,_L.parse)((s??[{}])[0].scalabilityMode),K;s?.length===1&&O.spatialLayers>1&&v.codecs[0].mimeType.toLowerCase()==="video/vp9"&&(Je.debug("send() | enabling legacy simulcast for VP9 SVC"),C=!0,u=Ds.parse(d.sdp),K=u.media[a.idx],hb.addLegacySimulcast({offerMediaObject:K,numStreams:O.spatialLayers}),d={type:"offer",sdp:Ds.write(u)}),Je.debug("send() | calling pc.setLocalDescription() [offer:%o]",d),i?.absCaptureTime&&(K=u.media[a.idx],Of.addHeaderExtension({offerMediaObject:K,headerExtensionUri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",headerExtensionId:S.headerExtensions.find(oe=>oe.uri==="http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time").id}),d={type:"offer",sdp:Ds.write(u)}),await this._pc.setLocalDescription(d);let z=c.mid;if(v.mid=z,u=Ds.parse(this._pc.localDescription.sdp),K=u.media[a.idx],v.rtcp.cname=Of.getCname({offerMediaObject:K}),v.msid=`${t??this._sendStream.id} ${e.id}`,!s)v.encodings=hb.getRtpEncodings({offerMediaObject:K,codecs:v.codecs});else if(s.length===1){let oe=hb.getRtpEncodings({offerMediaObject:K,codecs:v.codecs});Object.assign(oe[0],s[0]),C&&(oe=[oe[0]]),v.encodings=oe}else v.encodings=s;if(v.encodings.length>1&&(v.codecs[0].mimeType.toLowerCase()==="video/vp8"||v.codecs[0].mimeType.toLowerCase()==="video/h264"))for(let oe of v.encodings)oe.scalabilityMode?oe.scalabilityMode=`L1T${O.temporalLayers}`:oe.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:K,reuseMid:a.reuseMid,offerRtpParameters:v,answerRtpParameters:S,codecOptions:n});let Q={type:"answer",sdp:this._remoteSdp.getSdp()};return Je.debug("send() | calling pc.setRemoteDescription() [answer:%o]",Q),await this._pc.setRemoteDescription(Q),this._mapMidTransceiver.set(z,c),{localId:z,rtpParameters:v,rtpSender:c.sender}}async stopSending(e){if(this.assertSendDirection(),Je.debug("stopSending() [localId:%s]",e),this._closed)return;let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");if(t.sender.replaceTrack(null),this._pc.removeTrack(t.sender),this._remoteSdp.closeMediaSection(t.mid))try{t.stop()}catch{}let n=await this._pc.createOffer();Je.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);let i={type:"answer",sdp:this._remoteSdp.getSdp()};Je.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),Je.debug("pauseSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);let s=await this._pc.createOffer();Je.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",s),await this._pc.setLocalDescription(s);let n={type:"answer",sdp:this._remoteSdp.getSdp()};Je.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),Je.debug("resumeSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(this._remoteSdp.resumeSendingMediaSection(e),!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly";let s=await this._pc.createOffer();Je.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",s),await this._pc.setLocalDescription(s);let n={type:"answer",sdp:this._remoteSdp.getSdp()};Je.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?Je.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):Je.debug("replaceTrack() [localId:%s, no track]",e);let s=this._mapMidTransceiver.get(e);if(!s)throw new Error("associated RTCRtpTransceiver not found");await s.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),this.assertSendDirection(),Je.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);let s=this._mapMidTransceiver.get(e);if(!s)throw new Error("associated RTCRtpTransceiver not found");let n=s.sender.getParameters();n.encodings.forEach((a,c)=>{c<=t?a.active=!0:a.active=!1}),await s.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);let i=await this._pc.createOffer();Je.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);let o={type:"answer",sdp:this._remoteSdp.getSdp()};Je.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),Je.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);let s=this._mapMidTransceiver.get(e);if(!s)throw new Error("associated RTCRtpTransceiver not found");let n=s.sender.getParameters();n.encodings.forEach((a,c)=>{n.encodings[c]={...a,...t}}),await s.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);let i=await this._pc.createOffer();Je.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);let o={type:"answer",sdp:this._remoteSdp.getSdp()};Je.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({sctpStreamParameters:e}){this.assertNotClosed(),this.assertSendDirection();let t={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e.ordered,maxPacketLifeTime:e.maxPacketLifeTime,maxRetransmits:e.maxRetransmits,protocol:e.protocol};Je.debug("sendDataChannel() [options:%o]",t);let s=this._pc.createDataChannel(e.label,t);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%IC.MIS,!this._hasDataChannelMediaSection){let i=await this._pc.createOffer(),o=Ds.parse(i.sdp),a=o.media.find(d=>d.type==="application");this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),Je.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i),this._remoteSdp.sendSctpAssociation({offerMediaObject:a});let c={type:"answer",sdp:this._remoteSdp.getSdp()};Je.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",c),await this._pc.setRemoteDescription(c),this._hasDataChannelMediaSection=!0}let n={streamId:t.id,ordered:t.ordered,maxPacketLifeTime:t.maxPacketLifeTime,maxRetransmits:t.maxRetransmits};return{dataChannel:s,sctpStreamParameters:n}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();let t=[],s=new Map;for(let a of e){let{trackId:c,kind:d,rtpParameters:u,streamId:f}=a;Je.debug("receive() [trackId:%s, kind:%s]",c,d);let h=u.mid??String(this._mapMidTransceiver.size);s.set(c,h);let{msidStreamId:y}=pb.getMsidStreamIdAndTrackId(u.msid);this._remoteSdp.receive({mid:h,kind:d,offerRtpParameters:u,streamId:f??y??u.rtcp?.cname??"-",trackId:c})}let n={type:"offer",sdp:this._remoteSdp.getSdp()};Je.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",n),await this._pc.setRemoteDescription(n);let i=await this._pc.createAnswer(),o=Ds.parse(i.sdp);for(let a of e){let{trackId:c,rtpParameters:d}=a,u=s.get(c),f=o.media.find(h=>String(h.mid)===u);Of.applyCodecParameters({offerRtpParameters:d,answerMediaObject:f})}i={type:"answer",sdp:Ds.write(o)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),Je.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(let a of e){let{trackId:c}=a,d=s.get(c),u=this._pc.getTransceivers().find(f=>f.mid===d);if(u)this._mapMidTransceiver.set(d,u),t.push({localId:d,track:u.receiver.track,rtpReceiver:u.receiver});else throw new Error("new RTCRtpTransceiver not found")}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(let n of e){Je.debug("stopReceiving() [localId:%s]",n);let i=this._mapMidTransceiver.get(n);if(!i)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(i.mid)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};Je.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let s=await this._pc.createAnswer();Je.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",s),await this._pc.setLocalDescription(s);for(let n of e)this._mapMidTransceiver.delete(n)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(let n of e){Je.debug("pauseReceiving() [localId:%s]",n);let i=this._mapMidTransceiver.get(n);if(!i)throw new Error("associated RTCRtpTransceiver not found");i.direction="inactive",this._remoteSdp.pauseMediaSection(n)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};Je.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let s=await this._pc.createAnswer();Je.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",s),await this._pc.setLocalDescription(s)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(let n of e){Je.debug("resumeReceiving() [localId:%s]",n);let i=this._mapMidTransceiver.get(n);if(!i)throw new Error("associated RTCRtpTransceiver not found");i.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(n)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};Je.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let s=await this._pc.createAnswer();Je.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",s),await this._pc.setLocalDescription(s)}async getReceiverStats(e){this.assertNotClosed(),this.assertRecvDirection();let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({maxMessageSize:e,sctpStreamParameters:t,label:s,protocol:n}){this.assertNotClosed(),this.assertRecvDirection();let{streamId:i,ordered:o,maxPacketLifeTime:a,maxRetransmits:c}=t,d={negotiated:!0,id:i,ordered:o,maxPacketLifeTime:a,maxRetransmits:c,protocol:n};Je.debug("receiveDataChannel() [options:%o]",d);let u=this._pc.createDataChannel(s,d);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();let f={type:"offer",sdp:this._remoteSdp.getSdp()};Je.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",f),await this._pc.setRemoteDescription(f);let h=await this._pc.createAnswer(),y=Ds.parse(h.sdp),v=y.media.find(S=>S.type==="application");v.maxMessageSize=e,this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:y}),h={type:"answer",sdp:Ds.write(y)},Je.debug("receiveDataChannel() | calling pc.setLocalDescription() [answer:%o]",h),await this._pc.setLocalDescription(h),this._hasDataChannelMediaSection=!0}return{dataChannel:u}}getDataChannelMaxMessageSize(){return this._pc.sctp?.maxMessageSize}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=Ds.parse(this._pc.localDescription.sdp));let s=Of.extractDtlsParameters({sdpObject:t});s.role=e,this._remoteSdp.updateDtlsRole(e==="client"?"server":"client"),await new Promise((n,i)=>{this.safeEmit("@connect",{dtlsParameters:s},n,i)}),this._transportReady=!0}onIceGatheringStateChange=()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)};onIceCandidateError=e=>{this.emit("@icecandidateerror",e)};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 SL.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')}};R0.Chrome74=mb});var OC=re(P0=>{"use strict";Object.defineProperty(P0,"__esModule",{value:!0});P0.Firefox120=void 0;var _i=Si(),CL=as(),TL=Yr(),kC=Ls(),Lf=Rn(),AL=Oa(),IL=Pd(),k0=Bd(),PC=Nd(),RL=Od(),tt=new TL.Logger("Firefox120"),BC="Firefox120",NC={OS:16,MIS:2048},gb=class r extends CL.EnhancedEventEmitter{_closed=!1;_direction;_remoteSdp;_getSendExtendedRtpCapabilities;_pc;_mapMidTransceiver=new Map;_sendStream=new MediaStream;_hasDataChannelMediaSection=!1;_nextSendSctpStreamId=0;_transportReady=!1;static createFactory(){return{name:BC,factory:e=>new r(e),getNativeRtpCapabilities:async({direction:e})=>{tt.debug("getNativeRtpCapabilities() [direction:%o]",e);let t=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"}),s=document.createElement("canvas");s.getContext("2d");let i=s.captureStream().getVideoTracks()[0];try{t.addTransceiver("audio",{direction:e}),t.addTransceiver(i,{direction:e,sendEncodings:[{rid:"r0",maxBitrate:1e5},{rid:"r1",maxBitrate:5e5}]});let o=await t.createOffer();try{s.remove()}catch{}try{i.stop()}catch{}try{t.close()}catch{}t=void 0;let a=_i.parse(o.sdp);return r.getLocalRtpCapabilities(a)}catch(o){try{s.remove()}catch{}try{i.stop()}catch{}try{t?.close()}catch{}throw t=void 0,o}},getNativeSctpCapabilities:async()=>(tt.debug("getNativeSctpCapabilities()"),{numStreams:NC})}}static getLocalRtpCapabilities(e){let t=k0.extractRtpCapabilities({sdpObject:e});return Lf.validateAndNormalizeRtpCapabilities(t),t}constructor({direction:e,iceParameters:t,iceCandidates:s,dtlsParameters:n,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:c,getSendExtendedRtpCapabilities:d}){super(),tt.debug("constructor()"),this._direction=e,this._remoteSdp=new IL.RemoteSdp({iceParameters:t,iceCandidates:s,dtlsParameters:n,sctpParameters:i}),this._getSendExtendedRtpCapabilities=d,this._pc=new RTCPeerConnection({iceServers:o??[],iceTransportPolicy:a??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...c}),this._pc.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.addEventListener("icecandidateerror",this.onIceCandidateError),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",this.onConnectionStateChange):(tt.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return BC}close(){if(tt.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(e){throw this.assertNotClosed(),new kC.UnsupportedError("not supported")}async restartIce(e){if(this.assertNotClosed(),tt.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),!!this._transportReady)if(this._direction==="send"){let t=await this._pc.createOffer({iceRestart:!0});tt.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",t),await this._pc.setLocalDescription(t);let s={type:"answer",sdp:this._remoteSdp.getSdp()};tt.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}else{let t={type:"offer",sdp:this._remoteSdp.getSdp()};tt.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let s=await this._pc.createAnswer();tt.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",s),await this._pc.setLocalDescription(s)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,streamId:t,encodings:s,codecOptions:n,codec:i,onRtpSender:o}){this.assertNotClosed(),this.assertSendDirection(),tt.debug("send() [kind:%s, track.id:%s, streamId:%s]",e.kind,e.id,t),s&&s.length>1&&s.forEach((K,z)=>{K.rid=`r${z}`});let a=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:s});o&&o(a.sender);let c=await this._pc.createOffer(),d=_i.parse(c.sdp);d.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();let u=r.getLocalRtpCapabilities(d),f=this._getSendExtendedRtpCapabilities(u),h=Lf.getSendingRtpParameters(e.kind,f);h.codecs=Lf.reduceCodecs(h.codecs,i);let y=Lf.getSendingRemoteRtpParameters(e.kind,f);y.codecs=Lf.reduceCodecs(y.codecs,i),this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:d});let v=(0,AL.parse)((s??[{}])[0].scalabilityMode);tt.debug("send() | calling pc.setLocalDescription() [offer:%o]",c),await this._pc.setLocalDescription(c);let S=a.mid;h.mid=S,d=_i.parse(this._pc.localDescription.sdp);let C=d.media[d.media.length-1];if(h.rtcp.cname=k0.getCname({offerMediaObject:C}),h.msid=`${t??this._sendStream.id} ${e.id}`,!s)h.encodings=PC.getRtpEncodings({offerMediaObject:C,codecs:h.codecs});else if(s.length===1){let K=PC.getRtpEncodings({offerMediaObject:C,codecs:h.codecs});Object.assign(K[0],s[0]),h.encodings=K}else h.encodings=s;if(h.encodings.length>1&&(h.codecs[0].mimeType.toLowerCase()==="video/vp8"||h.codecs[0].mimeType.toLowerCase()==="video/h264"))for(let K of h.encodings)K.scalabilityMode?K.scalabilityMode=`L1T${v.temporalLayers}`:K.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:C,offerRtpParameters:h,answerRtpParameters:y,codecOptions:n});let O={type:"answer",sdp:this._remoteSdp.getSdp()};return tt.debug("send() | calling pc.setRemoteDescription() [answer:%o]",O),await this._pc.setRemoteDescription(O),this._mapMidTransceiver.set(S,a),{localId:S,rtpParameters:h,rtpSender:a.sender}}async stopSending(e){if(this.assertSendDirection(),tt.debug("stopSending() [localId:%s]",e),this._closed)return;let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated transceiver not found");t.sender.replaceTrack(null),this._pc.removeTrack(t.sender),this._remoteSdp.disableMediaSection(t.mid);let s=await this._pc.createOffer();tt.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",s),await this._pc.setLocalDescription(s);let n={type:"answer",sdp:this._remoteSdp.getSdp()};tt.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),tt.debug("pauseSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);let s=await this._pc.createOffer();tt.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",s),await this._pc.setLocalDescription(s);let n={type:"answer",sdp:this._remoteSdp.getSdp()};tt.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),tt.debug("resumeSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly",this._remoteSdp.resumeSendingMediaSection(e);let s=await this._pc.createOffer();tt.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",s),await this._pc.setLocalDescription(s);let n={type:"answer",sdp:this._remoteSdp.getSdp()};tt.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?tt.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):tt.debug("replaceTrack() [localId:%s, no track]",e);let s=this._mapMidTransceiver.get(e);if(!s)throw new Error("associated RTCRtpTransceiver not found");await s.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),this.assertSendDirection(),tt.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);let s=this._mapMidTransceiver.get(e);if(!s)throw new Error("associated transceiver not found");let n=s.sender.getParameters();n.encodings.forEach((a,c)=>{c<=t?a.active=!0:a.active=!1}),await s.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);let i=await this._pc.createOffer();tt.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);let o={type:"answer",sdp:this._remoteSdp.getSdp()};tt.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),tt.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);let s=this._mapMidTransceiver.get(e);if(!s)throw new Error("associated RTCRtpTransceiver not found");let n=s.sender.getParameters();n.encodings.forEach((a,c)=>{n.encodings[c]={...a,...t}}),await s.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);let i=await this._pc.createOffer();tt.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);let o={type:"answer",sdp:this._remoteSdp.getSdp()};tt.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({sctpStreamParameters:e}){this.assertNotClosed(),this.assertSendDirection();let t={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e.ordered,maxPacketLifeTime:e.maxPacketLifeTime,maxRetransmits:e.maxRetransmits,protocol:e.protocol};tt.debug("sendDataChannel() [options:%o]",t);let s=this._pc.createDataChannel(e.label,t);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%NC.MIS,!this._hasDataChannelMediaSection){let i=await this._pc.createOffer(),o=_i.parse(i.sdp),a=o.media.find(d=>d.type==="application");this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:o}),tt.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i),this._remoteSdp.sendSctpAssociation({offerMediaObject:a});let c={type:"answer",sdp:this._remoteSdp.getSdp()};tt.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",c),await this._pc.setRemoteDescription(c),this._hasDataChannelMediaSection=!0}let n={streamId:t.id,ordered:t.ordered,maxPacketLifeTime:t.maxPacketLifeTime,maxRetransmits:t.maxRetransmits};return{dataChannel:s,sctpStreamParameters:n}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();let t=[],s=new Map;for(let a of e){let{trackId:c,kind:d,rtpParameters:u,streamId:f}=a;tt.debug("receive() [trackId:%s, kind:%s]",c,d);let h=u.mid??String(this._mapMidTransceiver.size);s.set(c,h);let{msidStreamId:y}=RL.getMsidStreamIdAndTrackId(u.msid);this._remoteSdp.receive({mid:h,kind:d,offerRtpParameters:u,streamId:f??y??u.rtcp?.cname??"-",trackId:c})}let n={type:"offer",sdp:this._remoteSdp.getSdp()};tt.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",n),await this._pc.setRemoteDescription(n);for(let a of e){let{trackId:c,onRtpReceiver:d}=a;if(d){let u=s.get(c),f=this._pc.getTransceivers().find(h=>h.mid===u);if(!f)throw new Error("transceiver not found");d(f.receiver)}}let i=await this._pc.createAnswer(),o=_i.parse(i.sdp);for(let a of e){let{trackId:c,rtpParameters:d}=a,u=s.get(c),f=o.media.find(h=>String(h.mid)===u);k0.applyCodecParameters({offerRtpParameters:d,answerMediaObject:f}),i={type:"answer",sdp:_i.write(o)}}this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:o}),tt.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(let a of e){let{trackId:c}=a,d=s.get(c),u=this._pc.getTransceivers().find(f=>f.mid===d);if(!u)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(d,u),t.push({localId:d,track:u.receiver.track,rtpReceiver:u.receiver})}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(let n of e){tt.debug("stopReceiving() [localId:%s]",n);let i=this._mapMidTransceiver.get(n);if(!i)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(i.mid)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};tt.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let s=await this._pc.createAnswer();tt.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",s),await this._pc.setLocalDescription(s);for(let n of e)this._mapMidTransceiver.delete(n)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(let n of e){tt.debug("pauseReceiving() [localId:%s]",n);let i=this._mapMidTransceiver.get(n);if(!i)throw new Error("associated RTCRtpTransceiver not found");i.direction="inactive",this._remoteSdp.pauseMediaSection(n)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};tt.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let s=await this._pc.createAnswer();tt.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",s),await this._pc.setLocalDescription(s)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(let n of e){tt.debug("resumeReceiving() [localId:%s]",n);let i=this._mapMidTransceiver.get(n);if(!i)throw new Error("associated RTCRtpTransceiver not found");i.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(n)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};tt.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let s=await this._pc.createAnswer();tt.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",s),await this._pc.setLocalDescription(s)}async getReceiverStats(e){this.assertRecvDirection();let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({maxMessageSize:e,sctpStreamParameters:t,label:s,protocol:n}){this.assertNotClosed(),this.assertRecvDirection();let{streamId:i,ordered:o,maxPacketLifeTime:a,maxRetransmits:c}=t,d={negotiated:!0,id:i,ordered:o,maxPacketLifeTime:a,maxRetransmits:c,protocol:n};tt.debug("receiveDataChannel() [options:%o]",d);let u=this._pc.createDataChannel(s,d);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();let f={type:"offer",sdp:this._remoteSdp.getSdp()};tt.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",f),await this._pc.setRemoteDescription(f);let h=await this._pc.createAnswer(),y=_i.parse(h.sdp),v=y.media.find(S=>S.type==="application");v.maxMessageSize=e,this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:y}),h={type:"answer",sdp:_i.write(y)},tt.debug("receiveDataChannel() | calling pc.setLocalDescription() [answer:%o]",h),await this._pc.setLocalDescription(h),this._hasDataChannelMediaSection=!0}return{dataChannel:u}}getDataChannelMaxMessageSize(){return this._pc.sctp?.maxMessageSize}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=_i.parse(this._pc.localDescription.sdp));let s=k0.extractDtlsParameters({sdpObject:t});s.role=e,this._remoteSdp.updateDtlsRole(e==="client"?"server":"client"),await new Promise((n,i)=>{this.safeEmit("@connect",{dtlsParameters:s},n,i)}),this._transportReady=!0}onIceGatheringStateChange=()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)};onIceCandidateError=e=>{this.emit("@icecandidateerror",e)};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 kC.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')}};P0.Firefox120=gb});var UC=re(B0=>{"use strict";Object.defineProperty(B0,"__esModule",{value:!0});B0.Safari12=void 0;var Ms=Si(),kL=as(),PL=Yr(),Df=Rn(),BL=Ls(),NL=Oa(),OL=Pd(),Mf=Bd(),LC=Nd(),yb=Od(),Qe=new PL.Logger("Safari12"),DC="Safari12",MC={OS:65535,MIS:65535},xb=class r extends kL.EnhancedEventEmitter{_closed=!1;_direction;_remoteSdp;_getSendExtendedRtpCapabilities;_forcedLocalDtlsRole;_pc;_mapMidTransceiver=new Map;_sendStream=new MediaStream;_hasDataChannelMediaSection=!1;_nextSendSctpStreamId=0;_transportReady=!1;static createFactory(){return{name:DC,factory:e=>new r(e),getNativeRtpCapabilities:async({direction:e})=>{Qe.debug("getNativeRtpCapabilities() [direction:%o]",e);let t=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{t.addTransceiver("audio",{direction:e}),t.addTransceiver("video",{direction:e});let s=await t.createOffer();try{t.close()}catch{}t=void 0;let n=Ms.parse(s.sdp);return r.getLocalRtpCapabilities(n)}catch(s){try{t?.close()}catch{}throw t=void 0,s}},getNativeSctpCapabilities:async()=>(Qe.debug("getNativeSctpCapabilities()"),{numStreams:MC})}}static getLocalRtpCapabilities(e,t=[]){let s=Mf.extractRtpCapabilities({sdpObject:e});Df.validateAndNormalizeRtpCapabilities(s),yb.addNackSupportForOpus(s);for(let n of t)yb.addHeaderExtensionSupport(s,n);return s}constructor({direction:e,iceParameters:t,iceCandidates:s,dtlsParameters:n,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:c,getSendExtendedRtpCapabilities:d}){super(),Qe.debug("constructor()"),this._direction=e,this._remoteSdp=new OL.RemoteSdp({iceParameters:t,iceCandidates:s,dtlsParameters:n,sctpParameters:i}),this._getSendExtendedRtpCapabilities=d,n.role&&n.role!=="auto"&&(this._forcedLocalDtlsRole=n.role==="server"?"client":"server"),this._pc=new RTCPeerConnection({iceServers:o??[],iceTransportPolicy:a??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...c}),this._pc.addEventListener("icegatheringstatechange",()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)}),this._pc.addEventListener("icecandidateerror",u=>{this.emit("@icecandidateerror",u)}),this._pc.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.addEventListener("icecandidateerror",this.onIceCandidateError),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",this.onConnectionStateChange):(Qe.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return DC}close(){if(Qe.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(e){this.assertNotClosed(),Qe.debug("updateIceServers()");let t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),Qe.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),!!this._transportReady)if(this._direction==="send"){let t=await this._pc.createOffer({iceRestart:!0});Qe.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",t),await this._pc.setLocalDescription(t);let s={type:"answer",sdp:this._remoteSdp.getSdp()};Qe.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}else{let t={type:"offer",sdp:this._remoteSdp.getSdp()};Qe.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let s=await this._pc.createAnswer();Qe.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",s),await this._pc.setLocalDescription(s)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,streamId:t,encodings:s,codecOptions:n,headerExtensionOptions:i,codec:o,onRtpSender:a}){this.assertNotClosed(),this.assertSendDirection(),Qe.debug("send() [kind:%s, track.id:%s, streamId:%s]",e.kind,e.id,t);let c=this._remoteSdp.getNextMediaSectionIdx(),d=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream]});a&&a(d.sender);let u=await this._pc.createOffer(),f=Ms.parse(u.sdp);f.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();let h=[];h.push({uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",kind:e.kind,direction:"sendonly"});let y=r.getLocalRtpCapabilities(f,h),v=this._getSendExtendedRtpCapabilities(y),S=Df.getSendingRtpParameters(e.kind,v);S.codecs=Df.reduceCodecs(S.codecs,o);let C=Df.getSendingRemoteRtpParameters(e.kind,v);C.codecs=Df.reduceCodecs(C.codecs,o);let O;this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:f});let K=(0,NL.parse)((s??[{}])[0].scalabilityMode);s&&s.length>1&&(Qe.debug("send() | enabling legacy simulcast"),f=Ms.parse(u.sdp),O=f.media[c.idx],LC.addLegacySimulcast({offerMediaObject:O,numStreams:s.length}),u={type:"offer",sdp:Ms.write(f)}),i?.absCaptureTime&&(O=f.media[c.idx],Mf.addHeaderExtension({offerMediaObject:O,headerExtensionUri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",headerExtensionId:C.headerExtensions.find(oe=>oe.uri==="http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time").id}),u={type:"offer",sdp:Ms.write(f)}),Qe.debug("send() | calling pc.setLocalDescription() [offer:%o]",u),await this._pc.setLocalDescription(u);let z=d.mid;if(S.mid=z,f=Ms.parse(this._pc.localDescription.sdp),O=f.media[c.idx],S.rtcp.cname=Mf.getCname({offerMediaObject:O}),S.msid=`${t??this._sendStream.id} ${e.id}`,S.encodings=LC.getRtpEncodings({offerMediaObject:O,codecs:S.codecs}),s)for(let oe=0;oe<S.encodings.length;++oe)s[oe]&&Object.assign(S.encodings[oe],s[oe]);if(S.encodings.length>1&&(S.codecs[0].mimeType.toLowerCase()==="video/vp8"||S.codecs[0].mimeType.toLowerCase()==="video/h264"))for(let oe of S.encodings)oe.scalabilityMode?oe.scalabilityMode=`L1T${K.temporalLayers}`:oe.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:O,reuseMid:c.reuseMid,offerRtpParameters:S,answerRtpParameters:C,codecOptions:n});let Q={type:"answer",sdp:this._remoteSdp.getSdp()};return Qe.debug("send() | calling pc.setRemoteDescription() [answer:%o]",Q),await this._pc.setRemoteDescription(Q),this._mapMidTransceiver.set(z,d),{localId:z,rtpParameters:S,rtpSender:d.sender}}async stopSending(e){if(this.assertSendDirection(),this._closed)return;Qe.debug("stopSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");if(t.sender.replaceTrack(null),this._pc.removeTrack(t.sender),this._remoteSdp.closeMediaSection(t.mid))try{t.stop()}catch{}let n=await this._pc.createOffer();Qe.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);let i={type:"answer",sdp:this._remoteSdp.getSdp()};Qe.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),Qe.debug("pauseSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);let s=await this._pc.createOffer();Qe.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",s),await this._pc.setLocalDescription(s);let n={type:"answer",sdp:this._remoteSdp.getSdp()};Qe.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),Qe.debug("resumeSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly",this._remoteSdp.resumeSendingMediaSection(e);let s=await this._pc.createOffer();Qe.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",s),await this._pc.setLocalDescription(s);let n={type:"answer",sdp:this._remoteSdp.getSdp()};Qe.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?Qe.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):Qe.debug("replaceTrack() [localId:%s, no track]",e);let s=this._mapMidTransceiver.get(e);if(!s)throw new Error("associated RTCRtpTransceiver not found");await s.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),this.assertSendDirection(),Qe.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);let s=this._mapMidTransceiver.get(e);if(!s)throw new Error("associated RTCRtpTransceiver not found");let n=s.sender.getParameters();n.encodings.forEach((a,c)=>{c<=t?a.active=!0:a.active=!1}),await s.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);let i=await this._pc.createOffer();Qe.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);let o={type:"answer",sdp:this._remoteSdp.getSdp()};Qe.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),Qe.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);let s=this._mapMidTransceiver.get(e);if(!s)throw new Error("associated RTCRtpTransceiver not found");let n=s.sender.getParameters();n.encodings.forEach((a,c)=>{n.encodings[c]={...a,...t}}),await s.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);let i=await this._pc.createOffer();Qe.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);let o={type:"answer",sdp:this._remoteSdp.getSdp()};Qe.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({sctpStreamParameters:e}){this.assertNotClosed(),this.assertSendDirection();let t={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e.ordered,maxPacketLifeTime:e.maxPacketLifeTime,maxRetransmits:e.maxRetransmits,protocol:e.protocol};Qe.debug("sendDataChannel() [options:%o]",t);let s=this._pc.createDataChannel(e.label,t);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%MC.MIS,!this._hasDataChannelMediaSection){let i=await this._pc.createOffer(),o=Ms.parse(i.sdp),a=o.media.find(d=>d.type==="application");this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),Qe.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i),this._remoteSdp.sendSctpAssociation({offerMediaObject:a});let c={type:"answer",sdp:this._remoteSdp.getSdp()};Qe.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",c),await this._pc.setRemoteDescription(c),this._hasDataChannelMediaSection=!0}let n={streamId:t.id,ordered:t.ordered,maxPacketLifeTime:t.maxPacketLifeTime,maxRetransmits:t.maxRetransmits};return{dataChannel:s,sctpStreamParameters:n}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();let t=[],s=new Map;for(let a of e){let{trackId:c,kind:d,rtpParameters:u,streamId:f}=a;Qe.debug("receive() [trackId:%s, kind:%s]",c,d);let h=u.mid??String(this._mapMidTransceiver.size);s.set(c,h);let{msidStreamId:y}=yb.getMsidStreamIdAndTrackId(u.msid);this._remoteSdp.receive({mid:h,kind:d,offerRtpParameters:u,streamId:f??y??u.rtcp?.cname??"-",trackId:c})}let n={type:"offer",sdp:this._remoteSdp.getSdp()};Qe.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",n),await this._pc.setRemoteDescription(n);for(let a of e){let{trackId:c,onRtpReceiver:d}=a;if(d){let u=s.get(c),f=this._pc.getTransceivers().find(h=>h.mid===u);if(!f)throw new Error("transceiver not found");d(f.receiver)}}let i=await this._pc.createAnswer(),o=Ms.parse(i.sdp);for(let a of e){let{trackId:c,rtpParameters:d}=a,u=s.get(c),f=o.media.find(h=>String(h.mid)===u);Mf.applyCodecParameters({offerRtpParameters:d,answerMediaObject:f})}i={type:"answer",sdp:Ms.write(o)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),Qe.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(let a of e){let{trackId:c}=a,d=s.get(c),u=this._pc.getTransceivers().find(f=>f.mid===d);if(!u)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(d,u),t.push({localId:d,track:u.receiver.track,rtpReceiver:u.receiver})}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(let n of e){Qe.debug("stopReceiving() [localId:%s]",n);let i=this._mapMidTransceiver.get(n);if(!i)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(i.mid)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};Qe.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let s=await this._pc.createAnswer();Qe.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",s),await this._pc.setLocalDescription(s);for(let n of e)this._mapMidTransceiver.delete(n)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(let n of e){Qe.debug("pauseReceiving() [localId:%s]",n);let i=this._mapMidTransceiver.get(n);if(!i)throw new Error("associated RTCRtpTransceiver not found");i.direction="inactive",this._remoteSdp.pauseMediaSection(n)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};Qe.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let s=await this._pc.createAnswer();Qe.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",s),await this._pc.setLocalDescription(s)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(let n of e){Qe.debug("resumeReceiving() [localId:%s]",n);let i=this._mapMidTransceiver.get(n);if(!i)throw new Error("associated RTCRtpTransceiver not found");i.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(n)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};Qe.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let s=await this._pc.createAnswer();Qe.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",s),await this._pc.setLocalDescription(s)}async getReceiverStats(e){this.assertNotClosed(),this.assertRecvDirection();let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({maxMessageSize:e,sctpStreamParameters:t,label:s,protocol:n}){this.assertNotClosed(),this.assertRecvDirection();let{streamId:i,ordered:o,maxPacketLifeTime:a,maxRetransmits:c}=t,d={negotiated:!0,id:i,ordered:o,maxPacketLifeTime:a,maxRetransmits:c,protocol:n};Qe.debug("receiveDataChannel() [options:%o]",d);let u=this._pc.createDataChannel(s,d);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();let f={type:"offer",sdp:this._remoteSdp.getSdp()};Qe.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",f),await this._pc.setRemoteDescription(f);let h=await this._pc.createAnswer(),y=Ms.parse(h.sdp),v=y.media.find(S=>S.type==="application");v.maxMessageSize=e,this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:y}),h={type:"answer",sdp:Ms.write(y)},Qe.debug("receiveDataChannel() | calling pc.setLocalDescription() [answer:%o]",h),await this._pc.setLocalDescription(h),this._hasDataChannelMediaSection=!0}return{dataChannel:u}}getDataChannelMaxMessageSize(){return this._pc.sctp?.maxMessageSize}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=Ms.parse(this._pc.localDescription.sdp));let s=Mf.extractDtlsParameters({sdpObject:t});s.role=e,this._remoteSdp.updateDtlsRole(e==="client"?"server":"client"),await new Promise((n,i)=>{this.safeEmit("@connect",{dtlsParameters:s},n,i)}),this._transportReady=!0}onIceGatheringStateChange=()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)};onIceCandidateError=e=>{this.emit("@icecandidateerror",e)};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 BL.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')}};B0.Safari12=xb});var FC=re(N0=>{"use strict";Object.defineProperty(N0,"__esModule",{value:!0});N0.ReactNative106=void 0;var Us=Si(),LL=as(),DL=Yr(),Uf=Rn(),ML=Ls(),UL=Oa(),jL=Pd(),jf=Bd(),bb=Nd(),vb=Od(),Ye=new DL.Logger("ReactNative106"),jC="ReactNative106",HC={OS:65535,MIS:65535},wb=class r extends LL.EnhancedEventEmitter{_closed=!1;_direction;_remoteSdp;_getSendExtendedRtpCapabilities;_forcedLocalDtlsRole;_pc;_mapMidTransceiver=new Map;_sendStream=new MediaStream;_hasDataChannelMediaSection=!1;_nextSendSctpStreamId=0;_transportReady=!1;static createFactory(){return{name:jC,factory:e=>new r(e),getNativeRtpCapabilities:async({direction:e})=>{Ye.debug("getNativeRtpCapabilities() [direction:%o]",e);let t=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{t.addTransceiver("audio",{direction:e}),t.addTransceiver("video",{direction:e});let s=await t.createOffer();try{t.close()}catch{}t=void 0;let n=Us.parse(s.sdp);return r.getLocalRtpCapabilities(n)}catch(s){try{t?.close()}catch{}throw t=void 0,s}},getNativeSctpCapabilities:async()=>(Ye.debug("getNativeSctpCapabilities()"),{numStreams:HC})}}static getLocalRtpCapabilities(e,t=[]){let s=jf.extractRtpCapabilities({sdpObject:e});Uf.validateAndNormalizeRtpCapabilities(s),vb.addNackSupportForOpus(s);for(let n of t)vb.addHeaderExtensionSupport(s,n);return s}constructor({direction:e,iceParameters:t,iceCandidates:s,dtlsParameters:n,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:c,getSendExtendedRtpCapabilities:d}){super(),Ye.debug("constructor()"),this._direction=e,this._remoteSdp=new jL.RemoteSdp({iceParameters:t,iceCandidates:s,dtlsParameters:n,sctpParameters:i}),this._getSendExtendedRtpCapabilities=d,n.role&&n.role!=="auto"&&(this._forcedLocalDtlsRole=n.role==="server"?"client":"server"),this._pc=new RTCPeerConnection({iceServers:o??[],iceTransportPolicy:a??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...c}),this._pc.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.addEventListener("icecandidateerror",this.onIceCandidateError),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",this.onConnectionStateChange):(Ye.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return jC}close(){if(Ye.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(e){this.assertNotClosed(),Ye.debug("updateIceServers()");let t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),Ye.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),!!this._transportReady)if(this._direction==="send"){let t=await this._pc.createOffer({iceRestart:!0});Ye.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",t),await this._pc.setLocalDescription(t);let s={type:"answer",sdp:this._remoteSdp.getSdp()};Ye.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}else{let t={type:"offer",sdp:this._remoteSdp.getSdp()};Ye.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let s=await this._pc.createAnswer();Ye.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",s),await this._pc.setLocalDescription(s)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,streamId:t,encodings:s,codecOptions:n,headerExtensionOptions:i,codec:o,onRtpSender:a}){this.assertNotClosed(),this.assertSendDirection(),Ye.debug("send() [kind:%s, track.id:%s, streamId:%s]",e.kind,e.id,t),s&&s.length>1&&s.forEach((se,we)=>{se.rid=`r${we}`});let c=this._remoteSdp.getNextMediaSectionIdx(),d=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:s});a&&a(d.sender);let u=await this._pc.createOffer(),f=Us.parse(u.sdp);f.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();let h=[];h.push({uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",kind:e.kind,direction:"sendonly"});let y=r.getLocalRtpCapabilities(f,h),v=this._getSendExtendedRtpCapabilities(y),S=Uf.getSendingRtpParameters(e.kind,v);S.codecs=Uf.reduceCodecs(S.codecs,o);let C=Uf.getSendingRemoteRtpParameters(e.kind,v);C.codecs=Uf.reduceCodecs(C.codecs,o),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:f});let O=!1,K=(0,UL.parse)((s??[{}])[0].scalabilityMode),z;s?.length===1&&K.spatialLayers>1&&S.codecs[0].mimeType.toLowerCase()==="video/vp9"&&(Ye.debug("send() | enabling legacy simulcast for VP9 SVC"),O=!0,f=Us.parse(u.sdp),z=f.media[c.idx],bb.addLegacySimulcast({offerMediaObject:z,numStreams:K.spatialLayers}),u={type:"offer",sdp:Us.write(f)}),i?.absCaptureTime&&(z=f.media[c.idx],jf.addHeaderExtension({offerMediaObject:z,headerExtensionUri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",headerExtensionId:C.headerExtensions.find(se=>se.uri==="http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time").id}),u={type:"offer",sdp:Us.write(f)}),Ye.debug("send() | calling pc.setLocalDescription() [offer:%o]",u),await this._pc.setLocalDescription(u);let Q=d.mid??void 0;if(Q||Ye.warn("send() | missing transceiver.mid (bug in react-native-webrtc, using a workaround"),S.mid=Q,f=Us.parse(this._pc.localDescription.sdp),z=f.media[c.idx],S.rtcp.cname=jf.getCname({offerMediaObject:z}),S.msid=`${t??this._sendStream.id} ${e.id}`,!s)S.encodings=bb.getRtpEncodings({offerMediaObject:z,codecs:S.codecs});else if(s.length===1){let se=bb.getRtpEncodings({offerMediaObject:z,codecs:S.codecs});Object.assign(se[0],s[0]),O&&(se=[se[0]]),S.encodings=se}else S.encodings=s;if(S.encodings.length>1&&(S.codecs[0].mimeType.toLowerCase()==="video/vp8"||S.codecs[0].mimeType.toLowerCase()==="video/h264"))for(let se of S.encodings)se.scalabilityMode?se.scalabilityMode=`L1T${K.temporalLayers}`:se.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:z,reuseMid:c.reuseMid,offerRtpParameters:S,answerRtpParameters:C,codecOptions:n});let oe={type:"answer",sdp:this._remoteSdp.getSdp()};return Ye.debug("send() | calling pc.setRemoteDescription() [answer:%o]",oe),await this._pc.setRemoteDescription(oe),Q||(Q=d.mid,S.mid=Q),this._mapMidTransceiver.set(Q,d),{localId:Q,rtpParameters:S,rtpSender:d.sender}}async stopSending(e){if(this.assertSendDirection(),this._closed)return;Ye.debug("stopSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");if(t.sender.replaceTrack(null),this._pc.removeTrack(t.sender),this._remoteSdp.closeMediaSection(t.mid))try{t.stop()}catch{}let n=await this._pc.createOffer();Ye.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);let i={type:"answer",sdp:this._remoteSdp.getSdp()};Ye.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),Ye.debug("pauseSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);let s=await this._pc.createOffer();Ye.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",s),await this._pc.setLocalDescription(s);let n={type:"answer",sdp:this._remoteSdp.getSdp()};Ye.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),Ye.debug("resumeSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(this._remoteSdp.resumeSendingMediaSection(e),!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly";let s=await this._pc.createOffer();Ye.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",s),await this._pc.setLocalDescription(s);let n={type:"answer",sdp:this._remoteSdp.getSdp()};Ye.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?Ye.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):Ye.debug("replaceTrack() [localId:%s, no track]",e);let s=this._mapMidTransceiver.get(e);if(!s)throw new Error("associated RTCRtpTransceiver not found");await s.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),this.assertSendDirection(),Ye.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);let s=this._mapMidTransceiver.get(e);if(!s)throw new Error("associated RTCRtpTransceiver not found");let n=s.sender.getParameters();n.encodings.forEach((a,c)=>{c<=t?a.active=!0:a.active=!1}),await s.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);let i=await this._pc.createOffer();Ye.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);let o={type:"answer",sdp:this._remoteSdp.getSdp()};Ye.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),Ye.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);let s=this._mapMidTransceiver.get(e);if(!s)throw new Error("associated RTCRtpTransceiver not found");let n=s.sender.getParameters();n.encodings.forEach((a,c)=>{n.encodings[c]={...a,...t}}),await s.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);let i=await this._pc.createOffer();Ye.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);let o={type:"answer",sdp:this._remoteSdp.getSdp()};Ye.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({sctpStreamParameters:e}){this.assertNotClosed(),this.assertSendDirection();let t={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e.ordered,maxPacketLifeTime:e.maxPacketLifeTime,maxRetransmits:e.maxRetransmits,protocol:e.protocol};Ye.debug("sendDataChannel() [options:%o]",t);let s=this._pc.createDataChannel(e.label,t);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%HC.MIS,!this._hasDataChannelMediaSection){let i=await this._pc.createOffer(),o=Us.parse(i.sdp),a=o.media.find(d=>d.type==="application");this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),Ye.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i),this._remoteSdp.sendSctpAssociation({offerMediaObject:a});let c={type:"answer",sdp:this._remoteSdp.getSdp()};Ye.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",c),await this._pc.setRemoteDescription(c),this._hasDataChannelMediaSection=!0}let n={streamId:t.id,ordered:t.ordered,maxPacketLifeTime:t.maxPacketLifeTime,maxRetransmits:t.maxRetransmits};return{dataChannel:s,sctpStreamParameters:n}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();let t=[],s=new Map;for(let a of e){let{trackId:c,kind:d,rtpParameters:u,streamId:f}=a;Ye.debug("receive() [trackId:%s, kind:%s]",c,d);let h=u.mid??String(this._mapMidTransceiver.size);s.set(c,h);let{msidStreamId:y}=vb.getMsidStreamIdAndTrackId(u.msid);this._remoteSdp.receive({mid:h,kind:d,offerRtpParameters:u,streamId:f??y??u.rtcp?.cname??"-",trackId:c})}let n={type:"offer",sdp:this._remoteSdp.getSdp()};Ye.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",n),await this._pc.setRemoteDescription(n);for(let a of e){let{trackId:c,onRtpReceiver:d}=a;if(d){let u=s.get(c),f=this._pc.getTransceivers().find(h=>h.mid===u);if(!f)throw new Error("transceiver not found");d(f.receiver)}}let i=await this._pc.createAnswer(),o=Us.parse(i.sdp);for(let a of e){let{trackId:c,rtpParameters:d}=a,u=s.get(c),f=o.media.find(h=>String(h.mid)===u);jf.applyCodecParameters({offerRtpParameters:d,answerMediaObject:f})}i={type:"answer",sdp:Us.write(o)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),Ye.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(let a of e){let{trackId:c}=a,d=s.get(c),u=this._pc.getTransceivers().find(f=>f.mid===d);if(u)this._mapMidTransceiver.set(d,u),t.push({localId:d,track:u.receiver.track,rtpReceiver:u.receiver});else throw new Error("new RTCRtpTransceiver not found")}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(let n of e){Ye.debug("stopReceiving() [localId:%s]",n);let i=this._mapMidTransceiver.get(n);if(!i)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(i.mid)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};Ye.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let s=await this._pc.createAnswer();Ye.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",s),await this._pc.setLocalDescription(s);for(let n of e)this._mapMidTransceiver.delete(n)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(let n of e){Ye.debug("pauseReceiving() [localId:%s]",n);let i=this._mapMidTransceiver.get(n);if(!i)throw new Error("associated RTCRtpTransceiver not found");i.direction="inactive",this._remoteSdp.pauseMediaSection(n)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};Ye.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let s=await this._pc.createAnswer();Ye.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",s),await this._pc.setLocalDescription(s)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(let n of e){Ye.debug("resumeReceiving() [localId:%s]",n);let i=this._mapMidTransceiver.get(n);if(!i)throw new Error("associated RTCRtpTransceiver not found");i.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(n)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};Ye.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let s=await this._pc.createAnswer();Ye.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",s),await this._pc.setLocalDescription(s)}async getReceiverStats(e){this.assertNotClosed(),this.assertRecvDirection();let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({maxMessageSize:e,sctpStreamParameters:t,label:s,protocol:n}){this.assertNotClosed(),this.assertRecvDirection();let{streamId:i,ordered:o,maxPacketLifeTime:a,maxRetransmits:c}=t,d={negotiated:!0,id:i,ordered:o,maxPacketLifeTime:a,maxRetransmits:c,protocol:n};Ye.debug("receiveDataChannel() [options:%o]",d);let u=this._pc.createDataChannel(s,d);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();let f={type:"offer",sdp:this._remoteSdp.getSdp()};Ye.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",f),await this._pc.setRemoteDescription(f);let h=await this._pc.createAnswer(),y=Us.parse(h.sdp),v=y.media.find(S=>S.type==="application");v.maxMessageSize=e,this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:y}),h={type:"answer",sdp:Us.write(y)},Ye.debug("receiveDataChannel() | calling pc.setLocalDescription() [answer:%o]",h),await this._pc.setLocalDescription(h),this._hasDataChannelMediaSection=!0}return{dataChannel:u}}getDataChannelMaxMessageSize(){return this._pc.sctp?.maxMessageSize}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=Us.parse(this._pc.localDescription.sdp));let s=jf.extractDtlsParameters({sdpObject:t});s.role=e,this._remoteSdp.updateDtlsRole(e==="client"?"server":"client"),await new Promise((n,i)=>{this.safeEmit("@connect",{dtlsParameters:s},n,i)}),this._transportReady=!0}onIceGatheringStateChange=()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)};onIceCandidateError=e=>{this.emit("@icecandidateerror",e)};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 ML.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')}};N0.ReactNative106=wb});var VC=re(Ld=>{"use strict";Object.defineProperty(Ld,"__esModule",{value:!0});Ld.Device=void 0;Ld.detectDevice=qC;Ld.detectDeviceAsync=zC;var HL=Yr(),FL=as(),vo=Ls(),O0=ka(),Ss=Rn(),qL=fC(),zL=TC(),$L=RC(),VL=OC(),KL=UC(),WL=FC(),He=new HL.Logger("Device");function qC(r,e){return He.debug("detectDevice()"),!r&&typeof navigator=="object"&&(r=navigator.userAgent),!e&&typeof navigator=="object"&&(e=navigator.userAgentData),$C(r,e)}async function zC(r,e){return He.debug("detectDeviceAsync()"),!r&&typeof navigator=="object"&&(r=navigator.userAgent),!e&&typeof navigator=="object"&&(e=navigator.userAgentData),$C(r,e)}var Sb=class r{_handlerFactory;_handlerName;_loaded=!1;_getSendExtendedRtpCapabilities;_recvRtpCapabilities;_sendRtpCapabilities;_canProduceByKind={audio:!1,video:!1};_sctpCapabilities;_observer=new FL.EnhancedEventEmitter;static async factory({handlerName:e,handlerFactory:t}={}){if(He.debug("factory()"),e&&t)throw new TypeError("just one of handlerName or handlerInterface can be given");if(!e&&!t&&(e=await zC(),!e))throw new vo.UnsupportedError("device not supported");return new r({handlerName:e,handlerFactory:t})}constructor({handlerName:e,handlerFactory:t}={}){if(He.debug("constructor()"),e&&t)throw new TypeError("just one of handlerName or handlerInterface can be given");if(t)this._handlerFactory=t;else{if(e)He.debug("constructor() | handler given: %s",e);else if(e=qC(),e)He.debug("constructor() | detected handler: %s",e);else throw new vo.UnsupportedError("device not supported");switch(e){case"Chrome111":{this._handlerFactory=zL.Chrome111.createFactory();break}case"Chrome74":{this._handlerFactory=$L.Chrome74.createFactory();break}case"Firefox120":{this._handlerFactory=VL.Firefox120.createFactory();break}case"Safari12":{this._handlerFactory=KL.Safari12.createFactory();break}case"ReactNative106":{this._handlerFactory=WL.ReactNative106.createFactory();break}default:throw new TypeError(`unknown handlerName "${e}"`)}}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 vo.InvalidStateError("not loaded");return this._recvRtpCapabilities}get sendRtpCapabilities(){if(!this._loaded)throw new vo.InvalidStateError("not loaded");return this._sendRtpCapabilities}get sctpCapabilities(){if(!this._loaded)throw new vo.InvalidStateError("not loaded");return this._sctpCapabilities}get observer(){return this._observer}async load({routerRtpCapabilities:e,preferLocalCodecsOrder:t=!1}){if(He.debug("load() [routerRtpCapabilities:%o]",e),this._loaded)throw new vo.InvalidStateError("already loaded");let s=O0.clone(e);Ss.validateAndNormalizeRtpCapabilities(s);let{getNativeRtpCapabilities:n,getNativeSctpCapabilities:i}=this._handlerFactory,o=O0.clone(await n({direction:"recvonly"}));He.debug("load() | got native receiving RTP capabilities:%o",o),Ss.validateAndNormalizeRtpCapabilities(o);let a=O0.clone(await n({direction:"sendonly"}));He.debug("load() | got native sending RTP capabilities:%o",a),Ss.validateAndNormalizeRtpCapabilities(a),this._getSendExtendedRtpCapabilities=u=>O0.clone(Ss.getExtendedRtpCapabilities(u,s,t));let c=Ss.getExtendedRtpCapabilities(o,s,!1);this._recvRtpCapabilities=Ss.getRecvRtpCapabilities(c),He.debug("load() | got receiving RTP capabilities:%o",this._recvRtpCapabilities),Ss.validateAndNormalizeRtpCapabilities(this._recvRtpCapabilities);let d=Ss.getExtendedRtpCapabilities(a,s,t);this._sendRtpCapabilities=Ss.getSendRtpCapabilities(d),He.debug("load() | got sending RTP capabilities:%o",this._sendRtpCapabilities),Ss.validateAndNormalizeRtpCapabilities(this._sendRtpCapabilities),this._canProduceByKind.audio=Ss.canSend("audio",this._sendRtpCapabilities),this._canProduceByKind.video=Ss.canSend("video",this._sendRtpCapabilities),this._sctpCapabilities=await i(),Ss.validateSctpCapabilities(this._sctpCapabilities),He.debug("load() | got native SCTP capabilities:%o",this._sctpCapabilities),He.debug("load() succeeded"),this._loaded=!0}canProduce(e){if(this._loaded){if(e!=="audio"&&e!=="video")throw new TypeError(`invalid kind "${e}"`)}else throw new vo.InvalidStateError("not loaded");return this._canProduceByKind[e]}createSendTransport({id:e,iceParameters:t,iceCandidates:s,dtlsParameters:n,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:c,appData:d}){return He.debug("createSendTransport()"),this.createTransport({direction:"send",id:e,iceParameters:t,iceCandidates:s,dtlsParameters:n,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:c,appData:d})}createRecvTransport({id:e,iceParameters:t,iceCandidates:s,dtlsParameters:n,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:c,appData:d}){return He.debug("createRecvTransport()"),this.createTransport({direction:"recv",id:e,iceParameters:t,iceCandidates:s,dtlsParameters:n,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:c,appData:d})}createTransport({direction:e,id:t,iceParameters:s,iceCandidates:n,dtlsParameters:i,sctpParameters:o,iceServers:a,iceTransportPolicy:c,additionalSettings:d,appData:u}){if(this._loaded){if(typeof t!="string")throw new TypeError("missing id");if(typeof s!="object")throw new TypeError("missing iceParameters");if(Array.isArray(n)){if(typeof i!="object")throw new TypeError("missing dtlsParameters");if(o&&typeof o!="object")throw new TypeError("wrong sctpParameters");if(u&&typeof u!="object")throw new TypeError("if given, appData must be an object")}else throw new TypeError("missing iceCandidates")}else throw new vo.InvalidStateError("not loaded");let f=new qL.Transport({direction:e,id:t,iceParameters:s,iceCandidates:n,dtlsParameters:i,sctpParameters:o,iceServers:a,iceTransportPolicy:c,additionalSettings:d,appData:u,handlerFactory:this._handlerFactory,getSendExtendedRtpCapabilities:this._getSendExtendedRtpCapabilities,recvRtpCapabilities:this._recvRtpCapabilities,canProduceByKind:this._canProduceByKind});return this._observer.safeEmit("newtransport",f),f}};Ld.Device=Sb;function $C(r,e){He.debug('detectDeviceImpl() [userAgent:"%s", userAgentData:%o]',r,e);let t=GL(r,e);if(t){if(t>=111)return He.debug("detectDeviceImpl() | using Chrome111 handler"),"Chrome111";if(t>=74)return He.debug("detectDeviceImpl() | using Chrome74 handler"),"Chrome74";He.warn("detectDeviceImpl() | unsupported Chromium based browser/version");return}let s=XL(r);if(s){if(s>=120)return He.debug("detectDeviceImpl() | using Firefox120 handler"),"Firefox120";He.warn("detectDeviceImpl() | unsupported Firefox browser/version");return}let n=YL(r);if(n){if(n>=605)return He.debug("detectDeviceImpl() | using Safari12 handler"),"Safari12";He.warn("detectDeviceImpl() | unsupported desktop Safari browser/version");return}let i=JL(r);if(i){if(i>=605)return He.debug("detectDeviceImpl() | using Safari12 handler"),"Safari12";He.warn("detectDeviceImpl() | unsupported iOS Safari based browser/version");return}if(Hf()){if(typeof RTCPeerConnection<"u"&&typeof RTCRtpTransceiver<"u")return He.debug("detectDeviceImpl() | using ReactNative106 handler"),"ReactNative106";He.warn("detectDeviceImpl() | unsupported react-native-webrtc version without RTCPeerConnection or RTCRtpTransceiver, forgot to call registerGlobals() on it?");return}He.warn('detectDeviceImpl() | device not supported [userAgent:"%s", userAgentData:%o]',r,e)}function GL(r,e){if(He.debug("getChromiumMajorVersion()"),L0(r,e)){He.debug("getChromiumMajorVersion() | this is iOS => undefined");return}if(Hf()){He.debug("getChromiumMajorVersion() | this is React-Native => undefined");return}if(e){let n=(Array.isArray(e.brands)?e.brands:[]).find(i=>i.brand==="Chromium");if(n){let i=Number(n.version);return He.debug(`getChromiumMajorVersion() | Chromium major version based on NavigatorUAData => ${i}`),i}}let t=r?.match(/\b(?:Chrome|Chromium)\/(\w+)/i);if(t?.[1]){let s=Number(t[1]);return He.debug(`getChromiumMajorVersion() | Chromium major version based on User-Agent => ${s}`),s}He.debug("getChromiumMajorVersion() | this is not Chromium => undefined")}function XL(r){if(He.debug("getFirefoxMajorVersion()"),L0(r)){He.debug("getFirefoxMajorVersion() | this is iOS => undefined");return}if(Hf()){He.debug("getFirefoxMajorVersion() | this is React-Native => undefined");return}let e=r?.match(/\bFirefox\/(\w+)/i);if(e?.[1]){let t=Number(e[1]);return He.debug(`getFirefoxMajorVersion() | Firefox major version based on User-Agent => ${t}`),t}He.debug("getFirefoxMajorVersion() | this is not Firefox => undefined")}function YL(r){if(He.debug("getMacOSWebKitMajorVersion()"),L0(r)){He.debug("getMacOSWebKitMajorVersion() | this is iOS => undefined");return}if(Hf()){He.debug("getMacOSWebKitMajorVersion() | this is React-Native => undefined");return}if(!(r&&/\bSafari\b/i.test(r)&&!/\bChrome\b/i.test(r)&&!/\bChromium\b/i.test(r)&&!/\bFirefox\b/i.test(r))){He.debug("getMacOSWebKitMajorVersion() | this is not Safari => undefined");return}let t=r.match(/AppleWebKit\/(\w+)/i);if(t?.[1]){let s=Number(t[1]);return He.debug(`getMacOSWebKitMajorVersion() | WebKit major version based on User-Agent => ${s}`),s}He.debug("getMacOSWebKitMajorVersion() | this is not WebKit => undefined")}function JL(r){if(He.debug("getIOSWebKitMajorVersion()"),!L0(r)){He.debug("getIOSWebKitMajorVersion() | this is not iOS => undefined");return}if(Hf()){He.debug("getIOSWebKitMajorVersion() | this is React-Native => undefined");return}let e=r?.match(/AppleWebKit\/(\w+)/i);if(e?.[1]){let t=Number(e[1]);return He.debug(`getIOSWebKitMajorVersion() | WebKit major version based on User-Agent => ${t}`),t}He.debug("getIOSWebKitMajorVersion() | this is not WebKit => undefined")}function L0(r,e){return He.debug("isIOS()"),e?.platform==="iOS"?(He.debug("isIOS() | this is iOS based on NavigatorUAData.platform => true"),!0):e?.platform?(He.debug("isIOS() | this is not iOS based on NavigatorUAData.platform => false"),!1):r&&/iPad|iPhone|iPod/.test(r)?(He.debug("isIOS() | this is iOS based on User-Agent => true"),!0):typeof navigator=="object"&&navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1?(He.debug("isIOS() | this is iPadOS 13+ based on User-Agent => true"),!0):(He.debug("isIOS() | this is not iOS => false"),!1)}function Hf(){return He.debug("isReactNative()"),typeof navigator=="object"&&navigator.product==="ReactNative"?(He.debug("isReactNative() | this is React-Native based on navigator.product"),!0):(He.debug("isReactNative() | this is not React-Native => false"),!1)}});var WC=re(KC=>{"use strict";var Da=256,M0=[],D0;for(;Da--;)M0[Da]=(Da+256).toString(16).substring(1);function QL(){var r=0,e,t="";if(!D0||Da+16>256){for(D0=Array(r=256);r--;)D0[r]=256*Math.random()|0;r=Da=0}for(;r<16;r++)e=D0[Da+r],r==6?t+=M0[e&15|64]:r==8?t+=M0[e&63|128]:t+=M0[e],r&1&&r>1&&r<11&&(t+="-");return Da++,t}KC.v4=QL});var GC=re(U0=>{"use strict";Object.defineProperty(U0,"__esModule",{value:!0});U0.FakeEventTarget=void 0;var _b=class{listeners={};addEventListener(e,t,s){t&&(this.listeners[e]=this.listeners[e]??[],this.listeners[e].push({callback:typeof t=="function"?t:t.handleEvent,once:typeof s=="object"&&s.once===!0}))}removeEventListener(e,t,s){this.listeners[e]&&t&&(this.listeners[e]=this.listeners[e].filter(n=>n.callback!==(typeof t=="function"?t:t.handleEvent)))}dispatchEvent(e){if(!e||typeof e.type!="string")throw new Error("invalid event object");let t=this.listeners[e.type];if(!t)return!0;for(let s of[...t]){try{s.callback.call(this,e)}catch(n){setTimeout(()=>{throw n},0)}s.once&&this.removeEventListener(e.type,s.callback)}return!e.defaultPrevented}};U0.FakeEventTarget=_b});var XC=re(j0=>{"use strict";Object.defineProperty(j0,"__esModule",{value:!0});j0.FakeEvent=void 0;var Eb=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(e,t={}){this.type=e,this.bubbles=t.bubbles??!1,this.cancelable=t.cancelable??!1}preventDefault(){this.cancelable&&(this.defaultPrevented=!0)}stopPropagation(){}stopImmediatePropagation(){}composedPath(){return[]}initEvent(e,t,s){}};j0.FakeEvent=Eb});var YC=re(Cb=>{"use strict";Object.defineProperty(Cb,"__esModule",{value:!0});Cb.clone=ZL;function ZL(r){if(r!==void 0)return Number.isNaN(r)?NaN:typeof structuredClone=="function"?structuredClone(r):JSON.parse(JSON.stringify(r))}});var QC=re(F0=>{"use strict";Object.defineProperty(F0,"__esModule",{value:!0});F0.FakeMediaStreamTrack=void 0;var JC=WC(),eD=GC(),Dd=XC(),H0=YC(),Tb=class r extends eD.FakeEventTarget{#m;#f;#l;#e;#r;#t;#s;#h;#n;#p;#i;#o=null;#a=null;#c=null;#d=null;#u=null;constructor({kind:e,id:t,label:s,contentHint:n,enabled:i,muted:o,readyState:a,capabilities:c,constraints:d,settings:u,data:f}){super(),this.#m=t??(0,JC.v4)(),this.#f=e,this.#l=s??"",this.#s=n??"",this.#r=i??!0,this.#t=o??!1,this.#e=a??"live",this.#h=c??{},this.#n=d??{},this.#p=u??{},this.#i=f??{}}get id(){return this.#m}get kind(){return this.#f}get label(){return this.#l}get contentHint(){return this.#s}set contentHint(e){this.#s=e}get enabled(){return this.#r}set enabled(e){let t=this.#r!==e;this.#r=e,t&&this.dispatchEvent(new Dd.FakeEvent("enabledchange"))}get muted(){return this.#t}get readyState(){return this.#e}get data(){return this.#i}set data(e){this.#i=e}get onmute(){return this.#o}set onmute(e){this.#o&&this.removeEventListener("mute",this.#o),this.#o=e,e&&this.addEventListener("mute",e)}get onunmute(){return this.#a}set onunmute(e){this.#a&&this.removeEventListener("unmute",this.#a),this.#a=e,e&&this.addEventListener("unmute",e)}get onended(){return this.#c}set onended(e){this.#c&&this.removeEventListener("ended",this.#c),this.#c=e,e&&this.addEventListener("ended",e)}get onenabledchange(){return this.#d}set onenabledchange(e){this.#d&&this.removeEventListener("enabledchange",this.#d),this.#d=e,e&&this.addEventListener("enabledchange",e)}get onstopped(){return this.#u}set onstopped(e){this.#u&&this.removeEventListener("stopped",this.#u),this.#u=e,e&&this.addEventListener("stopped",e)}addEventListener(e,t,s){super.addEventListener(e,t,s)}removeEventListener(e,t,s){super.removeEventListener(e,t,s)}stop(){this.#e!=="ended"&&(this.#e="ended",this.dispatchEvent(new Dd.FakeEvent("stopped")))}clone({id:e,data:t}={}){return new r({id:e??(0,JC.v4)(),kind:this.#f,label:this.#l,contentHint:this.#s,enabled:this.#r,muted:this.#t,readyState:this.#e,capabilities:(0,H0.clone)(this.#h),constraints:(0,H0.clone)(this.#n),settings:(0,H0.clone)(this.#p),data:t??(0,H0.clone)(this.#i)})}getCapabilities(){return this.#h}getConstraints(){return this.#n}async applyConstraints(e={}){return this.#n=e,Promise.resolve()}getSettings(){return this.#p}remoteStop(){this.#e!=="ended"&&(this.#e="ended",this.dispatchEvent(new Dd.FakeEvent("stopped")),this.dispatchEvent(new Dd.FakeEvent("ended")))}remoteMute(){this.#t||(this.#t=!0,this.dispatchEvent(new Dd.FakeEvent("mute")))}remoteUnmute(){this.#t&&(this.#t=!1,this.dispatchEvent(new Dd.FakeEvent("unmute")))}};F0.FakeMediaStreamTrack=Tb});var ZC=re(q0=>{"use strict";Object.defineProperty(q0,"__esModule",{value:!0});q0.FakeEventTarget=void 0;var Ab=class{listeners={};addEventListener(e,t,s){t&&(this.listeners[e]=this.listeners[e]??[],this.listeners[e].push({callback:typeof t=="function"?t:t.handleEvent,once:typeof s=="object"&&s.once===!0}))}removeEventListener(e,t,s){this.listeners[e]&&t&&(this.listeners[e]=this.listeners[e].filter(n=>n.callback!==(typeof t=="function"?t:t.handleEvent)))}dispatchEvent(e){if(!e||typeof e.type!="string")throw new Error("invalid event object");let t=this.listeners[e.type];if(!t)return!0;for(let s of[...t]){try{s.callback.call(this,e)}catch(n){setTimeout(()=>{throw n},0)}s.once&&this.removeEventListener(e.type,s.callback)}return!e.defaultPrevented}};q0.FakeEventTarget=Ab});var r6=re($0=>{"use strict";Object.defineProperty($0,"__esModule",{value:!0});$0.FakeHandler=void 0;var tD=QC(),rD=as(),sD=Yr(),Md=ka(),Ib=Rn(),t6=Ls(),nD=ZC(),Ar=new sD.Logger("FakeHandler"),e6="FakeHandler",Rb=class r extends rD.EnhancedEventEmitter{_closed=!1;_fakeParameters;_getSendExtendedRtpCapabilities;_cname=`CNAME-${Md.generateRandomNumber()}`;_defaultSendStreamId=`${Md.generateRandomNumber()}`;_transportReady=!1;_nextLocalId=1;_tracks=new Map;_nextSctpStreamId=0;static createFactory(e){return{name:e6,factory:t=>new r(t,e),getNativeRtpCapabilities:async({direction:t})=>(Ar.debug("getNativeRtpCapabilities() [direction:%o]",t),r.getLocalRtpCapabilities(e)),getNativeSctpCapabilities:async()=>(Ar.debug("getNativeSctpCapabilities()"),e.generateNativeSctpCapabilities())}}static getLocalRtpCapabilities(e){let t=e.generateNativeRtpCapabilities();return Ib.validateAndNormalizeRtpCapabilities(t),t}constructor({getSendExtendedRtpCapabilities:e},t){super(),Ar.debug("constructor()"),this._getSendExtendedRtpCapabilities=e,this._fakeParameters=t}get name(){return e6}close(){Ar.debug("close()"),!this._closed&&(this._closed=!0,super.close())}setIceGatheringState(e){this.emit("@icegatheringstatechange",e)}setConnectionState(e){this.emit("@connectionstatechange",e)}async updateIceServers(e){this.assertNotClosed(),Ar.debug("updateIceServers()")}async restartIce(e){this.assertNotClosed(),Ar.debug("restartIce()")}async getTransportStats(){return this.assertNotClosed(),new Map}async send({track:e,streamId:t,encodings:s,codecOptions:n,codec:i}){this.assertNotClosed(),Ar.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),this._transportReady||await this.setupTransport({localDtlsRole:"server"});let o=r.getLocalRtpCapabilities(this._fakeParameters),a=this._getSendExtendedRtpCapabilities(o),c=Ib.getSendingRtpParameters(e.kind,a);c.codecs=Ib.reduceCodecs(c.codecs,i);let d=c.codecs.some(f=>/.+\/rtx$/i.test(f.mimeType));c.mid=`mid-${Md.generateRandomNumber()}`,c.msid=`${t??"-"} ${e.id}`,s||(s=[{}]);for(let f of s)f.ssrc=Md.generateRandomNumber(),d&&(f.rtx={ssrc:Md.generateRandomNumber()});c.encodings=s,c.rtcp={cname:this._cname,reducedSize:!0,mux:!0},c.msid=`${t??this._defaultSendStreamId} ${e.id}`;let u=this._nextLocalId++;return this._tracks.set(u,e),{localId:String(u),rtpParameters:c}}async stopSending(e){if(Ar.debug("stopSending() [localId:%s]",e),!this._closed){if(!this._tracks.has(Number(e)))throw new Error("local track not found");this._tracks.delete(Number(e))}}async pauseSending(e){this.assertNotClosed()}async resumeSending(e){this.assertNotClosed()}async replaceTrack(e,t){this.assertNotClosed(),t?Ar.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):Ar.debug("replaceTrack() [localId:%s, no track]",e),this._tracks.delete(Number(e)),this._tracks.set(Number(e),t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),Ar.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),Ar.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t)}async getSenderStats(e){return this.assertNotClosed(),new Map}async sendDataChannel({sctpStreamParameters:e}){this.assertNotClosed(),this._transportReady||await this.setupTransport({localDtlsRole:"server"}),Ar.debug("sendDataChannel()");let t=new z0({id:this._nextSctpStreamId++,ordered:e.ordered,maxPacketLifeTime:e.maxPacketLifeTime,maxRetransmits:e.maxRetransmits,label:e.label,protocol:e.protocol}),s={streamId:this._nextSctpStreamId,ordered:e.ordered,maxPacketLifeTime:e.maxPacketLifeTime,maxRetransmits:e.maxRetransmits};return{dataChannel:t,sctpStreamParameters:s}}async receive(e){this.assertNotClosed();let t=[];for(let s of e){let{trackId:n,kind:i}=s;this._transportReady||await this.setupTransport({localDtlsRole:"client"}),Ar.debug("receive() [trackId:%s, kind:%s]",n,i);let o=this._nextLocalId++,a=new tD.FakeMediaStreamTrack({kind:i});this._tracks.set(o,a),t.push({localId:String(o),track:a})}return t}async stopReceiving(e){if(!this._closed)for(let t of e)Ar.debug("stopReceiving() [localId:%s]",t),this._tracks.delete(Number(t))}async pauseReceiving(e){this.assertNotClosed()}async resumeReceiving(e){this.assertNotClosed()}async getReceiverStats(e){return this.assertNotClosed(),new Map}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:s}){return this.assertNotClosed(),this._transportReady||await this.setupTransport({localDtlsRole:"client"}),Ar.debug("receiveDataChannel()"),{dataChannel:new z0({id:e.streamId,ordered:e.ordered,maxPacketLifeTime:e.maxPacketLifeTime,maxRetransmits:e.maxRetransmits,label:t,protocol:s})}}getDataChannelMaxMessageSize(){return 5e5}async setupTransport({localDtlsRole:e,localSdpObject:t}){let s=Md.clone(this._fakeParameters.generateLocalDtlsParameters());e&&(s.role=e),this.emit("@connectionstatechange","connecting"),await new Promise((n,i)=>this.emit("@connect",{dtlsParameters:s},n,i)),this._transportReady=!0}assertNotClosed(){if(this._closed)throw new t6.InvalidStateError("method called in a closed handler")}};$0.FakeHandler=Rb;var z0=class extends nD.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:e,ordered:t=!0,maxPacketLifeTime:s=null,maxRetransmits:n=null,label:i="",protocol:o=""}){super(),Ar.debug(`constructor() [id:${e}, ordered:${t}, maxPacketLifeTime:${s}, maxRetransmits:${n}, label:${i}, protocol:${o}`),this._id=e,this._ordered=t,this._maxPacketLifeTime=s,this._maxRetransmits=n,this._label=i,this._protocol=o}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(e){this._bufferedAmountLowThreshold=e}get binaryType(){return this._binaryType}set binaryType(e){this._binaryType=e}get onopen(){return this._onopen}set onopen(e){this._onopen&&this.removeEventListener("open",this._onopen),this._onopen=e,e&&this.addEventListener("open",e)}get onclosing(){return this._onclosing}set onclosing(e){this._onclosing&&this.removeEventListener("closing",this._onclosing),this._onclosing=e,e&&this.addEventListener("closing",e)}get onclose(){return this._onclose}set onclose(e){this._onclose&&this.removeEventListener("close",this._onclose),this._onclose=e,e&&this.addEventListener("close",e)}get onmessage(){return this._onmessage}set onmessage(e){this._onmessage&&this.removeEventListener("message",this._onmessage),this._onmessage=e,e&&this.addEventListener("message",e)}get onbufferedamountlow(){return this._onbufferedamountlow}set onbufferedamountlow(e){this._onbufferedamountlow&&this.removeEventListener("bufferedamountlow",this._onbufferedamountlow),this._onbufferedamountlow=e,e&&this.addEventListener("bufferedamountlow",e)}get onerror(){return this._onerror}set onerror(e){this._onerror&&this.removeEventListener("error",this._onerror),this._onerror=e,e&&this.addEventListener("error",e)}addEventListener(e,t,s){super.addEventListener(e,t,s)}removeEventListener(e,t,s){super.removeEventListener(e,t,s)}close(){["closing","closed"].includes(this._readyState)||(this._readyState="closed")}send(e){if(this._readyState!=="open")throw new t6.InvalidStateError("not open")}}});var s6=re(sn=>{"use strict";Object.defineProperty(sn,"__esModule",{value:!0});sn.generateRouterRtpCapabilities=iD;sn.generateNativeRtpCapabilities=oD;sn.generateNativeSctpCapabilities=aD;sn.generateLocalDtlsParameters=cD;sn.generateTransportRemoteParameters=dD;sn.generateProducerRemoteParameters=uD;sn.generateConsumerRemoteParameters=fD;sn.generateDataProducerRemoteParameters=lD;sn.generateDataConsumerRemoteParameters=hD;var Qr=ka();function _s(){return String(Qr.generateRandomNumber())}function iD(){return Qr.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 oD(){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 aD(){return Qr.deepFreeze({numStreams:{OS:2048,MIS:2048}})}function cD(){return Qr.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 dD(){return{id:_s(),iceParameters:Qr.deepFreeze({iceLite:!0,password:"yku5ej8nvfaor28lvtrabcx0wkrpkztz",usernameFragment:"h3hk1iz6qqlnqlne"}),iceCandidates:Qr.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:Qr.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:Qr.deepFreeze({port:5e3,OS:2048,MIS:2048,maxMessageSize:2e6})}}function uD(){return Qr.deepFreeze({id:_s()})}function fD({id:r,codecMimeType:e}={}){switch(e){case"audio/opus":return{id:r??_s(),producerId:_s(),kind:"audio",rtpParameters:Qr.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:r??_s(),producerId:_s(),kind:"audio",rtpParameters:Qr.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:r??_s(),producerId:_s(),kind:"video",rtpParameters:Qr.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:r??_s(),producerId:_s(),kind:"video",rtpParameters:Qr.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 '${e}'`)}}function lD(){return Qr.deepFreeze({id:_s()})}function hD({id:r}={}){return{id:r??_s(),dataProducerId:_s(),sctpStreamParameters:Qr.deepFreeze({streamId:666,maxPacketLifeTime:5e3,maxRetransmits:void 0})}}});var ub=re(Qt=>{"use strict";Object.defineProperty(Qt,"__esModule",{value:!0});Qt.debug=Qt.testFakeParameters=Qt.FakeHandler=Qt.enhancedEvents=Qt.ortc=Qt.parseScalabilityMode=Qt.detectDeviceAsync=Qt.detectDevice=Qt.Device=Qt.version=Qt.types=void 0;var pD=Cf();Qt.debug=pD.default;Qt.types=IE();Qt.version="3.20.0";var kb=VC();Object.defineProperty(Qt,"Device",{enumerable:!0,get:function(){return kb.Device}});Object.defineProperty(Qt,"detectDevice",{enumerable:!0,get:function(){return kb.detectDevice}});Object.defineProperty(Qt,"detectDeviceAsync",{enumerable:!0,get:function(){return kb.detectDeviceAsync}});var mD=Oa();Object.defineProperty(Qt,"parseScalabilityMode",{enumerable:!0,get:function(){return mD.parse}});Qt.ortc=Rn();Qt.enhancedEvents=as();var gD=r6();Object.defineProperty(Qt,"FakeHandler",{enumerable:!0,get:function(){return gD.FakeHandler}});Qt.testFakeParameters=s6()});var i6=re((jK,Pb)=>{"use strict";var yD=Object.prototype.hasOwnProperty,Zr="~";function Ff(){}Object.create&&(Ff.prototype=Object.create(null),new Ff().__proto__||(Zr=!1));function xD(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function n6(r,e,t,s,n){if(typeof t!="function")throw new TypeError("The listener must be a function");var i=new xD(t,s||r,n),o=Zr?Zr+e:e;return r._events[o]?r._events[o].fn?r._events[o]=[r._events[o],i]:r._events[o].push(i):(r._events[o]=i,r._eventsCount++),r}function V0(r,e){--r._eventsCount===0?r._events=new Ff:delete r._events[e]}function qr(){this._events=new Ff,this._eventsCount=0}qr.prototype.eventNames=function(){var e=[],t,s;if(this._eventsCount===0)return e;for(s in t=this._events)yD.call(t,s)&&e.push(Zr?s.slice(1):s);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};qr.prototype.listeners=function(e){var t=Zr?Zr+e:e,s=this._events[t];if(!s)return[];if(s.fn)return[s.fn];for(var n=0,i=s.length,o=new Array(i);n<i;n++)o[n]=s[n].fn;return o};qr.prototype.listenerCount=function(e){var t=Zr?Zr+e:e,s=this._events[t];return s?s.fn?1:s.length:0};qr.prototype.emit=function(e,t,s,n,i,o){var a=Zr?Zr+e:e;if(!this._events[a])return!1;var c=this._events[a],d=arguments.length,u,f;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),d){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,s),!0;case 4:return c.fn.call(c.context,t,s,n),!0;case 5:return c.fn.call(c.context,t,s,n,i),!0;case 6:return c.fn.call(c.context,t,s,n,i,o),!0}for(f=1,u=new Array(d-1);f<d;f++)u[f-1]=arguments[f];c.fn.apply(c.context,u)}else{var h=c.length,y;for(f=0;f<h;f++)switch(c[f].once&&this.removeListener(e,c[f].fn,void 0,!0),d){case 1:c[f].fn.call(c[f].context);break;case 2:c[f].fn.call(c[f].context,t);break;case 3:c[f].fn.call(c[f].context,t,s);break;case 4:c[f].fn.call(c[f].context,t,s,n);break;default:if(!u)for(y=1,u=new Array(d-1);y<d;y++)u[y-1]=arguments[y];c[f].fn.apply(c[f].context,u)}}return!0};qr.prototype.on=function(e,t,s){return n6(this,e,t,s,!1)};qr.prototype.once=function(e,t,s){return n6(this,e,t,s,!0)};qr.prototype.removeListener=function(e,t,s,n){var i=Zr?Zr+e:e;if(!this._events[i])return this;if(!t)return V0(this,i),this;var o=this._events[i];if(o.fn)o.fn===t&&(!n||o.once)&&(!s||o.context===s)&&V0(this,i);else{for(var a=0,c=[],d=o.length;a<d;a++)(o[a].fn!==t||n&&!o[a].once||s&&o[a].context!==s)&&c.push(o[a]);c.length?this._events[i]=c.length===1?c[0]:c:V0(this,i)}return this};qr.prototype.removeAllListeners=function(e){var t;return e?(t=Zr?Zr+e:e,this._events[t]&&V0(this,t)):(this._events=new Ff,this._eventsCount=0),this};qr.prototype.off=qr.prototype.removeListener;qr.prototype.addListener=qr.prototype.on;qr.prefixed=Zr;qr.EventEmitter=qr;typeof Pb<"u"&&(Pb.exports=qr)});var wo=re(o6=>{"use strict";function bD(){var r,e=!1,t=this;t._DeArray=function(s,n,i){return[s.slice(n,n+i)]},t._EnArray=function(s,n,i,o){for(var a=0;a<i;s[n+a]=o[a]?o[a]:0,a++);},t._DeChar=function(s,n){return String.fromCharCode(s[n])},t._EnChar=function(s,n,i){s[n]=i.charCodeAt(0)},t._DeInt=function(s,n){var i=e?r.len-1:0,o=e?-1:1,a=i+o*r.len,c,d,u;for(c=0,d=i,u=1;d!=a;c+=s[n+d]*u,d+=o,u*=256);return r.bSigned&&c&Math.pow(2,r.len*8-1)&&(c-=Math.pow(2,r.len*8)),c},t._EnInt=function(s,n,i){var o=e?r.len-1:0,a=e?-1:1,c=o+a*r.len,d;for(i=i<r.min?r.min:i>r.max?r.max:i,d=o;d!=c;s[n+d]=i&255,d+=a,i>>=8);},t._DeString=function(s,n,i){for(var o=new Array(i),a=0;a<i;o[a]=String.fromCharCode(s[n+a]),a++);return o.join("")},t._EnString=function(s,n,i,o){for(var a,c=0;c<i;s[n+c]=(a=o.charCodeAt(c))?a:0,c++);},t._De754=function(s,n){var i,o,a,c,d,u,f,h,y,v;for(f=r.mLen,h=r.len*8-r.mLen-1,v=(1<<h)-1,y=v>>1,c=e?0:r.len-1,d=e?1:-1,i=s[n+c],c+=d,u=-7,o=i&(1<<-u)-1,i>>=-u,u+=h;u>0;o=o*256+s[n+c],c+=d,u-=8);for(a=o&(1<<-u)-1,o>>=-u,u+=f;u>0;a=a*256+s[n+c],c+=d,u-=8);switch(o){case 0:o=1-y;break;case v:return a?NaN:(i?-1:1)*(1/0);default:a=a+Math.pow(2,f),o=o-y;break}return(i?-1:1)*a*Math.pow(2,o-f)},t._En754=function(s,n,i){var o,a,c,d,u,f,h,y,v,S;for(h=r.mLen,y=r.len*8-r.mLen-1,S=(1<<y)-1,v=S>>1,o=i<0?1:0,i=Math.abs(i),isNaN(i)||i==1/0?(c=isNaN(i)?1:0,a=S):(a=Math.floor(Math.log(i)/Math.LN2),i*(f=Math.pow(2,-a))<1&&(a--,f*=2),a+v>=1?i+=r.rt/f:i+=r.rt*Math.pow(2,1-v),i*f>=2&&(a++,f/=2),a+v>=S?(c=0,a=S):a+v>=1?(c=(i*f-1)*Math.pow(2,h),a=a+v):(c=i*Math.pow(2,v-1)*Math.pow(2,h),a=0)),d=e?r.len-1:0,u=e?-1:1;h>=8;s[n+d]=c&255,d+=u,c/=256,h-=8);for(a=a<<h|c,y+=h;y>0;s[n+d]=a&255,d+=u,a/=256,y-=8);s[n+d-u]|=o*128},t._DeInt64=function(s,n){var i=e?0:7,o=e?1:-1,a=i+o*8,c=[0,0,!r.bSigned],d,u,f;for(d=i,f=1,u=0;d!=a;c[f]=(c[f]<<8>>>0)+s[n+d],d+=o,u++,f=u<4?1:0);return c},t._EnInt64=function(s,n,i){var o=e?0:7,a=e?1:-1,c=o+a*8,d,u,f,h;for(d=o,f=1,u=0,h=24;d!=c;s[n+d]=i[f]>>h&255,d+=a,u++,f=u<4?1:0,h=24-8*(u%4));},t._sPattern="(\\d + )?([AxcbBhHsfdiIlLqQ])",t._lenLut={A:1,x:1,c:1,b:1,B:1,h:2,H:2,s:1,f:4,d:8,i:4,I:4,l:4,L:4,q:8,Q:8},t._elLut={A:{en:t._EnArray,de:t._DeArray},s:{en:t._EnString,de:t._DeString},c:{en:t._EnChar,de:t._DeChar},b:{en:t._EnInt,de:t._DeInt,len:1,bSigned:!0,min:-Math.pow(2,7),max:Math.pow(2,7)-1},B:{en:t._EnInt,de:t._DeInt,len:1,bSigned:!1,min:0,max:Math.pow(2,8)-1},h:{en:t._EnInt,de:t._DeInt,len:2,bSigned:!0,min:-Math.pow(2,15),max:Math.pow(2,15)-1},H:{en:t._EnInt,de:t._DeInt,len:2,bSigned:!1,min:0,max:Math.pow(2,16)-1},i:{en:t._EnInt,de:t._DeInt,len:4,bSigned:!0,min:-Math.pow(2,31),max:Math.pow(2,31)-1},I:{en:t._EnInt,de:t._DeInt,len:4,bSigned:!1,min:0,max:Math.pow(2,32)-1},l:{en:t._EnInt,de:t._DeInt,len:4,bSigned:!0,min:-Math.pow(2,31),max:Math.pow(2,31)-1},L:{en:t._EnInt,de:t._DeInt,len:4,bSigned:!1,min:0,max:Math.pow(2,32)-1},f:{en:t._En754,de:t._De754,len:4,mLen:23,rt:Math.pow(2,-24)-Math.pow(2,-77)},d:{en:t._En754,de:t._De754,len:8,mLen:52,rt:0},q:{en:t._EnInt64,de:t._DeInt64,bSigned:!0},Q:{en:t._EnInt64,de:t._DeInt64,bSigned:!1}},t._UnpackSeries=function(s,n,i,o){for(var a=r.de,c=[],d=0;d<s;c.push(a(i,o+d*n)),d++);return c},t._PackSeries=function(s,n,i,o,a,c){for(var d=r.en,u=0;u<s;d(i,o+u*n,a[c+u]),u++);},t.Unpack=function(s,n,i){e=s.charAt(0)!="<",i=i||0;for(var o=new RegExp(this._sPattern,"g"),a,c,d,u=[];a=o.exec(s);){if(c=a[1]==null||a[1]==""?1:parseInt(a[1]),d=this._lenLut[a[2]],i+c*d>n.length)return;switch(a[2]){case"A":case"s":u.push(this._elLut[a[2]].de(n,i,c));break;case"c":case"b":case"B":case"h":case"H":case"i":case"I":case"l":case"L":case"f":case"d":case"q":case"Q":r=this._elLut[a[2]],u.push(this._UnpackSeries(c,d,n,i));break}i+=c*d}return Array.prototype.concat.apply([],u)},t.PackTo=function(s,n,i,o){e=s.charAt(0)!="<";for(var a=new RegExp(this._sPattern,"g"),c,d,u,f,h=0;c=a.exec(s);){if(d=c[1]==null||c[1]==""?1:parseInt(c[1]),u=this._lenLut[c[2]],i+d*u>n.length)return!1;switch(c[2]){case"A":case"s":if(h+1>o.length)return!1;this._elLut[c[2]].en(n,i,d,o[h]),h+=1;break;case"c":case"b":case"B":case"h":case"H":case"i":case"I":case"l":case"L":case"f":case"d":case"q":case"Q":if(r=this._elLut[c[2]],h+d>o.length)return!1;this._PackSeries(d,u,n,i,o,h),h+=d;break;case"x":for(f=0;f<d;f++)n[i+f]=0;break}i+=d*u}return n},t.Pack=function(s,n){return this.PackTo(s,new Array(this.CalcLength(s)),0,n)},t.CalcLength=function(s){for(var n=new RegExp(this._sPattern,"g"),i=0,o;o=n.exec(s);)i+=(o[1]==null||o[1]==""?1:parseInt(o[1]))*this._lenLut[o[2]];return i}}o6.jspack=new bD});var Nb=re((qK,a6)=>{"use strict";function vD(r){t.debug=t,t.default=t,t.coerce=c,t.disable=o,t.enable=n,t.enabled=a,t.humanize=Px(),t.destroy=d,Object.keys(r).forEach(u=>{t[u]=r[u]}),t.names=[],t.skips=[],t.formatters={};function e(u){let f=0;for(let h=0;h<u.length;h++)f=(f<<5)-f+u.charCodeAt(h),f|=0;return t.colors[Math.abs(f)%t.colors.length]}t.selectColor=e;function t(u){let f,h=null,y,v;function S(...C){if(!S.enabled)return;let O=S,K=Number(new Date),z=K-(f||K);O.diff=z,O.prev=f,O.curr=K,f=K,C[0]=t.coerce(C[0]),typeof C[0]!="string"&&C.unshift("%O");let Q=0;C[0]=C[0].replace(/%([a-zA-Z%])/g,(se,we)=>{if(se==="%%")return"%";Q++;let me=t.formatters[we];if(typeof me=="function"){let Y=C[Q];se=me.call(O,Y),C.splice(Q,1),Q--}return se}),t.formatArgs.call(O,C),(O.log||t.log).apply(O,C)}return S.namespace=u,S.useColors=t.useColors(),S.color=t.selectColor(u),S.extend=s,S.destroy=t.destroy,Object.defineProperty(S,"enabled",{enumerable:!0,configurable:!1,get:()=>h!==null?h:(y!==t.namespaces&&(y=t.namespaces,v=t.enabled(u)),v),set:C=>{h=C}}),typeof t.init=="function"&&t.init(S),S}function s(u,f){let h=t(this.namespace+(typeof f>"u"?":":f)+u);return h.log=this.log,h}function n(u){t.save(u),t.namespaces=u,t.names=[],t.skips=[];let f=(typeof u=="string"?u:"").trim().replace(" ",",").split(",").filter(Boolean);for(let h of f)h[0]==="-"?t.skips.push(h.slice(1)):t.names.push(h)}function i(u,f){let h=0,y=0,v=-1,S=0;for(;h<u.length;)if(y<f.length&&(f[y]===u[h]||f[y]==="*"))f[y]==="*"?(v=y,S=h,y++):(h++,y++);else if(v!==-1)y=v+1,S++,h=S;else return!1;for(;y<f.length&&f[y]==="*";)y++;return y===f.length}function o(){let u=[...t.names,...t.skips.map(f=>"-"+f)].join(",");return t.enable(""),u}function a(u){for(let f of t.skips)if(i(u,f))return!1;for(let f of t.names)if(i(u,f))return!0;return!1}function c(u){return u instanceof Error?u.stack||u.message:u}function d(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.enable(t.load()),t}a6.exports=vD});var c6=re((Es,K0)=>{"use strict";Es.formatArgs=SD;Es.save=_D;Es.load=ED;Es.useColors=wD;Es.storage=CD();Es.destroy=(()=>{let r=!1;return()=>{r||(r=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();Es.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 wD(){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 r;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&&(r=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(r[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function SD(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+K0.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,s=0;r[0].replace(/%[a-zA-Z%]/g,n=>{n!=="%%"&&(t++,n==="%c"&&(s=t))}),r.splice(s,0,e)}Es.log=console.debug||console.log||(()=>{});function _D(r){try{r?Es.storage.setItem("debug",r):Es.storage.removeItem("debug")}catch{}}function ED(){let r;try{r=Es.storage.getItem("debug")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function CD(){try{return localStorage}catch{}}K0.exports=Nb()(Es);var{formatters:TD}=K0.exports;TD.j=function(r){try{return JSON.stringify(r)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var u6=re((_r,G0)=>{"use strict";var AD=require("tty"),W0=require("util");_r.init=OD;_r.log=PD;_r.formatArgs=RD;_r.save=BD;_r.load=ND;_r.useColors=ID;_r.destroy=W0.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");_r.colors=[6,2,3,4,5,1];try{let r=(Dx(),kx(Lx));r&&(r.stderr||r).level>=2&&(_r.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{}_r.inspectOpts=Object.keys(process.env).filter(r=>/^debug_/i.test(r)).reduce((r,e)=>{let t=e.substring(6).toLowerCase().replace(/_([a-z])/g,(n,i)=>i.toUpperCase()),s=process.env[e];return/^(yes|on|true|enabled)$/i.test(s)?s=!0:/^(no|off|false|disabled)$/i.test(s)?s=!1:s==="null"?s=null:s=Number(s),r[t]=s,r},{});function ID(){return"colors"in _r.inspectOpts?!!_r.inspectOpts.colors:AD.isatty(process.stderr.fd)}function RD(r){let{namespace:e,useColors:t}=this;if(t){let s=this.color,n="\x1B[3"+(s<8?s:"8;5;"+s),i=` ${n};1m${e} \x1B[0m`;r[0]=i+r[0].split(`
8
+ `).join(`
9
+ `+i),r.push(n+"m+"+G0.exports.humanize(this.diff)+"\x1B[0m")}else r[0]=kD()+e+" "+r[0]}function kD(){return _r.inspectOpts.hideDate?"":new Date().toISOString()+" "}function PD(...r){return process.stderr.write(W0.formatWithOptions(_r.inspectOpts,...r)+`
10
+ `)}function BD(r){r?process.env.DEBUG=r:delete process.env.DEBUG}function ND(){return process.env.DEBUG}function OD(r){r.inspectOpts={};let e=Object.keys(_r.inspectOpts);for(let t=0;t<e.length;t++)r.inspectOpts[e[t]]=_r.inspectOpts[e[t]]}G0.exports=Nb()(_r);var{formatters:d6}=G0.exports;d6.o=function(r){return this.inspectOpts.colors=this.useColors,W0.inspect(r,this.inspectOpts).split(`
11
+ `).map(e=>e.trim()).join(" ")};d6.O=function(r){return this.inspectOpts.colors=this.useColors,W0.inspect(r,this.inspectOpts)}});var f6=re((zK,Ob)=>{"use strict";typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?Ob.exports=c6():Ob.exports=u6()});var X0=re(Ud=>{"use strict";Object.defineProperty(Ud,"__esModule",{value:!0});var LD=require("net");function DD(r){switch(LD.isIP(r)){case 4:return Buffer.from(r.split(".").map(n=>parseInt(n,10)));case 6:let e=r.split(":"),t=Buffer.alloc(16),s=0;e[e.length-1]===""&&(e[e.length-1]="0");for(let n=0;n<e.length;n++){if(e[n]===""){n+1<e.length&&e[n+1]!==""&&(s=16-(e.length-n-1)*2);continue}t.writeUInt16BE(parseInt(e[n],16),s),s+=2}return t;default:return null}}Ud.bytesFromIP=DD;function MD(r){switch(r.length){case 4:return[r[0],r[1],r[2],r[3]].join(".");case 16:let e=[],t=-1,s=0,n=-1,i=0;for(let o=0;o<r.length;o+=2){let a=r[o]<<8|r[o+1];a===0?(s++,t===-1&&(t=e.length),s>i&&(i=s,n=t)):(t=-1,s=0),e.push(a.toString(16))}if(i>0){let o="",a=e.slice(n+i);e.length=n,e.length===0&&(o+=":"),a.length===0&&(o+=":"),e.push(o,...a)}return e.join(":");default:return""}}Ud.bytesToIP=MD;var So=Object.create(null),l6=/^[0-9.]+$/;function UD(r){return l6.test(r)&&So[r]!==""?r:So[r]==null?"":So[r]}Ud.getOID=UD;function jD(r){return!l6.test(r)&&So[r]!==""||So[r]==null?r:So[r]}Ud.getOIDName=jD;function Z(r,e){So[r]=e,So[e]=r}Z("1.2.840.113549.1.1.1","rsaEncryption");Z("1.2.840.113549.1.1.4","md5WithRsaEncryption");Z("1.2.840.113549.1.1.5","sha1WithRsaEncryption");Z("1.2.840.113549.1.1.8","mgf1");Z("1.2.840.113549.1.1.10","RSASSA-PSS");Z("1.2.840.113549.1.1.11","sha256WithRsaEncryption");Z("1.2.840.113549.1.1.12","sha384WithRsaEncryption");Z("1.2.840.113549.1.1.13","sha512WithRsaEncryption");Z("1.2.840.10045.2.1","ecEncryption");Z("1.2.840.10045.4.1","ecdsaWithSha1");Z("1.2.840.10045.4.3.2","ecdsaWithSha256");Z("1.2.840.10045.4.3.3","ecdsaWithSha384");Z("1.2.840.10045.4.3.4","ecdsaWithSha512");Z("1.2.840.10040.4.3","dsaWithSha1");Z("2.16.840.1.101.3.4.3.2","dsaWithSha256");Z("1.3.14.3.2.7","desCBC");Z("1.3.14.3.2.26","sha1");Z("2.16.840.1.101.3.4.2.1","sha256");Z("2.16.840.1.101.3.4.2.2","sha384");Z("2.16.840.1.101.3.4.2.3","sha512");Z("1.2.840.113549.2.5","md5");Z("1.3.101.110","X25519");Z("1.3.101.111","X448");Z("1.3.101.112","Ed25519");Z("1.3.101.113","Ed448");Z("1.2.840.113549.1.7.1","data");Z("1.2.840.113549.1.7.2","signedData");Z("1.2.840.113549.1.7.3","envelopedData");Z("1.2.840.113549.1.7.4","signedAndEnvelopedData");Z("1.2.840.113549.1.7.5","digestedData");Z("1.2.840.113549.1.7.6","encryptedData");Z("1.2.840.113549.1.9.1","emailAddress");Z("1.2.840.113549.1.9.2","unstructuredName");Z("1.2.840.113549.1.9.3","contentType");Z("1.2.840.113549.1.9.4","messageDigest");Z("1.2.840.113549.1.9.5","signingTime");Z("1.2.840.113549.1.9.6","counterSignature");Z("1.2.840.113549.1.9.7","challengePassword");Z("1.2.840.113549.1.9.8","unstructuredAddress");Z("1.2.840.113549.1.9.14","extensionRequest");Z("1.2.840.113549.1.9.20","friendlyName");Z("1.2.840.113549.1.9.21","localKeyId");Z("1.2.840.113549.1.9.22.1","x509Certificate");Z("1.2.840.113549.1.12.10.1.1","keyBag");Z("1.2.840.113549.1.12.10.1.2","pkcs8ShroudedKeyBag");Z("1.2.840.113549.1.12.10.1.3","certBag");Z("1.2.840.113549.1.12.10.1.4","crlBag");Z("1.2.840.113549.1.12.10.1.5","secretBag");Z("1.2.840.113549.1.12.10.1.6","safeContentsBag");Z("1.2.840.113549.1.5.13","pkcs5PBES2");Z("1.2.840.113549.1.5.12","pkcs5PBKDF2");Z("1.2.840.113549.2.7","hmacWithSha1");Z("1.2.840.113549.2.9","hmacWithSha256");Z("1.2.840.113549.2.10","hmacWithSha384");Z("1.2.840.113549.2.11","hmacWithSha512");Z("1.2.840.113549.3.7","3desCBC");Z("2.16.840.1.101.3.4.1.2","aesCBC128");Z("2.16.840.1.101.3.4.1.42","aesCBC256");Z("2.5.4.3","commonName");Z("2.5.4.5","serialName");Z("2.5.4.6","countryName");Z("2.5.4.7","localityName");Z("2.5.4.8","stateOrProvinceName");Z("2.5.4.10","organizationName");Z("2.5.4.11","organizationalUnitName");Z("2.5.4.15","businessCategory");Z("2.16.840.1.113730.1.1","nsCertType");Z("2.5.29.2","keyAttributes");Z("2.5.29.4","keyUsageRestriction");Z("2.5.29.6","subtreesConstraint");Z("2.5.29.9","subjectDirectoryAttributes");Z("2.5.29.14","subjectKeyIdentifier");Z("2.5.29.15","keyUsage");Z("2.5.29.16","privateKeyUsagePeriod");Z("2.5.29.17","subjectAltName");Z("2.5.29.18","issuerAltName");Z("2.5.29.19","basicConstraints");Z("2.5.29.20","cRLNumber");Z("2.5.29.21","cRLReason");Z("2.5.29.22","expirationDate");Z("2.5.29.23","instructionCode");Z("2.5.29.24","invalidityDate");Z("2.5.29.27","deltaCRLIndicator");Z("2.5.29.28","issuingDistributionPoint");Z("2.5.29.29","certificateIssuer");Z("2.5.29.30","nameConstraints");Z("2.5.29.31","cRLDistributionPoints");Z("2.5.29.32","certificatePolicies");Z("2.5.29.33","policyMappings");Z("2.5.29.35","authorityKeyIdentifier");Z("2.5.29.36","policyConstraints");Z("2.5.29.37","extKeyUsage");Z("2.5.29.46","freshestCRL");Z("2.5.29.54","inhibitAnyPolicy");Z("1.3.6.1.4.1.311.60.2.1.2","jurisdictionST");Z("1.3.6.1.4.1.311.60.2.1.3","jurisdictionC");Z("1.3.6.1.4.1.11129.2.4.2","timestampList");Z("1.3.6.1.5.5.7.1.1","authorityInfoAccess");Z("1.3.6.1.5.5.7.3.1","serverAuth");Z("1.3.6.1.5.5.7.3.2","clientAuth");Z("1.3.6.1.5.5.7.3.3","codeSigning");Z("1.3.6.1.5.5.7.3.4","emailProtection");Z("1.3.6.1.5.5.7.3.8","timeStamping");Z("1.3.6.1.5.5.7.48.1","authorityInfoAccessOcsp");Z("1.3.6.1.5.5.7.48.2","authorityInfoAccessIssuers")});var J0=re((VK,Y0)=>{"use strict";(function(r){"use strict";var e=function(m){var b,x=new Float64Array(16);if(m)for(b=0;b<m.length;b++)x[b]=m[b];return x},t=function(){throw new Error("no PRNG")},s=new Uint8Array(16),n=new Uint8Array(32);n[0]=9;var i=e(),o=e([1]),a=e([56129,1]),c=e([30883,4953,19914,30187,55467,16705,2637,112,59544,30585,16505,36039,65139,11119,27886,20995]),d=e([61785,9906,39828,60374,45398,33411,5274,224,53552,61171,33010,6542,64743,22239,55772,9222]),u=e([54554,36645,11616,51542,42930,38181,51040,26924,56412,64982,57905,49316,21502,52590,14035,8553]),f=e([26200,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214]),h=e([41136,18958,6951,50414,58488,44335,6150,12099,55207,15867,153,11085,57099,20417,9344,11139]);function y(m,b,x,l){m[b]=x>>24&255,m[b+1]=x>>16&255,m[b+2]=x>>8&255,m[b+3]=x&255,m[b+4]=l>>24&255,m[b+5]=l>>16&255,m[b+6]=l>>8&255,m[b+7]=l&255}function v(m,b,x,l,w){var k,N=0;for(k=0;k<w;k++)N|=m[b+k]^x[l+k];return(1&N-1>>>8)-1}function S(m,b,x,l){return v(m,b,x,l,16)}function C(m,b,x,l){return v(m,b,x,l,32)}function O(m,b,x,l){for(var w=l[0]&255|(l[1]&255)<<8|(l[2]&255)<<16|(l[3]&255)<<24,k=x[0]&255|(x[1]&255)<<8|(x[2]&255)<<16|(x[3]&255)<<24,N=x[4]&255|(x[5]&255)<<8|(x[6]&255)<<16|(x[7]&255)<<24,G=x[8]&255|(x[9]&255)<<8|(x[10]&255)<<16|(x[11]&255)<<24,de=x[12]&255|(x[13]&255)<<8|(x[14]&255)<<16|(x[15]&255)<<24,Le=l[4]&255|(l[5]&255)<<8|(l[6]&255)<<16|(l[7]&255)<<24,Se=b[0]&255|(b[1]&255)<<8|(b[2]&255)<<16|(b[3]&255)<<24,Pt=b[4]&255|(b[5]&255)<<8|(b[6]&255)<<16|(b[7]&255)<<24,Ie=b[8]&255|(b[9]&255)<<8|(b[10]&255)<<16|(b[11]&255)<<24,rt=b[12]&255|(b[13]&255)<<8|(b[14]&255)<<16|(b[15]&255)<<24,nt=l[8]&255|(l[9]&255)<<8|(l[10]&255)<<16|(l[11]&255)<<24,pt=x[16]&255|(x[17]&255)<<8|(x[18]&255)<<16|(x[19]&255)<<24,lt=x[20]&255|(x[21]&255)<<8|(x[22]&255)<<16|(x[23]&255)<<24,it=x[24]&255|(x[25]&255)<<8|(x[26]&255)<<16|(x[27]&255)<<24,dt=x[28]&255|(x[29]&255)<<8|(x[30]&255)<<16|(x[31]&255)<<24,ot=l[12]&255|(l[13]&255)<<8|(l[14]&255)<<16|(l[15]&255)<<24,ke=w,qe=k,_e=N,Pe=G,Ne=de,be=Le,j=Se,H=Pt,te=Ie,W=rt,X=nt,ie=pt,Xe=lt,mt=it,yt=dt,gt=ot,E,vt=0;vt<20;vt+=2)E=ke+Xe|0,Ne^=E<<7|E>>>25,E=Ne+ke|0,te^=E<<9|E>>>23,E=te+Ne|0,Xe^=E<<13|E>>>19,E=Xe+te|0,ke^=E<<18|E>>>14,E=be+qe|0,W^=E<<7|E>>>25,E=W+be|0,mt^=E<<9|E>>>23,E=mt+W|0,qe^=E<<13|E>>>19,E=qe+mt|0,be^=E<<18|E>>>14,E=X+j|0,yt^=E<<7|E>>>25,E=yt+X|0,_e^=E<<9|E>>>23,E=_e+yt|0,j^=E<<13|E>>>19,E=j+_e|0,X^=E<<18|E>>>14,E=gt+ie|0,Pe^=E<<7|E>>>25,E=Pe+gt|0,H^=E<<9|E>>>23,E=H+Pe|0,ie^=E<<13|E>>>19,E=ie+H|0,gt^=E<<18|E>>>14,E=ke+Pe|0,qe^=E<<7|E>>>25,E=qe+ke|0,_e^=E<<9|E>>>23,E=_e+qe|0,Pe^=E<<13|E>>>19,E=Pe+_e|0,ke^=E<<18|E>>>14,E=be+Ne|0,j^=E<<7|E>>>25,E=j+be|0,H^=E<<9|E>>>23,E=H+j|0,Ne^=E<<13|E>>>19,E=Ne+H|0,be^=E<<18|E>>>14,E=X+W|0,ie^=E<<7|E>>>25,E=ie+X|0,te^=E<<9|E>>>23,E=te+ie|0,W^=E<<13|E>>>19,E=W+te|0,X^=E<<18|E>>>14,E=gt+yt|0,Xe^=E<<7|E>>>25,E=Xe+gt|0,mt^=E<<9|E>>>23,E=mt+Xe|0,yt^=E<<13|E>>>19,E=yt+mt|0,gt^=E<<18|E>>>14;ke=ke+w|0,qe=qe+k|0,_e=_e+N|0,Pe=Pe+G|0,Ne=Ne+de|0,be=be+Le|0,j=j+Se|0,H=H+Pt|0,te=te+Ie|0,W=W+rt|0,X=X+nt|0,ie=ie+pt|0,Xe=Xe+lt|0,mt=mt+it|0,yt=yt+dt|0,gt=gt+ot|0,m[0]=ke>>>0&255,m[1]=ke>>>8&255,m[2]=ke>>>16&255,m[3]=ke>>>24&255,m[4]=qe>>>0&255,m[5]=qe>>>8&255,m[6]=qe>>>16&255,m[7]=qe>>>24&255,m[8]=_e>>>0&255,m[9]=_e>>>8&255,m[10]=_e>>>16&255,m[11]=_e>>>24&255,m[12]=Pe>>>0&255,m[13]=Pe>>>8&255,m[14]=Pe>>>16&255,m[15]=Pe>>>24&255,m[16]=Ne>>>0&255,m[17]=Ne>>>8&255,m[18]=Ne>>>16&255,m[19]=Ne>>>24&255,m[20]=be>>>0&255,m[21]=be>>>8&255,m[22]=be>>>16&255,m[23]=be>>>24&255,m[24]=j>>>0&255,m[25]=j>>>8&255,m[26]=j>>>16&255,m[27]=j>>>24&255,m[28]=H>>>0&255,m[29]=H>>>8&255,m[30]=H>>>16&255,m[31]=H>>>24&255,m[32]=te>>>0&255,m[33]=te>>>8&255,m[34]=te>>>16&255,m[35]=te>>>24&255,m[36]=W>>>0&255,m[37]=W>>>8&255,m[38]=W>>>16&255,m[39]=W>>>24&255,m[40]=X>>>0&255,m[41]=X>>>8&255,m[42]=X>>>16&255,m[43]=X>>>24&255,m[44]=ie>>>0&255,m[45]=ie>>>8&255,m[46]=ie>>>16&255,m[47]=ie>>>24&255,m[48]=Xe>>>0&255,m[49]=Xe>>>8&255,m[50]=Xe>>>16&255,m[51]=Xe>>>24&255,m[52]=mt>>>0&255,m[53]=mt>>>8&255,m[54]=mt>>>16&255,m[55]=mt>>>24&255,m[56]=yt>>>0&255,m[57]=yt>>>8&255,m[58]=yt>>>16&255,m[59]=yt>>>24&255,m[60]=gt>>>0&255,m[61]=gt>>>8&255,m[62]=gt>>>16&255,m[63]=gt>>>24&255}function K(m,b,x,l){for(var w=l[0]&255|(l[1]&255)<<8|(l[2]&255)<<16|(l[3]&255)<<24,k=x[0]&255|(x[1]&255)<<8|(x[2]&255)<<16|(x[3]&255)<<24,N=x[4]&255|(x[5]&255)<<8|(x[6]&255)<<16|(x[7]&255)<<24,G=x[8]&255|(x[9]&255)<<8|(x[10]&255)<<16|(x[11]&255)<<24,de=x[12]&255|(x[13]&255)<<8|(x[14]&255)<<16|(x[15]&255)<<24,Le=l[4]&255|(l[5]&255)<<8|(l[6]&255)<<16|(l[7]&255)<<24,Se=b[0]&255|(b[1]&255)<<8|(b[2]&255)<<16|(b[3]&255)<<24,Pt=b[4]&255|(b[5]&255)<<8|(b[6]&255)<<16|(b[7]&255)<<24,Ie=b[8]&255|(b[9]&255)<<8|(b[10]&255)<<16|(b[11]&255)<<24,rt=b[12]&255|(b[13]&255)<<8|(b[14]&255)<<16|(b[15]&255)<<24,nt=l[8]&255|(l[9]&255)<<8|(l[10]&255)<<16|(l[11]&255)<<24,pt=x[16]&255|(x[17]&255)<<8|(x[18]&255)<<16|(x[19]&255)<<24,lt=x[20]&255|(x[21]&255)<<8|(x[22]&255)<<16|(x[23]&255)<<24,it=x[24]&255|(x[25]&255)<<8|(x[26]&255)<<16|(x[27]&255)<<24,dt=x[28]&255|(x[29]&255)<<8|(x[30]&255)<<16|(x[31]&255)<<24,ot=l[12]&255|(l[13]&255)<<8|(l[14]&255)<<16|(l[15]&255)<<24,ke=w,qe=k,_e=N,Pe=G,Ne=de,be=Le,j=Se,H=Pt,te=Ie,W=rt,X=nt,ie=pt,Xe=lt,mt=it,yt=dt,gt=ot,E,vt=0;vt<20;vt+=2)E=ke+Xe|0,Ne^=E<<7|E>>>25,E=Ne+ke|0,te^=E<<9|E>>>23,E=te+Ne|0,Xe^=E<<13|E>>>19,E=Xe+te|0,ke^=E<<18|E>>>14,E=be+qe|0,W^=E<<7|E>>>25,E=W+be|0,mt^=E<<9|E>>>23,E=mt+W|0,qe^=E<<13|E>>>19,E=qe+mt|0,be^=E<<18|E>>>14,E=X+j|0,yt^=E<<7|E>>>25,E=yt+X|0,_e^=E<<9|E>>>23,E=_e+yt|0,j^=E<<13|E>>>19,E=j+_e|0,X^=E<<18|E>>>14,E=gt+ie|0,Pe^=E<<7|E>>>25,E=Pe+gt|0,H^=E<<9|E>>>23,E=H+Pe|0,ie^=E<<13|E>>>19,E=ie+H|0,gt^=E<<18|E>>>14,E=ke+Pe|0,qe^=E<<7|E>>>25,E=qe+ke|0,_e^=E<<9|E>>>23,E=_e+qe|0,Pe^=E<<13|E>>>19,E=Pe+_e|0,ke^=E<<18|E>>>14,E=be+Ne|0,j^=E<<7|E>>>25,E=j+be|0,H^=E<<9|E>>>23,E=H+j|0,Ne^=E<<13|E>>>19,E=Ne+H|0,be^=E<<18|E>>>14,E=X+W|0,ie^=E<<7|E>>>25,E=ie+X|0,te^=E<<9|E>>>23,E=te+ie|0,W^=E<<13|E>>>19,E=W+te|0,X^=E<<18|E>>>14,E=gt+yt|0,Xe^=E<<7|E>>>25,E=Xe+gt|0,mt^=E<<9|E>>>23,E=mt+Xe|0,yt^=E<<13|E>>>19,E=yt+mt|0,gt^=E<<18|E>>>14;m[0]=ke>>>0&255,m[1]=ke>>>8&255,m[2]=ke>>>16&255,m[3]=ke>>>24&255,m[4]=be>>>0&255,m[5]=be>>>8&255,m[6]=be>>>16&255,m[7]=be>>>24&255,m[8]=X>>>0&255,m[9]=X>>>8&255,m[10]=X>>>16&255,m[11]=X>>>24&255,m[12]=gt>>>0&255,m[13]=gt>>>8&255,m[14]=gt>>>16&255,m[15]=gt>>>24&255,m[16]=j>>>0&255,m[17]=j>>>8&255,m[18]=j>>>16&255,m[19]=j>>>24&255,m[20]=H>>>0&255,m[21]=H>>>8&255,m[22]=H>>>16&255,m[23]=H>>>24&255,m[24]=te>>>0&255,m[25]=te>>>8&255,m[26]=te>>>16&255,m[27]=te>>>24&255,m[28]=W>>>0&255,m[29]=W>>>8&255,m[30]=W>>>16&255,m[31]=W>>>24&255}function z(m,b,x,l){O(m,b,x,l)}function Q(m,b,x,l){K(m,b,x,l)}var oe=new Uint8Array([101,120,112,97,110,100,32,51,50,45,98,121,116,101,32,107]);function se(m,b,x,l,w,k,N){var G=new Uint8Array(16),de=new Uint8Array(64),Le,Se;for(Se=0;Se<16;Se++)G[Se]=0;for(Se=0;Se<8;Se++)G[Se]=k[Se];for(;w>=64;){for(z(de,G,N,oe),Se=0;Se<64;Se++)m[b+Se]=x[l+Se]^de[Se];for(Le=1,Se=8;Se<16;Se++)Le=Le+(G[Se]&255)|0,G[Se]=Le&255,Le>>>=8;w-=64,b+=64,l+=64}if(w>0)for(z(de,G,N,oe),Se=0;Se<w;Se++)m[b+Se]=x[l+Se]^de[Se];return 0}function we(m,b,x,l,w){var k=new Uint8Array(16),N=new Uint8Array(64),G,de;for(de=0;de<16;de++)k[de]=0;for(de=0;de<8;de++)k[de]=l[de];for(;x>=64;){for(z(N,k,w,oe),de=0;de<64;de++)m[b+de]=N[de];for(G=1,de=8;de<16;de++)G=G+(k[de]&255)|0,k[de]=G&255,G>>>=8;x-=64,b+=64}if(x>0)for(z(N,k,w,oe),de=0;de<x;de++)m[b+de]=N[de];return 0}function me(m,b,x,l,w){var k=new Uint8Array(32);Q(k,l,w,oe);for(var N=new Uint8Array(8),G=0;G<8;G++)N[G]=l[G+16];return we(m,b,x,N,k)}function Y(m,b,x,l,w,k,N){var G=new Uint8Array(32);Q(G,k,N,oe);for(var de=new Uint8Array(8),Le=0;Le<8;Le++)de[Le]=k[Le+16];return se(m,b,x,l,w,de,G)}var Ze=function(m){this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.leftover=0,this.fin=0;var b,x,l,w,k,N,G,de;b=m[0]&255|(m[1]&255)<<8,this.r[0]=b&8191,x=m[2]&255|(m[3]&255)<<8,this.r[1]=(b>>>13|x<<3)&8191,l=m[4]&255|(m[5]&255)<<8,this.r[2]=(x>>>10|l<<6)&7939,w=m[6]&255|(m[7]&255)<<8,this.r[3]=(l>>>7|w<<9)&8191,k=m[8]&255|(m[9]&255)<<8,this.r[4]=(w>>>4|k<<12)&255,this.r[5]=k>>>1&8190,N=m[10]&255|(m[11]&255)<<8,this.r[6]=(k>>>14|N<<2)&8191,G=m[12]&255|(m[13]&255)<<8,this.r[7]=(N>>>11|G<<5)&8065,de=m[14]&255|(m[15]&255)<<8,this.r[8]=(G>>>8|de<<8)&8191,this.r[9]=de>>>5&127,this.pad[0]=m[16]&255|(m[17]&255)<<8,this.pad[1]=m[18]&255|(m[19]&255)<<8,this.pad[2]=m[20]&255|(m[21]&255)<<8,this.pad[3]=m[22]&255|(m[23]&255)<<8,this.pad[4]=m[24]&255|(m[25]&255)<<8,this.pad[5]=m[26]&255|(m[27]&255)<<8,this.pad[6]=m[28]&255|(m[29]&255)<<8,this.pad[7]=m[30]&255|(m[31]&255)<<8};Ze.prototype.blocks=function(m,b,x){for(var l=this.fin?0:2048,w,k,N,G,de,Le,Se,Pt,Ie,rt,nt,pt,lt,it,dt,ot,ke,qe,_e,Pe=this.h[0],Ne=this.h[1],be=this.h[2],j=this.h[3],H=this.h[4],te=this.h[5],W=this.h[6],X=this.h[7],ie=this.h[8],Xe=this.h[9],mt=this.r[0],yt=this.r[1],gt=this.r[2],E=this.r[3],vt=this.r[4],Bt=this.r[5],Nt=this.r[6],bt=this.r[7],At=this.r[8],It=this.r[9];x>=16;)w=m[b+0]&255|(m[b+1]&255)<<8,Pe+=w&8191,k=m[b+2]&255|(m[b+3]&255)<<8,Ne+=(w>>>13|k<<3)&8191,N=m[b+4]&255|(m[b+5]&255)<<8,be+=(k>>>10|N<<6)&8191,G=m[b+6]&255|(m[b+7]&255)<<8,j+=(N>>>7|G<<9)&8191,de=m[b+8]&255|(m[b+9]&255)<<8,H+=(G>>>4|de<<12)&8191,te+=de>>>1&8191,Le=m[b+10]&255|(m[b+11]&255)<<8,W+=(de>>>14|Le<<2)&8191,Se=m[b+12]&255|(m[b+13]&255)<<8,X+=(Le>>>11|Se<<5)&8191,Pt=m[b+14]&255|(m[b+15]&255)<<8,ie+=(Se>>>8|Pt<<8)&8191,Xe+=Pt>>>5|l,Ie=0,rt=Ie,rt+=Pe*mt,rt+=Ne*(5*It),rt+=be*(5*At),rt+=j*(5*bt),rt+=H*(5*Nt),Ie=rt>>>13,rt&=8191,rt+=te*(5*Bt),rt+=W*(5*vt),rt+=X*(5*E),rt+=ie*(5*gt),rt+=Xe*(5*yt),Ie+=rt>>>13,rt&=8191,nt=Ie,nt+=Pe*yt,nt+=Ne*mt,nt+=be*(5*It),nt+=j*(5*At),nt+=H*(5*bt),Ie=nt>>>13,nt&=8191,nt+=te*(5*Nt),nt+=W*(5*Bt),nt+=X*(5*vt),nt+=ie*(5*E),nt+=Xe*(5*gt),Ie+=nt>>>13,nt&=8191,pt=Ie,pt+=Pe*gt,pt+=Ne*yt,pt+=be*mt,pt+=j*(5*It),pt+=H*(5*At),Ie=pt>>>13,pt&=8191,pt+=te*(5*bt),pt+=W*(5*Nt),pt+=X*(5*Bt),pt+=ie*(5*vt),pt+=Xe*(5*E),Ie+=pt>>>13,pt&=8191,lt=Ie,lt+=Pe*E,lt+=Ne*gt,lt+=be*yt,lt+=j*mt,lt+=H*(5*It),Ie=lt>>>13,lt&=8191,lt+=te*(5*At),lt+=W*(5*bt),lt+=X*(5*Nt),lt+=ie*(5*Bt),lt+=Xe*(5*vt),Ie+=lt>>>13,lt&=8191,it=Ie,it+=Pe*vt,it+=Ne*E,it+=be*gt,it+=j*yt,it+=H*mt,Ie=it>>>13,it&=8191,it+=te*(5*It),it+=W*(5*At),it+=X*(5*bt),it+=ie*(5*Nt),it+=Xe*(5*Bt),Ie+=it>>>13,it&=8191,dt=Ie,dt+=Pe*Bt,dt+=Ne*vt,dt+=be*E,dt+=j*gt,dt+=H*yt,Ie=dt>>>13,dt&=8191,dt+=te*mt,dt+=W*(5*It),dt+=X*(5*At),dt+=ie*(5*bt),dt+=Xe*(5*Nt),Ie+=dt>>>13,dt&=8191,ot=Ie,ot+=Pe*Nt,ot+=Ne*Bt,ot+=be*vt,ot+=j*E,ot+=H*gt,Ie=ot>>>13,ot&=8191,ot+=te*yt,ot+=W*mt,ot+=X*(5*It),ot+=ie*(5*At),ot+=Xe*(5*bt),Ie+=ot>>>13,ot&=8191,ke=Ie,ke+=Pe*bt,ke+=Ne*Nt,ke+=be*Bt,ke+=j*vt,ke+=H*E,Ie=ke>>>13,ke&=8191,ke+=te*gt,ke+=W*yt,ke+=X*mt,ke+=ie*(5*It),ke+=Xe*(5*At),Ie+=ke>>>13,ke&=8191,qe=Ie,qe+=Pe*At,qe+=Ne*bt,qe+=be*Nt,qe+=j*Bt,qe+=H*vt,Ie=qe>>>13,qe&=8191,qe+=te*E,qe+=W*gt,qe+=X*yt,qe+=ie*mt,qe+=Xe*(5*It),Ie+=qe>>>13,qe&=8191,_e=Ie,_e+=Pe*It,_e+=Ne*At,_e+=be*bt,_e+=j*Nt,_e+=H*Bt,Ie=_e>>>13,_e&=8191,_e+=te*vt,_e+=W*E,_e+=X*gt,_e+=ie*yt,_e+=Xe*mt,Ie+=_e>>>13,_e&=8191,Ie=(Ie<<2)+Ie|0,Ie=Ie+rt|0,rt=Ie&8191,Ie=Ie>>>13,nt+=Ie,Pe=rt,Ne=nt,be=pt,j=lt,H=it,te=dt,W=ot,X=ke,ie=qe,Xe=_e,b+=16,x-=16;this.h[0]=Pe,this.h[1]=Ne,this.h[2]=be,this.h[3]=j,this.h[4]=H,this.h[5]=te,this.h[6]=W,this.h[7]=X,this.h[8]=ie,this.h[9]=Xe},Ze.prototype.finish=function(m,b){var x=new Uint16Array(10),l,w,k,N;if(this.leftover){for(N=this.leftover,this.buffer[N++]=1;N<16;N++)this.buffer[N]=0;this.fin=1,this.blocks(this.buffer,0,16)}for(l=this.h[1]>>>13,this.h[1]&=8191,N=2;N<10;N++)this.h[N]+=l,l=this.h[N]>>>13,this.h[N]&=8191;for(this.h[0]+=l*5,l=this.h[0]>>>13,this.h[0]&=8191,this.h[1]+=l,l=this.h[1]>>>13,this.h[1]&=8191,this.h[2]+=l,x[0]=this.h[0]+5,l=x[0]>>>13,x[0]&=8191,N=1;N<10;N++)x[N]=this.h[N]+l,l=x[N]>>>13,x[N]&=8191;for(x[9]-=8192,w=(l^1)-1,N=0;N<10;N++)x[N]&=w;for(w=~w,N=0;N<10;N++)this.h[N]=this.h[N]&w|x[N];for(this.h[0]=(this.h[0]|this.h[1]<<13)&65535,this.h[1]=(this.h[1]>>>3|this.h[2]<<10)&65535,this.h[2]=(this.h[2]>>>6|this.h[3]<<7)&65535,this.h[3]=(this.h[3]>>>9|this.h[4]<<4)&65535,this.h[4]=(this.h[4]>>>12|this.h[5]<<1|this.h[6]<<14)&65535,this.h[5]=(this.h[6]>>>2|this.h[7]<<11)&65535,this.h[6]=(this.h[7]>>>5|this.h[8]<<8)&65535,this.h[7]=(this.h[8]>>>8|this.h[9]<<5)&65535,k=this.h[0]+this.pad[0],this.h[0]=k&65535,N=1;N<8;N++)k=(this.h[N]+this.pad[N]|0)+(k>>>16)|0,this.h[N]=k&65535;m[b+0]=this.h[0]>>>0&255,m[b+1]=this.h[0]>>>8&255,m[b+2]=this.h[1]>>>0&255,m[b+3]=this.h[1]>>>8&255,m[b+4]=this.h[2]>>>0&255,m[b+5]=this.h[2]>>>8&255,m[b+6]=this.h[3]>>>0&255,m[b+7]=this.h[3]>>>8&255,m[b+8]=this.h[4]>>>0&255,m[b+9]=this.h[4]>>>8&255,m[b+10]=this.h[5]>>>0&255,m[b+11]=this.h[5]>>>8&255,m[b+12]=this.h[6]>>>0&255,m[b+13]=this.h[6]>>>8&255,m[b+14]=this.h[7]>>>0&255,m[b+15]=this.h[7]>>>8&255},Ze.prototype.update=function(m,b,x){var l,w;if(this.leftover){for(w=16-this.leftover,w>x&&(w=x),l=0;l<w;l++)this.buffer[this.leftover+l]=m[b+l];if(x-=w,b+=w,this.leftover+=w,this.leftover<16)return;this.blocks(this.buffer,0,16),this.leftover=0}if(x>=16&&(w=x-x%16,this.blocks(m,b,w),b+=w,x-=w),x){for(l=0;l<x;l++)this.buffer[this.leftover+l]=m[b+l];this.leftover+=x}};function Tt(m,b,x,l,w,k){var N=new Ze(k);return N.update(x,l,w),N.finish(m,b),0}function Fe(m,b,x,l,w,k){var N=new Uint8Array(16);return Tt(N,0,x,l,w,k),S(m,b,N,0)}function V(m,b,x,l,w){var k;if(x<32)return-1;for(Y(m,0,b,0,x,l,w),Tt(m,16,m,32,x-32,m),k=0;k<16;k++)m[k]=0;return 0}function D(m,b,x,l,w){var k,N=new Uint8Array(32);if(x<32||(me(N,0,32,l,w),Fe(b,16,b,32,x-32,N)!==0))return-1;for(Y(m,0,b,0,x,l,w),k=0;k<32;k++)m[k]=0;return 0}function F(m,b){var x;for(x=0;x<16;x++)m[x]=b[x]|0}function le(m){var b,x,l=1;for(b=0;b<16;b++)x=m[b]+l+65535,l=Math.floor(x/65536),m[b]=x-l*65536;m[0]+=l-1+37*(l-1)}function Ae(m,b,x){for(var l,w=~(x-1),k=0;k<16;k++)l=w&(m[k]^b[k]),m[k]^=l,b[k]^=l}function Oe(m,b){var x,l,w,k=e(),N=e();for(x=0;x<16;x++)N[x]=b[x];for(le(N),le(N),le(N),l=0;l<2;l++){for(k[0]=N[0]-65517,x=1;x<15;x++)k[x]=N[x]-65535-(k[x-1]>>16&1),k[x-1]&=65535;k[15]=N[15]-32767-(k[14]>>16&1),w=k[15]>>16&1,k[14]&=65535,Ae(N,k,1-w)}for(x=0;x<16;x++)m[2*x]=N[x]&255,m[2*x+1]=N[x]>>8}function A(m,b){var x=new Uint8Array(32),l=new Uint8Array(32);return Oe(x,m),Oe(l,b),C(x,0,l,0)}function R(m){var b=new Uint8Array(32);return Oe(b,m),b[0]&1}function q(m,b){var x;for(x=0;x<16;x++)m[x]=b[2*x]+(b[2*x+1]<<8);m[15]&=32767}function I(m,b,x){for(var l=0;l<16;l++)m[l]=b[l]+x[l]}function L(m,b,x){for(var l=0;l<16;l++)m[l]=b[l]-x[l]}function ae(m,b,x){var l,w,k=0,N=0,G=0,de=0,Le=0,Se=0,Pt=0,Ie=0,rt=0,nt=0,pt=0,lt=0,it=0,dt=0,ot=0,ke=0,qe=0,_e=0,Pe=0,Ne=0,be=0,j=0,H=0,te=0,W=0,X=0,ie=0,Xe=0,mt=0,yt=0,gt=0,E=x[0],vt=x[1],Bt=x[2],Nt=x[3],bt=x[4],At=x[5],It=x[6],cr=x[7],Mt=x[8],rr=x[9],sr=x[10],nr=x[11],gr=x[12],jr=x[13],Hr=x[14],Fr=x[15];l=b[0],k+=l*E,N+=l*vt,G+=l*Bt,de+=l*Nt,Le+=l*bt,Se+=l*At,Pt+=l*It,Ie+=l*cr,rt+=l*Mt,nt+=l*rr,pt+=l*sr,lt+=l*nr,it+=l*gr,dt+=l*jr,ot+=l*Hr,ke+=l*Fr,l=b[1],N+=l*E,G+=l*vt,de+=l*Bt,Le+=l*Nt,Se+=l*bt,Pt+=l*At,Ie+=l*It,rt+=l*cr,nt+=l*Mt,pt+=l*rr,lt+=l*sr,it+=l*nr,dt+=l*gr,ot+=l*jr,ke+=l*Hr,qe+=l*Fr,l=b[2],G+=l*E,de+=l*vt,Le+=l*Bt,Se+=l*Nt,Pt+=l*bt,Ie+=l*At,rt+=l*It,nt+=l*cr,pt+=l*Mt,lt+=l*rr,it+=l*sr,dt+=l*nr,ot+=l*gr,ke+=l*jr,qe+=l*Hr,_e+=l*Fr,l=b[3],de+=l*E,Le+=l*vt,Se+=l*Bt,Pt+=l*Nt,Ie+=l*bt,rt+=l*At,nt+=l*It,pt+=l*cr,lt+=l*Mt,it+=l*rr,dt+=l*sr,ot+=l*nr,ke+=l*gr,qe+=l*jr,_e+=l*Hr,Pe+=l*Fr,l=b[4],Le+=l*E,Se+=l*vt,Pt+=l*Bt,Ie+=l*Nt,rt+=l*bt,nt+=l*At,pt+=l*It,lt+=l*cr,it+=l*Mt,dt+=l*rr,ot+=l*sr,ke+=l*nr,qe+=l*gr,_e+=l*jr,Pe+=l*Hr,Ne+=l*Fr,l=b[5],Se+=l*E,Pt+=l*vt,Ie+=l*Bt,rt+=l*Nt,nt+=l*bt,pt+=l*At,lt+=l*It,it+=l*cr,dt+=l*Mt,ot+=l*rr,ke+=l*sr,qe+=l*nr,_e+=l*gr,Pe+=l*jr,Ne+=l*Hr,be+=l*Fr,l=b[6],Pt+=l*E,Ie+=l*vt,rt+=l*Bt,nt+=l*Nt,pt+=l*bt,lt+=l*At,it+=l*It,dt+=l*cr,ot+=l*Mt,ke+=l*rr,qe+=l*sr,_e+=l*nr,Pe+=l*gr,Ne+=l*jr,be+=l*Hr,j+=l*Fr,l=b[7],Ie+=l*E,rt+=l*vt,nt+=l*Bt,pt+=l*Nt,lt+=l*bt,it+=l*At,dt+=l*It,ot+=l*cr,ke+=l*Mt,qe+=l*rr,_e+=l*sr,Pe+=l*nr,Ne+=l*gr,be+=l*jr,j+=l*Hr,H+=l*Fr,l=b[8],rt+=l*E,nt+=l*vt,pt+=l*Bt,lt+=l*Nt,it+=l*bt,dt+=l*At,ot+=l*It,ke+=l*cr,qe+=l*Mt,_e+=l*rr,Pe+=l*sr,Ne+=l*nr,be+=l*gr,j+=l*jr,H+=l*Hr,te+=l*Fr,l=b[9],nt+=l*E,pt+=l*vt,lt+=l*Bt,it+=l*Nt,dt+=l*bt,ot+=l*At,ke+=l*It,qe+=l*cr,_e+=l*Mt,Pe+=l*rr,Ne+=l*sr,be+=l*nr,j+=l*gr,H+=l*jr,te+=l*Hr,W+=l*Fr,l=b[10],pt+=l*E,lt+=l*vt,it+=l*Bt,dt+=l*Nt,ot+=l*bt,ke+=l*At,qe+=l*It,_e+=l*cr,Pe+=l*Mt,Ne+=l*rr,be+=l*sr,j+=l*nr,H+=l*gr,te+=l*jr,W+=l*Hr,X+=l*Fr,l=b[11],lt+=l*E,it+=l*vt,dt+=l*Bt,ot+=l*Nt,ke+=l*bt,qe+=l*At,_e+=l*It,Pe+=l*cr,Ne+=l*Mt,be+=l*rr,j+=l*sr,H+=l*nr,te+=l*gr,W+=l*jr,X+=l*Hr,ie+=l*Fr,l=b[12],it+=l*E,dt+=l*vt,ot+=l*Bt,ke+=l*Nt,qe+=l*bt,_e+=l*At,Pe+=l*It,Ne+=l*cr,be+=l*Mt,j+=l*rr,H+=l*sr,te+=l*nr,W+=l*gr,X+=l*jr,ie+=l*Hr,Xe+=l*Fr,l=b[13],dt+=l*E,ot+=l*vt,ke+=l*Bt,qe+=l*Nt,_e+=l*bt,Pe+=l*At,Ne+=l*It,be+=l*cr,j+=l*Mt,H+=l*rr,te+=l*sr,W+=l*nr,X+=l*gr,ie+=l*jr,Xe+=l*Hr,mt+=l*Fr,l=b[14],ot+=l*E,ke+=l*vt,qe+=l*Bt,_e+=l*Nt,Pe+=l*bt,Ne+=l*At,be+=l*It,j+=l*cr,H+=l*Mt,te+=l*rr,W+=l*sr,X+=l*nr,ie+=l*gr,Xe+=l*jr,mt+=l*Hr,yt+=l*Fr,l=b[15],ke+=l*E,qe+=l*vt,_e+=l*Bt,Pe+=l*Nt,Ne+=l*bt,be+=l*At,j+=l*It,H+=l*cr,te+=l*Mt,W+=l*rr,X+=l*sr,ie+=l*nr,Xe+=l*gr,mt+=l*jr,yt+=l*Hr,gt+=l*Fr,k+=38*qe,N+=38*_e,G+=38*Pe,de+=38*Ne,Le+=38*be,Se+=38*j,Pt+=38*H,Ie+=38*te,rt+=38*W,nt+=38*X,pt+=38*ie,lt+=38*Xe,it+=38*mt,dt+=38*yt,ot+=38*gt,w=1,l=k+w+65535,w=Math.floor(l/65536),k=l-w*65536,l=N+w+65535,w=Math.floor(l/65536),N=l-w*65536,l=G+w+65535,w=Math.floor(l/65536),G=l-w*65536,l=de+w+65535,w=Math.floor(l/65536),de=l-w*65536,l=Le+w+65535,w=Math.floor(l/65536),Le=l-w*65536,l=Se+w+65535,w=Math.floor(l/65536),Se=l-w*65536,l=Pt+w+65535,w=Math.floor(l/65536),Pt=l-w*65536,l=Ie+w+65535,w=Math.floor(l/65536),Ie=l-w*65536,l=rt+w+65535,w=Math.floor(l/65536),rt=l-w*65536,l=nt+w+65535,w=Math.floor(l/65536),nt=l-w*65536,l=pt+w+65535,w=Math.floor(l/65536),pt=l-w*65536,l=lt+w+65535,w=Math.floor(l/65536),lt=l-w*65536,l=it+w+65535,w=Math.floor(l/65536),it=l-w*65536,l=dt+w+65535,w=Math.floor(l/65536),dt=l-w*65536,l=ot+w+65535,w=Math.floor(l/65536),ot=l-w*65536,l=ke+w+65535,w=Math.floor(l/65536),ke=l-w*65536,k+=w-1+37*(w-1),w=1,l=k+w+65535,w=Math.floor(l/65536),k=l-w*65536,l=N+w+65535,w=Math.floor(l/65536),N=l-w*65536,l=G+w+65535,w=Math.floor(l/65536),G=l-w*65536,l=de+w+65535,w=Math.floor(l/65536),de=l-w*65536,l=Le+w+65535,w=Math.floor(l/65536),Le=l-w*65536,l=Se+w+65535,w=Math.floor(l/65536),Se=l-w*65536,l=Pt+w+65535,w=Math.floor(l/65536),Pt=l-w*65536,l=Ie+w+65535,w=Math.floor(l/65536),Ie=l-w*65536,l=rt+w+65535,w=Math.floor(l/65536),rt=l-w*65536,l=nt+w+65535,w=Math.floor(l/65536),nt=l-w*65536,l=pt+w+65535,w=Math.floor(l/65536),pt=l-w*65536,l=lt+w+65535,w=Math.floor(l/65536),lt=l-w*65536,l=it+w+65535,w=Math.floor(l/65536),it=l-w*65536,l=dt+w+65535,w=Math.floor(l/65536),dt=l-w*65536,l=ot+w+65535,w=Math.floor(l/65536),ot=l-w*65536,l=ke+w+65535,w=Math.floor(l/65536),ke=l-w*65536,k+=w-1+37*(w-1),m[0]=k,m[1]=N,m[2]=G,m[3]=de,m[4]=Le,m[5]=Se,m[6]=Pt,m[7]=Ie,m[8]=rt,m[9]=nt,m[10]=pt,m[11]=lt,m[12]=it,m[13]=dt,m[14]=ot,m[15]=ke}function he(m,b){ae(m,b,b)}function ct(m,b){var x=e(),l;for(l=0;l<16;l++)x[l]=b[l];for(l=253;l>=0;l--)he(x,x),l!==2&&l!==4&&ae(x,x,b);for(l=0;l<16;l++)m[l]=x[l]}function xt(m,b){var x=e(),l;for(l=0;l<16;l++)x[l]=b[l];for(l=250;l>=0;l--)he(x,x),l!==1&&ae(x,x,b);for(l=0;l<16;l++)m[l]=x[l]}function Ot(m,b,x){var l=new Uint8Array(32),w=new Float64Array(80),k,N,G=e(),de=e(),Le=e(),Se=e(),Pt=e(),Ie=e();for(N=0;N<31;N++)l[N]=b[N];for(l[31]=b[31]&127|64,l[0]&=248,q(w,x),N=0;N<16;N++)de[N]=w[N],Se[N]=G[N]=Le[N]=0;for(G[0]=Se[0]=1,N=254;N>=0;--N)k=l[N>>>3]>>>(N&7)&1,Ae(G,de,k),Ae(Le,Se,k),I(Pt,G,Le),L(G,G,Le),I(Le,de,Se),L(de,de,Se),he(Se,Pt),he(Ie,G),ae(G,Le,G),ae(Le,de,Pt),I(Pt,G,Le),L(G,G,Le),he(de,G),L(Le,Se,Ie),ae(G,Le,a),I(G,G,Se),ae(Le,Le,G),ae(G,Se,Ie),ae(Se,de,w),he(de,Pt),Ae(G,de,k),Ae(Le,Se,k);for(N=0;N<16;N++)w[N+16]=G[N],w[N+32]=Le[N],w[N+48]=de[N],w[N+64]=Se[N];var rt=w.subarray(32),nt=w.subarray(16);return ct(rt,rt),ae(nt,nt,rt),Oe(m,nt),0}function St(m,b){return Ot(m,b,n)}function Dt(m,b){return t(b,32),St(m,b)}function Bs(m,b,x){var l=new Uint8Array(32);return Ot(l,x,b),Q(m,s,l,oe)}var Ns=V,Ca=D;function Ax(m,b,x,l,w,k){var N=new Uint8Array(32);return Bs(N,w,k),Ns(m,b,x,l,N)}function yf(m,b,x,l,w,k){var N=new Uint8Array(32);return Bs(N,w,k),Ca(m,b,x,l,N)}var xf=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591];function bf(m,b,x,l){for(var w=new Int32Array(16),k=new Int32Array(16),N,G,de,Le,Se,Pt,Ie,rt,nt,pt,lt,it,dt,ot,ke,qe,_e,Pe,Ne,be,j,H,te,W,X,ie,Xe=m[0],mt=m[1],yt=m[2],gt=m[3],E=m[4],vt=m[5],Bt=m[6],Nt=m[7],bt=b[0],At=b[1],It=b[2],cr=b[3],Mt=b[4],rr=b[5],sr=b[6],nr=b[7],gr=0;l>=128;){for(Ne=0;Ne<16;Ne++)be=8*Ne+gr,w[Ne]=x[be+0]<<24|x[be+1]<<16|x[be+2]<<8|x[be+3],k[Ne]=x[be+4]<<24|x[be+5]<<16|x[be+6]<<8|x[be+7];for(Ne=0;Ne<80;Ne++)if(N=Xe,G=mt,de=yt,Le=gt,Se=E,Pt=vt,Ie=Bt,rt=Nt,nt=bt,pt=At,lt=It,it=cr,dt=Mt,ot=rr,ke=sr,qe=nr,j=Nt,H=nr,te=H&65535,W=H>>>16,X=j&65535,ie=j>>>16,j=(E>>>14|Mt<<18)^(E>>>18|Mt<<14)^(Mt>>>9|E<<23),H=(Mt>>>14|E<<18)^(Mt>>>18|E<<14)^(E>>>9|Mt<<23),te+=H&65535,W+=H>>>16,X+=j&65535,ie+=j>>>16,j=E&vt^~E&Bt,H=Mt&rr^~Mt&sr,te+=H&65535,W+=H>>>16,X+=j&65535,ie+=j>>>16,j=xf[Ne*2],H=xf[Ne*2+1],te+=H&65535,W+=H>>>16,X+=j&65535,ie+=j>>>16,j=w[Ne%16],H=k[Ne%16],te+=H&65535,W+=H>>>16,X+=j&65535,ie+=j>>>16,W+=te>>>16,X+=W>>>16,ie+=X>>>16,_e=X&65535|ie<<16,Pe=te&65535|W<<16,j=_e,H=Pe,te=H&65535,W=H>>>16,X=j&65535,ie=j>>>16,j=(Xe>>>28|bt<<4)^(bt>>>2|Xe<<30)^(bt>>>7|Xe<<25),H=(bt>>>28|Xe<<4)^(Xe>>>2|bt<<30)^(Xe>>>7|bt<<25),te+=H&65535,W+=H>>>16,X+=j&65535,ie+=j>>>16,j=Xe&mt^Xe&yt^mt&yt,H=bt&At^bt&It^At&It,te+=H&65535,W+=H>>>16,X+=j&65535,ie+=j>>>16,W+=te>>>16,X+=W>>>16,ie+=X>>>16,rt=X&65535|ie<<16,qe=te&65535|W<<16,j=Le,H=it,te=H&65535,W=H>>>16,X=j&65535,ie=j>>>16,j=_e,H=Pe,te+=H&65535,W+=H>>>16,X+=j&65535,ie+=j>>>16,W+=te>>>16,X+=W>>>16,ie+=X>>>16,Le=X&65535|ie<<16,it=te&65535|W<<16,mt=N,yt=G,gt=de,E=Le,vt=Se,Bt=Pt,Nt=Ie,Xe=rt,At=nt,It=pt,cr=lt,Mt=it,rr=dt,sr=ot,nr=ke,bt=qe,Ne%16===15)for(be=0;be<16;be++)j=w[be],H=k[be],te=H&65535,W=H>>>16,X=j&65535,ie=j>>>16,j=w[(be+9)%16],H=k[(be+9)%16],te+=H&65535,W+=H>>>16,X+=j&65535,ie+=j>>>16,_e=w[(be+1)%16],Pe=k[(be+1)%16],j=(_e>>>1|Pe<<31)^(_e>>>8|Pe<<24)^_e>>>7,H=(Pe>>>1|_e<<31)^(Pe>>>8|_e<<24)^(Pe>>>7|_e<<25),te+=H&65535,W+=H>>>16,X+=j&65535,ie+=j>>>16,_e=w[(be+14)%16],Pe=k[(be+14)%16],j=(_e>>>19|Pe<<13)^(Pe>>>29|_e<<3)^_e>>>6,H=(Pe>>>19|_e<<13)^(_e>>>29|Pe<<3)^(Pe>>>6|_e<<26),te+=H&65535,W+=H>>>16,X+=j&65535,ie+=j>>>16,W+=te>>>16,X+=W>>>16,ie+=X>>>16,w[be]=X&65535|ie<<16,k[be]=te&65535|W<<16;j=Xe,H=bt,te=H&65535,W=H>>>16,X=j&65535,ie=j>>>16,j=m[0],H=b[0],te+=H&65535,W+=H>>>16,X+=j&65535,ie+=j>>>16,W+=te>>>16,X+=W>>>16,ie+=X>>>16,m[0]=Xe=X&65535|ie<<16,b[0]=bt=te&65535|W<<16,j=mt,H=At,te=H&65535,W=H>>>16,X=j&65535,ie=j>>>16,j=m[1],H=b[1],te+=H&65535,W+=H>>>16,X+=j&65535,ie+=j>>>16,W+=te>>>16,X+=W>>>16,ie+=X>>>16,m[1]=mt=X&65535|ie<<16,b[1]=At=te&65535|W<<16,j=yt,H=It,te=H&65535,W=H>>>16,X=j&65535,ie=j>>>16,j=m[2],H=b[2],te+=H&65535,W+=H>>>16,X+=j&65535,ie+=j>>>16,W+=te>>>16,X+=W>>>16,ie+=X>>>16,m[2]=yt=X&65535|ie<<16,b[2]=It=te&65535|W<<16,j=gt,H=cr,te=H&65535,W=H>>>16,X=j&65535,ie=j>>>16,j=m[3],H=b[3],te+=H&65535,W+=H>>>16,X+=j&65535,ie+=j>>>16,W+=te>>>16,X+=W>>>16,ie+=X>>>16,m[3]=gt=X&65535|ie<<16,b[3]=cr=te&65535|W<<16,j=E,H=Mt,te=H&65535,W=H>>>16,X=j&65535,ie=j>>>16,j=m[4],H=b[4],te+=H&65535,W+=H>>>16,X+=j&65535,ie+=j>>>16,W+=te>>>16,X+=W>>>16,ie+=X>>>16,m[4]=E=X&65535|ie<<16,b[4]=Mt=te&65535|W<<16,j=vt,H=rr,te=H&65535,W=H>>>16,X=j&65535,ie=j>>>16,j=m[5],H=b[5],te+=H&65535,W+=H>>>16,X+=j&65535,ie+=j>>>16,W+=te>>>16,X+=W>>>16,ie+=X>>>16,m[5]=vt=X&65535|ie<<16,b[5]=rr=te&65535|W<<16,j=Bt,H=sr,te=H&65535,W=H>>>16,X=j&65535,ie=j>>>16,j=m[6],H=b[6],te+=H&65535,W+=H>>>16,X+=j&65535,ie+=j>>>16,W+=te>>>16,X+=W>>>16,ie+=X>>>16,m[6]=Bt=X&65535|ie<<16,b[6]=sr=te&65535|W<<16,j=Nt,H=nr,te=H&65535,W=H>>>16,X=j&65535,ie=j>>>16,j=m[7],H=b[7],te+=H&65535,W+=H>>>16,X+=j&65535,ie+=j>>>16,W+=te>>>16,X+=W>>>16,ie+=X>>>16,m[7]=Nt=X&65535|ie<<16,b[7]=nr=te&65535|W<<16,gr+=128,l-=128}return l}function In(m,b,x){var l=new Int32Array(8),w=new Int32Array(8),k=new Uint8Array(256),N,G=x;for(l[0]=1779033703,l[1]=3144134277,l[2]=1013904242,l[3]=2773480762,l[4]=1359893119,l[5]=2600822924,l[6]=528734635,l[7]=1541459225,w[0]=4089235720,w[1]=2227873595,w[2]=4271175723,w[3]=1595750129,w[4]=2917565137,w[5]=725511199,w[6]=4215389547,w[7]=327033209,bf(l,w,b,x),x%=128,N=0;N<x;N++)k[N]=b[G-x+N];for(k[x]=128,x=256-128*(x<112?1:0),k[x-9]=0,y(k,x-8,G/536870912|0,G<<3),bf(l,w,k,x),N=0;N<8;N++)y(m,8*N,l[N],w[N]);return 0}function Ta(m,b){var x=e(),l=e(),w=e(),k=e(),N=e(),G=e(),de=e(),Le=e(),Se=e();L(x,m[1],m[0]),L(Se,b[1],b[0]),ae(x,x,Se),I(l,m[0],m[1]),I(Se,b[0],b[1]),ae(l,l,Se),ae(w,m[3],b[3]),ae(w,w,d),ae(k,m[2],b[2]),I(k,k,k),L(N,l,x),L(G,k,w),I(de,k,w),I(Le,l,x),ae(m[0],N,G),ae(m[1],Le,de),ae(m[2],de,G),ae(m[3],N,Le)}function vf(m,b,x){var l;for(l=0;l<4;l++)Ae(m[l],b[l],x)}function Aa(m,b){var x=e(),l=e(),w=e();ct(w,b[2]),ae(x,b[0],w),ae(l,b[1],w),Oe(m,l),m[31]^=R(x)<<7}function wf(m,b,x){var l,w;for(F(m[0],i),F(m[1],o),F(m[2],o),F(m[3],i),w=255;w>=0;--w)l=x[w/8|0]>>(w&7)&1,vf(m,b,l),Ta(b,m),Ta(m,m),vf(m,b,l)}function ud(m,b){var x=[e(),e(),e(),e()];F(x[0],u),F(x[1],f),F(x[2],o),ae(x[3],u,f),wf(m,x,b)}function Sf(m,b,x){var l=new Uint8Array(64),w=[e(),e(),e(),e()],k;for(x||t(b,32),In(l,b,32),l[0]&=248,l[31]&=127,l[31]|=64,ud(w,l),Aa(m,w),k=0;k<32;k++)b[k+32]=m[k];return 0}var fd=new Float64Array([237,211,245,92,26,99,18,88,214,156,247,162,222,249,222,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16]);function xi(m,b){var x,l,w,k;for(l=63;l>=32;--l){for(x=0,w=l-32,k=l-12;w<k;++w)b[w]+=x-16*b[l]*fd[w-(l-32)],x=Math.floor((b[w]+128)/256),b[w]-=x*256;b[w]+=x,b[l]=0}for(x=0,w=0;w<32;w++)b[w]+=x-(b[31]>>4)*fd[w],x=b[w]>>8,b[w]&=255;for(w=0;w<32;w++)b[w]-=x*fd[w];for(l=0;l<32;l++)b[l+1]+=b[l]>>8,m[l]=b[l]&255}function _f(m){var b=new Float64Array(64),x;for(x=0;x<64;x++)b[x]=m[x];for(x=0;x<64;x++)m[x]=0;xi(m,b)}function r0(m,b,x,l){var w=new Uint8Array(64),k=new Uint8Array(64),N=new Uint8Array(64),G,de,Le=new Float64Array(64),Se=[e(),e(),e(),e()];In(w,l,32),w[0]&=248,w[31]&=127,w[31]|=64;var Pt=x+64;for(G=0;G<x;G++)m[64+G]=b[G];for(G=0;G<32;G++)m[32+G]=w[32+G];for(In(N,m.subarray(32),x+32),_f(N),ud(Se,N),Aa(m,Se),G=32;G<64;G++)m[G]=l[G];for(In(k,m,x+64),_f(k),G=0;G<64;G++)Le[G]=0;for(G=0;G<32;G++)Le[G]=N[G];for(G=0;G<32;G++)for(de=0;de<32;de++)Le[G+de]+=k[G]*w[de];return xi(m.subarray(32),Le),Pt}function Ix(m,b){var x=e(),l=e(),w=e(),k=e(),N=e(),G=e(),de=e();return F(m[2],o),q(m[1],b),he(w,m[1]),ae(k,w,c),L(w,w,m[2]),I(k,m[2],k),he(N,k),he(G,N),ae(de,G,N),ae(x,de,w),ae(x,x,k),xt(x,x),ae(x,x,w),ae(x,x,k),ae(x,x,k),ae(m[0],x,k),he(l,m[0]),ae(l,l,k),A(l,w)&&ae(m[0],m[0],h),he(l,m[0]),ae(l,l,k),A(l,w)?-1:(R(m[0])===b[31]>>7&&L(m[0],i,m[0]),ae(m[3],m[0],m[1]),0)}function Ia(m,b,x,l){var w,k=new Uint8Array(32),N=new Uint8Array(64),G=[e(),e(),e(),e()],de=[e(),e(),e(),e()];if(x<64||Ix(de,l))return-1;for(w=0;w<x;w++)m[w]=b[w];for(w=0;w<32;w++)m[w+32]=l[w];if(In(N,m,x),_f(N),wf(G,de,N),ud(de,b.subarray(32)),Ta(G,de),Aa(k,G),x-=64,C(b,0,k,0)){for(w=0;w<x;w++)m[w]=0;return-1}for(w=0;w<x;w++)m[w]=b[w+64];return x}var P=32,M=24,$=32,ce=16,Me=32,$t=32,Wt=32,ft=32,ge=32,Ee=M,Re=$,Be=ce,st=64,kt=32,jt=64,Xr=32,ld=64;r.lowlevel={crypto_core_hsalsa20:Q,crypto_stream_xor:Y,crypto_stream:me,crypto_stream_salsa20_xor:se,crypto_stream_salsa20:we,crypto_onetimeauth:Tt,crypto_onetimeauth_verify:Fe,crypto_verify_16:S,crypto_verify_32:C,crypto_secretbox:V,crypto_secretbox_open:D,crypto_scalarmult:Ot,crypto_scalarmult_base:St,crypto_box_beforenm:Bs,crypto_box_afternm:Ns,crypto_box:Ax,crypto_box_open:yf,crypto_box_keypair:Dt,crypto_hash:In,crypto_sign:r0,crypto_sign_keypair:Sf,crypto_sign_open:Ia,crypto_secretbox_KEYBYTES:P,crypto_secretbox_NONCEBYTES:M,crypto_secretbox_ZEROBYTES:$,crypto_secretbox_BOXZEROBYTES:ce,crypto_scalarmult_BYTES:Me,crypto_scalarmult_SCALARBYTES:$t,crypto_box_PUBLICKEYBYTES:Wt,crypto_box_SECRETKEYBYTES:ft,crypto_box_BEFORENMBYTES:ge,crypto_box_NONCEBYTES:Ee,crypto_box_ZEROBYTES:Re,crypto_box_BOXZEROBYTES:Be,crypto_sign_BYTES:st,crypto_sign_PUBLICKEYBYTES:kt,crypto_sign_SECRETKEYBYTES:jt,crypto_sign_SEEDBYTES:Xr,crypto_hash_BYTES:ld,gf:e,D:c,L:fd,pack25519:Oe,unpack25519:q,M:ae,A:I,S:he,Z:L,pow2523:xt,add:Ta,set25519:F,modL:xi,scalarmult:wf,scalarbase:ud};function s0(m,b){if(m.length!==P)throw new Error("bad key size");if(b.length!==M)throw new Error("bad nonce size")}function Rx(m,b){if(m.length!==Wt)throw new Error("bad public key size");if(b.length!==ft)throw new Error("bad secret key size")}function ws(){for(var m=0;m<arguments.length;m++)if(!(arguments[m]instanceof Uint8Array))throw new TypeError("unexpected type, use Uint8Array")}function bE(m){for(var b=0;b<m.length;b++)m[b]=0}r.randomBytes=function(m){var b=new Uint8Array(m);return t(b,m),b},r.secretbox=function(m,b,x){ws(m,b,x),s0(x,b);for(var l=new Uint8Array($+m.length),w=new Uint8Array(l.length),k=0;k<m.length;k++)l[k+$]=m[k];return V(w,l,l.length,b,x),w.subarray(ce)},r.secretbox.open=function(m,b,x){ws(m,b,x),s0(x,b);for(var l=new Uint8Array(ce+m.length),w=new Uint8Array(l.length),k=0;k<m.length;k++)l[k+ce]=m[k];return l.length<32||D(w,l,l.length,b,x)!==0?null:w.subarray($)},r.secretbox.keyLength=P,r.secretbox.nonceLength=M,r.secretbox.overheadLength=ce,r.scalarMult=function(m,b){if(ws(m,b),m.length!==$t)throw new Error("bad n size");if(b.length!==Me)throw new Error("bad p size");var x=new Uint8Array(Me);return Ot(x,m,b),x},r.scalarMult.base=function(m){if(ws(m),m.length!==$t)throw new Error("bad n size");var b=new Uint8Array(Me);return St(b,m),b},r.scalarMult.scalarLength=$t,r.scalarMult.groupElementLength=Me,r.box=function(m,b,x,l){var w=r.box.before(x,l);return r.secretbox(m,b,w)},r.box.before=function(m,b){ws(m,b),Rx(m,b);var x=new Uint8Array(ge);return Bs(x,m,b),x},r.box.after=r.secretbox,r.box.open=function(m,b,x,l){var w=r.box.before(x,l);return r.secretbox.open(m,b,w)},r.box.open.after=r.secretbox.open,r.box.keyPair=function(){var m=new Uint8Array(Wt),b=new Uint8Array(ft);return Dt(m,b),{publicKey:m,secretKey:b}},r.box.keyPair.fromSecretKey=function(m){if(ws(m),m.length!==ft)throw new Error("bad secret key size");var b=new Uint8Array(Wt);return St(b,m),{publicKey:b,secretKey:new Uint8Array(m)}},r.box.publicKeyLength=Wt,r.box.secretKeyLength=ft,r.box.sharedKeyLength=ge,r.box.nonceLength=Ee,r.box.overheadLength=r.secretbox.overheadLength,r.sign=function(m,b){if(ws(m,b),b.length!==jt)throw new Error("bad secret key size");var x=new Uint8Array(st+m.length);return r0(x,m,m.length,b),x},r.sign.open=function(m,b){if(ws(m,b),b.length!==kt)throw new Error("bad public key size");var x=new Uint8Array(m.length),l=Ia(x,m,m.length,b);if(l<0)return null;for(var w=new Uint8Array(l),k=0;k<w.length;k++)w[k]=x[k];return w},r.sign.detached=function(m,b){for(var x=r.sign(m,b),l=new Uint8Array(st),w=0;w<l.length;w++)l[w]=x[w];return l},r.sign.detached.verify=function(m,b,x){if(ws(m,b,x),b.length!==st)throw new Error("bad signature size");if(x.length!==kt)throw new Error("bad public key size");var l=new Uint8Array(st+m.length),w=new Uint8Array(st+m.length),k;for(k=0;k<st;k++)l[k]=b[k];for(k=0;k<m.length;k++)l[k+st]=m[k];return Ia(w,l,l.length,x)>=0},r.sign.keyPair=function(){var m=new Uint8Array(kt),b=new Uint8Array(jt);return Sf(m,b),{publicKey:m,secretKey:b}},r.sign.keyPair.fromSecretKey=function(m){if(ws(m),m.length!==jt)throw new Error("bad secret key size");for(var b=new Uint8Array(kt),x=0;x<b.length;x++)b[x]=m[32+x];return{publicKey:b,secretKey:new Uint8Array(m)}},r.sign.keyPair.fromSeed=function(m){if(ws(m),m.length!==Xr)throw new Error("bad seed size");for(var b=new Uint8Array(kt),x=new Uint8Array(jt),l=0;l<32;l++)x[l]=m[l];return Sf(b,x,!0),{publicKey:b,secretKey:x}},r.sign.publicKeyLength=kt,r.sign.secretKeyLength=jt,r.sign.seedLength=Xr,r.sign.signatureLength=st,r.hash=function(m){ws(m);var b=new Uint8Array(ld);return In(b,m,m.length),b},r.hash.hashLength=ld,r.verify=function(m,b){return ws(m,b),m.length===0||b.length===0||m.length!==b.length?!1:v(m,0,b,0,m.length)===0},r.setPRNG=function(m){t=m},(function(){var m=typeof self<"u"?self.crypto||self.msCrypto:null;if(m&&m.getRandomValues){var b=65536;r.setPRNG(function(x,l){var w,k=new Uint8Array(l);for(w=0;w<l;w+=b)m.getRandomValues(k.subarray(w,w+Math.min(l-w,b)));for(w=0;w<l;w++)x[w]=k[w];bE(k)})}else typeof require<"u"&&(m=require("crypto"),m&&m.randomBytes&&r.setPRNG(function(x,l){var w,k=m.randomBytes(l);for(w=0;w<l;w++)x[w]=k[w];bE(k)}))})()})(typeof Y0<"u"&&Y0.exports?Y0.exports:self.nacl=self.nacl||{})});var Mb=re(Db=>{"use strict";Object.defineProperty(Db,"__esModule",{value:!0});var Lb=class{constructor(e,t=0,s=0){this.start=t,this.end=s>t?s:t,this.buf=e}get length(){return this.buf.length}reset(e=0,t=0){return this.start=e,t>=this.start?this.end=t:this.end<this.start&&(this.end=this.start),this}walk(e){return this.start=this.end,this.end+=e,this}mustHas(e,t="Too few bytes to parse."){let s=this.end+e;if(s>this.buf.length){let n=new Error(t);throw n.available=this.buf.length,n.requested=s,n}return this.walk(0),this}mustWalk(e,t){return this.mustHas(e,t),this.walk(e),this}};Db.BufferVisitor=Lb});var m6=re(Fb=>{"use strict";Object.defineProperty(Fb,"__esModule",{value:!0});var h6=require("util"),p6=64,jb="-----BEGIN ",Hb="-----END ",qf="-----",Ub="Proc-Type",Q0=class{static parse(e){let t=[],s=e.toString("utf8").split(`
12
+ `).map(n=>n.trim()).filter(n=>n!==""&&!n.startsWith("#"));for(;s.length>0;)t.push(HD(s));if(t.length===0)throw new Error("PEM: no block");return t}constructor(e,t){this.type=e,this.body=t,this.headers=Object.create(null)}get procType(){return this.getHeader(Ub)}getHeader(e){let t=this.headers[e];return t??""}setHeader(e,t){if(e.includes(":"))throw new Error("pem: cannot encode a header key that contains a colon");if(e===""||t==="")throw new Error("pem: invalid header key or value");this.headers[e]=t}toString(){let e=jb+this.type+qf+`
13
+ `,t=Object.keys(this.headers);if(t.length>0){let i=this.procType;i!==""&&(e+=`${Ub}: ${i}
14
+ `),t.sort();for(let o of t)o!==Ub&&(e+=`${o}: ${this.headers[o]}
15
+ `);e+=`
16
+ `}let s=this.body.toString("base64"),n=0;for(;n<s.length;)e+=s.slice(n,n+p6)+`
17
+ `,n+=p6;return e+=Hb+this.type+qf+`
18
+ `,e}toBuffer(){return Buffer.from(this.toString(),"utf8")}valueOf(){return this.body}toJSON(){return{type:this.type,body:this.body,headers:this.headers}}[h6.inspect.custom](e,t){return`<${this.constructor.name} ${h6.inspect(this.toJSON(),t)}>`}};Fb.PEM=Q0;function HD(r){let e=r.shift();if(e==null||!e.startsWith(jb)||!e.endsWith(qf))throw new Error("pem: invalid BEGIN line");let t=e.slice(jb.length,e.length-qf.length);if(t==="")throw new Error("pem: invalid type");let s=[];for(e=r.shift();e!=null&&e.includes(": ");){let o=e.split(": ");if(o.length!==2||o[0]===""||o[1]==="")throw new Error("pem: invalid Header line");s.push(o),e=r.shift()}let n="";for(;e!=null&&!e.startsWith(Hb);)n+=e,e=r.shift();if(e==null||e!==`${Hb}${t}${qf}`)throw new Error("pem: invalid END line");let i=new Q0(t,Buffer.from(n,"base64"));if(n===""||i.body.toString("base64")!==n)throw new Error("pem: invalid base64 body");for(let o of s)i.setHeader(o[0],o[1]);return i}});var b6=re(_o=>{"use strict";Object.defineProperty(_o,"__esModule",{value:!0});var g6=require("util"),Z0=Mb(),ir;(function(r){r[r.UNIVERSAL=0]="UNIVERSAL",r[r.APPLICATION=64]="APPLICATION",r[r.CONTEXT_SPECIFIC=128]="CONTEXT_SPECIFIC",r[r.PRIVATE=192]="PRIVATE"})(ir=_o.Class||(_o.Class={}));var _t;(function(r){r[r.NONE=0]="NONE",r[r.BOOLEAN=1]="BOOLEAN",r[r.INTEGER=2]="INTEGER",r[r.BITSTRING=3]="BITSTRING",r[r.OCTETSTRING=4]="OCTETSTRING",r[r.NULL=5]="NULL",r[r.OID=6]="OID",r[r.ENUMERATED=10]="ENUMERATED",r[r.UTF8=12]="UTF8",r[r.SEQUENCE=16]="SEQUENCE",r[r.SET=17]="SET",r[r.NUMERICSTRING=18]="NUMERICSTRING",r[r.PRINTABLESTRING=19]="PRINTABLESTRING",r[r.T61STRING=20]="T61STRING",r[r.IA5STRING=22]="IA5STRING",r[r.UTCTIME=23]="UTCTIME",r[r.GENERALIZEDTIME=24]="GENERALIZEDTIME",r[r.GENERALSTRING=27]="GENERALSTRING"})(_t=_o.Tag||(_o.Tag={}));var zf=class{constructor(e,t){this.buf=e,this.bitLen=t}at(e){if(e<0||e>=this.bitLen||!Number.isInteger(e))return 0;let t=Math.floor(e/8),s=7-e%8;return this.buf[t]>>s&1}rightAlign(){let e=8-this.bitLen%8;if(e===8||this.buf.length===0)return this.buf;let t=Buffer.alloc(this.buf.length);t[0]=this.buf[0]>>e;for(let s=1;s<this.buf.length;s++)t[s]=this.buf[s-1]<<8-e,t[s]|=this.buf[s]>>e;return t}};_o.BitString=zf;var qb=class r{static Bool(e){let t=new r(ir.UNIVERSAL,_t.BOOLEAN,Buffer.from([e?255:0]));return t._value=e,t}static parseBool(e){if(!(e instanceof Buffer)||e.length!==1)throw new Error("ASN1 syntax error: invalid boolean");switch(e[0]){case 0:return!1;case 255:return!0;default:throw new Error("ASN1 syntax error: invalid boolean")}}static Integer(e){if(e instanceof Buffer){let n=new r(ir.UNIVERSAL,_t.INTEGER,e);return n._value=e.toString("hex"),n}if(!Number.isSafeInteger(e))throw new Error("ASN1 syntax error: invalid integer");let t;if(e>=-128&&e<128)t=Buffer.alloc(1),t.writeInt8(e,0);else if(e>=-32768&&e<32768)t=Buffer.alloc(2),t.writeIntBE(e,0,2);else if(e>=-8388608&&e<8388608)t=Buffer.alloc(3),t.writeIntBE(e,0,3);else if(e>=-2147483648&&e<2147483648)t=Buffer.alloc(4),t.writeIntBE(e,0,4);else if(e>=-549755813888&&e<549755813888)t=Buffer.alloc(5),t.writeIntBE(e,0,5);else if(e>=-0x800000000000&&e<0x800000000000)t=Buffer.alloc(6),t.writeIntBE(e,0,6);else throw new Error("ASN1 syntax error: invalid Integer");let s=new r(ir.UNIVERSAL,_t.INTEGER,t);return s._value=e,s}static parseInteger(e){if(!(e instanceof Buffer)||e.length===0)throw new Error("ASN1 syntax error: invalid Integer");return e.length>6?e.toString("hex"):e.readIntBE(0,e.length)}static parseIntegerNum(e){let t=r.parseInteger(e);if(typeof t!="number")throw new Error("ASN1 syntax error: invalid Integer number");return t}static parseIntegerStr(e){let t=r.parseInteger(e);return typeof t=="number"?t.toString(16):t}static BitString(e){e instanceof Buffer&&(e=new zf(e,e.length*8));let t=e.buf.length*8-e.bitLen,s=Buffer.alloc(e.buf.length+1);return s.writeInt8(t,0),e.buf.copy(s,1),new r(ir.UNIVERSAL,_t.BITSTRING,s)}static parseBitString(e){if(!(e instanceof Buffer)||e.length===0)throw new Error("ASN1 syntax error: invalid BitString");let t=e[0];if(t>7||e.length===1&&t>0||(e[e.length-1]&(1<<e[0])-1)!==0)throw new Error("ASN1 syntax error: invalid padding bits in BIT STRING");return new zf(e.slice(1),(e.length-1)*8-t)}static Null(){let e=new r(ir.UNIVERSAL,_t.NULL,Buffer.alloc(0));return e._value=null,e}static parseNull(e){if(!(e instanceof Buffer)||e.length!==0)throw new Error("ASN1 syntax error: invalid null");return null}static OID(e){let t=e.split(".");if(t.length===0)throw new Error("ASN1 syntax error: invalid Object Identifier");let s=[];s.push(40*xr(t[0])+xr(t[1]));let n=[];for(let o=2;o<t.length;++o){let a=xr(t[o]);for(n.length=0,n.push(a&127);a>127;)a=a>>>7,n.unshift(a&127|128);s.push(...n)}let i=new r(ir.UNIVERSAL,_t.OID,Buffer.from(s));return i._value=e,i}static parseOID(e){if(!(e instanceof Buffer)||e.length===0)throw new Error("ASN1 syntax error: invalid OID");let t=Math.floor(e[0]/40)+"."+e[0]%40,s=0;for(let n=1;n<e.length;n++)e[n]>=128?(s+=e[n]&127,s=s<<7):(t+="."+(s+e[n]),s=0);return t}static UTF8(e){let t=new r(ir.UNIVERSAL,_t.UTF8,Buffer.from(e,"utf8"));return t._value=e,t}static parseUTF8(e){if(!(e instanceof Buffer))throw new Error("parse ASN1 error: invalid Buffer");return e.toString("utf8")}static NumericString(e){if(!y6(e))throw new Error("ASN1 syntax error: invalid NumericString");let t=new r(ir.UNIVERSAL,_t.NUMERICSTRING,Buffer.from(e,"utf8"));return t._value=e,t}static parseNumericString(e){if(!(e instanceof Buffer))throw new Error("parse ASN1 error: invalid Buffer");let t=e.toString("utf8");if(!y6(t))throw new Error("ASN1 syntax error: invalid NumericString");return t}static PrintableString(e){let t=new r(ir.UNIVERSAL,_t.PRINTABLESTRING,Buffer.from(e,"utf8"));return t._value=e,t}static parsePrintableString(e){if(!(e instanceof Buffer))throw new Error("parse ASN1 error: invalid Buffer");return e.toString("utf8")}static IA5String(e){if(!x6(e))throw new Error("ASN1 syntax error: invalid IA5String");let t=new r(ir.UNIVERSAL,_t.IA5STRING,Buffer.from(e,"utf8"));return t._value=e,t}static parseIA5String(e){if(!(e instanceof Buffer))throw new Error("parse ASN1 error: invalid Buffer");let t=e.toString("utf8");if(!x6(t))throw new Error("ASN1 syntax error: invalid IA5String");return t}static T61String(e){let t=new r(ir.UNIVERSAL,_t.T61STRING,Buffer.from(e,"utf8"));return t._value=e,t}static parseT61String(e){if(!(e instanceof Buffer))throw new Error("parse ASN1 error: invalid Buffer");return e.toString("utf8")}static GeneralString(e){let t=new r(ir.UNIVERSAL,_t.GENERALSTRING,Buffer.from(e,"utf8"));return t._value=e,t}static parseGeneralString(e){if(!(e instanceof Buffer))throw new Error("parse ASN1 error: invalid Buffer");return e.toString("utf8")}static UTCTime(e){let t="",s=[];s.push((""+e.getUTCFullYear()).substr(2)),s.push(""+(e.getUTCMonth()+1)),s.push(""+e.getUTCDate()),s.push(""+e.getUTCHours()),s.push(""+e.getUTCMinutes()),s.push(""+e.getUTCSeconds());for(let i of s)i.length<2&&(t+="0"),t+=i;t+="Z";let n=new r(ir.UNIVERSAL,_t.UTCTIME,Buffer.from(t,"utf8"));return n._value=e,n}static parseUTCTime(e){if(!(e instanceof Buffer)||e.length===0)throw new Error("ASN1 syntax error: invalid UTC Time");let t=e.toString("utf8"),s=new Date,n=xr(t.substr(0,2));n=n>=50?1900+n:2e3+n;let i=xr(t.substr(2,2))-1,o=xr(t.substr(4,2)),a=xr(t.substr(6,2)),c=xr(t.substr(8,2)),d=0,u=0,f="";if(t.length>11&&(u=10,f=t.charAt(u),f!=="+"&&f!=="-"&&(d=xr(t.substr(10,2)),u+=2)),s.setUTCFullYear(n,i,o),s.setUTCHours(a,c,d,0),u>0&&(f=t.charAt(u),f==="+"||f==="-")){let h=xr(t.substr(u+1,2)),y=xr(t.substr(u+4,2)),v=h*60+y;v*=6e4,f==="+"?s.setTime(+s-v):s.setTime(+s+v)}return s}static GeneralizedTime(e){let t="",s=[];s.push(""+e.getUTCFullYear()),s.push(""+(e.getUTCMonth()+1)),s.push(""+e.getUTCDate()),s.push(""+e.getUTCHours()),s.push(""+e.getUTCMinutes()),s.push(""+e.getUTCSeconds());for(let i of s)i.length<2&&(t+="0"),t+=i;t+="Z";let n=new r(ir.UNIVERSAL,_t.GENERALIZEDTIME,Buffer.from(t,"utf8"));return n._value=e,n}static parseGeneralizedTime(e){if(!(e instanceof Buffer)||e.length===0)throw new Error("ASN1 syntax error: invalid Generalized Time");let t=e.toString("utf8"),s=new Date,n=xr(t.substr(0,4)),i=xr(t.substr(4,2))-1,o=xr(t.substr(6,2)),a=xr(t.substr(8,2)),c=xr(t.substr(10,2)),d=xr(t.substr(12,2)),u=0,f=0,h=!1;t.charAt(t.length-1)==="Z"&&(h=!0);let y=t.length-5,v=t.charAt(y);if(v==="+"||v==="-"){let S=xr(t.substr(y+1,2)),C=xr(t.substr(y+4,2));f=S*60+C,f*=6e4,v==="+"&&(f*=-1),h=!0}return t.charAt(14)==="."&&(u=parseFloat(t.substr(14))*1e3),h?(s.setUTCFullYear(n,i,o),s.setUTCHours(a,c,d,u),s.setTime(+s+f)):(s.setFullYear(n,i,o),s.setHours(a,c,d,u)),s}static parseTime(e,t){switch(e){case _t.UTCTIME:return r.parseUTCTime(t);case _t.GENERALIZEDTIME:return r.parseGeneralizedTime(t);default:throw new Error("Invalid ASN1 time tag")}}static Set(e){let t=new r(ir.UNIVERSAL,_t.SET,Buffer.concat(e.map(s=>s.toDER())));return t._value=e,t}static Seq(e){let t=new r(ir.UNIVERSAL,_t.SEQUENCE,Buffer.concat(e.map(s=>s.toDER())));return t._value=e,t}static Spec(e,t,s=!0){let n=Array.isArray(t)?Buffer.concat(t.map(o=>o.toDER())):t.toDER();Array.isArray(t)&&(s=!0);let i=new r(ir.CONTEXT_SPECIFIC,e,n,s);return i._value=t,i}static fromDER(e,t=!1){return r._fromDER(new Z0.BufferVisitor(e),t)}static parseDER(e,t,s){let n=r._fromDER(new Z0.BufferVisitor(e),!1);if(n.class!==t&&n.tag!==s)throw new Error(`invalid ASN.1 DER for class ${t} and tag ${s}`);return n}static parseDERWithTemplate(e,t){let s=r._fromDER(new Z0.BufferVisitor(e),!0),n={},i=s.validate(t,n);if(i!=null)throw i.data=s,i;return n}static _parseCompound(e,t){let s=[],n=e.length,i=new Z0.BufferVisitor(e),o=0;for(;o<n;){let a=i.end;s.push(r._fromDER(i,t)),o+=i.end-a}return s}static _fromDER(e,t){if(!(e.buf instanceof Buffer)||e.length===0)throw new Error("ASN1 syntax error: invalid Generalized Time");e.mustWalk(1,"Too few bytes to read ASN.1 tag.");let s=e.start,n=e.buf[s],i=n&192,o=n&31,a=FD(e);if(e.mustHas(a),a!==0&&o===_t.NULL)throw new Error("invalid value length or NULL tag.");e.mustWalk(a);let c=(n&32)===32,d=new r(i,o,e.buf.slice(e.start,e.end),c);return c&&t&&(d._value=r._parseCompound(d.bytes,t)),d._der=e.buf.slice(s,e.end),d}constructor(e,t,s,n=!1){this.class=e,this.tag=t,this.bytes=s,this.isCompound=n||t===_t.SEQUENCE||t===_t.SET,this._value=void 0,this._der=null}get value(){return this._value===void 0&&(this._value=this.valueOf()),this._value}get DER(){return this._der==null&&(this._der=this.toDER()),this._der}mustCompound(e="asn1 object value is not compound"){if(!this.isCompound||!Array.isArray(this.value)){let t=new Error(e);throw t.data=this.toJSON(),t}return this.value}equals(e){return!(!(e instanceof r)||this.class!==e.class||this.tag!==e.tag||this.isCompound!==e.isCompound||!this.bytes.equals(e.bytes))}toDER(){let e=this.class|this.tag;this.isCompound&&(e|=32);let t=qD(this.bytes.length),s=Buffer.allocUnsafe(2+t+this.bytes.length);return s.writeInt8(e,0),t===0?(s.writeUInt8(this.bytes.length,1),this.bytes.copy(s,2)):(s.writeUInt8(t|128,1),s.writeUIntBE(this.bytes.length,2,t),this.bytes.copy(s,2+t)),s}valueOf(){if(this.isCompound)return r._parseCompound(this.bytes,!1);if(this.class!==ir.UNIVERSAL)return this.bytes;switch(this.tag){case _t.BOOLEAN:return r.parseBool(this.bytes);case _t.INTEGER:return r.parseInteger(this.bytes);case _t.BITSTRING:return r.parseBitString(this.bytes);case _t.NULL:return r.parseNull(this.bytes);case _t.OID:return r.parseOID(this.bytes);case _t.UTF8:return r.parseUTF8(this.bytes);case _t.NUMERICSTRING:return r.parseNumericString(this.bytes);case _t.PRINTABLESTRING:return r.parsePrintableString(this.bytes);case _t.T61STRING:return r.parseT61String(this.bytes);case _t.IA5STRING:return r.parseIA5String(this.bytes);case _t.GENERALSTRING:return r.parseGeneralString(this.bytes);case _t.UTCTIME:return r.parseUTCTime(this.bytes);case _t.GENERALIZEDTIME:return r.parseGeneralizedTime(this.bytes);default:return this.bytes}}validate(e,t={}){if(this.class!==e.class)return new Error(`ASN.1 object validate failure for ${e.name} : error class ${ir[this.class]}`);if(!(Array.isArray(e.tag)?e.tag:[e.tag]).includes(this.tag))return new Error(`ASN.1 object validate failure for ${e.name}: error tag ${_t[this.tag]}`);if(e.capture!=null&&(t[e.capture]=this),Array.isArray(e.value)){let n=this.mustCompound(`${e.name} need compound ASN1 value`);for(let i=0,o=0;i<e.value.length;i++)if(n[o]!=null){let a=n[o].validate(e.value[i],t);if(a==null)o++;else if(e.value[i].optional!==!0)return a}else if(e.value[i].optional!==!0)return new Error(`ASN.1 object validate failure for ${e.value[i].name}: not exists`)}else if(e.value!=null){let n=this.tag===_t.BITSTRING?this.bytes.slice(1):this.bytes;return r.fromDER(n).validate(e.value,t)}return null}toJSON(){let e=this.value;return Array.isArray(e)&&(e=e.map(t=>t.toJSON())),{class:ir[this.class],tag:this.class===ir.UNIVERSAL?_t[this.tag]:this.tag,value:e}}[g6.inspect.custom](e,t){return t.depth<=2&&(t.depth=10),`<${this.constructor.name} ${g6.inspect(this.toJSON(),t)}>`}};_o.ASN1=qb;function FD(r){r.mustWalk(1,"Too few bytes to read ASN.1 value length.");let e=r.buf[r.start];if((e&128)===0)return e;let t=e&127;return r.mustWalk(t,"Too few bytes to read ASN.1 value length."),r.buf.readUIntBE(r.start,t)}function qD(r){if(r<=127)return 0;if(r<=255)return 1;if(r<=65535)return 2;if(r<=16777215)return 3;if(r<=4294967295)return 4;if(r<=0xffffffffff)return 5;if(r<=0xffffffffffff)return 6;throw new Error("invalid value length")}function y6(r){for(let e of r){let t=e.charCodeAt(0);if(t!==32&&(t<48||t>57))return!1}return!0}function x6(r){for(let e of r)if(e.charCodeAt(0)>=128)return!1;return!0}function xr(r,e=10){let t=parseInt(r,e);if(Number.isNaN(t))throw new Error(`Invalid numeric string "${r}" in radix ${e}.`);return t}});var zb=re(Eo=>{"use strict";Object.defineProperty(Eo,"__esModule",{value:!0});var zD=Mb();Eo.BufferVisitor=zD.BufferVisitor;var $D=m6();Eo.PEM=$D.PEM;var em=b6();Eo.ASN1=em.ASN1;Eo.Class=em.Class;Eo.Tag=em.Tag;Eo.BitString=em.BitString});var Wb=re(On=>{"use strict";Object.defineProperty(On,"__esModule",{value:!0});var To=require("util"),$f=require("crypto"),Kb=J0(),fe=zb(),zr=X0();On.publicKeyValidator={name:"PublicKeyInfo",class:fe.Class.UNIVERSAL,tag:fe.Tag.SEQUENCE,capture:"publicKeyInfo",value:[{name:"PublicKeyInfo.AlgorithmIdentifier",class:fe.Class.UNIVERSAL,tag:fe.Tag.SEQUENCE,value:[{name:"PublicKeyAlgorithmIdentifier.algorithm",class:fe.Class.UNIVERSAL,tag:fe.Tag.OID,capture:"publicKeyOID"}]},{name:"PublicKeyInfo.PublicKey",class:fe.Class.UNIVERSAL,tag:fe.Tag.BITSTRING,capture:"publicKey"}]};On.privateKeyValidator={name:"PrivateKeyInfo",class:fe.Class.UNIVERSAL,tag:fe.Tag.SEQUENCE,capture:"privateKeyInfo",value:[{name:"PrivateKeyInfo.Version",class:fe.Class.UNIVERSAL,tag:fe.Tag.INTEGER,capture:"privateKeyVersion"},{name:"PrivateKeyInfo.AlgorithmIdentifier",class:fe.Class.UNIVERSAL,tag:fe.Tag.SEQUENCE,value:[{name:"PrivateKeyAlgorithmIdentifier.algorithm",class:fe.Class.UNIVERSAL,tag:fe.Tag.OID,capture:"privateKeyOID"}]},{name:"PrivateKeyInfo.PrivateKey",class:fe.Class.UNIVERSAL,tag:fe.Tag.OCTETSTRING,capture:"privateKey"}]};var VD={name:"RSAPublicKey",class:fe.Class.UNIVERSAL,tag:fe.Tag.SEQUENCE,value:[{name:"RSAPublicKey.modulus",class:fe.Class.UNIVERSAL,tag:fe.Tag.INTEGER,capture:"publicKeyModulus"},{name:"RSAPublicKey.exponent",class:fe.Class.UNIVERSAL,tag:fe.Tag.INTEGER,capture:"publicKeyExponent"}]},KD={name:"RSAPrivateKey",class:fe.Class.UNIVERSAL,tag:fe.Tag.SEQUENCE,value:[{name:"RSAPrivateKey.version",class:fe.Class.UNIVERSAL,tag:fe.Tag.INTEGER,capture:"privateKeyVersion"},{name:"RSAPrivateKey.modulus",class:fe.Class.UNIVERSAL,tag:fe.Tag.INTEGER,capture:"privateKeyModulus"},{name:"RSAPrivateKey.publicExponent",class:fe.Class.UNIVERSAL,tag:fe.Tag.INTEGER,capture:"privateKeyPublicExponent"},{name:"RSAPrivateKey.privateExponent",class:fe.Class.UNIVERSAL,tag:fe.Tag.INTEGER,capture:"privateKeyPrivateExponent"},{name:"RSAPrivateKey.prime1",class:fe.Class.UNIVERSAL,tag:fe.Tag.INTEGER,capture:"privateKeyPrime1"},{name:"RSAPrivateKey.prime2",class:fe.Class.UNIVERSAL,tag:fe.Tag.INTEGER,capture:"privateKeyPrime2"},{name:"RSAPrivateKey.exponent1",class:fe.Class.UNIVERSAL,tag:fe.Tag.INTEGER,capture:"privateKeyExponent1"},{name:"RSAPrivateKey.exponent2",class:fe.Class.UNIVERSAL,tag:fe.Tag.INTEGER,capture:"privateKeyExponent2"},{name:"RSAPrivateKey.coefficient",class:fe.Class.UNIVERSAL,tag:fe.Tag.INTEGER,capture:"privateKeyCoefficient"}]},WD=[zr.getOID("X25519"),zr.getOID("X448"),zr.getOID("Ed25519"),zr.getOID("Ed448")],jd=class r{constructor(e){let t={},s=e.validate(On.publicKeyValidator,t);if(s!=null)throw new Error("Cannot read X.509 public key: "+s.message);this.oid=fe.ASN1.parseOID(t.publicKeyOID.bytes),this.algo=zr.getOIDName(this.oid),this._pkcs8=e,this._keyRaw=fe.ASN1.parseBitString(t.publicKey.bytes).buf,this._finalKey=this._keyRaw,this._finalPEM=""}static fromPEM(e){let t=fe.PEM.parse(e)[0];if(t.procType.includes("ENCRYPTED"))throw new Error("Could not convert public key from PEM, PEM is encrypted.");let s=fe.ASN1.fromDER(t.body,!0);switch(t.type){case"PUBLIC KEY":return new r(s);case"RSA PUBLIC KEY":let n=fe.ASN1.Seq([fe.ASN1.Seq([fe.ASN1.OID(zr.getOID("rsaEncryption")),fe.ASN1.Null()]),fe.ASN1.BitString(s.DER)]);return new r(n);default:throw new Error("Could not convert public key from PEM, recommend PKCS#8 PEM")}}static addVerifier(e,t){if(e=zr.getOID(e),e==="")throw new Error(`Invalid object identifier: ${e}`);if(r._verifiers[e]!=null)throw new Error(`Verifier ${e} exists`);r._verifiers[e]=t}get keyRaw(){return this._finalKey}verify(e,t,s){let n=r._verifiers[this.oid];if(n!=null){let o=$f.createHash(s).update(e).digest();return n.call(this,o,t)}let i=$f.createVerify(s);return i.update(e),i.verify(this.toPEM(),t)}getFingerprint(e,t="PublicKey"){let s;switch(t){case"PublicKeyInfo":s=this._pkcs8.DER;break;case"PublicKey":s=this._keyRaw;break;default:throw new Error(`Unknown fingerprint type "${t}".`)}let n=$f.createHash(e);return n.update(s),n.digest()}toASN1(){return this._pkcs8}toDER(){return this._pkcs8.DER}toPEM(){return this._finalPEM===""&&(this._finalPEM=new fe.PEM("PUBLIC KEY",this._pkcs8.DER).toString()),this._finalPEM}toJSON(){return{oid:this.oid,algo:this.algo,publicKey:this._keyRaw}}[To.inspect.custom](e,t){return`<${this.constructor.name} ${To.inspect(this.toJSON(),t)}>`}};jd._verifiers=Object.create(null);On.PublicKey=jd;var Hd=class r{constructor(e){let t=Object.create(null),s=e.validate(On.privateKeyValidator,t);if(s!=null)throw new Error("Cannot read X.509 private key: "+s.message);if(this.version=fe.ASN1.parseIntegerNum(t.privateKeyVersion.bytes)+1,this.oid=fe.ASN1.parseOID(t.privateKeyOID.bytes),this.algo=zr.getOIDName(this.oid),this._pkcs8=e,this._keyRaw=t.privateKey.bytes,this._publicKeyRaw=null,this._finalKey=this._keyRaw,this._finalPEM="",WD.includes(this.oid)){if(this._finalKey=this._keyRaw=fe.ASN1.parseDER(this._keyRaw,fe.Class.UNIVERSAL,fe.Tag.OCTETSTRING).bytes,this.oid==="1.3.101.112"){let n=Kb.sign.keyPair.fromSeed(this._keyRaw);this._publicKeyRaw=Buffer.from(n.publicKey),this._finalKey=Buffer.from(n.secretKey)}else if(this.version===2)for(let n of e.mustCompound())n.class===fe.Class.CONTEXT_SPECIFIC&&n.tag===1&&(this._publicKeyRaw=fe.ASN1.parseBitString(n.bytes).buf,this._finalKey=Buffer.concat([this._keyRaw,this._publicKeyRaw]))}}static fromPEM(e){let t=fe.PEM.parse(e)[0];if(t.procType.includes("ENCRYPTED"))throw new Error("Could not convert private key from PEM, PEM is encrypted.");let s=fe.ASN1.fromDER(t.body,!0);switch(t.type){case"PRIVATE KEY":return new r(s);case"RSA PRIVATE KEY":return s=fe.ASN1.Seq([s.value[0],fe.ASN1.Seq([fe.ASN1.OID(zr.getOID("rsaEncryption")),fe.ASN1.Null()]),new fe.ASN1(fe.Class.UNIVERSAL,fe.Tag.OCTETSTRING,s.DER)]),new r(s);default:throw new Error("Could not convert private key from PEM, recommend PKCS#8 PEM")}}static addSigner(e,t){if(e=zr.getOID(e),e==="")throw new Error(`Invalid object identifier: ${e}`);if(r._signers[e]!=null)throw new Error(`Signer ${e} exists`);r._signers[e]=t}get keyRaw(){return this._finalKey}get publicKeyRaw(){return this._publicKeyRaw}sign(e,t){let s=r._signers[this.oid];if(s!=null){let i=$f.createHash(t).update(e).digest();return s.call(this,i)}let n=$f.createSign(t);return n.update(e),n.sign(this.toPEM())}toASN1(){return this._pkcs8}toDER(){return this._pkcs8.DER}toPEM(){return this._finalPEM===""&&(this._finalPEM=new fe.PEM("PRIVATE KEY",this._pkcs8.DER).toString()),this._finalPEM}toJSON(){return{version:this.version,oid:this.oid,algo:this.algo,privateKey:this._keyRaw,publicKey:this._publicKeyRaw}}[To.inspect.custom](e,t){return`<${this.constructor.name} ${To.inspect(this.toJSON(),t)}>`}};Hd._signers=Object.create(null);On.PrivateKey=Hd;var $b=class r extends jd{static fromPublicKey(e){return new r(e.toASN1())}constructor(e){if(super(e),zr.getOID(this.oid)!==zr.getOID("rsaEncryption"))throw new Error(`Invalid RSA public key, unknown OID: ${this.oid}`);let t=Object.create(null);this._pkcs1=fe.ASN1.fromDER(this._keyRaw,!0);let s=this._pkcs1.validate(VD,t);if(s!=null)throw new Error("Cannot read RSA public key: "+s.message);this.modulus=fe.ASN1.parseIntegerStr(t.publicKeyModulus.bytes),this.exponent=fe.ASN1.parseIntegerNum(t.publicKeyExponent.bytes)}toASN1(){return this._pkcs1}toDER(){return this._keyRaw}toPEM(){return this._finalPEM===""&&(this._finalPEM=new fe.PEM("RSA PUBLIC KEY",this._keyRaw).toString()),this._finalPEM}toPublicKeyPEM(){return new fe.PEM("PUBLIC KEY",this._pkcs8.DER).toString()}toJSON(){return{oid:this.oid,algo:this.algo,modulus:Co(this.modulus),exponent:this.exponent}}[To.inspect.custom](e,t){return`<${this.constructor.name} ${To.inspect(this.toJSON(),t)}>`}};On.RSAPublicKey=$b;var Vb=class r extends Hd{static fromPrivateKey(e){return new r(e.toASN1())}constructor(e){if(super(e),zr.getOID(this.oid)!==zr.getOID("rsaEncryption"))throw new Error(`Invalid RSA private key, unknown OID: ${this.oid}`);let t=Object.create(null);this._pkcs1=fe.ASN1.fromDER(this._keyRaw,!0);let s=this._pkcs1.validate(KD,t);if(s!=null)throw new Error("Cannot read RSA private key: "+s.message);this.publicExponent=fe.ASN1.parseIntegerNum(t.privateKeyPublicExponent.bytes),this.privateExponent=fe.ASN1.parseIntegerStr(t.privateKeyPrivateExponent.bytes),this.modulus=fe.ASN1.parseIntegerStr(t.privateKeyModulus.bytes),this.prime1=fe.ASN1.parseIntegerStr(t.privateKeyPrime1.bytes),this.prime2=fe.ASN1.parseIntegerStr(t.privateKeyPrime2.bytes),this.exponent1=fe.ASN1.parseIntegerStr(t.privateKeyExponent1.bytes),this.exponent2=fe.ASN1.parseIntegerStr(t.privateKeyExponent2.bytes),this.coefficient=fe.ASN1.parseIntegerStr(t.privateKeyCoefficient.bytes)}toASN1(){return this._pkcs1}toDER(){return this._keyRaw}toPEM(){return this._finalPEM===""&&(this._finalPEM=new fe.PEM("RSA PRIVATE KEY",this._keyRaw).toString()),this._finalPEM}toPrivateKeyPEM(){return new fe.PEM("PRIVATE KEY",this._pkcs8.DER).toString()}toJSON(){return{version:this.version,oid:this.oid,algo:this.algo,publicExponent:this.publicExponent,privateExponent:Co(this.privateExponent),modulus:Co(this.modulus),prime1:Co(this.prime1),prime2:Co(this.prime2),exponent1:Co(this.exponent1),exponent2:Co(this.exponent2),coefficient:Co(this.coefficient)}}[To.inspect.custom](e,t){return`<${this.constructor.name} ${To.inspect(this.toJSON(),t)}>`}};On.RSAPrivateKey=Vb;function Co(r){return r.length%8!==0&&r.startsWith("00")?r.slice(2):r}jd.addVerifier(zr.getOID("Ed25519"),function(r,e){return Kb.sign.detached.verify(r,e,this.keyRaw)});Hd.addSigner(zr.getOID("Ed25519"),function(r){let e=this.keyRaw;if(e.length!==64)throw new Error("Invalid signing key.");return Buffer.from(Kb.sign.detached(r,e))})});var C6=re(tm=>{"use strict";Object.defineProperty(tm,"__esModule",{value:!0});var v6=require("util"),GD=require("crypto"),ne=zb(),$r=X0(),E6=Wb(),br=Object.create(null);br.CN=$r.getOID("commonName");br.commonName="CN";br.C=$r.getOID("countryName");br.countryName="C";br.L=$r.getOID("localityName");br.localityName="L";br.ST=$r.getOID("stateOrProvinceName");br.stateOrProvinceName="ST";br.O=$r.getOID("organizationName");br.organizationName="O";br.OU=$r.getOID("organizationalUnitName");br.organizationalUnitName="OU";br.E=$r.getOID("emailAddress");br.emailAddress="E";function XD(r){return br[r]==null?"":br[r]}var YD={name:"Certificate",class:ne.Class.UNIVERSAL,tag:ne.Tag.SEQUENCE,value:[{name:"Certificate.TBSCertificate",class:ne.Class.UNIVERSAL,tag:ne.Tag.SEQUENCE,capture:"tbsCertificate",value:[{name:"Certificate.TBSCertificate.version",class:ne.Class.CONTEXT_SPECIFIC,tag:ne.Tag.NONE,optional:!0,value:[{name:"Certificate.TBSCertificate.version.integer",class:ne.Class.UNIVERSAL,tag:ne.Tag.INTEGER,capture:"certVersion"}]},{name:"Certificate.TBSCertificate.serialNumber",class:ne.Class.UNIVERSAL,tag:ne.Tag.INTEGER,capture:"certSerialNumber"},{name:"Certificate.TBSCertificate.signature",class:ne.Class.UNIVERSAL,tag:ne.Tag.SEQUENCE,value:[{name:"Certificate.TBSCertificate.signature.algorithm",class:ne.Class.UNIVERSAL,tag:ne.Tag.OID,capture:"certinfoSignatureOID"},{name:"Certificate.TBSCertificate.signature.parameters",class:ne.Class.UNIVERSAL,tag:ne.Tag.OCTETSTRING,optional:!0,capture:"certinfoSignatureParams"}]},{name:"Certificate.TBSCertificate.issuer",class:ne.Class.UNIVERSAL,tag:ne.Tag.SEQUENCE,capture:"certIssuer"},{name:"Certificate.TBSCertificate.validity",class:ne.Class.UNIVERSAL,tag:ne.Tag.SEQUENCE,value:[{name:"Certificate.TBSCertificate.validity.notBefore",class:ne.Class.UNIVERSAL,tag:[ne.Tag.UTCTIME,ne.Tag.GENERALIZEDTIME],capture:"certValidityNotBefore"},{name:"Certificate.TBSCertificate.validity.notAfter",class:ne.Class.UNIVERSAL,tag:[ne.Tag.UTCTIME,ne.Tag.GENERALIZEDTIME],capture:"certValidityNotAfter"}]},{name:"Certificate.TBSCertificate.subject",class:ne.Class.UNIVERSAL,tag:ne.Tag.SEQUENCE,capture:"certSubject"},E6.publicKeyValidator,{name:"Certificate.TBSCertificate.issuerUniqueID",class:ne.Class.CONTEXT_SPECIFIC,tag:ne.Tag.BOOLEAN,optional:!0,value:[{name:"Certificate.TBSCertificate.issuerUniqueID.id",class:ne.Class.UNIVERSAL,tag:ne.Tag.BITSTRING,capture:"certIssuerUniqueId"}]},{name:"Certificate.TBSCertificate.subjectUniqueID",class:ne.Class.CONTEXT_SPECIFIC,tag:ne.Tag.INTEGER,optional:!0,value:[{name:"Certificate.TBSCertificate.subjectUniqueID.id",class:ne.Class.UNIVERSAL,tag:ne.Tag.BITSTRING,capture:"certSubjectUniqueId"}]},{name:"Certificate.TBSCertificate.extensions",class:ne.Class.CONTEXT_SPECIFIC,tag:ne.Tag.BITSTRING,capture:"certExtensions",optional:!0}]},{name:"Certificate.signatureAlgorithm",class:ne.Class.UNIVERSAL,tag:ne.Tag.SEQUENCE,value:[{name:"Certificate.signatureAlgorithm.algorithm",class:ne.Class.UNIVERSAL,tag:ne.Tag.OID,capture:"certSignatureOID"},{name:"Certificate.TBSCertificate.signature.parameters",class:ne.Class.UNIVERSAL,tag:ne.Tag.OCTETSTRING,optional:!0,capture:"certSignatureParams"}]},{name:"Certificate.signatureValue",class:ne.Class.UNIVERSAL,tag:ne.Tag.BITSTRING,capture:"certSignature"}]},Vf=class{constructor(){this.attributes=[],this.uniqueId=null}get commonName(){return this.getFieldValue("commonName")}get organizationName(){return this.getFieldValue("organizationName")}get organizationalUnitName(){return this.getFieldValue("organizationalUnitName")}get countryName(){return this.getFieldValue("countryName")}get localityName(){return this.getFieldValue("localityName")}get serialName(){return this.getFieldValue("serialName")}getHash(){let e=GD.createHash("sha1");for(let t of this.attributes)e.update(t.oid),e.update(t.value);return e.digest()}getField(e){for(let t of this.attributes)if(e===t.oid||e===t.name||e===t.shortName)return t;return null}addField(e){S6([e]),this.attributes.push(e)}setAttrs(e){S6(e),this.attributes=e}toJSON(){let e={};for(let t of this.attributes){let s=t.shortName;typeof s=="string"&&s!==""&&(e[s]=t.value)}return e.uniqueId=this.uniqueId,e.attributes=this.attributes,e}getFieldValue(e){let t=this.getField(e);return t!=null?t.value:""}};tm.DistinguishedName=Vf;var Gb=class r{static fromPEMs(e){let t=[],s=ne.PEM.parse(e);for(let n of s){if(n.type!=="CERTIFICATE"&&n.type!=="X509 CERTIFICATE"&&n.type!=="TRUSTED CERTIFICATE")throw new Error("Could not convert certificate from PEM: invalid type");if(n.procType.includes("ENCRYPTED"))throw new Error("Could not convert certificate from PEM: PEM is encrypted.");let i=ne.ASN1.fromDER(n.body);t.push(new r(i))}if(t.length===0)throw new Error("No Certificate");return t}static fromPEM(e){return r.fromPEMs(e)[0]}constructor(e){let t=Object.create(null),s=e.validate(YD,t);if(s!=null)throw new Error("Cannot read X.509 certificate: "+s.message);if(this.raw=e.DER,this.version=t.certVersion==null?0:ne.ASN1.parseIntegerNum(t.certVersion.bytes)+1,this.serialNumber=ne.ASN1.parseIntegerStr(t.certSerialNumber.bytes),this.signatureOID=ne.ASN1.parseOID(t.certSignatureOID.bytes),this.signatureAlgorithm=$r.getOIDName(this.signatureOID),this.infoSignatureOID=ne.ASN1.parseOID(t.certinfoSignatureOID.bytes),this.signature=ne.ASN1.parseBitString(t.certSignature.bytes).buf,this.validFrom=ne.ASN1.parseTime(t.certValidityNotBefore.tag,t.certValidityNotBefore.bytes),this.validTo=ne.ASN1.parseTime(t.certValidityNotAfter.tag,t.certValidityNotAfter.bytes),this.issuer=new Vf,this.issuer.setAttrs(_6(t.certIssuer)),t.certIssuerUniqueId!=null&&(this.issuer.uniqueId=ne.ASN1.parseBitString(t.certIssuerUniqueId.bytes)),this.subject=new Vf,this.subject.setAttrs(_6(t.certSubject)),t.certSubjectUniqueId!=null&&(this.subject.uniqueId=ne.ASN1.parseBitString(t.certSubjectUniqueId.bytes)),this.extensions=[],this.subjectKeyIdentifier="",this.authorityKeyIdentifier="",this.ocspServer="",this.issuingCertificateURL="",this.isCA=!1,this.maxPathLen=-1,this.basicConstraintsValid=!1,this.keyUsage=0,this.dnsNames=[],this.emailAddresses=[],this.ipAddresses=[],this.uris=[],t.certExtensions!=null){this.extensions=JD(t.certExtensions);for(let n of this.extensions)if(typeof n.subjectKeyIdentifier=="string"&&(this.subjectKeyIdentifier=n.subjectKeyIdentifier),typeof n.authorityKeyIdentifier=="string"&&(this.authorityKeyIdentifier=n.authorityKeyIdentifier),typeof n.authorityInfoAccessOcsp=="string"&&(this.ocspServer=n.authorityInfoAccessOcsp),typeof n.authorityInfoAccessIssuers=="string"&&(this.issuingCertificateURL=n.authorityInfoAccessIssuers),typeof n.basicConstraintsValid=="boolean"&&(this.isCA=n.isCA,this.maxPathLen=n.maxPathLen,this.basicConstraintsValid=n.basicConstraintsValid),typeof n.keyUsage=="number"&&(this.keyUsage=n.keyUsage),Array.isArray(n.altNames))for(let i of n.altNames)i.dnsName!=null&&this.dnsNames.push(i.dnsName),i.email!=null&&this.emailAddresses.push(i.email),i.ip!=null&&this.ipAddresses.push(i.ip),i.uri!=null&&this.uris.push(i.uri)}this.publicKey=new E6.PublicKey(t.publicKeyInfo),this.publicKeyRaw=this.publicKey.toDER(),this.tbsCertificate=t.tbsCertificate}getExtension(e,t=""){for(let s of this.extensions)if(e===s.oid||e===s.name)return t===""?s:s[t];return null}checkSignature(e){if(this.version===3&&!this.basicConstraintsValid||this.basicConstraintsValid&&!this.isCA)return new Error("The parent constraint violation error");if(this.getExtension("keyUsage","keyCertSign")!==!0)return new Error("The parent constraint violation error");if(!e.isIssuer(this))return new Error("The parent certificate did not issue the given child certificate");let t=dM(e.signatureOID);return t===""?new Error("Unknown child signature OID."):this.publicKey.verify(e.tbsCertificate.DER,e.signature,t)===!1?new Error("Child signature not matched"):null}isIssuer(e){return this.issuer.getHash().equals(e.subject.getHash())}verifySubjectKeyIdentifier(){return this.publicKey.getFingerprint("sha1","PublicKey").toString("hex")===this.subjectKeyIdentifier}toJSON(){let e={};for(let t of Object.keys(this))e[t]=uM(this[t]);return delete e.tbsCertificate,e}[v6.inspect.custom](e,t){return t.depth<=2&&(t.depth=10),`<${this.constructor.name} ${v6.inspect(this.toJSON(),t)}>`}};tm.Certificate=Gb;function JD(r){let e=[];for(let t of r.mustCompound())for(let s of t.mustCompound())e.push(QD(s));return e}function QD(r){let e={};switch(e.oid=ne.ASN1.parseOID(r.value[0].bytes),e.critical=!1,r.value[1].tag===ne.Tag.BOOLEAN?(e.critical=ne.ASN1.parseBool(r.value[1].bytes),e.value=r.value[2].bytes):e.value=r.value[1].bytes,e.name=$r.getOIDName(e.oid),e.name){case"keyUsage":ZD(e);break;case"basicConstraints":eM(e);break;case"extKeyUsage":tM(e);break;case"nsCertType":rM(e);break;case"subjectAltName":w6(e);break;case"issuerAltName":w6(e);break;case"subjectKeyIdentifier":nM(e);break;case"authorityKeyIdentifier":oM(e);break;case"authorityInfoAccess":cM(e);break}return e}function ZD(r){let e=ne.ASN1.parseBitString(ne.ASN1.fromDER(r.value).bytes),t=0,s=0;r.keyUsage=0;for(let n=0;n<9;n++)e.at(n)!==0&&(r.keyUsage|=1<<n);e.buf.length>0&&(t=e.buf[0],s=e.buf.length>1?e.buf[1]:0),r.digitalSignature=(t&128)===128,r.nonRepudiation=(t&64)===64,r.keyEncipherment=(t&32)===32,r.dataEncipherment=(t&16)===16,r.keyAgreement=(t&8)===8,r.keyCertSign=(t&4)===4,r.cRLSign=(t&2)===2,r.encipherOnly=(t&1)===1,r.decipherOnly=(s&128)===128}function eM(r){let t=ne.ASN1.fromDER(r.value).mustCompound();t.length>0&&t[0].tag===ne.Tag.BOOLEAN?r.isCA=ne.ASN1.parseBool(t[0].bytes):r.isCA=!1;let s=null;t.length>0&&t[0].tag===ne.Tag.INTEGER?s=t[0].bytes:t.length>1&&(s=t[1].bytes),s!==null?r.maxPathLen=ne.ASN1.parseInteger(s):r.maxPathLen=-1,r.basicConstraintsValid=!0}function tM(r){let t=ne.ASN1.fromDER(r.value).mustCompound();for(let s of t)r[$r.getOIDName(ne.ASN1.parseOID(s.bytes))]=!0}function rM(r){let e=ne.ASN1.parseBitString(ne.ASN1.fromDER(r.value).bytes),t=0;e.buf.length>0&&(t=e.buf[0]),r.client=(t&128)===128,r.server=(t&64)===64,r.email=(t&32)===32,r.objsign=(t&16)===16,r.reserved=(t&8)===8,r.sslCA=(t&4)===4,r.emailCA=(t&2)===2,r.objCA=(t&1)===1}function w6(r){r.altNames=[];let t=ne.ASN1.fromDER(r.value).mustCompound();for(let s of t){let n={tag:s.tag,value:s.bytes};switch(r.altNames.push(n),s.tag){case 1:n.email=s.bytes.toString();break;case 2:n.dnsName=s.bytes.toString();break;case 6:n.uri=s.bytes.toString();break;case 7:n.ip=$r.bytesToIP(s.bytes);break;case 8:n.oid=ne.ASN1.parseOID(s.bytes);break;default:}}}var sM={name:"subjectKeyIdentifier",class:ne.Class.UNIVERSAL,tag:ne.Tag.OCTETSTRING,capture:"subjectKeyIdentifier"};function nM(r){let e=ne.ASN1.parseDERWithTemplate(r.value,sM);r.subjectKeyIdentifier=e.subjectKeyIdentifier.bytes.toString("hex")}var iM={name:"authorityKeyIdentifier",class:ne.Class.UNIVERSAL,tag:ne.Tag.SEQUENCE,value:[{name:"authorityKeyIdentifier.value",class:ne.Class.CONTEXT_SPECIFIC,tag:ne.Tag.NONE,capture:"authorityKeyIdentifier"}]};function oM(r){let e=ne.ASN1.parseDERWithTemplate(r.value,iM);r.authorityKeyIdentifier=e.authorityKeyIdentifier.bytes.toString("hex")}var aM={name:"authorityInfoAccess",class:ne.Class.UNIVERSAL,tag:ne.Tag.SEQUENCE,value:[{name:"authorityInfoAccess.authorityInfoAccessOcsp",class:ne.Class.UNIVERSAL,tag:ne.Tag.SEQUENCE,optional:!0,value:[{name:"authorityInfoAccess.authorityInfoAccessOcsp.oid",class:ne.Class.UNIVERSAL,tag:ne.Tag.OID},{name:"authorityInfoAccess.authorityInfoAccessOcsp.value",class:ne.Class.CONTEXT_SPECIFIC,tag:ne.Tag.OID,capture:"authorityInfoAccessOcsp"}]},{name:"authorityInfoAccess.authorityInfoAccessIssuers",class:ne.Class.UNIVERSAL,tag:ne.Tag.SEQUENCE,optional:!0,value:[{name:"authorityInfoAccess.authorityInfoAccessIssuers.oid",class:ne.Class.UNIVERSAL,tag:ne.Tag.OID},{name:"authorityInfoAccess.authorityInfoAccessIssuers.value",class:ne.Class.CONTEXT_SPECIFIC,tag:ne.Tag.OID,capture:"authorityInfoAccessIssuers"}]}]};function cM(r){let e=ne.ASN1.parseDERWithTemplate(r.value,aM);e.authorityInfoAccessOcsp!=null&&(r.authorityInfoAccessOcsp=e.authorityInfoAccessOcsp.bytes.toString()),e.authorityInfoAccessIssuers!=null&&(r.authorityInfoAccessIssuers=e.authorityInfoAccessIssuers.bytes.toString())}function S6(r){for(let e of r){if((e.name==null||e.name==="")&&(e.oid!=null&&(e.name=$r.getOIDName(e.oid)),e.name===""&&e.shortName!=null&&(e.name=$r.getOIDName(br[e.shortName]))),e.oid==null||e.oid==="")if(e.name!=="")e.oid=$r.getOID(e.name);else throw new Error("Attribute oid not specified.");if((e.shortName==null||e.shortName==="")&&(e.shortName=br[e.name]==null?"":br[e.name]),e.value==null)throw new Error("Attribute value not specified.")}}function dM(r){switch($r.getOIDName(r)){case"sha1WithRsaEncryption":return"sha1";case"md5WithRsaEncryption":return"md5";case"sha256WithRsaEncryption":return"sha256";case"sha384WithRsaEncryption":return"sha384";case"sha512WithRsaEncryption":return"sha512";case"RSASSA-PSS":return"sha256";case"ecdsaWithSha1":return"sha1";case"ecdsaWithSha256":return"sha256";case"ecdsaWithSha384":return"sha384";case"ecdsaWithSha512":return"sha512";case"dsaWithSha1":return"sha1";case"dsaWithSha256":return"sha256";default:return""}}function _6(r){let e=[];for(let t of r.mustCompound())for(let s of t.mustCompound()){let n=s.mustCompound(),i={};i.oid=ne.ASN1.parseOID(n[0].bytes),i.value=n[1].value,i.valueTag=n[1].tag,i.name=$r.getOIDName(i.oid),i.shortName=XD(i.name),e.push(i)}return e}function uM(r){return r!=null&&!(r instanceof Buffer)&&typeof r.toJSON=="function"?r.toJSON():r}});var Xb=re(js=>{"use strict";Object.defineProperty(js,"__esModule",{value:!0});var rm=X0();js.bytesFromIP=rm.bytesFromIP;js.bytesToIP=rm.bytesToIP;js.getOID=rm.getOID;js.getOIDName=rm.getOIDName;var sm=Wb();js.PublicKey=sm.PublicKey;js.PrivateKey=sm.PrivateKey;js.RSAPublicKey=sm.RSAPublicKey;js.RSAPrivateKey=sm.RSAPrivateKey;var T6=C6();js.Certificate=T6.Certificate;js.DistinguishedName=T6.DistinguishedName});var I6=re(()=>{"use strict";var A6;(function(r){(function(e){var t=typeof globalThis=="object"?globalThis:typeof global=="object"?global:typeof self=="object"?self:typeof this=="object"?this:a(),s=n(r);typeof t.Reflect<"u"&&(s=n(t.Reflect,s)),e(s,t),typeof t.Reflect>"u"&&(t.Reflect=r);function n(c,d){return function(u,f){Object.defineProperty(c,u,{configurable:!0,writable:!0,value:f}),d&&d(u,f)}}function i(){try{return Function("return this;")()}catch{}}function o(){try{return(0,eval)("(function() { return this; })()")}catch{}}function a(){return i()||o()}})(function(e,t){var s=Object.prototype.hasOwnProperty,n=typeof Symbol=="function",i=n&&typeof Symbol.toPrimitive<"u"?Symbol.toPrimitive:"@@toPrimitive",o=n&&typeof Symbol.iterator<"u"?Symbol.iterator:"@@iterator",a=typeof Object.create=="function",c={__proto__:[]}instanceof Array,d=!a&&!c,u={create:a?function(){return Ia(Object.create(null))}:c?function(){return Ia({__proto__:null})}:function(){return Ia({})},has:d?function(P,M){return s.call(P,M)}:function(P,M){return M in P},get:d?function(P,M){return s.call(P,M)?P[M]:void 0}:function(P,M){return P[M]}},f=Object.getPrototypeOf(Function),h=typeof Map=="function"&&typeof Map.prototype.entries=="function"?Map:_f(),y=typeof Set=="function"&&typeof Set.prototype.entries=="function"?Set:r0(),v=typeof WeakMap=="function"?WeakMap:Ix(),S=n?Symbol.for("@reflect-metadata:registry"):void 0,C=ud(),O=Sf(C);function K(P,M,$,ce){if(I($)){if(!Bs(P))throw new TypeError;if(!Ca(M))throw new TypeError;return Fe(P,M)}else{if(!Bs(P))throw new TypeError;if(!he(M))throw new TypeError;if(!he(ce)&&!I(ce)&&!L(ce))throw new TypeError;return L(ce)&&(ce=void 0),$=Dt($),V(P,M,$,ce)}}e("decorate",K);function z(P,M){function $(ce,Me){if(!he(ce))throw new TypeError;if(!I(Me)&&!Ax(Me))throw new TypeError;Oe(P,M,ce,Me)}return $}e("metadata",z);function Q(P,M,$,ce){if(!he($))throw new TypeError;return I(ce)||(ce=Dt(ce)),Oe(P,M,$,ce)}e("defineMetadata",Q);function oe(P,M,$){if(!he(M))throw new TypeError;return I($)||($=Dt($)),D(P,M,$)}e("hasMetadata",oe);function se(P,M,$){if(!he(M))throw new TypeError;return I($)||($=Dt($)),F(P,M,$)}e("hasOwnMetadata",se);function we(P,M,$){if(!he(M))throw new TypeError;return I($)||($=Dt($)),le(P,M,$)}e("getMetadata",we);function me(P,M,$){if(!he(M))throw new TypeError;return I($)||($=Dt($)),Ae(P,M,$)}e("getOwnMetadata",me);function Y(P,M){if(!he(P))throw new TypeError;return I(M)||(M=Dt(M)),A(P,M)}e("getMetadataKeys",Y);function Ze(P,M){if(!he(P))throw new TypeError;return I(M)||(M=Dt(M)),R(P,M)}e("getOwnMetadataKeys",Ze);function Tt(P,M,$){if(!he(M))throw new TypeError;if(I($)||($=Dt($)),!he(M))throw new TypeError;I($)||($=Dt($));var ce=xi(M,$,!1);return I(ce)?!1:ce.OrdinaryDeleteMetadata(P,M,$)}e("deleteMetadata",Tt);function Fe(P,M){for(var $=P.length-1;$>=0;--$){var ce=P[$],Me=ce(M);if(!I(Me)&&!L(Me)){if(!Ca(Me))throw new TypeError;M=Me}}return M}function V(P,M,$,ce){for(var Me=P.length-1;Me>=0;--Me){var $t=P[Me],Wt=$t(M,$,ce);if(!I(Wt)&&!L(Wt)){if(!he(Wt))throw new TypeError;ce=Wt}}return ce}function D(P,M,$){var ce=F(P,M,$);if(ce)return!0;var Me=Aa(M);return L(Me)?!1:D(P,Me,$)}function F(P,M,$){var ce=xi(M,$,!1);return I(ce)?!1:Ot(ce.OrdinaryHasOwnMetadata(P,M,$))}function le(P,M,$){var ce=F(P,M,$);if(ce)return Ae(P,M,$);var Me=Aa(M);if(!L(Me))return le(P,Me,$)}function Ae(P,M,$){var ce=xi(M,$,!1);if(!I(ce))return ce.OrdinaryGetOwnMetadata(P,M,$)}function Oe(P,M,$,ce){var Me=xi($,ce,!0);Me.OrdinaryDefineOwnMetadata(P,M,$,ce)}function A(P,M){var $=R(P,M),ce=Aa(P);if(ce===null)return $;var Me=A(ce,M);if(Me.length<=0)return $;if($.length<=0)return Me;for(var $t=new y,Wt=[],ft=0,ge=$;ft<ge.length;ft++){var Ee=ge[ft],Re=$t.has(Ee);Re||($t.add(Ee),Wt.push(Ee))}for(var Be=0,st=Me;Be<st.length;Be++){var Ee=st[Be],Re=$t.has(Ee);Re||($t.add(Ee),Wt.push(Ee))}return Wt}function R(P,M){var $=xi(P,M,!1);return $?$.OrdinaryOwnMetadataKeys(P,M):[]}function q(P){if(P===null)return 1;switch(typeof P){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return P===null?1:6;default:return 6}}function I(P){return P===void 0}function L(P){return P===null}function ae(P){return typeof P=="symbol"}function he(P){return typeof P=="object"?P!==null:typeof P=="function"}function ct(P,M){switch(q(P)){case 0:return P;case 1:return P;case 2:return P;case 3:return P;case 4:return P;case 5:return P}var $=M===3?"string":M===5?"number":"default",ce=xf(P,i);if(ce!==void 0){var Me=ce.call(P,$);if(he(Me))throw new TypeError;return Me}return xt(P,$==="default"?"number":$)}function xt(P,M){if(M==="string"){var $=P.toString;if(Ns($)){var ce=$.call(P);if(!he(ce))return ce}var Me=P.valueOf;if(Ns(Me)){var ce=Me.call(P);if(!he(ce))return ce}}else{var Me=P.valueOf;if(Ns(Me)){var ce=Me.call(P);if(!he(ce))return ce}var $t=P.toString;if(Ns($t)){var ce=$t.call(P);if(!he(ce))return ce}}throw new TypeError}function Ot(P){return!!P}function St(P){return""+P}function Dt(P){var M=ct(P,3);return ae(M)?M:St(M)}function Bs(P){return Array.isArray?Array.isArray(P):P instanceof Object?P instanceof Array:Object.prototype.toString.call(P)==="[object Array]"}function Ns(P){return typeof P=="function"}function Ca(P){return typeof P=="function"}function Ax(P){switch(q(P)){case 3:return!0;case 4:return!0;default:return!1}}function yf(P,M){return P===M||P!==P&&M!==M}function xf(P,M){var $=P[M];if($!=null){if(!Ns($))throw new TypeError;return $}}function bf(P){var M=xf(P,o);if(!Ns(M))throw new TypeError;var $=M.call(P);if(!he($))throw new TypeError;return $}function In(P){return P.value}function Ta(P){var M=P.next();return M.done?!1:M}function vf(P){var M=P.return;M&&M.call(P)}function Aa(P){var M=Object.getPrototypeOf(P);if(typeof P!="function"||P===f||M!==f)return M;var $=P.prototype,ce=$&&Object.getPrototypeOf($);if(ce==null||ce===Object.prototype)return M;var Me=ce.constructor;return typeof Me!="function"||Me===P?M:Me}function wf(){var P;!I(S)&&typeof t.Reflect<"u"&&!(S in t.Reflect)&&typeof t.Reflect.defineMetadata=="function"&&(P=fd(t.Reflect));var M,$,ce,Me=new v,$t={registerProvider:Wt,getProvider:ge,setProvider:Re};return $t;function Wt(Be){if(!Object.isExtensible($t))throw new Error("Cannot add provider to a frozen registry.");switch(!0){case P===Be:break;case I(M):M=Be;break;case M===Be:break;case I($):$=Be;break;case $===Be:break;default:ce===void 0&&(ce=new y),ce.add(Be);break}}function ft(Be,st){if(!I(M)){if(M.isProviderFor(Be,st))return M;if(!I($)){if($.isProviderFor(Be,st))return M;if(!I(ce))for(var kt=bf(ce);;){var jt=Ta(kt);if(!jt)return;var Xr=In(jt);if(Xr.isProviderFor(Be,st))return vf(kt),Xr}}}if(!I(P)&&P.isProviderFor(Be,st))return P}function ge(Be,st){var kt=Me.get(Be),jt;return I(kt)||(jt=kt.get(st)),I(jt)&&(jt=ft(Be,st),I(jt)||(I(kt)&&(kt=new h,Me.set(Be,kt)),kt.set(st,jt))),jt}function Ee(Be){if(I(Be))throw new TypeError;return M===Be||$===Be||!I(ce)&&ce.has(Be)}function Re(Be,st,kt){if(!Ee(kt))throw new Error("Metadata provider not registered.");var jt=ge(Be,st);if(jt!==kt){if(!I(jt))return!1;var Xr=Me.get(Be);I(Xr)&&(Xr=new h,Me.set(Be,Xr)),Xr.set(st,kt)}return!0}}function ud(){var P;return!I(S)&&he(t.Reflect)&&Object.isExtensible(t.Reflect)&&(P=t.Reflect[S]),I(P)&&(P=wf()),!I(S)&&he(t.Reflect)&&Object.isExtensible(t.Reflect)&&Object.defineProperty(t.Reflect,S,{enumerable:!1,configurable:!1,writable:!1,value:P}),P}function Sf(P){var M=new v,$={isProviderFor:function(Ee,Re){var Be=M.get(Ee);return I(Be)?!1:Be.has(Re)},OrdinaryDefineOwnMetadata:Wt,OrdinaryHasOwnMetadata:Me,OrdinaryGetOwnMetadata:$t,OrdinaryOwnMetadataKeys:ft,OrdinaryDeleteMetadata:ge};return C.registerProvider($),$;function ce(Ee,Re,Be){var st=M.get(Ee),kt=!1;if(I(st)){if(!Be)return;st=new h,M.set(Ee,st),kt=!0}var jt=st.get(Re);if(I(jt)){if(!Be)return;if(jt=new h,st.set(Re,jt),!P.setProvider(Ee,Re,$))throw st.delete(Re),kt&&M.delete(Ee),new Error("Wrong provider for target.")}return jt}function Me(Ee,Re,Be){var st=ce(Re,Be,!1);return I(st)?!1:Ot(st.has(Ee))}function $t(Ee,Re,Be){var st=ce(Re,Be,!1);if(!I(st))return st.get(Ee)}function Wt(Ee,Re,Be,st){var kt=ce(Be,st,!0);kt.set(Ee,Re)}function ft(Ee,Re){var Be=[],st=ce(Ee,Re,!1);if(I(st))return Be;for(var kt=st.keys(),jt=bf(kt),Xr=0;;){var ld=Ta(jt);if(!ld)return Be.length=Xr,Be;var s0=In(ld);try{Be[Xr]=s0}catch(Rx){try{vf(jt)}finally{throw Rx}}Xr++}}function ge(Ee,Re,Be){var st=ce(Re,Be,!1);if(I(st)||!st.delete(Ee))return!1;if(st.size===0){var kt=M.get(Re);I(kt)||(kt.delete(Be),kt.size===0&&M.delete(kt))}return!0}}function fd(P){var M=P.defineMetadata,$=P.hasOwnMetadata,ce=P.getOwnMetadata,Me=P.getOwnMetadataKeys,$t=P.deleteMetadata,Wt=new v,ft={isProviderFor:function(ge,Ee){var Re=Wt.get(ge);return!I(Re)&&Re.has(Ee)?!0:Me(ge,Ee).length?(I(Re)&&(Re=new y,Wt.set(ge,Re)),Re.add(Ee),!0):!1},OrdinaryDefineOwnMetadata:M,OrdinaryHasOwnMetadata:$,OrdinaryGetOwnMetadata:ce,OrdinaryOwnMetadataKeys:Me,OrdinaryDeleteMetadata:$t};return ft}function xi(P,M,$){var ce=C.getProvider(P,M);if(!I(ce))return ce;if($){if(C.setProvider(P,M,O))return O;throw new Error("Illegal state.")}}function _f(){var P={},M=[],$=(function(){function ft(ge,Ee,Re){this._index=0,this._keys=ge,this._values=Ee,this._selector=Re}return ft.prototype["@@iterator"]=function(){return this},ft.prototype[o]=function(){return this},ft.prototype.next=function(){var ge=this._index;if(ge>=0&&ge<this._keys.length){var Ee=this._selector(this._keys[ge],this._values[ge]);return ge+1>=this._keys.length?(this._index=-1,this._keys=M,this._values=M):this._index++,{value:Ee,done:!1}}return{value:void 0,done:!0}},ft.prototype.throw=function(ge){throw this._index>=0&&(this._index=-1,this._keys=M,this._values=M),ge},ft.prototype.return=function(ge){return this._index>=0&&(this._index=-1,this._keys=M,this._values=M),{value:ge,done:!0}},ft})(),ce=(function(){function ft(){this._keys=[],this._values=[],this._cacheKey=P,this._cacheIndex=-2}return Object.defineProperty(ft.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),ft.prototype.has=function(ge){return this._find(ge,!1)>=0},ft.prototype.get=function(ge){var Ee=this._find(ge,!1);return Ee>=0?this._values[Ee]:void 0},ft.prototype.set=function(ge,Ee){var Re=this._find(ge,!0);return this._values[Re]=Ee,this},ft.prototype.delete=function(ge){var Ee=this._find(ge,!1);if(Ee>=0){for(var Re=this._keys.length,Be=Ee+1;Be<Re;Be++)this._keys[Be-1]=this._keys[Be],this._values[Be-1]=this._values[Be];return this._keys.length--,this._values.length--,yf(ge,this._cacheKey)&&(this._cacheKey=P,this._cacheIndex=-2),!0}return!1},ft.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=P,this._cacheIndex=-2},ft.prototype.keys=function(){return new $(this._keys,this._values,Me)},ft.prototype.values=function(){return new $(this._keys,this._values,$t)},ft.prototype.entries=function(){return new $(this._keys,this._values,Wt)},ft.prototype["@@iterator"]=function(){return this.entries()},ft.prototype[o]=function(){return this.entries()},ft.prototype._find=function(ge,Ee){if(!yf(this._cacheKey,ge)){this._cacheIndex=-1;for(var Re=0;Re<this._keys.length;Re++)if(yf(this._keys[Re],ge)){this._cacheIndex=Re;break}}return this._cacheIndex<0&&Ee&&(this._cacheIndex=this._keys.length,this._keys.push(ge),this._values.push(void 0)),this._cacheIndex},ft})();return ce;function Me(ft,ge){return ft}function $t(ft,ge){return ge}function Wt(ft,ge){return[ft,ge]}}function r0(){var P=(function(){function M(){this._map=new h}return Object.defineProperty(M.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),M.prototype.has=function($){return this._map.has($)},M.prototype.add=function($){return this._map.set($,$),this},M.prototype.delete=function($){return this._map.delete($)},M.prototype.clear=function(){this._map.clear()},M.prototype.keys=function(){return this._map.keys()},M.prototype.values=function(){return this._map.keys()},M.prototype.entries=function(){return this._map.entries()},M.prototype["@@iterator"]=function(){return this.keys()},M.prototype[o]=function(){return this.keys()},M})();return P}function Ix(){var P=16,M=u.create(),$=ce();return(function(){function ge(){this._key=ce()}return ge.prototype.has=function(Ee){var Re=Me(Ee,!1);return Re!==void 0?u.has(Re,this._key):!1},ge.prototype.get=function(Ee){var Re=Me(Ee,!1);return Re!==void 0?u.get(Re,this._key):void 0},ge.prototype.set=function(Ee,Re){var Be=Me(Ee,!0);return Be[this._key]=Re,this},ge.prototype.delete=function(Ee){var Re=Me(Ee,!1);return Re!==void 0?delete Re[this._key]:!1},ge.prototype.clear=function(){this._key=ce()},ge})();function ce(){var ge;do ge="@@WeakMap@@"+ft();while(u.has(M,ge));return M[ge]=!0,ge}function Me(ge,Ee){if(!s.call(ge,$)){if(!Ee)return;Object.defineProperty(ge,$,{value:u.create()})}return ge[$]}function $t(ge,Ee){for(var Re=0;Re<Ee;++Re)ge[Re]=Math.random()*255|0;return ge}function Wt(ge){if(typeof Uint8Array=="function"){var Ee=new Uint8Array(ge);return typeof crypto<"u"?crypto.getRandomValues(Ee):typeof msCrypto<"u"?msCrypto.getRandomValues(Ee):$t(Ee,ge),Ee}return $t(new Array(ge),ge)}function ft(){var ge=Wt(P);ge[6]=ge[6]&79|64,ge[8]=ge[8]&191|128;for(var Ee="",Re=0;Re<P;++Re){var Be=ge[Re];(Re===4||Re===6||Re===8)&&(Ee+="-"),Be<16&&(Ee+="0"),Ee+=Be.toString(16).toLowerCase()}return Ee}}function Ia(P){return P.__=void 0,delete P.__,P}})})(A6||(A6={}))});function R6(...r){let e=r.map(n=>n.byteLength).reduce((n,i)=>n+i),t=new Uint8Array(e),s=0;return r.map(n=>new Uint8Array(n)).forEach(n=>{for(let i of n)t[s++]=i}),t.buffer}function k6(r,e){if(!(r&&e)||r.byteLength!==e.byteLength)return!1;let t=new Uint8Array(r),s=new Uint8Array(e);for(let n=0;n<r.byteLength;n++)if(t[n]!==s[n])return!1;return!0}var fM,xe,Yb,lM,hM,pM,nm,Hs,Ue,Jb=T(()=>{"use strict";fM="[object ArrayBuffer]",xe=class r{static isArrayBuffer(e){return Object.prototype.toString.call(e)===fM}static toArrayBuffer(e){return this.isArrayBuffer(e)?e:e.byteLength===e.buffer.byteLength||e.byteOffset===0&&e.byteLength===e.buffer.byteLength?e.buffer:this.toUint8Array(e.buffer).slice(e.byteOffset,e.byteOffset+e.byteLength).buffer}static toUint8Array(e){return this.toView(e,Uint8Array)}static toView(e,t){if(e.constructor===t)return e;if(this.isArrayBuffer(e))return new t(e);if(this.isArrayBufferView(e))return new t(e.buffer,e.byteOffset,e.byteLength);throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'")}static isBufferSource(e){return this.isArrayBufferView(e)||this.isArrayBuffer(e)}static isArrayBufferView(e){return ArrayBuffer.isView(e)||e&&this.isArrayBuffer(e.buffer)}static isEqual(e,t){let s=r.toUint8Array(e),n=r.toUint8Array(t);if(s.length!==n.byteLength)return!1;for(let i=0;i<s.length;i++)if(s[i]!==n[i])return!1;return!0}static concat(...e){let t;Array.isArray(e[0])&&!(e[1]instanceof Function)||Array.isArray(e[0])&&e[1]instanceof Function?t=e[0]:e[e.length-1]instanceof Function?t=e.slice(0,e.length-1):t=e;let s=0;for(let o of t)s+=o.byteLength;let n=new Uint8Array(s),i=0;for(let o of t){let a=this.toUint8Array(o);n.set(a,i),i+=a.length}return e[e.length-1]instanceof Function?this.toView(n,e[e.length-1]):n.buffer}},Yb="string",lM=/^[0-9a-f\s]+$/i,hM=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,pM=/^[a-zA-Z0-9-_]+$/,nm=class{static fromString(e){let t=unescape(encodeURIComponent(e)),s=new Uint8Array(t.length);for(let n=0;n<t.length;n++)s[n]=t.charCodeAt(n);return s.buffer}static toString(e){let t=xe.toUint8Array(e),s="";for(let i=0;i<t.length;i++)s+=String.fromCharCode(t[i]);return decodeURIComponent(escape(s))}},Hs=class{static toString(e,t=!1){let s=xe.toArrayBuffer(e),n=new DataView(s),i="";for(let o=0;o<s.byteLength;o+=2){let a=n.getUint16(o,t);i+=String.fromCharCode(a)}return i}static fromString(e,t=!1){let s=new ArrayBuffer(e.length*2),n=new DataView(s);for(let i=0;i<e.length;i++)n.setUint16(i*2,e.charCodeAt(i),t);return s}},Ue=class r{static isHex(e){return typeof e===Yb&&lM.test(e)}static isBase64(e){return typeof e===Yb&&hM.test(e)}static isBase64Url(e){return typeof e===Yb&&pM.test(e)}static ToString(e,t="utf8"){let s=xe.toUint8Array(e);switch(t.toLowerCase()){case"utf8":return this.ToUtf8String(s);case"binary":return this.ToBinary(s);case"hex":return this.ToHex(s);case"base64":return this.ToBase64(s);case"base64url":return this.ToBase64Url(s);case"utf16le":return Hs.toString(s,!0);case"utf16":case"utf16be":return Hs.toString(s);default:throw new Error(`Unknown type of encoding '${t}'`)}}static FromString(e,t="utf8"){if(!e)return new ArrayBuffer(0);switch(t.toLowerCase()){case"utf8":return this.FromUtf8String(e);case"binary":return this.FromBinary(e);case"hex":return this.FromHex(e);case"base64":return this.FromBase64(e);case"base64url":return this.FromBase64Url(e);case"utf16le":return Hs.fromString(e,!0);case"utf16":case"utf16be":return Hs.fromString(e);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToBase64(e){let t=xe.toUint8Array(e);if(typeof btoa<"u"){let s=this.ToString(t,"binary");return btoa(s)}else return Buffer.from(t).toString("base64")}static FromBase64(e){let t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!r.isBase64(t))throw new TypeError("Argument 'base64Text' is not Base64 encoded");return typeof atob<"u"?this.FromBinary(atob(t)):new Uint8Array(Buffer.from(t,"base64")).buffer}static FromBase64Url(e){let t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!r.isBase64Url(t))throw new TypeError("Argument 'base64url' is not Base64Url encoded");return this.FromBase64(this.Base64Padding(t.replace(/\-/g,"+").replace(/\_/g,"/")))}static ToBase64Url(e){return this.ToBase64(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/\=/g,"")}static FromUtf8String(e,t=r.DEFAULT_UTF8_ENCODING){switch(t){case"ascii":return this.FromBinary(e);case"utf8":return nm.fromString(e);case"utf16":case"utf16be":return Hs.fromString(e);case"utf16le":case"usc2":return Hs.fromString(e,!0);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToUtf8String(e,t=r.DEFAULT_UTF8_ENCODING){switch(t){case"ascii":return this.ToBinary(e);case"utf8":return nm.toString(e);case"utf16":case"utf16be":return Hs.toString(e);case"utf16le":case"usc2":return Hs.toString(e,!0);default:throw new Error(`Unknown type of encoding '${t}'`)}}static FromBinary(e){let t=e.length,s=new Uint8Array(t);for(let n=0;n<t;n++)s[n]=e.charCodeAt(n);return s.buffer}static ToBinary(e){let t=xe.toUint8Array(e),s="";for(let n=0;n<t.length;n++)s+=String.fromCharCode(t[n]);return s}static ToHex(e){let t=xe.toUint8Array(e),s="",n=t.length;for(let i=0;i<n;i++){let o=t[i];o<16&&(s+="0"),s+=o.toString(16)}return s}static FromHex(e){let t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!r.isHex(t))throw new TypeError("Argument 'hexString' is not HEX encoded");t.length%2&&(t=`0${t}`);let s=new Uint8Array(t.length/2);for(let n=0;n<t.length;n=n+2){let i=t.slice(n,n+2);s[n/2]=parseInt(i,16)}return s.buffer}static ToUtf16String(e,t=!1){return Hs.toString(e,t)}static FromUtf16String(e,t=!1){return Hs.fromString(e,t)}static Base64Padding(e){let t=4-e.length%4;if(t<4)for(let s=0;s<t;s++)e+="=";return e}static formatString(e){return e?.replace(/[\n\r\t ]/g,"")||""}};Ue.DEFAULT_UTF8_ENCODING="utf8"});function Ma(r,e){let t=0;if(r.length===1)return r[0];for(let s=r.length-1;s>=0;s--)t+=r[r.length-1-s]*Math.pow(2,e*s);return t}function Ao(r,e,t=-1){let s=t,n=r,i=0,o=Math.pow(2,e);for(let a=1;a<8;a++){if(r<o){let c;if(s<0)c=new ArrayBuffer(a),i=a;else{if(s<a)return new ArrayBuffer(0);c=new ArrayBuffer(s),i=s}let d=new Uint8Array(c);for(let u=a-1;u>=0;u--){let f=Math.pow(2,u*e);d[i-u-1]=Math.floor(n/f),n-=d[i-u-1]*f}return c}o*=Math.pow(2,e)}return new ArrayBuffer(0)}function im(...r){let e=0,t=0;for(let i of r)e+=i.length;let s=new ArrayBuffer(e),n=new Uint8Array(s);for(let i of r)n.set(i,t),t+=i.length;return n}function Qb(){let r=new Uint8Array(this.valueHex);if(this.valueHex.byteLength>=2){let a=r[0]===255&&r[1]&128,c=r[0]===0&&(r[1]&128)===0;(a||c)&&this.warnings.push("Needlessly long format")}let e=new ArrayBuffer(this.valueHex.byteLength),t=new Uint8Array(e);for(let a=0;a<this.valueHex.byteLength;a++)t[a]=0;t[0]=r[0]&128;let s=Ma(t,8),n=new ArrayBuffer(this.valueHex.byteLength),i=new Uint8Array(n);for(let a=0;a<this.valueHex.byteLength;a++)i[a]=r[a];return i[0]&=127,Ma(i,8)-s}function P6(r){let e=r<0?r*-1:r,t=128;for(let s=1;s<8;s++){if(e<=t){if(r<0){let o=t-e,a=Ao(o,8,s),c=new Uint8Array(a);return c[0]|=128,a}let n=Ao(e,8,s),i=new Uint8Array(n);if(i[0]&128){let o=n.slice(0),a=new Uint8Array(o);n=new ArrayBuffer(n.byteLength+1),i=new Uint8Array(n);for(let c=0;c<o.byteLength;c++)i[c+1]=a[c];i[0]=0}return n}t*=Math.pow(2,8)}return new ArrayBuffer(0)}function B6(r,e){if(r.byteLength!==e.byteLength)return!1;let t=new Uint8Array(r),s=new Uint8Array(e);for(let n=0;n<t.length;n++)if(t[n]!==s[n])return!1;return!0}function cs(r,e){let t=r.toString(10);if(e<t.length)return"";let s=e-t.length,n=new Array(s);for(let o=0;o<s;o++)n[o]="0";return n.join("").concat(t)}var tW,N6=T(()=>{"use strict";tW=Math.log(2)});var jn={};Ef(jn,{Any:()=>Dn,BaseBlock:()=>ur,BaseStringBlock:()=>Xf,BitString:()=>an,BmpString:()=>Fa,Boolean:()=>Ua,CharacterString:()=>Ya,Choice:()=>qd,Constructed:()=>fr,DATE:()=>tl,DEFAULT_MAX_CONTENT_LENGTH:()=>z6,DEFAULT_MAX_DEPTH:()=>F6,DEFAULT_MAX_NODES:()=>q6,DateTime:()=>sl,Duration:()=>nl,EndOfContent:()=>Yf,Enumerated:()=>ja,GeneralString:()=>Xa,GeneralizedTime:()=>Ja,GraphicString:()=>Ga,HexBlock:()=>Un,IA5String:()=>Wa,Integer:()=>Ai,Null:()=>nn,NumericString:()=>za,ObjectIdentifier:()=>Ha,OctetString:()=>on,Primitive:()=>Ti,PrintableString:()=>$a,RawData:()=>e1,RelativeObjectIdentifier:()=>el,Repeated:()=>Qa,Sequence:()=>Vr,Set:()=>es,TIME:()=>il,TeletexString:()=>Va,TimeOfDay:()=>rl,UTCTime:()=>Ro,UniversalString:()=>qa,Utf8String:()=>Fs,ValueBlock:()=>Er,VideotexString:()=>Ka,ViewWriter:()=>Fd,VisibleString:()=>Io,compareSchema:()=>Ei,fromBER:()=>Ri,verifySchema:()=>LM});function om(){if(typeof BigInt>"u")throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function t1(r){let e=0,t=0;for(let n=0;n<r.length;n++){let i=r[n];e+=i.byteLength}let s=new Uint8Array(e);for(let n=0;n<r.length;n++){let i=r[n];s.set(new Uint8Array(i),t),t+=i.byteLength}return s.buffer}function Ii(r,e,t,s){return e instanceof Uint8Array?e.byteLength?t<0?(r.error="Wrong parameter: inputOffset less than zero",!1):s<0?(r.error="Wrong parameter: inputLength less than zero",!1):e.byteLength-t-s<0?(r.error="End of input reached before message was fully decoded (inconsistent offset and length values)",!1):!0:(r.error="Wrong parameter: inputBuffer has zero length",!1):(r.error="Wrong parameter: inputBuffer must be 'Uint8Array'",!1)}function Un(r){var e;return e=class extends r{get valueHex(){return this.valueHexView.slice().buffer}set valueHex(s){this.valueHexView=new Uint8Array(s)}constructor(...s){var n;super(...s);let i=s[0]||{};this.isHexOnly=(n=i.isHexOnly)!==null&&n!==void 0?n:!1,this.valueHexView=i.valueHex?xe.toUint8Array(i.valueHex):wm}fromBER(s,n,i,o){let a=s instanceof ArrayBuffer?new Uint8Array(s):s;if(!Ii(this,a,n,i))return-1;let c=n+i;return this.valueHexView=a.subarray(n,c),this.valueHexView.length?(this.blockLength=i,c):(this.warnings.push("Zero buffer length"),n)}toBER(s=!1){return this.isHexOnly?s?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.byteLength===this.valueHexView.buffer.byteLength?this.valueHexView.buffer:this.valueHexView.slice().buffer:(this.error="Flag 'isHexOnly' is not set, abort",Mn)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:Ue.ToHex(this.valueHexView)}}},e.NAME="hexBlock",e}function j6(r){var e;if(r instanceof Ce.Constructed)for(let t of r.valueBlock.value)j6(t)&&(r.lenBlock.isIndefiniteForm=!0);return!!(!((e=r.lenBlock)===null||e===void 0)&&e.isIndefiniteForm)}function ol(r={}){var e,t,s;return{depth:0,maxDepth:(e=r.maxDepth)!==null&&e!==void 0?e:F6,nodesCount:0,maxNodes:(t=r.maxNodes)!==null&&t!==void 0?t:q6,maxContentLength:(s=r.maxContentLength)!==null&&s!==void 0?s:z6}}function IM(r){let e=new ur({},Er);return e.error=r,{offset:-1,result:e}}function RM(r){if(r.nodesCount+=1,r.nodesCount>r.maxNodes)return TM}function kM(r,e){if(r>e.maxContentLength)return AM}function r1(r,e,t,s){let n=s.depth+1;if(n>s.maxDepth)return IM(CM);s.depth=n;try{return Sm(r,e,t,s)}finally{s.depth-=1}}function PM(r,e){if(r instanceof e)return r;let t=new e;return t.idBlock=r.idBlock,t.lenBlock=r.lenBlock,t.warnings=r.warnings,t.valueBeforeDecodeView=r.valueBeforeDecodeView,t}function Sm(r,e=0,t=r.length,s=ol()){let n=e,i=new ur({},Er),o=new Ci;if(!Ii(o,r,e,t))return i.error=o.error,{offset:-1,result:i};if(!r.subarray(e,e+t).length)return i.error="Zero buffer length",{offset:-1,result:i};let c=RM(s);if(c)return i.error=c,{offset:-1,result:i};let d=i.idBlock.fromBER(r,e,t);if(i.idBlock.warnings.length&&i.warnings.concat(i.idBlock.warnings),d===-1)return i.error=i.idBlock.error,{offset:-1,result:i};if(e=d,t-=i.idBlock.blockLength,d=i.lenBlock.fromBER(r,e,t),i.lenBlock.warnings.length&&i.warnings.concat(i.lenBlock.warnings),d===-1)return i.error=i.lenBlock.error,{offset:-1,result:i};e=d,t-=i.lenBlock.blockLength;let u=i.lenBlock.isIndefiniteForm?t:i.lenBlock.length,f=kM(u,s);if(f)return i.error=f,{offset:-1,result:i};if(!i.idBlock.isConstructed&&i.lenBlock.isIndefiniteForm)return i.error="Indefinite length form used for primitive encoding form",{offset:-1,result:i};let h=ur;switch(i.idBlock.tagClass){case 1:if(i.idBlock.tagNumber>=37&&i.idBlock.isHexOnly===!1)return i.error="UNIVERSAL 37 and upper tags are reserved by ASN.1 standard",{offset:-1,result:i};switch(i.idBlock.tagNumber){case 0:if(i.idBlock.isConstructed&&i.lenBlock.length>0)return i.error="Type [UNIVERSAL 0] is reserved",{offset:-1,result:i};h=Ce.EndOfContent;break;case 1:h=Ce.Boolean;break;case 2:h=Ce.Integer;break;case 3:h=Ce.BitString;break;case 4:h=Ce.OctetString;break;case 5:h=Ce.Null;break;case 6:h=Ce.ObjectIdentifier;break;case 10:h=Ce.Enumerated;break;case 12:h=Ce.Utf8String;break;case 13:h=Ce.RelativeObjectIdentifier;break;case 14:h=Ce.TIME;break;case 15:return i.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:i};case 16:h=Ce.Sequence;break;case 17:h=Ce.Set;break;case 18:h=Ce.NumericString;break;case 19:h=Ce.PrintableString;break;case 20:h=Ce.TeletexString;break;case 21:h=Ce.VideotexString;break;case 22:h=Ce.IA5String;break;case 23:h=Ce.UTCTime;break;case 24:h=Ce.GeneralizedTime;break;case 25:h=Ce.GraphicString;break;case 26:h=Ce.VisibleString;break;case 27:h=Ce.GeneralString;break;case 28:h=Ce.UniversalString;break;case 29:h=Ce.CharacterString;break;case 30:h=Ce.BmpString;break;case 31:h=Ce.DATE;break;case 32:h=Ce.TimeOfDay;break;case 33:h=Ce.DateTime;break;case 34:h=Ce.Duration;break;default:{let y=i.idBlock.isConstructed?new Ce.Constructed:new Ce.Primitive;y.idBlock=i.idBlock,y.lenBlock=i.lenBlock,y.warnings=i.warnings,i=y}}break;default:h=i.idBlock.isConstructed?Ce.Constructed:Ce.Primitive}return i=PM(i,h),d=i.fromBER(r,e,u,s),i.valueBeforeDecodeView=r.subarray(n,n+i.blockLength),{offset:d,result:i}}function Ri(r,e={}){if(!r.byteLength){let t=new ur({},Er);return t.error="Input buffer has zero length",{offset:-1,result:t}}return Sm(xe.toUint8Array(r).slice(),0,r.byteLength,ol(e))}function BM(r,e){return r?1:e}function NM(r,e){let t=new Uint8Array([0]),s=new Uint8Array(r),n=new Uint8Array(e),i=s.slice(0),o=i.length-1,a=n.slice(0),c=a.length-1,d=0,u=c<o?o:c,f=0;for(let h=u;h>=0;h--,f++)!0===f<a.length?d=i[o-f]+a[c-f]+t[0]:d=i[o-f]+t[0],t[0]=d/10,!0===f>=i.length?i=im(new Uint8Array([d%10]),i):i[o-f]=d%10;return t[0]>0&&(i=im(t,i)),i}function D6(r){if(r>=Kf.length)for(let e=Kf.length;e<=r;e++){let t=new Uint8Array([0]),s=Kf[e-1].slice(0);for(let n=s.length-1;n>=0;n--){let i=new Uint8Array([(s[n]<<1)+t[0]]);t[0]=i[0]/10,s[n]=i[0]%10}t[0]>0&&(s=im(t,s)),Kf.push(s)}return Kf[r]}function OM(r,e){let t=0,s=new Uint8Array(r),n=new Uint8Array(e),i=s.slice(0),o=i.length-1,a=n.slice(0),c=a.length-1,d,u=0;for(let f=c;f>=0;f--,u++)d=i[o-u]-a[c-u]-t,!0===d<0?(t=1,i[o-u]=d+10):(t=0,i[o-u]=d);if(t>0)for(let f=o-c+1;f>=0;f--,u++)if(d=i[o-u]-t,d<0)t=1,i[o-u]=d+10;else{t=0,i[o-u]=d;break}return i.slice()}function Ei(r,e,t){if(t instanceof qd){for(let i of t.value)if(Ei(r,e,i).verified)return{verified:!0,result:r};{let i={verified:!1,result:{error:"Wrong values for Choice type"}};return t.hasOwnProperty(Zb)&&(i.name=t.name),i}}if(t instanceof Dn)return t.hasOwnProperty(Zb)&&(r[t.name]=e),{verified:!0,result:r};if(!(r instanceof Object))return{verified:!1,result:{error:"Wrong root object"}};if(!(e instanceof Object))return{verified:!1,result:{error:"Wrong ASN.1 data"}};if(!(t instanceof Object))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(!(xM in t))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(!(SM in t.idBlock))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(!(_M in t.idBlock))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};let s=t.idBlock.toBER(!1);if(s.byteLength===0)return{verified:!1,result:{error:"Error encoding idBlock for ASN.1 schema"}};if(t.idBlock.fromBER(s,0,s.byteLength)===-1)return{verified:!1,result:{error:"Error decoding idBlock for ASN.1 schema"}};if(t.idBlock.hasOwnProperty(bM)===!1)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(t.idBlock.tagClass!==e.idBlock.tagClass)return{verified:!1,result:r};if(t.idBlock.hasOwnProperty(vM)===!1)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(t.idBlock.tagNumber!==e.idBlock.tagNumber)return{verified:!1,result:r};if(t.idBlock.hasOwnProperty(wM)===!1)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(t.idBlock.isConstructed!==e.idBlock.isConstructed)return{verified:!1,result:r};if(!(yM in t.idBlock))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(t.idBlock.isHexOnly!==e.idBlock.isHexOnly)return{verified:!1,result:r};if(t.idBlock.isHexOnly){if(!(L6 in t.idBlock))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};let i=t.idBlock.valueHexView,o=e.idBlock.valueHexView;if(i.length!==o.length)return{verified:!1,result:r};for(let a=0;a<i.length;a++)if(i[a]!==o[1])return{verified:!1,result:r}}if(t.name&&(t.name=t.name.replace(/^\s+|\s+$/g,ds),t.name&&(r[t.name]=e)),t instanceof Ce.Constructed){let i=0,o={verified:!1,result:{error:"Unknown error"}},a=t.valueBlock.value.length;if(a>0&&t.valueBlock.value[0]instanceof Qa&&(a=e.valueBlock.value.length),a===0)return{verified:!0,result:r};if(e.valueBlock.value.length===0&&t.valueBlock.value.length!==0){let c=!0;for(let d=0;d<t.valueBlock.value.length;d++)c=c&&(t.valueBlock.value[d].optional||!1);return c?{verified:!0,result:r}:(t.name&&(t.name=t.name.replace(/^\s+|\s+$/g,ds),t.name&&delete r[t.name]),r.error="Inconsistent object length",{verified:!1,result:r})}for(let c=0;c<a;c++)if(c-i>=e.valueBlock.value.length){if(t.valueBlock.value[c].optional===!1){let d={verified:!1,result:r};return r.error="Inconsistent length between ASN.1 data and schema",t.name&&(t.name=t.name.replace(/^\s+|\s+$/g,ds),t.name&&(delete r[t.name],d.name=t.name)),d}}else if(t.valueBlock.value[0]instanceof Qa){if(o=Ei(r,e.valueBlock.value[c],t.valueBlock.value[0].value),o.verified===!1)if(t.valueBlock.value[0].optional)i++;else return t.name&&(t.name=t.name.replace(/^\s+|\s+$/g,ds),t.name&&delete r[t.name]),o;if(Zb in t.valueBlock.value[0]&&t.valueBlock.value[0].name.length>0){let d={};EM in t.valueBlock.value[0]&&t.valueBlock.value[0].local?d=e:d=r,typeof d[t.valueBlock.value[0].name]>"u"&&(d[t.valueBlock.value[0].name]=[]),d[t.valueBlock.value[0].name].push(e.valueBlock.value[c])}}else if(o=Ei(r,e.valueBlock.value[c-i],t.valueBlock.value[c]),o.verified===!1)if(t.valueBlock.value[c].optional)i++;else return t.name&&(t.name=t.name.replace(/^\s+|\s+$/g,ds),t.name&&delete r[t.name]),o;if(o.verified===!1){let c={verified:!1,result:r};return t.name&&(t.name=t.name.replace(/^\s+|\s+$/g,ds),t.name&&(delete r[t.name],c.name=t.name)),c}return{verified:!0,result:r}}if(t.primitiveSchema&&L6 in e.valueBlock){let i=Sm(e.valueBlock.valueHexView);if(i.offset===-1){let o={verified:!1,result:i.result};return t.name&&(t.name=t.name.replace(/^\s+|\s+$/g,ds),t.name&&(delete r[t.name],o.name=t.name)),o}return Ei(r,i.result,t.primitiveSchema)}return{verified:!0,result:r}}function LM(r,e){if(!(e instanceof Object))return{verified:!1,result:{error:"Wrong ASN.1 schema type"}};let t=Sm(xe.toUint8Array(r));return t.offset===-1?{verified:!1,result:t.result}:Ei(t.result,t.result,e)}var Fd,Kf,O6,Zb,L6,yM,xM,bM,vM,wM,SM,_M,EM,ds,Mn,wm,Gf,M6,U6,Ci,Er,am,cm,Ce,ur,Xf,dm,H6,Ti,F6,q6,z6,CM,TM,AM,Ln,$6,fr,um,V6,Yf,K6,nn,fm,W6,Ua,lm,s1,on,hm,G6,an,X6,Jf,Wf,Ai,Y6,ja,Qf,pm,J6,Ha,Zf,mm,Q6,el,Z6,Vr,e3,es,gm,ym,ts,xm,t3,Fs,bm,r3,Fa,vm,s3,qa,n3,za,i3,$a,o3,Va,a3,Ka,c3,Wa,d3,Ga,u3,Io,f3,Xa,l3,Ya,h3,Ro,p3,Ja,m3,tl,g3,rl,y3,sl,x3,nl,b3,il,Dn,qd,Qa,e1,ko=T(()=>{"use strict";Jb();N6();Fd=class{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return t1(this.items)}},Kf=[new Uint8Array([1])],O6="0123456789",Zb="name",L6="valueHexView",yM="isHexOnly",xM="idBlock",bM="tagClass",vM="tagNumber",wM="isConstructed",SM="fromBER",_M="toBER",EM="local",ds="",Mn=new ArrayBuffer(0),wm=new Uint8Array(0),Gf="EndOfContent",M6="OCTET STRING",U6="BIT STRING";Ci=class{static blockName(){return this.NAME}get valueBeforeDecode(){return this.valueBeforeDecodeView.slice().buffer}set valueBeforeDecode(e){this.valueBeforeDecodeView=new Uint8Array(e)}constructor({blockLength:e=0,error:t=ds,warnings:s=[],valueBeforeDecode:n=wm}={}){this.blockLength=e,this.error=t,this.warnings=s,this.valueBeforeDecodeView=xe.toUint8Array(n)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:Ue.ToHex(this.valueBeforeDecodeView)}}};Ci.NAME="baseBlock";Er=class extends Ci{fromBER(e,t,s,n){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}toBER(e,t){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}};Er.NAME="valueBlock";am=class extends Un(Ci){constructor({idBlock:e={}}={}){var t,s,n,i;super(),e?(this.isHexOnly=(t=e.isHexOnly)!==null&&t!==void 0?t:!1,this.valueHexView=e.valueHex?xe.toUint8Array(e.valueHex):wm,this.tagClass=(s=e.tagClass)!==null&&s!==void 0?s:-1,this.tagNumber=(n=e.tagNumber)!==null&&n!==void 0?n:-1,this.isConstructed=(i=e.isConstructed)!==null&&i!==void 0?i:!1):(this.tagClass=-1,this.tagNumber=-1,this.isConstructed=!1)}toBER(e=!1){let t=0;switch(this.tagClass){case 1:t|=0;break;case 2:t|=64;break;case 3:t|=128;break;case 4:t|=192;break;default:return this.error="Unknown tag class",Mn}if(this.isConstructed&&(t|=32),this.tagNumber<31&&!this.isHexOnly){let n=new Uint8Array(1);if(!e){let i=this.tagNumber;i&=31,t|=i,n[0]=t}return n.buffer}if(!this.isHexOnly){let n=Ao(this.tagNumber,7),i=new Uint8Array(n),o=n.byteLength,a=new Uint8Array(o+1);if(a[0]=t|31,!e){for(let c=0;c<o-1;c++)a[c+1]=i[c]|128;a[o]=i[o-1]}return a.buffer}let s=new Uint8Array(this.valueHexView.byteLength+1);if(s[0]=t|31,!e){let n=this.valueHexView;for(let i=0;i<n.length-1;i++)s[i+1]=n[i]|128;s[this.valueHexView.byteLength]=n[n.length-1]}return s.buffer}fromBER(e,t,s){let n=xe.toUint8Array(e);if(!Ii(this,n,t,s))return-1;let i=n.subarray(t,t+s);if(i.length===0)return this.error="Zero buffer length",-1;switch(i[0]&192){case 0:this.tagClass=1;break;case 64:this.tagClass=2;break;case 128:this.tagClass=3;break;case 192:this.tagClass=4;break;default:return this.error="Unknown tag class",-1}this.isConstructed=(i[0]&32)===32,this.isHexOnly=!1;let a=i[0]&31;if(a!==31)this.tagNumber=a,this.blockLength=1;else{let c=0;for(;;){let u=c+1;if(u>=i.length)return this.error="End of input reached before message was fully decoded",-1;if(c++,(i[u]&128)===0)break}this.blockLength=c+1;let d=this.valueHexView=new Uint8Array(c);for(let u=0;u<c;u++)d[u]=i[u+1]&127;this.blockLength<=9?this.tagNumber=Ma(d,7):(this.isHexOnly=!0,this.warnings.push("Tag too long, represented as hex-coded"))}if(this.tagClass===1&&this.isConstructed)switch(this.tagNumber){case 1:case 2:case 5:case 6:case 9:case 13:case 14:case 23:case 24:case 31:case 32:case 33:case 34:return this.error="Constructed encoding used for primitive type",-1}return t+this.blockLength}toJSON(){return{...super.toJSON(),tagClass:this.tagClass,tagNumber:this.tagNumber,isConstructed:this.isConstructed}}};am.NAME="identificationBlock";cm=class extends Ci{constructor({lenBlock:e={}}={}){var t,s,n;super(),this.isIndefiniteForm=(t=e.isIndefiniteForm)!==null&&t!==void 0?t:!1,this.longFormUsed=(s=e.longFormUsed)!==null&&s!==void 0?s:!1,this.length=(n=e.length)!==null&&n!==void 0?n:0}fromBER(e,t,s){let n=xe.toUint8Array(e);if(!Ii(this,n,t,s))return-1;let i=n.subarray(t,t+s);if(i.length===0)return this.error="Zero buffer length",-1;if(i[0]===255)return this.error="Length block 0xFF is reserved by standard",-1;if(this.isIndefiniteForm=i[0]===128,this.isIndefiniteForm)return this.blockLength=1,t+this.blockLength;if(this.longFormUsed=!!(i[0]&128),this.longFormUsed===!1)return this.length=i[0],this.blockLength=1,t+this.blockLength;let o=i[0]&127;if(o>8)return this.error="Too big integer",-1;if(o+1>i.length)return this.error="End of input reached before message was fully decoded",-1;let a=t+1,c=n.subarray(a,a+o);return c[o-1]===0&&this.warnings.push("Needlessly long encoded length"),this.length=Ma(c,8),this.longFormUsed&&this.length<=127&&this.warnings.push("Unnecessary usage of long length form"),this.blockLength=o+1,t+this.blockLength}toBER(e=!1){let t,s;if(this.length>127&&(this.longFormUsed=!0),this.isIndefiniteForm)return t=new ArrayBuffer(1),e===!1&&(s=new Uint8Array(t),s[0]=128),t;if(this.longFormUsed){let n=Ao(this.length,8);if(n.byteLength>127)return this.error="Too big length",Mn;if(t=new ArrayBuffer(n.byteLength+1),e)return t;let i=new Uint8Array(n);s=new Uint8Array(t),s[0]=n.byteLength|128;for(let o=0;o<n.byteLength;o++)s[o+1]=i[o];return t}return t=new ArrayBuffer(1),e===!1&&(s=new Uint8Array(t),s[0]=this.length),t}toJSON(){return{...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,longFormUsed:this.longFormUsed,length:this.length}}};cm.NAME="lengthBlock";Ce={},ur=class extends Ci{constructor({name:e=ds,optional:t=!1,primitiveSchema:s,...n}={},i){super(n),this.name=e,this.optional=t,s&&(this.primitiveSchema=s),this.idBlock=new am(n),this.lenBlock=new cm(n),this.valueBlock=i?new i(n):new Er(n)}fromBER(e,t,s,n){let i=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?s:this.lenBlock.length,n);return i===-1?(this.error=this.valueBlock.error,i):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),i)}toBER(e,t){let s=t||new Fd;t||j6(this);let n=this.idBlock.toBER(e);if(s.write(n),this.lenBlock.isIndefiniteForm)s.write(new Uint8Array([128]).buffer),this.valueBlock.toBER(e,s),s.write(new ArrayBuffer(2));else{let i=this.valueBlock.toBER(e);this.lenBlock.length=i.byteLength;let o=this.lenBlock.toBER(e);s.write(o),s.write(i)}return t?Mn:s.final()}toJSON(){let e={...super.toJSON(),idBlock:this.idBlock.toJSON(),lenBlock:this.lenBlock.toJSON(),valueBlock:this.valueBlock.toJSON(),name:this.name,optional:this.optional};return this.primitiveSchema&&(e.primitiveSchema=this.primitiveSchema.toJSON()),e}toString(e="ascii"){return e==="ascii"?this.onAsciiEncoding():Ue.ToHex(this.toBER())}onAsciiEncoding(){let e=this.constructor.NAME,t=Ue.ToHex(this.valueBlock.valueBeforeDecodeView);return`${e} : ${t}`}isEqual(e){if(this===e)return!0;if(!(e instanceof this.constructor))return!1;let t=this.toBER(),s=e.toBER();return B6(t,s)}};ur.NAME="BaseBlock";Xf=class extends ur{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor({value:e=ds,...t}={},s){super(t,s),e&&this.fromString(e)}fromBER(e,t,s){let n=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?s:this.lenBlock.length);return n===-1?(this.error=this.valueBlock.error,n):(this.fromBuffer(this.valueBlock.valueHexView),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),n)}onAsciiEncoding(){return`${this.constructor.NAME} : '${this.valueBlock.value}'`}};Xf.NAME="BaseStringBlock";dm=class extends Un(Er){constructor({isHexOnly:e=!0,...t}={}){super(t),this.isHexOnly=e}};dm.NAME="PrimitiveValueBlock";Ti=class extends ur{constructor(e={}){super(e,dm),this.idBlock.isConstructed=!1}};H6=Ti;Ce.Primitive=H6;Ti.NAME="PRIMITIVE";F6=100,q6=1e4,z6=16*1024*1024,CM="Maximum ASN.1 nesting depth exceeded",TM="Maximum ASN.1 node count exceeded",AM="Maximum ASN.1 content length exceeded";Ln=class extends Er{constructor({value:e=[],isIndefiniteForm:t=!1,...s}={}){super(s),this.value=e,this.isIndefiniteForm=t}fromBER(e,t,s,n){let i=xe.toUint8Array(e),o=n??ol();if(!Ii(this,i,t,s))return-1;if(this.valueBeforeDecodeView=i.subarray(t,t+s),this.valueBeforeDecodeView.length===0)return this.warnings.push("Zero buffer length"),t;let a=t;for(;BM(this.isIndefiniteForm,s)>0;){let c=r1(i,a,s,o);if(c.offset===-1)return this.error=c.result.error,this.warnings.concat(c.result.warnings),-1;if(a=c.offset,this.blockLength+=c.result.blockLength,s-=c.result.blockLength,this.value.push(c.result),this.isIndefiniteForm&&c.result.constructor.NAME===Gf)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===Gf?this.value.pop():this.warnings.push("No EndOfContent block encoded")),a}toBER(e,t){let s=t||new Fd;for(let n=0;n<this.value.length;n++)this.value[n].toBER(e,s);return t?Mn:s.final()}toJSON(){let e={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(let t of this.value)e.value.push(t.toJSON());return e}};Ln.NAME="ConstructedValueBlock";fr=class extends ur{constructor(e={}){super(e,Ln),this.idBlock.isConstructed=!0}fromBER(e,t,s,n){this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm;let i=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?s:this.lenBlock.length,n);return i===-1?(this.error=this.valueBlock.error,i):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),i)}onAsciiEncoding(){let e=[];for(let s of this.valueBlock.value)e.push(s.toString("ascii").split(`
19
+ `).map(n=>` ${n}`).join(`
20
+ `));let t=this.idBlock.tagClass===3?`[${this.idBlock.tagNumber}]`:this.constructor.NAME;return e.length?`${t} :
21
+ ${e.join(`
22
+ `)}`:`${t} :`}};$6=fr;Ce.Constructed=$6;fr.NAME="CONSTRUCTED";um=class extends Er{fromBER(e,t,s){return t}toBER(e){return Mn}};um.override="EndOfContentValueBlock";Yf=class extends ur{constructor(e={}){super(e,um),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};V6=Yf;Ce.EndOfContent=V6;Yf.NAME=Gf;nn=class extends ur{constructor(e={}){super(e,Er),this.idBlock.tagClass=1,this.idBlock.tagNumber=5}fromBER(e,t,s){return this.lenBlock.length>0&&this.warnings.push("Non-zero length of value block for Null type"),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.blockLength+=s,t+s>e.byteLength?(this.error="End of input reached before message was fully decoded (inconsistent offset and length values)",-1):t+s}toBER(e,t){let s=new ArrayBuffer(2);if(!e){let n=new Uint8Array(s);n[0]=5,n[1]=0}return t&&t.write(s),s}onAsciiEncoding(){return`${this.constructor.NAME}`}};K6=nn;Ce.Null=K6;nn.NAME="NULL";fm=class extends Un(Er){get value(){for(let e of this.valueHexView)if(e>0)return!0;return!1}set value(e){this.valueHexView[0]=e?255:0}constructor({value:e,...t}={}){super(t),t.valueHex?this.valueHexView=xe.toUint8Array(t.valueHex):this.valueHexView=new Uint8Array(1),e&&(this.value=e)}fromBER(e,t,s){let n=xe.toUint8Array(e);return Ii(this,n,t,s)?(this.valueHexView=n.subarray(t,t+s),s>1&&this.warnings.push("Boolean value encoded in more then 1 octet"),this.isHexOnly=!0,Qb.call(this),this.blockLength=s,t+s):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};fm.NAME="BooleanValueBlock";Ua=class extends ur{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor(e={}){super(e,fm),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}};W6=Ua;Ce.Boolean=W6;Ua.NAME="BOOLEAN";lm=class extends Un(Ln){constructor({isConstructed:e=!1,...t}={}){super(t),this.isConstructed=e}fromBER(e,t,s,n){let i=0;if(this.isConstructed){if(this.isHexOnly=!1,i=Ln.prototype.fromBER.call(this,e,t,s,n),i===-1)return i;for(let o=0;o<this.value.length;o++){let a=this.value[o].constructor.NAME;if(a===Gf){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(a!==M6)return this.error="OCTET STRING may consists of OCTET STRINGs only",-1}}else this.isHexOnly=!0,i=super.fromBER(e,t,s),this.blockLength=s;return i}toBER(e,t){return this.isConstructed?Ln.prototype.toBER.call(this,e,t):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}};lm.NAME="OctetStringValueBlock";on=class extends ur{constructor({idBlock:e={},lenBlock:t={},...s}={}){var n,i;(n=s.isConstructed)!==null&&n!==void 0||(s.isConstructed=!!(!((i=s.value)===null||i===void 0)&&i.length)),super({idBlock:{isConstructed:s.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!s.isIndefiniteForm},...s},lm),this.idBlock.tagClass=1,this.idBlock.tagNumber=4}fromBER(e,t,s,n){if(this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,s===0)return this.idBlock.error.length===0&&(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length===0&&(this.blockLength+=this.lenBlock.blockLength),t;if(!this.valueBlock.isConstructed){let o=(e instanceof ArrayBuffer?new Uint8Array(e):e).subarray(t,t+s);try{if(o.byteLength){let a=n??ol(),c=r1(o,0,o.byteLength,a);c.offset!==-1&&c.offset===s&&(this.valueBlock.value=[c.result])}}catch{}}return super.fromBER(e,t,s,n)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return fr.prototype.onAsciiEncoding.call(this);let e=this.constructor.NAME,t=Ue.ToHex(this.valueBlock.valueHexView);return`${e} : ${t}`}getValue(){if(!this.idBlock.isConstructed)return this.valueBlock.valueHexView.slice().buffer;let e=[];for(let t of this.valueBlock.value)t instanceof s1&&e.push(t.valueBlock.valueHexView);return xe.concat(e)}};s1=on;Ce.OctetString=s1;on.NAME=M6;hm=class extends Un(Ln){constructor({unusedBits:e=0,isConstructed:t=!1,...s}={}){super(s),this.unusedBits=e,this.isConstructed=t,this.blockLength=this.valueHexView.byteLength}fromBER(e,t,s,n){if(!s)return t;let i=-1;if(this.isConstructed){if(i=Ln.prototype.fromBER.call(this,e,t,s,n),i===-1)return i;for(let c of this.value){let d=c.constructor.NAME;if(d===Gf){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(d!==U6)return this.error="BIT STRING may consists of BIT STRINGs only",-1;let u=c.valueBlock;if(this.unusedBits>0&&u.unusedBits>0)return this.error='Using of "unused bits" inside constructive BIT STRING allowed for least one only',-1;this.unusedBits=u.unusedBits}return i}let o=xe.toUint8Array(e);if(!Ii(this,o,t,s))return-1;let a=o.subarray(t,t+s);if(this.unusedBits=a[0],this.unusedBits>7)return this.error="Unused bits for BitString must be in range 0-7",-1;if(!this.unusedBits){let c=a.subarray(1);try{if(c.byteLength){let d=n??ol(),u=r1(c,0,c.byteLength,d);u.offset!==-1&&u.offset===s-1&&(this.value=[u.result])}}catch{}}return this.valueHexView=a.subarray(1),this.blockLength=a.length,t+s}toBER(e,t){if(this.isConstructed)return Ln.prototype.toBER.call(this,e,t);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength){let n=new Uint8Array(1);return n[0]=0,n.buffer}let s=new Uint8Array(this.valueHexView.length+1);return s[0]=this.unusedBits,s.set(this.valueHexView,1),s.buffer}toJSON(){return{...super.toJSON(),unusedBits:this.unusedBits,isConstructed:this.isConstructed}}};hm.NAME="BitStringValueBlock";an=class extends ur{constructor({idBlock:e={},lenBlock:t={},...s}={}){var n,i;(n=s.isConstructed)!==null&&n!==void 0||(s.isConstructed=!!(!((i=s.value)===null||i===void 0)&&i.length)),super({idBlock:{isConstructed:s.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!s.isIndefiniteForm},...s},hm),this.idBlock.tagClass=1,this.idBlock.tagNumber=3}fromBER(e,t,s,n){return this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,super.fromBER(e,t,s,n)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return fr.prototype.onAsciiEncoding.call(this);{let e=[],t=this.valueBlock.valueHexView;for(let o of t)e.push(o.toString(2).padStart(8,"0"));let s=e.join(""),n=this.constructor.NAME,i=s.substring(0,s.length-this.valueBlock.unusedBits);return`${n} : ${i}`}}};G6=an;Ce.BitString=G6;an.NAME=U6;Jf=class extends Un(Er){setValueHex(){this.valueHexView.length>=4?(this.warnings.push("Too big Integer for decoding, hex only"),this.isHexOnly=!0,this._valueDec=0):(this.isHexOnly=!1,this.valueHexView.length>0&&(this._valueDec=Qb.call(this)))}constructor({value:e,...t}={}){super(t),this._valueDec=0,t.valueHex&&this.setValueHex(),e!==void 0&&(this.valueDec=e)}set valueDec(e){this._valueDec=e,this.isHexOnly=!1,this.valueHexView=new Uint8Array(P6(e))}get valueDec(){return this._valueDec}fromDER(e,t,s,n=0){let i=this.fromBER(e,t,s);if(i===-1)return i;let o=this.valueHexView;return o[0]===0&&(o[1]&128)!==0?this.valueHexView=o.subarray(1):n!==0&&o.length<n&&(n-o.length>1&&(n=o.length+1),this.valueHexView=o.subarray(n-o.length)),i}toDER(e=!1){let t=this.valueHexView;switch(!0){case(t[0]&128)!==0:{let s=new Uint8Array(this.valueHexView.length+1);s[0]=0,s.set(t,1),this.valueHexView=s}break;case(t[0]===0&&(t[1]&128)===0):this.valueHexView=this.valueHexView.subarray(1);break}return this.toBER(e)}fromBER(e,t,s){let n=super.fromBER(e,t,s);return n===-1||this.setValueHex(),n}toBER(e){return e?new ArrayBuffer(this.valueHexView.length):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}toString(){let e=this.valueHexView.length*8-1,t=new Uint8Array(this.valueHexView.length*8/3),s=0,n,i=this.valueHexView,o="",a=!1;for(let c=i.byteLength-1;c>=0;c--){n=i[c];for(let d=0;d<8;d++)(n&1)===1&&(s===e?(t=OM(D6(s),t),o="-"):t=NM(t,D6(s))),s++,n>>=1}for(let c=0;c<t.length;c++)t[c]&&(a=!0),a&&(o+=O6.charAt(t[c]));return a===!1&&(o+=O6.charAt(0)),o}};X6=Jf;Jf.NAME="IntegerValueBlock";Object.defineProperty(X6.prototype,"valueHex",{set:function(r){this.valueHexView=new Uint8Array(r),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});Ai=class extends ur{constructor(e={}){super(e,Jf),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return om(),BigInt(this.valueBlock.toString())}static fromBigInt(e){om();let t=BigInt(e),s=new Fd,n=t.toString(16).replace(/^-/,""),i=new Uint8Array(Ue.FromHex(n));if(t<0){let a=new Uint8Array(i.length+(i[0]&128?1:0));a[0]|=128;let d=BigInt(`0x${Ue.ToHex(a)}`)+t,u=xe.toUint8Array(Ue.FromHex(d.toString(16)));u[0]|=128,s.write(u)}else i[0]&128&&s.write(new Uint8Array([0])),s.write(i);return new Wf({valueHex:s.final()})}convertToDER(){let e=new Wf({valueHex:this.valueBlock.valueHexView});return e.valueBlock.toDER(),e}convertFromDER(){return new Wf({valueHex:this.valueBlock.valueHexView[0]===0?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}};Wf=Ai;Ce.Integer=Wf;Ai.NAME="INTEGER";ja=class extends Ai{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};Y6=ja;Ce.Enumerated=Y6;ja.NAME="ENUMERATED";Qf=class extends Un(Er){constructor({valueDec:e=-1,isFirstSid:t=!1,...s}={}){super(s),this.valueDec=e,this.isFirstSid=t}fromBER(e,t,s){if(!s)return t;let n=xe.toUint8Array(e);if(!Ii(this,n,t,s))return-1;let i=n.subarray(t,t+s);this.valueHexView=new Uint8Array(s);for(let a=0;a<s&&(this.valueHexView[a]=i[a]&127,this.blockLength++,(i[a]&128)!==0);a++);let o=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)o[a]=this.valueHexView[a];return this.valueHexView=o,(i[this.blockLength-1]&128)!==0?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=Ma(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}set valueBigInt(e){om();let t=BigInt(e).toString(2);for(;t.length%7;)t="0"+t;let s=new Uint8Array(t.length/7);for(let n=0;n<s.length;n++)s[n]=parseInt(t.slice(n*7,n*7+7),2)+(n+1<s.length?128:0);this.fromBER(s.buffer,0,s.length)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let n=this.valueHexView,i=new Uint8Array(this.blockLength);for(let o=0;o<this.blockLength-1;o++)i[o]=n[o]|128;return i[this.blockLength-1]=n[this.blockLength-1],i.buffer}let t=Ao(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",Mn;let s=new Uint8Array(t.byteLength);if(!e){let n=new Uint8Array(t),i=t.byteLength-1;for(let o=0;o<i;o++)s[o]=n[o]|128;s[i]=n[i]}return s}toString(){let e="";if(this.isHexOnly)e=Ue.ToHex(this.valueHexView);else if(this.isFirstSid){let t=this.valueDec;this.valueDec<=39?e="0.":this.valueDec<=79?(e="1.",t-=40):(e="2.",t-=80),e+=t.toString()}else e=this.valueDec.toString();return e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec,isFirstSid:this.isFirstSid}}};Qf.NAME="sidBlock";pm=class extends Er{constructor({value:e=ds,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,s){let n=t;for(;s>0;){let i=new Qf;if(n=i.fromBER(e,n,s),n===-1)return this.blockLength=0,this.error=i.error,n;this.value.length===0&&(i.isFirstSid=!0),this.blockLength+=i.blockLength,s-=i.blockLength,this.value.push(i)}return n}toBER(e){let t=[];for(let s=0;s<this.value.length;s++){let n=this.value[s].toBER(e);if(n.byteLength===0)return this.error=this.value[s].error,Mn;t.push(n)}return t1(t)}fromString(e){this.value=[];let t=0,s=0,n="",i=!1;do if(s=e.indexOf(".",t),s===-1?n=e.substring(t):n=e.substring(t,s),t=s+1,i){let o=this.value[0],a=0;switch(o.valueDec){case 0:break;case 1:a=40;break;case 2:a=80;break;default:this.value=[];return}let c=parseInt(n,10);if(isNaN(c))return;o.valueDec=c+a,i=!1}else{let o=new Qf;if(n>Number.MAX_SAFE_INTEGER){om();let a=BigInt(n);o.valueBigInt=a}else if(o.valueDec=parseInt(n,10),isNaN(o.valueDec))return;this.value.length||(o.isFirstSid=!0,i=!0),this.value.push(o)}while(s!==-1)}toString(){let e="",t=!1;for(let s=0;s<this.value.length;s++){t=this.value[s].isHexOnly;let n=this.value[s].toString();s!==0&&(e=`${e}.`),t?(n=`{${n}}`,this.value[s].isFirstSid?e=`2.{${n} - 80}`:e+=n):e+=n}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}};pm.NAME="ObjectIdentifierValueBlock";Ha=class extends ur{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(e={}){super(e,pm),this.idBlock.tagClass=1,this.idBlock.tagNumber=6}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};J6=Ha;Ce.ObjectIdentifier=J6;Ha.NAME="OBJECT IDENTIFIER";Zf=class extends Un(Ci){constructor({valueDec:e=0,...t}={}){super(t),this.valueDec=e}fromBER(e,t,s){if(s===0)return t;let n=xe.toUint8Array(e);if(!Ii(this,n,t,s))return-1;let i=n.subarray(t,t+s);this.valueHexView=new Uint8Array(s);for(let a=0;a<s&&(this.valueHexView[a]=i[a]&127,this.blockLength++,(i[a]&128)!==0);a++);let o=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)o[a]=this.valueHexView[a];return this.valueHexView=o,(i[this.blockLength-1]&128)!==0?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=Ma(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let n=this.valueHexView,i=new Uint8Array(this.blockLength);for(let o=0;o<this.blockLength-1;o++)i[o]=n[o]|128;return i[this.blockLength-1]=n[this.blockLength-1],i.buffer}let t=Ao(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",Mn;let s=new Uint8Array(t.byteLength);if(!e){let n=new Uint8Array(t),i=t.byteLength-1;for(let o=0;o<i;o++)s[o]=n[o]|128;s[i]=n[i]}return s.buffer}toString(){let e="";return this.isHexOnly?e=Ue.ToHex(this.valueHexView):e=this.valueDec.toString(),e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}};Zf.NAME="relativeSidBlock";mm=class extends Er{constructor({value:e=ds,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,s){let n=t;for(;s>0;){let i=new Zf;if(n=i.fromBER(e,n,s),n===-1)return this.blockLength=0,this.error=i.error,n;this.blockLength+=i.blockLength,s-=i.blockLength,this.value.push(i)}return n}toBER(e,t){let s=[];for(let n=0;n<this.value.length;n++){let i=this.value[n].toBER(e);if(i.byteLength===0)return this.error=this.value[n].error,Mn;s.push(i)}return t1(s)}fromString(e){this.value=[];let t=0,s=0,n="";do{s=e.indexOf(".",t),s===-1?n=e.substring(t):n=e.substring(t,s),t=s+1;let i=new Zf;if(i.valueDec=parseInt(n,10),isNaN(i.valueDec))return!0;this.value.push(i)}while(s!==-1);return!0}toString(){let e="",t=!1;for(let s=0;s<this.value.length;s++){t=this.value[s].isHexOnly;let n=this.value[s].toString();s!==0&&(e=`${e}.`),t&&(n=`{${n}}`),e+=n}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}};mm.NAME="RelativeObjectIdentifierValueBlock";el=class extends ur{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(e={}){super(e,mm),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};Q6=el;Ce.RelativeObjectIdentifier=Q6;el.NAME="RelativeObjectIdentifier";Vr=class extends fr{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};Z6=Vr;Ce.Sequence=Z6;Vr.NAME="SEQUENCE";es=class extends fr{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};e3=es;Ce.Set=e3;es.NAME="SET";gm=class extends Un(Er){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=ds}toJSON(){return{...super.toJSON(),value:this.value}}};gm.NAME="StringValueBlock";ym=class extends gm{};ym.NAME="SimpleStringValueBlock";ts=class extends Xf{constructor({...e}={}){super(e,ym)}fromBuffer(e){this.valueBlock.value=String.fromCharCode.apply(null,xe.toUint8Array(e))}fromString(e){let t=e.length,s=this.valueBlock.valueHexView=new Uint8Array(t);for(let n=0;n<t;n++)s[n]=e.charCodeAt(n);this.valueBlock.value=e}};ts.NAME="SIMPLE STRING";xm=class extends ts{fromBuffer(e){this.valueBlock.valueHexView=xe.toUint8Array(e);try{this.valueBlock.value=Ue.ToUtf8String(e)}catch(t){this.warnings.push(`Error during "decodeURIComponent": ${t}, using raw string`),this.valueBlock.value=Ue.ToBinary(e)}}fromString(e){this.valueBlock.valueHexView=new Uint8Array(Ue.FromUtf8String(e)),this.valueBlock.value=e}};xm.NAME="Utf8StringValueBlock";Fs=class extends xm{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};t3=Fs;Ce.Utf8String=t3;Fs.NAME="UTF8String";bm=class extends ts{fromBuffer(e){this.valueBlock.value=Ue.ToUtf16String(e),this.valueBlock.valueHexView=xe.toUint8Array(e)}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array(Ue.FromUtf16String(e))}};bm.NAME="BmpStringValueBlock";Fa=class extends bm{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};r3=Fa;Ce.BmpString=r3;Fa.NAME="BMPString";vm=class extends ts{fromBuffer(e){let t=ArrayBuffer.isView(e)?e.slice().buffer:e.slice(0),s=new Uint8Array(t);for(let n=0;n<s.length;n+=4)s[n]=s[n+3],s[n+1]=s[n+2],s[n+2]=0,s[n+3]=0;this.valueBlock.value=String.fromCharCode.apply(null,new Uint32Array(t))}fromString(e){let t=e.length,s=this.valueBlock.valueHexView=new Uint8Array(t*4);for(let n=0;n<t;n++){let i=Ao(e.charCodeAt(n),8),o=new Uint8Array(i);if(o.length>4)continue;let a=4-o.length;for(let c=o.length-1;c>=0;c--)s[n*4+c+a]=o[c]}this.valueBlock.value=e}};vm.NAME="UniversalStringValueBlock";qa=class extends vm{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};s3=qa;Ce.UniversalString=s3;qa.NAME="UniversalString";za=class extends ts{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};n3=za;Ce.NumericString=n3;za.NAME="NumericString";$a=class extends ts{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};i3=$a;Ce.PrintableString=i3;$a.NAME="PrintableString";Va=class extends ts{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};o3=Va;Ce.TeletexString=o3;Va.NAME="TeletexString";Ka=class extends ts{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};a3=Ka;Ce.VideotexString=a3;Ka.NAME="VideotexString";Wa=class extends ts{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};c3=Wa;Ce.IA5String=c3;Wa.NAME="IA5String";Ga=class extends ts{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};d3=Ga;Ce.GraphicString=d3;Ga.NAME="GraphicString";Io=class extends ts{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};u3=Io;Ce.VisibleString=u3;Io.NAME="VisibleString";Xa=class extends ts{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};f3=Xa;Ce.GeneralString=f3;Xa.NAME="GeneralString";Ya=class extends ts{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};l3=Ya;Ce.CharacterString=l3;Ya.NAME="CharacterString";Ro=class extends Io{constructor({value:e,valueDate:t,...s}={}){if(super(s),this.year=0,this.month=0,this.day=0,this.hour=0,this.minute=0,this.second=0,e){this.fromString(e),this.valueBlock.valueHexView=new Uint8Array(e.length);for(let n=0;n<e.length;n++)this.valueBlock.valueHexView[n]=e.charCodeAt(n)}t&&(this.fromDate(t),this.valueBlock.valueHexView=new Uint8Array(this.toBuffer())),this.idBlock.tagClass=1,this.idBlock.tagNumber=23}fromBuffer(e){this.fromString(String.fromCharCode.apply(null,xe.toUint8Array(e)))}toBuffer(){let e=this.toString(),t=new ArrayBuffer(e.length),s=new Uint8Array(t);for(let n=0;n<e.length;n++)s[n]=e.charCodeAt(n);return t}fromDate(e){this.year=e.getUTCFullYear(),this.month=e.getUTCMonth()+1,this.day=e.getUTCDate(),this.hour=e.getUTCHours(),this.minute=e.getUTCMinutes(),this.second=e.getUTCSeconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second))}fromString(e){let s=/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/ig.exec(e);if(s===null){this.error="Wrong input string for conversion";return}let n=parseInt(s[1],10);n>=50?this.year=1900+n:this.year=2e3+n,this.month=parseInt(s[2],10),this.day=parseInt(s[3],10),this.hour=parseInt(s[4],10),this.minute=parseInt(s[5],10),this.second=parseInt(s[6],10)}toString(e="iso"){if(e==="iso"){let t=new Array(7);return t[0]=cs(this.year<2e3?this.year-1900:this.year-2e3,2),t[1]=cs(this.month,2),t[2]=cs(this.day,2),t[3]=cs(this.hour,2),t[4]=cs(this.minute,2),t[5]=cs(this.second,2),t[6]="Z",t.join("")}return super.toString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.toDate().toISOString()}`}toJSON(){return{...super.toJSON(),year:this.year,month:this.month,day:this.day,hour:this.hour,minute:this.minute,second:this.second}}};h3=Ro;Ce.UTCTime=h3;Ro.NAME="UTCTime";Ja=class extends Ro{constructor(e={}){var t;super(e),(t=this.millisecond)!==null&&t!==void 0||(this.millisecond=0),this.idBlock.tagClass=1,this.idBlock.tagNumber=24}fromDate(e){super.fromDate(e),this.millisecond=e.getUTCMilliseconds()}toDate(){let e=Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second,this.millisecond);return new Date(e)}fromString(e){let t=!1,s="",n="",i=0,o,a=0,c=0;if(e[e.length-1]==="Z")s=e.substring(0,e.length-1),t=!0;else{let f=new Number(e[e.length-1]);if(isNaN(f.valueOf()))throw new Error("Wrong input string for conversion");s=e}if(t){if(s.indexOf("+")!==-1)throw new Error("Wrong input string for conversion");if(s.indexOf("-")!==-1)throw new Error("Wrong input string for conversion")}else{let f=1,h=s.indexOf("+"),y="";if(h===-1&&(h=s.indexOf("-"),f=-1),h!==-1){if(y=s.substring(h+1),s=s.substring(0,h),y.length!==2&&y.length!==4)throw new Error("Wrong input string for conversion");let v=parseInt(y.substring(0,2),10);if(isNaN(v.valueOf()))throw new Error("Wrong input string for conversion");if(a=f*v,y.length===4){if(v=parseInt(y.substring(2,4),10),isNaN(v.valueOf()))throw new Error("Wrong input string for conversion");c=f*v}}}let d=s.indexOf(".");if(d===-1&&(d=s.indexOf(",")),d!==-1){let f=new Number(`0${s.substring(d)}`);if(isNaN(f.valueOf()))throw new Error("Wrong input string for conversion");i=f.valueOf(),n=s.substring(0,d)}else n=s;switch(!0){case n.length===8:if(o=/(\d{4})(\d{2})(\d{2})/ig,d!==-1)throw new Error("Wrong input string for conversion");break;case n.length===10:if(o=/(\d{4})(\d{2})(\d{2})(\d{2})/ig,d!==-1){let f=60*i;this.minute=Math.floor(f),f=60*(f-this.minute),this.second=Math.floor(f),f=1e3*(f-this.second),this.millisecond=Math.floor(f)}break;case n.length===12:if(o=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/ig,d!==-1){let f=60*i;this.second=Math.floor(f),f=1e3*(f-this.second),this.millisecond=Math.floor(f)}break;case n.length===14:if(o=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/ig,d!==-1){let f=1e3*i;this.millisecond=Math.floor(f)}break;default:throw new Error("Wrong input string for conversion")}let u=o.exec(n);if(u===null)throw new Error("Wrong input string for conversion");for(let f=1;f<u.length;f++)switch(f){case 1:this.year=parseInt(u[f],10);break;case 2:this.month=parseInt(u[f],10);break;case 3:this.day=parseInt(u[f],10);break;case 4:this.hour=parseInt(u[f],10)+a;break;case 5:this.minute=parseInt(u[f],10)+c;break;case 6:this.second=parseInt(u[f],10);break;default:throw new Error("Wrong input string for conversion")}if(t===!1){let f=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);this.year=f.getUTCFullYear(),this.month=f.getUTCMonth(),this.day=f.getUTCDay(),this.hour=f.getUTCHours(),this.minute=f.getUTCMinutes(),this.second=f.getUTCSeconds(),this.millisecond=f.getUTCMilliseconds()}}toString(e="iso"){if(e==="iso"){let t=[];return t.push(cs(this.year,4)),t.push(cs(this.month,2)),t.push(cs(this.day,2)),t.push(cs(this.hour,2)),t.push(cs(this.minute,2)),t.push(cs(this.second,2)),this.millisecond!==0&&(t.push("."),t.push(cs(this.millisecond,3))),t.push("Z"),t.join("")}return super.toString(e)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}};p3=Ja;Ce.GeneralizedTime=p3;Ja.NAME="GeneralizedTime";tl=class extends Fs{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};m3=tl;Ce.DATE=m3;tl.NAME="DATE";rl=class extends Fs{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};g3=rl;Ce.TimeOfDay=g3;rl.NAME="TimeOfDay";sl=class extends Fs{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};y3=sl;Ce.DateTime=y3;sl.NAME="DateTime";nl=class extends Fs{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};x3=nl;Ce.Duration=x3;nl.NAME="Duration";il=class extends Fs{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};b3=il;Ce.TIME=b3;il.NAME="TIME";Dn=class{constructor({name:e=ds,optional:t=!1}={}){this.name=e,this.optional=t}},qd=class extends Dn{constructor({value:e=[],...t}={}){super(t),this.value=e}},Qa=class extends Dn{constructor({value:e=new Dn,local:t=!1,...s}={}){super(s),this.value=e,this.local=t}},e1=class{get data(){return this.dataView.slice().buffer}set data(e){this.dataView=xe.toUint8Array(e)}constructor({data:e=wm}={}){this.dataView=xe.toUint8Array(e)}fromBER(e,t,s){let n=t+s;return this.dataView=xe.toUint8Array(e).subarray(t,n),n}toBER(e){return this.dataView.slice().buffer}}});function v3(r){return Object.prototype.toString.call(r)}function UM(r){if(ArrayBuffer.isView(r))return!0;if(!r||typeof r!="object")return!1;let e=r;return typeof e.byteOffset=="number"&&typeof e.byteLength=="number"&&_m(e.buffer)}function n1(r){return v3(r)===DM}function w3(r){return typeof SharedArrayBuffer<"u"&&v3(r)===MM}function _m(r){return n1(r)||w3(r)}function S3(r){return UM(r)}function ki(r){return _m(r)||S3(r)}function i1(r){if(!ki(r))throw new TypeError("Expected ArrayBuffer, SharedArrayBuffer, or ArrayBufferView")}function qs(r){return i1(r),_m(r)?new Uint8Array(r):new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}function vr(r){if(i1(r),n1(r))return r;let e=new ArrayBuffer(r.byteLength);return new Uint8Array(e).set(qs(r)),e}var DM,MM,al=T(()=>{"use strict";DM="[object ArrayBuffer]",MM="[object SharedArrayBuffer]"});var _3=T(()=>{"use strict";al()});function o1(r,e,t={}){let s=qs(r),n=qs(e);if(!t.constantTime&&s.byteLength!==n.byteLength)return!1;let i=Math.max(s.byteLength,n.byteLength),o=s.byteLength^n.byteLength;for(let a=0;a<i;a++)o|=(s[a]??0)^(n[a]??0);return o===0}var E3=T(()=>{"use strict";al()});var C3=T(()=>{"use strict";al()});var Cs=T(()=>{"use strict";al();_3();E3();C3()});var B,_,Za=T(()=>{"use strict";(function(r){r[r.Sequence=0]="Sequence",r[r.Set=1]="Set",r[r.Choice=2]="Choice"})(B||(B={}));(function(r){r[r.Any=1]="Any",r[r.Boolean=2]="Boolean",r[r.OctetString=3]="OctetString",r[r.BitString=4]="BitString",r[r.Integer=5]="Integer",r[r.Enumerated=6]="Enumerated",r[r.ObjectIdentifier=7]="ObjectIdentifier",r[r.Utf8String=8]="Utf8String",r[r.BmpString=9]="BmpString",r[r.UniversalString=10]="UniversalString",r[r.NumericString=11]="NumericString",r[r.PrintableString=12]="PrintableString",r[r.TeletexString=13]="TeletexString",r[r.VideotexString=14]="VideotexString",r[r.IA5String=15]="IA5String",r[r.GraphicString=16]="GraphicString",r[r.VisibleString=17]="VisibleString",r[r.GeneralString=18]="GeneralString",r[r.CharacterString=19]="CharacterString",r[r.UTCTime=20]="UTCTime",r[r.GeneralizedTime=21]="GeneralizedTime",r[r.DATE=22]="DATE",r[r.TimeOfDay=23]="TimeOfDay",r[r.DateTime=24]="DateTime",r[r.Duration=25]="Duration",r[r.TIME=26]="TIME",r[r.Null=27]="Null"})(_||(_={}))});var Hn,T3=T(()=>{"use strict";ko();Cs();Hn=class{unusedBits=0;value=new ArrayBuffer(0);constructor(e,t=0){if(e)if(typeof e=="number")this.fromNumber(e);else if(ki(e))this.unusedBits=t,this.value=vr(e);else throw TypeError("Unsupported type of 'params' argument for BitString")}fromASN(e){if(!(e instanceof an))throw new TypeError("Argument 'asn' is not instance of ASN.1 BitString");return this.unusedBits=e.valueBlock.unusedBits,this.value=vr(e.valueBlock.valueHex),this}toASN(){return new an({unusedBits:this.unusedBits,valueHex:this.value})}toSchema(e){return new an({name:e})}toNumber(){let e="",t=new Uint8Array(this.value);for(let s of t)e+=s.toString(2).padStart(8,"0");return e=e.split("").reverse().join(""),this.unusedBits&&(e=e.slice(this.unusedBits).padStart(this.unusedBits,"0")),parseInt(e,2)}fromNumber(e){let t=e.toString(2),s=t.length+7>>3;this.unusedBits=(s<<3)-t.length;let n=new Uint8Array(s);t=t.padStart(s<<3,"0").split("").reverse().join("");let i=0;for(;i<s;)n[i]=parseInt(t.slice(i<<3,(i<<3)+8),2),i++;this.value=n.buffer}}});var ze,A3=T(()=>{"use strict";ko();Cs();ze=class{buffer;get byteLength(){return this.buffer.byteLength}get byteOffset(){return 0}constructor(e){typeof e=="number"?this.buffer=new ArrayBuffer(e):ki(e)?this.buffer=vr(e):Array.isArray(e)?this.buffer=new Uint8Array(e).buffer:this.buffer=new ArrayBuffer(0)}fromASN(e){if(!(e instanceof on))throw new TypeError("Argument 'asn' is not instance of ASN.1 OctetString");return this.buffer=vr(e.valueBlock.valueHex),this}toASN(){return new on({valueHex:this.buffer})}toSchema(e){return new on({name:e})}}});var a1=T(()=>{"use strict";T3();A3()});function zs(r){return{fromASN:e=>e.valueBlock.value,toASN:e=>new r({value:e})}}function Po(r){switch(r){case _.Any:return FM;case _.BitString:return $M;case _.BmpString:return WM;case _.Boolean:return KM;case _.CharacterString:return sU;case _.Enumerated:return zM;case _.GeneralString:return rU;case _.GeneralizedTime:return iU;case _.GraphicString:return eU;case _.IA5String:return ZM;case _.Integer:return qM;case _.Null:return oU;case _.NumericString:return XM;case _.ObjectIdentifier:return VM;case _.OctetString:return zd;case _.PrintableString:return YM;case _.TeletexString:return JM;case _.UTCTime:return nU;case _.UniversalString:return GM;case _.Utf8String:return c1;case _.VideotexString:return QM;case _.VisibleString:return tU;default:return null}}var FM,qM,zM,Et,$M,VM,KM,zd,I3,c1,WM,GM,XM,YM,JM,QM,ZM,eU,tU,rU,sU,nU,iU,oU,cl=T(()=>{"use strict";ko();Cs();Za();a1();FM={fromASN:r=>r instanceof nn?null:vr(r.valueBeforeDecodeView),toASN:r=>{if(r===null)return new nn;let e=Ri(r);if(e.result.error)throw new Error(e.result.error);return e.result}},qM={fromASN:r=>r.valueBlock.valueHexView.byteLength>=4?r.valueBlock.toString():r.valueBlock.valueDec,toASN:r=>new Ai({value:+r})},zM={fromASN:r=>r.valueBlock.valueDec,toASN:r=>new ja({value:r})},Et={fromASN:r=>vr(r.valueBlock.valueHexView),toASN:r=>new Ai({valueHex:r})},$M={fromASN:r=>vr(r.valueBlock.valueHexView),toASN:r=>new an({valueHex:r})},VM={fromASN:r=>r.valueBlock.toString(),toASN:r=>new Ha({value:r})},KM={fromASN:r=>r.valueBlock.value,toASN:r=>new Ua({value:r})},zd={fromASN:r=>vr(r.valueBlock.valueHexView),toASN:r=>new on({valueHex:r})},I3={fromASN:r=>new ze(r.getValue()),toASN:r=>r.toASN()};c1=zs(Fs),WM=zs(Fa),GM=zs(qa),XM=zs(za),YM=zs($a),JM=zs(Va),QM=zs(Ka),ZM=zs(Wa),eU=zs(Ga),tU=zs(Io),rU=zs(Xa),sU=zs(Ya),nU={fromASN:r=>r.toDate(),toASN:r=>new Ro({valueDate:r})},iU={fromASN:r=>r.toDate(),toASN:r=>new Ja({valueDate:r})},oU={fromASN:()=>null,toASN:()=>new nn}});function $s(r){return typeof r=="function"&&r.prototype?r.prototype.toASN&&r.prototype.fromASN?!0:$s(r.prototype):!!(r&&typeof r=="object"&&"toASN"in r&&"fromASN"in r)}function u1(r){if(r){let e=Object.getPrototypeOf(r);return e?.prototype?.constructor===Array?!0:u1(e)}return!1}function R3(r,e){if(!(r&&e)||r.byteLength!==e.byteLength)return!1;let t=new Uint8Array(r),s=new Uint8Array(e);for(let n=0;n<r.byteLength;n++)if(t[n]!==s[n])return!1;return!0}var Em=T(()=>{"use strict"});var Cm,k3=T(()=>{"use strict";ko();Za();Em();Cm=class{items=new WeakMap;has(e){return this.items.has(e)}get(e,t=!1){let s=this.items.get(e);if(!s)throw new Error(`Cannot get schema for '${e.prototype.constructor.name}' target`);if(t&&!s.schema)throw new Error(`Schema '${e.prototype.constructor.name}' doesn't contain ASN.1 schema. Call 'AsnSchemaStorage.cache'.`);return s}cache(e){let t=this.get(e);t.schema||(t.schema=this.create(e,!0))}createDefault(e){let t={type:B.Sequence,items:{}},s=this.findParentSchema(e);return s&&(Object.assign(t,s),t.items=Object.assign({},t.items,s.items)),t}create(e,t){let s=this.items.get(e)||this.createDefault(e),n=[];for(let i in s.items){let o=s.items[i],a=t?i:"",c;if(typeof o.type=="number"){let u=_[o.type],f=jn[u];if(!f)throw new Error(`Cannot get ASN1 class by name '${u}'`);c=new f({name:a})}else $s(o.type)?c=new o.type().toSchema(a):o.optional?this.get(o.type).type===B.Choice?c=new Dn({name:a}):(c=this.create(o.type,!1),c.name=a):c=new Dn({name:a});let d=!!o.optional||o.defaultValue!==void 0;if(o.repeated){c.name="";let u=o.repeated==="set"?es:Vr;c=new u({name:"",value:[new Qa({name:a,value:c})]})}if(o.context!==null&&o.context!==void 0)if(o.implicit)if(typeof o.type=="number"||$s(o.type)){let u=o.repeated?fr:Ti;n.push(new u({name:a,optional:d,idBlock:{tagClass:3,tagNumber:o.context}}))}else{this.cache(o.type);let u=!!o.repeated,f=u?c:this.get(o.type,!0).schema;f="valueBlock"in f?f.valueBlock.value:f.value,n.push(new fr({name:u?"":a,optional:d,idBlock:{tagClass:3,tagNumber:o.context},value:f}))}else n.push(new fr({optional:d,idBlock:{tagClass:3,tagNumber:o.context},value:[c]}));else c.optional=d,n.push(c)}switch(s.type){case B.Sequence:return new Vr({value:n,name:""});case B.Set:return new es({value:n,name:""});case B.Choice:return new qd({value:n,name:""});default:throw new Error("Unsupported ASN1 type in use")}}set(e,t){return this.items.set(e,t),this}findParentSchema(e){let t=Object.getPrototypeOf(e);return t?this.items.get(t)||this.findParentSchema(t):null}}});var lr,Tm=T(()=>{"use strict";k3();lr=new Cm});var U,g,P3=T(()=>{"use strict";cl();Za();Tm();U=r=>e=>{let t;lr.has(e)?t=lr.get(e):(t=lr.createDefault(e),lr.set(e,t)),Object.assign(t,r)},g=r=>(e,t)=>{let s;lr.has(e.constructor)?s=lr.get(e.constructor):(s=lr.createDefault(e.constructor),lr.set(e.constructor,s));let n=Object.assign({},r);if(typeof n.type=="number"&&!n.converter){let i=Po(r.type);if(!i)throw new Error(`Cannot get default converter for property '${t}' of ${e.constructor.name}`);n.converter=i}n.raw=r.raw,s.items[t]=n}});var Bo,B3=T(()=>{"use strict";Bo=class extends Error{schemas=[]}});var f1=T(()=>{"use strict";B3()});var dl,l1=T(()=>{"use strict";ko();Cs();Za();cl();f1();Em();Tm();dl=class{static parse(e,t,s){let n=Ri(vr(e),s?.berOptions);if(n.result.error)throw new Error(n.result.error);return this.fromASN(n.result,t,s)}static fromASN(e,t,s){try{if($s(t))return new t().fromASN(e);let n=lr.get(t);lr.cache(t);let i=n.schema,o=this.handleChoiceTypes(e,n,t,i,s);if(o?.result)return o.result;o?.targetSchema&&(i=o.targetSchema);let a=this.handleSequenceTypes(e,n,t,i),c=new t;return u1(t)?this.handleArrayTypes(e,n,t,s):(this.processSchemaItems(n,a,c,s),c)}catch(n){throw n instanceof Bo&&n.schemas.push(t.name),n}}static handleChoiceTypes(e,t,s,n,i){if(e.constructor===fr&&t.type===B.Choice&&e.idBlock.tagClass===3)for(let o in t.items){let a=t.items[o];if(a.context===e.idBlock.tagNumber&&a.implicit&&typeof a.type=="function"&&lr.has(a.type)){let c=lr.get(a.type);if(c&&c.type===B.Sequence){let d=new Vr;if("value"in e.valueBlock&&Array.isArray(e.valueBlock.value)&&"value"in d.valueBlock){d.valueBlock.value=e.valueBlock.value;let u=this.fromASN(d,a.type,i),f=new s;return f[o]=u,{result:f}}}}}else if(e.constructor===fr&&t.type!==B.Choice){let o=new fr({idBlock:{tagClass:3,tagNumber:e.idBlock.tagNumber},value:t.schema.valueBlock.value});for(let a in t.items)delete e[a];return{targetSchema:o}}return null}static handleSequenceTypes(e,t,s,n){if(t.type===B.Sequence){let i=Ei({},e,n);if(!i.verified)throw new Bo(`Data does not match to ${s.name} ASN1 schema.${i.result.error?` ${i.result.error}`:""}`);return i}else{let i=Ei({},e,n);if(!i.verified)throw new Bo(`Data does not match to ${s.name} ASN1 schema.${i.result.error?` ${i.result.error}`:""}`);return i}}static processRepeatedField(e,t,s){let n=e.slice(t);if(n.length===1&&n[0].constructor.name==="Sequence"){let i=n[0];i.valueBlock&&i.valueBlock.value&&Array.isArray(i.valueBlock.value)&&(n=i.valueBlock.value)}if(typeof s.type=="number"){let i=Po(s.type);if(!i)throw new Error(`No converter for ASN.1 type ${s.type}`);return n.filter(o=>o&&o.valueBlock).map(o=>{try{return i.fromASN(o)}catch{return}}).filter(o=>o!==void 0)}else return n.filter(i=>i&&i.valueBlock).map(i=>{try{return this.fromASN(i,s.type)}catch{return}}).filter(i=>i!==void 0)}static processPrimitiveField(e,t){let s=Po(t.type);if(!s)throw new Error(`No converter for ASN.1 type ${t.type}`);return s.fromASN(e)}static isOptionalChoiceField(e){return e.optional&&typeof e.type=="function"&&lr.has(e.type)&&lr.get(e.type).type===B.Choice}static processOptionalChoiceField(e,t){try{return{processed:!0,value:this.fromASN(e,t.type)}}catch(s){if(s instanceof Bo&&/Wrong values for Choice type/.test(s.message))return{processed:!1};throw s}}static handleArrayTypes(e,t,s,n){if(!("value"in e.valueBlock&&Array.isArray(e.valueBlock.value)))throw new Error("Cannot get items from the ASN.1 parsed value. ASN.1 object is not constructed.");let i=t.itemType;if(typeof i=="number"){let o=Po(i);if(!o)throw new Error(`Cannot get default converter for array item of ${s.name} ASN1 schema`);return s.from(e.valueBlock.value,a=>o.fromASN(a))}else return s.from(e.valueBlock.value,o=>this.fromASN(o,i,n))}static processSchemaItems(e,t,s,n){for(let i in e.items){let o=t.result[i];if(!o)continue;let a=e.items[i],c=a.type,d;typeof c=="number"||$s(c)?d=this.processPrimitiveSchemaItem(o,a,c,n):d=this.processComplexSchemaItem(o,a,c,n),d&&typeof d=="object"&&"value"in d&&"raw"in d?(s[i]=d.value,s[`${i}Raw`]=d.raw):s[i]=d}}static processPrimitiveSchemaItem(e,t,s,n){let i=t.converter??($s(s)?new s:null);if(!i)throw new Error("Converter is empty");return t.repeated?this.processRepeatedPrimitiveItem(e,t,i,n):this.processSinglePrimitiveItem(e,t,s,i,n)}static processRepeatedPrimitiveItem(e,t,s,n){if(t.implicit){let i=t.repeated==="sequence"?Vr:es,o=new i;o.valueBlock=e.valueBlock;let a=Ri(o.toBER(!1),n?.berOptions);if(a.offset===-1)throw new Error(`Cannot parse the child item. ${a.result.error}`);if(!("value"in a.result.valueBlock&&Array.isArray(a.result.valueBlock.value)))throw new Error("Cannot get items from the ASN.1 parsed value. ASN.1 object is not constructed.");let c=a.result.valueBlock.value;return Array.from(c,d=>s.fromASN(d))}else return Array.from(e,i=>s.fromASN(i))}static processSinglePrimitiveItem(e,t,s,n,i){let o=e;if(t.implicit){let a;if($s(s))a=new s().toSchema("");else{let c=_[s],d=jn[c];if(!d)throw new Error(`Cannot get '${c}' class from asn1js module`);a=new d}a.valueBlock=o.valueBlock,o=Ri(a.toBER(!1),i?.berOptions).result}return n.fromASN(o)}static processComplexSchemaItem(e,t,s,n){if(t.repeated){if(!Array.isArray(e))throw new Error("Cannot get list of items from the ASN.1 parsed value. ASN.1 value should be iterable.");return Array.from(e,i=>this.fromASN(i,s,n))}else{let i=this.handleImplicitTagging(e,t,s);if(this.isOptionalChoiceField(t))try{return this.fromASN(i,s,n)}catch(o){if(o instanceof Bo&&/Wrong values for Choice type/.test(o.message))return;throw o}else{let o=this.fromASN(i,s,n);return t.raw?{value:o,raw:e.valueBeforeDecodeView}:o}}}static handleImplicitTagging(e,t,s){if(t.implicit&&typeof t.context=="number"){let n=lr.get(s);if(n.type===B.Sequence){let i=new Vr;if("value"in e.valueBlock&&Array.isArray(e.valueBlock.value)&&"value"in i.valueBlock)return i.valueBlock.value=e.valueBlock.value,i}else if(n.type===B.Set){let i=new es;if("value"in e.valueBlock&&Array.isArray(e.valueBlock.value)&&"value"in i.valueBlock)return i.valueBlock.value=e.valueBlock.value,i}}return e}}});var ul,h1=T(()=>{"use strict";ko();Cs();cl();Za();Em();Tm();ul=class r{static serialize(e){return e instanceof ur?e.toBER(!1):this.toASN(e).toBER(!1)}static toASN(e){if(e&&typeof e=="object"&&$s(e))return e.toASN();if(!(e&&typeof e=="object"))throw new TypeError("Parameter 1 should be type of Object.");let t=e.constructor,s=lr.get(t);lr.cache(t);let n=[];if(s.itemType){if(!Array.isArray(e))throw new TypeError("Parameter 1 should be type of Array.");if(typeof s.itemType=="number"){let o=Po(s.itemType);if(!o)throw new Error(`Cannot get default converter for array item of ${t.name} ASN1 schema`);n=e.map(a=>o.toASN(a))}else n=e.map(o=>this.toAsnItem({type:s.itemType},"[]",t,o))}else for(let o in s.items){let a=s.items[o],c=e[o];if(c===void 0||a.defaultValue===c||typeof a.defaultValue=="object"&&typeof c=="object"&&R3(this.serialize(a.defaultValue),this.serialize(c)))continue;let d=r.toAsnItem(a,o,t,c);if(typeof a.context=="number")if(a.implicit)if(!a.repeated&&(typeof a.type=="number"||$s(a.type))){let u={};u.valueHex=d instanceof nn?vr(d.valueBeforeDecodeView):d.valueBlock.toBER(),n.push(new Ti({optional:a.optional,idBlock:{tagClass:3,tagNumber:a.context},...u}))}else n.push(new fr({optional:a.optional,idBlock:{tagClass:3,tagNumber:a.context},value:d.valueBlock.value}));else n.push(new fr({optional:a.optional,idBlock:{tagClass:3,tagNumber:a.context},value:[d]}));else a.repeated?n=n.concat(d):n.push(d)}let i;switch(s.type){case B.Sequence:i=new Vr({value:n});break;case B.Set:i=new es({value:n});break;case B.Choice:if(!n[0])throw new Error(`Schema '${t.name}' has wrong data. Choice cannot be empty.`);i=n[0];break}return i}static toAsnItem(e,t,s,n){let i;if(typeof e.type=="number"){let o=e.converter;if(!o)throw new Error(`Property '${t}' doesn't have converter for type ${_[e.type]} in schema '${s.name}'`);if(e.repeated){if(!Array.isArray(n))throw new TypeError("Parameter 'objProp' should be type of Array.");let a=Array.from(n,d=>o.toASN(d)),c=e.repeated==="sequence"?Vr:es;i=new c({value:a})}else i=o.toASN(n)}else if(e.repeated){if(!Array.isArray(n))throw new TypeError("Parameter 'objProp' should be type of Array.");let o=Array.from(n,c=>this.toASN(c)),a=e.repeated==="sequence"?Vr:es;i=new a({value:o})}else i=this.toASN(n);return i}}});var je,N3=T(()=>{"use strict";je=class extends Array{constructor(e=[]){if(typeof e=="number")super(e);else{super();for(let t of e)this.push(t)}}}});var pe,O3=T(()=>{"use strict";ko();Cs();l1();h1();pe=class r{static serialize(e){return ul.serialize(e)}static parse(e,t,s){return dl.parse(e,t,s)}static toString(e,t){let s=ki(e)?vr(e):r.serialize(e),n=Ri(s,t?.berOptions);if(n.offset===-1)throw new Error(`Cannot decode ASN.1 data. ${n.result.error}`);return n.result.toString()}}});var J=T(()=>{"use strict";cl();a1();P3();Za();l1();h1();f1();N3();O3()});function p(r,e,t,s){var n=arguments.length,i=n<3?e:s===null?s=Object.getOwnPropertyDescriptor(e,t):s,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,s);else for(var a=r.length-1;a>=0;a--)(o=r[a])&&(i=(n<3?o(i):n>3?o(e,t,i):o(e,t))||i);return n>3&&i&&Object.defineProperty(e,t,i),i}function ht(r,e,t,s){if(t==="a"&&!s)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!s:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?s:t==="a"?s.call(r):s?s.value:e.get(r)}function Gt(r,e,t,s,n){if(s==="m")throw new TypeError("Private method is not writable");if(s==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return s==="a"?n.call(r,t):n?n.value=t:e.set(r,t),t}var ee=T(()=>{"use strict"});var p1=T(()=>{"use strict";Cs()});var $d={};Ef($d,{decode:()=>g1,encode:()=>m1,format:()=>j3,formats:()=>H3,hex:()=>xU,is:()=>M3,normalize:()=>fl,parse:()=>U3});function uU(r){return r.separators==="none"?[]:!r.separators||r.separators==="common"?dU:r.separators}function fU(r){if(!r)throw new TypeError("Hex separators must be non-empty strings")}function lU(r,e,t){for(let s of t)if(r.startsWith(s,e))return s}function hU(r){let e=/[A-F]/.test(r),t=/[a-f]/.test(r);return e&&!t?"upper":"lower"}function pU(r){let e=/\r\n|\n/.exec(r);if(e)return e[0]===`\r
23
+ `?`\r
24
+ `:`
25
+ `}function L3(r){return r.replace(/[^0-9a-f]/gi,"")}function mU(r){let e=r.match(/[0-9A-Fa-f]+|[^0-9A-Fa-f]+/g)??[];if(e.length<3)return;let t=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)||t.some(o=>o.length===0||o.length%2!==0))return;let i=t[0]?.length??0;if(i&&!t.slice(0,-1).some(o=>o.length!==i)&&!((t[t.length-1]?.length??0)>i))return{size:i/2,separator:n}}function gU(r){let e=r.trim(),t=/^0x/i.test(e)?"0x":"",s=t?e.slice(2):e,n=pU(s),i=s.split(/\r\n|\n/).filter(d=>d.length>0),o=i[0]?.trim()??"",a=mU(o),c={case:hU(e),prefix:t};if(a&&(c.group=a),n&&i.length>1){let d=L3(i[0]??"").length/2;d>0&&i.slice(0,-1).every(u=>L3(u).length/2===d)&&(c.line={bytesPerLine:d,separator:n})}return c}function yU(r,e){let t=e.allowPrefix??!0,s=[...uU(e)].sort((a,c)=>c.length-a.length);for(let a of s)fU(a);let n=r.trim();if(/^0x/i.test(n)){if(!t)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(cU.test(c)){i+=c,o=!1,a+=1;continue}let d=lU(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 D3(r,e){if(!e)return r.join("");if(!Number.isInteger(e.size)||e.size<1)throw new RangeError("Hex group size must be a positive integer");let t=[];for(let s=0;s<r.length;s+=e.size)t.push(r.slice(s,s+e.size).join(""));return t.join(e.separator)}function fl(r,e={}){return yU(r,e)}function M3(r,e={}){if(typeof r!="string")return!1;try{return fl(r,e),!0}catch{return!1}}function m1(r,e={}){let t=qs(r),s=e.case??"lower",n=Array.from(t,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??`
26
+ `,c=[];for(let d=0;d<n.length;d+=o)c.push(D3(n.slice(d,d+o),e.group));i=c.join(a)}else i=D3(n,e.group);return`${e.prefix??""}${i}`}function g1(r,e={}){let t=fl(r,e),s=new Uint8Array(t.length/2);for(let n=0;n<t.length;n+=2)s[n/2]=Number.parseInt(t.slice(n,n+2),16);return s}function U3(r,e={}){let t=fl(r,e);return{bytes:g1(t),format:gU(r),normalized:t}}function j3(r,e){return m1(r,e)}var cU,dU,H3,xU,F3=T(()=>{"use strict";Cs();cU=/^[0-9a-f]$/i,dU=[" "," ",`
27
+ `,"\r",":","-","."];H3={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"})},xU={encode:m1,decode:g1,format:j3,formats:H3,is:M3,normalize:fl,parse:U3}});var q3=T(()=>{"use strict";Cs()});var z3=T(()=>{"use strict";Cs()});var y1=T(()=>{"use strict";Cs();p1()});var $3=T(()=>{"use strict";y1()});var x1=T(()=>{"use strict";p1();F3();q3();z3();y1();$3()});var ll,V3=T(()=>{"use strict";x1();ll=class{static isIPv4(e){return/^(\d{1,3}\.){3}\d{1,3}$/.test(e)}static parseIPv4(e){let t=e.split(".");if(t.length!==4)throw new Error("Invalid IPv4 address");return t.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 t=e.split("::");if(t.length>2)throw new Error("Invalid IPv6 address");let s=t[0]?t[0].split(":"):[],n=t[1]?t[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 t=[];for(let s=0;s<16;s+=2)t.push((e[s]<<8|e[s+1]).toString(16));return this.compressIPv6(t.join(":"))}static compressIPv6(e){let t=e.split(":"),s=-1,n=0,i=-1,o=0;for(let a=0;a<t.length;a++)t[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=t.slice(0,s).join(":"),c=t.slice(s+n).join(":");return`${a}::${c}`}return e}static parseCIDR(e){let[t,s]=e.split("/"),n=parseInt(s,10);if(this.isIPv4(t)){if(n<0||n>32)throw new Error("Invalid IPv4 prefix length");return[this.parseIPv4(t),n]}else{if(n<0||n>128)throw new Error("Invalid IPv6 prefix length");return[this.parseIPv6(t),n]}}static decodeIP(e){if(e.length===64&&parseInt(e,16)===0)return"::/0";if(e.length!==16)return e;let t=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}/${t}`}static toString(e){let t=new Uint8Array(e);if(t.length===4)return Array.from(t).join(".");if(t.length===16)return this.formatIPv6(t);if(t.length===8||t.length===32){let s=t.length/2,n=t.slice(0,s),i=t.slice(s);if(t.every(c=>c===0))return t.length===8?"0.0.0.0/0":"::/0";let a=i.reduce((c,d)=>c+(d.toString(2).match(/1/g)||[]).length,0);return t.length===8?`${Array.from(n).join(".")}/${a}`:`${this.formatIPv6(n)}/${a}`}return this.decodeIP($d.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 t=this.isIPv4(e)?this.parseIPv4(e):this.parseIPv6(e);return new Uint8Array(t).buffer}}});var b1,v1,w1,hr,Vd,ec,No,S1,Ft,Kd=T(()=>{"use strict";ee();J();x1();hr=class{teletexString;printableString;universalString;utf8String;bmpString;constructor(e={}){Object.assign(this,e)}toString(){return this.bmpString||this.printableString||this.teletexString||this.universalString||this.utf8String||""}};p([g({type:_.TeletexString})],hr.prototype,"teletexString",void 0);p([g({type:_.PrintableString})],hr.prototype,"printableString",void 0);p([g({type:_.UniversalString})],hr.prototype,"universalString",void 0);p([g({type:_.Utf8String})],hr.prototype,"utf8String",void 0);p([g({type:_.BmpString})],hr.prototype,"bmpString",void 0);hr=p([U({type:B.Choice})],hr);Vd=class extends hr{ia5String;anyValue;constructor(e={}){super(e),Object.assign(this,e)}toString(){return this.ia5String||(this.anyValue?$d.encode(this.anyValue):super.toString())}};p([g({type:_.IA5String})],Vd.prototype,"ia5String",void 0);p([g({type:_.Any})],Vd.prototype,"anyValue",void 0);Vd=p([U({type:B.Choice})],Vd);ec=class{type="";value=new Vd;constructor(e={}){Object.assign(this,e)}};p([g({type:_.ObjectIdentifier})],ec.prototype,"type",void 0);p([g({type:Vd})],ec.prototype,"value",void 0);No=b1=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,b1.prototype)}};No=b1=p([U({type:B.Set,itemType:ec})],No);S1=v1=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,v1.prototype)}};S1=v1=p([U({type:B.Sequence,itemType:No})],S1);Ft=w1=class extends S1{constructor(e){super(e),Object.setPrototypeOf(this,w1.prototype)}};Ft=w1=p([U({type:B.Sequence})],Ft)});var _U,Oo,hl,We,tc=T(()=>{"use strict";ee();J();V3();Kd();_U={fromASN:r=>ll.toString(zd.fromASN(r)),toASN:r=>zd.toASN(ll.fromString(r))},Oo=class{typeId="";value=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};p([g({type:_.ObjectIdentifier})],Oo.prototype,"typeId",void 0);p([g({type:_.Any,context:0})],Oo.prototype,"value",void 0);hl=class{nameAssigner;partyName=new hr;constructor(e={}){Object.assign(this,e)}};p([g({type:hr,optional:!0,context:0,implicit:!0})],hl.prototype,"nameAssigner",void 0);p([g({type:hr,context:1,implicit:!0})],hl.prototype,"partyName",void 0);We=class{otherName;rfc822Name;dNSName;x400Address;directoryName;ediPartyName;uniformResourceIdentifier;iPAddress;registeredID;constructor(e={}){Object.assign(this,e)}};p([g({type:Oo,context:0,implicit:!0})],We.prototype,"otherName",void 0);p([g({type:_.IA5String,context:1,implicit:!0})],We.prototype,"rfc822Name",void 0);p([g({type:_.IA5String,context:2,implicit:!0})],We.prototype,"dNSName",void 0);p([g({type:_.Any,context:3,implicit:!0})],We.prototype,"x400Address",void 0);p([g({type:Ft,context:4,implicit:!1})],We.prototype,"directoryName",void 0);p([g({type:hl,context:5})],We.prototype,"ediPartyName",void 0);p([g({type:_.IA5String,context:6,implicit:!0})],We.prototype,"uniformResourceIdentifier",void 0);p([g({type:_.OctetString,context:7,implicit:!0,converter:_U})],We.prototype,"iPAddress",void 0);p([g({type:_.ObjectIdentifier,context:8,implicit:!0})],We.prototype,"registeredID",void 0);We=p([U({type:B.Choice})],We)});var Lo,Do,K3,rc,Am,tX,rX,_1,E1,C1,T1,at,Vt=T(()=>{"use strict";Lo="1.3.6.1.5.5.7",Do=`${Lo}.1`,K3=`${Lo}.2`,rc=`${Lo}.3`,Am=`${Lo}.48`,tX=`${K3}.1`,rX=`${K3}.2`,_1=`${Am}.1`,E1=`${Am}.2`,C1=`${Am}.3`,T1=`${Am}.5`,at="2.5.29"});var A1,Im,Pi,sc,I1=T(()=>{"use strict";ee();J();tc();Vt();Im=`${Do}.1`,Pi=class{accessMethod="";accessLocation=new We;constructor(e={}){Object.assign(this,e)}};p([g({type:_.ObjectIdentifier})],Pi.prototype,"accessMethod",void 0);p([g({type:We})],Pi.prototype,"accessLocation",void 0);sc=A1=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,A1.prototype)}};sc=A1=p([U({type:B.Sequence,itemType:Pi})],sc)});var Rm,nc,Fn,R1=T(()=>{"use strict";ee();J();tc();Vt();Rm=`${at}.35`,nc=class extends ze{},Fn=class{keyIdentifier;authorityCertIssuer;authorityCertSerialNumber;constructor(e={}){e&&Object.assign(this,e)}};p([g({type:nc,context:0,optional:!0,implicit:!0})],Fn.prototype,"keyIdentifier",void 0);p([g({type:We,context:1,optional:!0,implicit:!0,repeated:"sequence"})],Fn.prototype,"authorityCertIssuer",void 0);p([g({type:_.Integer,context:2,optional:!0,implicit:!0,converter:Et})],Fn.prototype,"authorityCertSerialNumber",void 0)});var km,ic,W3=T(()=>{"use strict";ee();J();Vt();km=`${at}.19`,ic=class{cA=!1;pathLenConstraint;constructor(e={}){Object.assign(this,e)}};p([g({type:_.Boolean,defaultValue:!1})],ic.prototype,"cA",void 0);p([g({type:_.Integer,optional:!0})],ic.prototype,"pathLenConstraint",void 0)});var k1,Xt,pl=T(()=>{"use strict";ee();J();tc();Xt=k1=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,k1.prototype)}};Xt=k1=p([U({type:B.Sequence,itemType:We})],Xt)});var P1,EU,G3,X3=T(()=>{"use strict";ee();J();pl();Vt();EU=`${at}.29`,G3=P1=class extends Xt{constructor(e){super(e),Object.setPrototypeOf(this,P1.prototype)}};G3=P1=p([U({type:B.Sequence})],G3)});var B1,Bm,NX,Bi,ml,gl,Pm,yl,oc,xl,Y3=T(()=>{"use strict";ee();J();Vt();Bm=`${at}.32`,NX=`${Bm}.0`,Bi=class{ia5String;visibleString;bmpString;utf8String;constructor(e={}){Object.assign(this,e)}toString(){return this.ia5String||this.visibleString||this.bmpString||this.utf8String||""}};p([g({type:_.IA5String})],Bi.prototype,"ia5String",void 0);p([g({type:_.VisibleString})],Bi.prototype,"visibleString",void 0);p([g({type:_.BmpString})],Bi.prototype,"bmpString",void 0);p([g({type:_.Utf8String})],Bi.prototype,"utf8String",void 0);Bi=p([U({type:B.Choice})],Bi);ml=class{organization=new Bi;noticeNumbers=[];constructor(e={}){Object.assign(this,e)}};p([g({type:Bi})],ml.prototype,"organization",void 0);p([g({type:_.Integer,repeated:"sequence"})],ml.prototype,"noticeNumbers",void 0);gl=class{noticeRef;explicitText;constructor(e={}){Object.assign(this,e)}};p([g({type:ml,optional:!0})],gl.prototype,"noticeRef",void 0);p([g({type:Bi,optional:!0})],gl.prototype,"explicitText",void 0);Pm=class{cPSuri;userNotice;constructor(e={}){Object.assign(this,e)}};p([g({type:_.IA5String})],Pm.prototype,"cPSuri",void 0);p([g({type:gl})],Pm.prototype,"userNotice",void 0);Pm=p([U({type:B.Choice})],Pm);yl=class{policyQualifierId="";qualifier=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};p([g({type:_.ObjectIdentifier})],yl.prototype,"policyQualifierId",void 0);p([g({type:_.Any})],yl.prototype,"qualifier",void 0);oc=class{policyIdentifier="";policyQualifiers;constructor(e={}){Object.assign(this,e)}};p([g({type:_.ObjectIdentifier})],oc.prototype,"policyIdentifier",void 0);p([g({type:yl,repeated:"sequence",optional:!0})],oc.prototype,"policyQualifiers",void 0);xl=B1=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,B1.prototype)}};xl=B1=p([U({type:B.Sequence,itemType:oc})],xl)});var FX,bl,N1=T(()=>{"use strict";ee();J();Vt();FX=`${at}.20`,bl=class{value;constructor(e=0){this.value=e}};p([g({type:_.Integer})],bl.prototype,"value",void 0);bl=p([U({type:B.Choice})],bl)});var GX,J3,Q3=T(()=>{"use strict";ee();J();Vt();N1();GX=`${at}.27`,J3=class extends bl{};J3=p([U({type:B.Choice})],J3)});var O1,Nm,cn,vl,Ni,qn,Mo,Om=T(()=>{"use strict";ee();J();Kd();tc();Vt();Nm=`${at}.31`;(function(r){r[r.unused=1]="unused",r[r.keyCompromise=2]="keyCompromise",r[r.cACompromise=4]="cACompromise",r[r.affiliationChanged=8]="affiliationChanged",r[r.superseded=16]="superseded",r[r.cessationOfOperation=32]="cessationOfOperation",r[r.certificateHold=64]="certificateHold",r[r.privilegeWithdrawn=128]="privilegeWithdrawn",r[r.aACompromise=256]="aACompromise"})(cn||(cn={}));vl=class extends Hn{toJSON(){let e=[],t=this.toNumber();return t&cn.aACompromise&&e.push("aACompromise"),t&cn.affiliationChanged&&e.push("affiliationChanged"),t&cn.cACompromise&&e.push("cACompromise"),t&cn.certificateHold&&e.push("certificateHold"),t&cn.cessationOfOperation&&e.push("cessationOfOperation"),t&cn.keyCompromise&&e.push("keyCompromise"),t&cn.privilegeWithdrawn&&e.push("privilegeWithdrawn"),t&cn.superseded&&e.push("superseded"),t&cn.unused&&e.push("unused"),e}toString(){return`[${this.toJSON().join(", ")}]`}},Ni=class{fullName;nameRelativeToCRLIssuer;constructor(e={}){Object.assign(this,e)}};p([g({type:We,context:0,repeated:"sequence",implicit:!0})],Ni.prototype,"fullName",void 0);p([g({type:No,context:1,implicit:!0})],Ni.prototype,"nameRelativeToCRLIssuer",void 0);Ni=p([U({type:B.Choice})],Ni);qn=class{distributionPoint;reasons;cRLIssuer;constructor(e={}){Object.assign(this,e)}};p([g({type:Ni,context:0,optional:!0})],qn.prototype,"distributionPoint",void 0);p([g({type:vl,context:1,optional:!0,implicit:!0})],qn.prototype,"reasons",void 0);p([g({type:We,context:2,optional:!0,repeated:"sequence",implicit:!0})],qn.prototype,"cRLIssuer",void 0);Mo=O1=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,O1.prototype)}};Mo=O1=p([U({type:B.Sequence,itemType:qn})],Mo)});var L1,dY,Z3,eT=T(()=>{"use strict";ee();J();Vt();Om();dY=`${at}.46`,Z3=L1=class extends Mo{constructor(e){super(e),Object.setPrototypeOf(this,L1.prototype)}};Z3=L1=p([U({type:B.Sequence,itemType:qn})],Z3)});var gY,Vs,tT=T(()=>{"use strict";ee();J();Vt();Om();gY=`${at}.28`,Vs=class r{static ONLY=!1;distributionPoint;onlyContainsUserCerts=r.ONLY;onlyContainsCACerts=r.ONLY;onlySomeReasons;indirectCRL=r.ONLY;onlyContainsAttributeCerts=r.ONLY;constructor(e={}){Object.assign(this,e)}};p([g({type:Ni,context:0,optional:!0})],Vs.prototype,"distributionPoint",void 0);p([g({type:_.Boolean,context:1,defaultValue:Vs.ONLY,implicit:!0})],Vs.prototype,"onlyContainsUserCerts",void 0);p([g({type:_.Boolean,context:2,defaultValue:Vs.ONLY,implicit:!0})],Vs.prototype,"onlyContainsCACerts",void 0);p([g({type:vl,context:3,optional:!0,implicit:!0})],Vs.prototype,"onlySomeReasons",void 0);p([g({type:_.Boolean,context:4,defaultValue:Vs.ONLY,implicit:!0})],Vs.prototype,"indirectCRL",void 0);p([g({type:_.Boolean,context:5,defaultValue:Vs.ONLY,implicit:!0})],Vs.prototype,"onlyContainsAttributeCerts",void 0)});var rT,wl,Sl,sT=T(()=>{"use strict";ee();J();Vt();rT=`${at}.21`;(function(r){r[r.unspecified=0]="unspecified",r[r.keyCompromise=1]="keyCompromise",r[r.cACompromise=2]="cACompromise",r[r.affiliationChanged=3]="affiliationChanged",r[r.superseded=4]="superseded",r[r.cessationOfOperation=5]="cessationOfOperation",r[r.certificateHold=6]="certificateHold",r[r.removeFromCRL=8]="removeFromCRL",r[r.privilegeWithdrawn=9]="privilegeWithdrawn",r[r.aACompromise=10]="aACompromise"})(wl||(wl={}));Sl=class{reason=wl.unspecified;constructor(e=wl.unspecified){this.reason=e}toJSON(){return wl[this.reason]}toString(){return this.toJSON()}};p([g({type:_.Enumerated})],Sl.prototype,"reason",void 0);Sl=p([U({type:B.Choice})],Sl)});var D1,Lm,_l,AY,nT,iT,oT,aT,cT,dT,uT=T(()=>{"use strict";ee();J();Vt();Lm=`${at}.37`,_l=D1=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,D1.prototype)}};_l=D1=p([U({type:B.Sequence,itemType:_.ObjectIdentifier})],_l);AY=`${Lm}.0`,nT=`${rc}.1`,iT=`${rc}.2`,oT=`${rc}.3`,aT=`${rc}.4`,cT=`${rc}.8`,dT=`${rc}.9`});var BY,M1,fT=T(()=>{"use strict";ee();J();Vt();BY=`${at}.54`,M1=class{value;constructor(e=new ArrayBuffer(0)){this.value=e}};p([g({type:_.Integer,converter:Et})],M1.prototype,"value",void 0);M1=p([U({type:B.Choice})],M1)});var lT,El,hT=T(()=>{"use strict";ee();J();Vt();lT=`${at}.24`,El=class{value=new Date;constructor(e){e&&(this.value=e)}};p([g({type:_.GeneralizedTime})],El.prototype,"value",void 0);El=p([U({type:B.Choice})],El)});var U1,j1,pT,mT=T(()=>{"use strict";ee();J();pl();Vt();j1=`${at}.18`,pT=U1=class extends Xt{constructor(e){super(e),Object.setPrototypeOf(this,U1.prototype)}};pT=U1=p([U({type:B.Sequence})],pT)});var Dm,dn,Wd,gT=T(()=>{"use strict";J();Vt();Dm=`${at}.15`;(function(r){r[r.digitalSignature=1]="digitalSignature",r[r.nonRepudiation=2]="nonRepudiation",r[r.keyEncipherment=4]="keyEncipherment",r[r.dataEncipherment=8]="dataEncipherment",r[r.keyAgreement=16]="keyAgreement",r[r.keyCertSign=32]="keyCertSign",r[r.cRLSign=64]="cRLSign",r[r.encipherOnly=128]="encipherOnly",r[r.decipherOnly=256]="decipherOnly"})(dn||(dn={}));Wd=class extends Hn{toJSON(){let e=this.toNumber(),t=[];return e&dn.cRLSign&&t.push("crlSign"),e&dn.dataEncipherment&&t.push("dataEncipherment"),e&dn.decipherOnly&&t.push("decipherOnly"),e&dn.digitalSignature&&t.push("digitalSignature"),e&dn.encipherOnly&&t.push("encipherOnly"),e&dn.keyAgreement&&t.push("keyAgreement"),e&dn.keyCertSign&&t.push("keyCertSign"),e&dn.keyEncipherment&&t.push("keyEncipherment"),e&dn.nonRepudiation&&t.push("nonRepudiation"),t}toString(){return`[${this.toJSON().join(", ")}]`}}});var H1,ZY,Gd,Mm,Um,yT=T(()=>{"use strict";ee();J();tc();Vt();ZY=`${at}.30`,Gd=class{base=new We;minimum=0;maximum;constructor(e={}){Object.assign(this,e)}};p([g({type:We})],Gd.prototype,"base",void 0);p([g({type:_.Integer,context:0,defaultValue:0,implicit:!0})],Gd.prototype,"minimum",void 0);p([g({type:_.Integer,context:1,optional:!0,implicit:!0})],Gd.prototype,"maximum",void 0);Mm=H1=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,H1.prototype)}};Mm=H1=p([U({type:B.Sequence,itemType:Gd})],Mm);Um=class{permittedSubtrees;excludedSubtrees;constructor(e={}){Object.assign(this,e)}};p([g({type:Mm,context:0,optional:!0,implicit:!0})],Um.prototype,"permittedSubtrees",void 0);p([g({type:Mm,context:1,optional:!0,implicit:!0})],Um.prototype,"excludedSubtrees",void 0)});var iJ,jm,xT=T(()=>{"use strict";ee();J();Vt();iJ=`${at}.36`,jm=class{requireExplicitPolicy;inhibitPolicyMapping;constructor(e={}){Object.assign(this,e)}};p([g({type:_.Integer,context:0,implicit:!0,optional:!0,converter:Et})],jm.prototype,"requireExplicitPolicy",void 0);p([g({type:_.Integer,context:1,implicit:!0,optional:!0,converter:Et})],jm.prototype,"inhibitPolicyMapping",void 0)});var F1,uJ,Cl,bT,vT=T(()=>{"use strict";ee();J();Vt();uJ=`${at}.33`,Cl=class{issuerDomainPolicy="";subjectDomainPolicy="";constructor(e={}){Object.assign(this,e)}};p([g({type:_.ObjectIdentifier})],Cl.prototype,"issuerDomainPolicy",void 0);p([g({type:_.ObjectIdentifier})],Cl.prototype,"subjectDomainPolicy",void 0);bT=F1=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,F1.prototype)}};bT=F1=p([U({type:B.Sequence,itemType:Cl})],bT)});var q1,z1,Hm,wT=T(()=>{"use strict";ee();J();pl();Vt();z1=`${at}.17`,Hm=q1=class extends Xt{constructor(e){super(e),Object.setPrototypeOf(this,q1.prototype)}};Hm=q1=p([U({type:B.Sequence})],Hm)});var Ir,$1=T(()=>{"use strict";ee();J();Ir=class{type="";values=[];constructor(e={}){Object.assign(this,e)}};p([g({type:_.ObjectIdentifier})],Ir.prototype,"type",void 0);p([g({type:_.Any,repeated:"set"})],Ir.prototype,"values",void 0)});var V1,TJ,ST,_T=T(()=>{"use strict";ee();J();$1();Vt();TJ=`${at}.9`,ST=V1=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,V1.prototype)}};ST=V1=p([U({type:B.Sequence,itemType:Ir})],ST)});var K1,us,ET=T(()=>{"use strict";Vt();R1();K1=`${at}.14`,us=class extends nc{}});var LJ,Fm,CT=T(()=>{"use strict";ee();J();Vt();LJ=`${at}.16`,Fm=class{notBefore;notAfter;constructor(e={}){Object.assign(this,e)}};p([g({type:_.GeneralizedTime,context:0,implicit:!0,optional:!0})],Fm.prototype,"notBefore",void 0);p([g({type:_.GeneralizedTime,context:1,implicit:!0,optional:!0})],Fm.prototype,"notAfter",void 0)});var Tl,qm,zm,TT=T(()=>{"use strict";ee();J();(function(r){r[r.keyUpdateAllowed=1]="keyUpdateAllowed",r[r.newExtensions=2]="newExtensions",r[r.pKIXCertificate=4]="pKIXCertificate"})(Tl||(Tl={}));qm=class extends Hn{toJSON(){let e=[],t=this.toNumber();return t&Tl.pKIXCertificate&&e.push("pKIXCertificate"),t&Tl.newExtensions&&e.push("newExtensions"),t&Tl.keyUpdateAllowed&&e.push("keyUpdateAllowed"),e}toString(){return`[${this.toJSON().join(", ")}]`}},zm=class{entrustVers="";entrustInfoFlags=new qm;constructor(e={}){Object.assign(this,e)}};p([g({type:_.GeneralString})],zm.prototype,"entrustVers",void 0);p([g({type:qm})],zm.prototype,"entrustInfoFlags",void 0)});var W1,$J,AT,IT=T(()=>{"use strict";ee();J();Vt();I1();$J=`${Do}.11`,AT=W1=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,W1.prototype)}};AT=W1=p([U({type:B.Sequence,itemType:Pi})],AT)});var RT=T(()=>{"use strict";I1();R1();W3();X3();Y3();Q3();Om();eT();tT();N1();sT();uT();fT();hT();mT();gT();yT();xT();vT();wT();_T();ET();CT();TT();IT()});var ue,ac=T(()=>{"use strict";ee();J();Cs();ue=class r{algorithm="";parameters;constructor(e={}){Object.assign(this,e)}isEqual(e){return e instanceof r&&e.algorithm==this.algorithm&&(e.parameters&&this.parameters&&o1(e.parameters,this.parameters)||e.parameters===this.parameters)}};p([g({type:_.ObjectIdentifier})],ue.prototype,"algorithm",void 0);p([g({type:_.Any,optional:!0})],ue.prototype,"parameters",void 0)});var Rr,G1=T(()=>{"use strict";ee();J();ac();Rr=class{algorithm=new ue;subjectPublicKey=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};p([g({type:ue})],Rr.prototype,"algorithm",void 0);p([g({type:_.BitString})],Rr.prototype,"subjectPublicKey",void 0)});var or,$m=T(()=>{"use strict";ee();J();or=class{utcTime;generalTime;constructor(e){if(e)if(typeof e=="string"||typeof e=="number"||e instanceof Date){let t=new Date(e);t.setMilliseconds(0),t.getUTCFullYear()>2049?this.generalTime=t:this.utcTime=t}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}};p([g({type:_.UTCTime})],or.prototype,"utcTime",void 0);p([g({type:_.GeneralizedTime})],or.prototype,"generalTime",void 0);or=p([U({type:B.Choice})],or)});var Oi,X1=T(()=>{"use strict";ee();J();$m();Oi=class{notBefore=new or(new Date);notAfter=new or(new Date);constructor(e){e&&(this.notBefore=new or(e.notBefore),this.notAfter=new or(e.notAfter))}};p([g({type:or})],Oi.prototype,"notBefore",void 0);p([g({type:or})],Oi.prototype,"notAfter",void 0)});var Y1,Kr,Ts,Vm=T(()=>{"use strict";ee();J();Kr=class r{static CRITICAL=!1;extnID="";critical=r.CRITICAL;extnValue=new ze;constructor(e={}){Object.assign(this,e)}};p([g({type:_.ObjectIdentifier})],Kr.prototype,"extnID",void 0);p([g({type:_.Boolean,defaultValue:Kr.CRITICAL})],Kr.prototype,"critical",void 0);p([g({type:ze})],Kr.prototype,"extnValue",void 0);Ts=Y1=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,Y1.prototype)}};Ts=Y1=p([U({type:B.Sequence,itemType:Kr})],Ts)});var zn,J1=T(()=>{"use strict";(function(r){r[r.v1=0]="v1",r[r.v2=1]="v2",r[r.v3=2]="v3"})(zn||(zn={}))});var kr,Q1=T(()=>{"use strict";ee();J();ac();Kd();G1();X1();Vm();J1();kr=class{version=zn.v1;serialNumber=new ArrayBuffer(0);signature=new ue;issuer=new Ft;validity=new Oi;subject=new Ft;subjectPublicKeyInfo=new Rr;issuerUniqueID;subjectUniqueID;extensions;constructor(e={}){Object.assign(this,e)}};p([g({type:_.Integer,context:0,defaultValue:zn.v1})],kr.prototype,"version",void 0);p([g({type:_.Integer,converter:Et})],kr.prototype,"serialNumber",void 0);p([g({type:ue})],kr.prototype,"signature",void 0);p([g({type:Ft})],kr.prototype,"issuer",void 0);p([g({type:Oi})],kr.prototype,"validity",void 0);p([g({type:Ft})],kr.prototype,"subject",void 0);p([g({type:Rr})],kr.prototype,"subjectPublicKeyInfo",void 0);p([g({type:_.BitString,context:1,implicit:!0,optional:!0})],kr.prototype,"issuerUniqueID",void 0);p([g({type:_.BitString,context:2,implicit:!0,optional:!0})],kr.prototype,"subjectUniqueID",void 0);p([g({type:Ts,context:3,optional:!0})],kr.prototype,"extensions",void 0)});var Ks,kT=T(()=>{"use strict";ee();J();ac();Q1();Ks=class{tbsCertificate=new kr;tbsCertificateRaw;signatureAlgorithm=new ue;signatureValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};p([g({type:kr,raw:!0})],Ks.prototype,"tbsCertificate",void 0);p([g({type:ue})],Ks.prototype,"signatureAlgorithm",void 0);p([g({type:_.BitString})],Ks.prototype,"signatureValue",void 0)});var cc,As,Z1=T(()=>{"use strict";ee();J();ac();Kd();$m();Vm();cc=class{userCertificate=new ArrayBuffer(0);revocationDate=new or;crlEntryExtensions;constructor(e={}){Object.assign(this,e)}};p([g({type:_.Integer,converter:Et})],cc.prototype,"userCertificate",void 0);p([g({type:or})],cc.prototype,"revocationDate",void 0);p([g({type:Kr,optional:!0,repeated:"sequence"})],cc.prototype,"crlEntryExtensions",void 0);As=class{version;signature=new ue;issuer=new Ft;thisUpdate=new or;nextUpdate;revokedCertificates;crlExtensions;constructor(e={}){Object.assign(this,e)}};p([g({type:_.Integer,optional:!0})],As.prototype,"version",void 0);p([g({type:ue})],As.prototype,"signature",void 0);p([g({type:Ft})],As.prototype,"issuer",void 0);p([g({type:or})],As.prototype,"thisUpdate",void 0);p([g({type:or,optional:!0})],As.prototype,"nextUpdate",void 0);p([g({type:cc,repeated:"sequence",optional:!0})],As.prototype,"revokedCertificates",void 0);p([g({type:Kr,optional:!0,context:0,repeated:"sequence"})],As.prototype,"crlExtensions",void 0)});var dc,PT=T(()=>{"use strict";ee();J();ac();Z1();dc=class{tbsCertList=new As;tbsCertListRaw;signatureAlgorithm=new ue;signature=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};p([g({type:As,raw:!0})],dc.prototype,"tbsCertList",void 0);p([g({type:ue})],dc.prototype,"signatureAlgorithm",void 0);p([g({type:_.BitString})],dc.prototype,"signature",void 0)});var Ct=T(()=>{"use strict";RT();ac();$1();kT();PT();Vm();tc();pl();Kd();Vt();G1();Z1();Q1();$m();J1();X1()});var un,Al=T(()=>{"use strict";ee();J();Ct();un=class{issuer=new Ft;serialNumber=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};p([g({type:Ft})],un.prototype,"issuer",void 0);p([g({type:_.Integer,converter:Et})],un.prototype,"serialNumber",void 0)});var uc,ev=T(()=>{"use strict";ee();J();Ct();Al();uc=class{subjectKeyIdentifier;issuerAndSerialNumber;constructor(e={}){Object.assign(this,e)}};p([g({type:us,context:0,implicit:!0})],uc.prototype,"subjectKeyIdentifier",void 0);p([g({type:un})],uc.prototype,"issuerAndSerialNumber",void 0);uc=p([U({type:B.Choice})],uc)});var Pr,fc,Il,fs,Rl,NT,Km,$n=T(()=>{"use strict";ee();Ct();J();(function(r){r[r.v0=0]="v0",r[r.v1=1]="v1",r[r.v2=2]="v2",r[r.v3=3]="v3",r[r.v4=4]="v4",r[r.v5=5]="v5"})(Pr||(Pr={}));fc=class extends ue{};fc=p([U({type:B.Sequence})],fc);Il=class extends ue{};Il=p([U({type:B.Sequence})],Il);fs=class extends ue{};fs=p([U({type:B.Sequence})],fs);Rl=class extends ue{};Rl=p([U({type:B.Sequence})],Rl);NT=class extends ue{};NT=p([U({type:B.Sequence})],NT);Km=class extends ue{};Km=p([U({type:B.Sequence})],Km)});var fn,Wm=T(()=>{"use strict";ee();J();fn=class{attrType="";attrValues=[];constructor(e={}){Object.assign(this,e)}};p([g({type:_.ObjectIdentifier})],fn.prototype,"attrType",void 0);p([g({type:_.Any,repeated:"set"})],fn.prototype,"attrValues",void 0)});var tv,ls,kl,Gm=T(()=>{"use strict";ee();J();ev();$n();Wm();ls=class{version=Pr.v0;sid=new uc;digestAlgorithm=new fc;signedAttrs;signedAttrsRaw;signatureAlgorithm=new Il;signature=new ze;unsignedAttrs;constructor(e={}){Object.assign(this,e)}};p([g({type:_.Integer})],ls.prototype,"version",void 0);p([g({type:uc})],ls.prototype,"sid",void 0);p([g({type:fc})],ls.prototype,"digestAlgorithm",void 0);p([g({type:fn,repeated:"set",context:0,implicit:!0,optional:!0,raw:!0})],ls.prototype,"signedAttrs",void 0);p([g({type:Il})],ls.prototype,"signatureAlgorithm",void 0);p([g({type:ze})],ls.prototype,"signature",void 0);p([g({type:fn,repeated:"set",context:1,implicit:!0,optional:!0})],ls.prototype,"unsignedAttrs",void 0);kl=tv=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,tv.prototype)}};kl=tv=p([U({type:B.Set,itemType:ls})],kl)});var OT,LT=T(()=>{"use strict";ee();J();Gm();OT=class extends ls{};OT=p([U({type:B.Sequence})],OT)});var DT=T(()=>{"use strict";J()});var MT,UT=T(()=>{"use strict";ee();Ct();J();MT=class extends or{};MT=p([U({type:B.Choice})],MT)});var jT=T(()=>{"use strict";LT();DT();UT()});var Pl,HT=T(()=>{"use strict";ee();J();Ct();Pl=class{acIssuer=new We;acSerial=0;attrs=[];constructor(e={}){Object.assign(this,e)}};p([g({type:We})],Pl.prototype,"acIssuer",void 0);p([g({type:_.Integer})],Pl.prototype,"acSerial",void 0);p([g({type:Ir,repeated:"sequence"})],Pl.prototype,"attrs",void 0)});var rv,Bl,sv=T(()=>{"use strict";ee();J();Bl=rv=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,rv.prototype)}};Bl=rv=p([U({type:B.Sequence,itemType:_.ObjectIdentifier})],Bl)});var Xd,FT=T(()=>{"use strict";ee();J();sv();Xd=class{pathLenConstraint;permittedAttrs;excludedAttrs;permitUnSpecified=!0;constructor(e={}){Object.assign(this,e)}};p([g({type:_.Integer,optional:!0})],Xd.prototype,"pathLenConstraint",void 0);p([g({type:Bl,implicit:!0,context:0,optional:!0})],Xd.prototype,"permittedAttrs",void 0);p([g({type:Bl,implicit:!0,context:1,optional:!0})],Xd.prototype,"excludedAttrs",void 0);p([g({type:_.Boolean,defaultValue:!0})],Xd.prototype,"permitUnSpecified",void 0)});var Ws,Nl=T(()=>{"use strict";ee();J();Ct();Ws=class{issuer=new Xt;serial=new ArrayBuffer(0);issuerUID=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};p([g({type:Xt})],Ws.prototype,"issuer",void 0);p([g({type:_.Integer,converter:Et})],Ws.prototype,"serial",void 0);p([g({type:_.BitString,optional:!0})],Ws.prototype,"issuerUID",void 0)});var nv,Gs,Ol=T(()=>{"use strict";ee();J();Ct();(function(r){r[r.publicKey=0]="publicKey",r[r.publicKeyCert=1]="publicKeyCert",r[r.otherObjectTypes=2]="otherObjectTypes"})(nv||(nv={}));Gs=class{digestedObjectType=nv.publicKey;otherObjectTypeID;digestAlgorithm=new ue;objectDigest=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};p([g({type:_.Enumerated})],Gs.prototype,"digestedObjectType",void 0);p([g({type:_.ObjectIdentifier,optional:!0})],Gs.prototype,"otherObjectTypeID",void 0);p([g({type:ue})],Gs.prototype,"digestAlgorithm",void 0);p([g({type:_.BitString})],Gs.prototype,"objectDigest",void 0)});var lc,iv=T(()=>{"use strict";ee();J();Ct();Nl();Ol();lc=class{issuerName;baseCertificateID;objectDigestInfo;constructor(e={}){Object.assign(this,e)}};p([g({type:Xt,optional:!0})],lc.prototype,"issuerName",void 0);p([g({type:Ws,context:0,implicit:!0,optional:!0})],lc.prototype,"baseCertificateID",void 0);p([g({type:Gs,context:1,implicit:!0,optional:!0})],lc.prototype,"objectDigestInfo",void 0)});var hc,ov=T(()=>{"use strict";ee();J();Ct();iv();hc=class{v1Form;v2Form;constructor(e={}){Object.assign(this,e)}};p([g({type:We,repeated:"sequence"})],hc.prototype,"v1Form",void 0);p([g({type:lc,context:0,implicit:!0})],hc.prototype,"v2Form",void 0);hc=p([U({type:B.Choice})],hc)});var pc,av=T(()=>{"use strict";ee();J();pc=class{notBeforeTime=new Date;notAfterTime=new Date;constructor(e={}){Object.assign(this,e)}};p([g({type:_.GeneralizedTime})],pc.prototype,"notBeforeTime",void 0);p([g({type:_.GeneralizedTime})],pc.prototype,"notAfterTime",void 0)});var Uo,cv=T(()=>{"use strict";ee();J();Ct();Nl();Ol();Uo=class{baseCertificateID;entityName;objectDigestInfo;constructor(e={}){Object.assign(this,e)}};p([g({type:Ws,implicit:!0,context:0,optional:!0})],Uo.prototype,"baseCertificateID",void 0);p([g({type:Xt,implicit:!0,context:1,optional:!0})],Uo.prototype,"entityName",void 0);p([g({type:Gs,implicit:!0,context:2,optional:!0})],Uo.prototype,"objectDigestInfo",void 0)});var dv,hs,uv=T(()=>{"use strict";ee();J();Ct();cv();ov();av();(function(r){r[r.v2=1]="v2"})(dv||(dv={}));hs=class{version=dv.v2;holder=new Uo;issuer=new hc;signature=new ue;serialNumber=new ArrayBuffer(0);attrCertValidityPeriod=new pc;attributes=[];issuerUniqueID;extensions;constructor(e={}){Object.assign(this,e)}};p([g({type:_.Integer})],hs.prototype,"version",void 0);p([g({type:Uo})],hs.prototype,"holder",void 0);p([g({type:hc})],hs.prototype,"issuer",void 0);p([g({type:ue})],hs.prototype,"signature",void 0);p([g({type:_.Integer,converter:Et})],hs.prototype,"serialNumber",void 0);p([g({type:pc})],hs.prototype,"attrCertValidityPeriod",void 0);p([g({type:Ir,repeated:"sequence"})],hs.prototype,"attributes",void 0);p([g({type:_.BitString,optional:!0})],hs.prototype,"issuerUniqueID",void 0);p([g({type:Ts,optional:!0})],hs.prototype,"extensions",void 0)});var mc,qT=T(()=>{"use strict";ee();J();Ct();uv();mc=class{acinfo=new hs;signatureAlgorithm=new ue;signatureValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};p([g({type:hs})],mc.prototype,"acinfo",void 0);p([g({type:ue})],mc.prototype,"signatureAlgorithm",void 0);p([g({type:_.BitString})],mc.prototype,"signatureValue",void 0)});var Ll,Yd,fv=T(()=>{"use strict";J();(function(r){r[r.unmarked=1]="unmarked",r[r.unclassified=2]="unclassified",r[r.restricted=4]="restricted",r[r.confidential=8]="confidential",r[r.secret=16]="secret",r[r.topSecret=32]="topSecret"})(Ll||(Ll={}));Yd=class extends Hn{}});var Jd,lv=T(()=>{"use strict";ee();J();Jd=class{type="";value=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};p([g({type:_.ObjectIdentifier,implicit:!0,context:0})],Jd.prototype,"type",void 0);p([g({type:_.Any,implicit:!0,context:1})],Jd.prototype,"value",void 0)});var Dl,zT=T(()=>{"use strict";ee();J();fv();lv();Dl=class{policyId="";classList=new Yd(Ll.unclassified);securityCategories;constructor(e={}){Object.assign(this,e)}};p([g({type:_.ObjectIdentifier})],Dl.prototype,"policyId",void 0);p([g({type:Yd,defaultValue:new Yd(Ll.unclassified)})],Dl.prototype,"classList",void 0);p([g({type:Jd,repeated:"set"})],Dl.prototype,"securityCategories",void 0)});var Qd,Xm,$T=T(()=>{"use strict";ee();J();Ct();Qd=class{cotets;oid;string;constructor(e={}){Object.assign(this,e)}};p([g({type:ze})],Qd.prototype,"cotets",void 0);p([g({type:_.ObjectIdentifier})],Qd.prototype,"oid",void 0);p([g({type:_.Utf8String})],Qd.prototype,"string",void 0);Xm=class{policyAuthority;values=[];constructor(e={}){Object.assign(this,e)}};p([g({type:Xt,implicit:!0,context:0,optional:!0})],Xm.prototype,"policyAuthority",void 0);p([g({type:Qd,repeated:"sequence"})],Xm.prototype,"values",void 0)});var Ote,Lte,Dte,Mte,Ml,Ute,jte,Hte,Fte,qte,hv,zte,VT=T(()=>{"use strict";Ct();Ote=`${Do}.4`,Lte=`${Do}.6`,Dte=`${Do}.10`,Mte=`${at}.55`,Ml=`${Lo}.10`,Ute=`${Ml}.1`,jte=`${Ml}.2`,Hte=`${Ml}.3`,Fte=`${Ml}.4`,qte=`${Ml}.6`,hv="2.5.4",zte=`${hv}.72`});var pv,Zd,eu,Ym,mv=T(()=>{"use strict";ee();J();Ct();Nl();Ol();Zd=class{targetCertificate=new Ws;targetName;certDigestInfo;constructor(e={}){Object.assign(this,e)}};p([g({type:Ws})],Zd.prototype,"targetCertificate",void 0);p([g({type:We,optional:!0})],Zd.prototype,"targetName",void 0);p([g({type:Gs,optional:!0})],Zd.prototype,"certDigestInfo",void 0);eu=class{targetName;targetGroup;targetCert;constructor(e={}){Object.assign(this,e)}};p([g({type:We,context:0,implicit:!0})],eu.prototype,"targetName",void 0);p([g({type:We,context:1,implicit:!0})],eu.prototype,"targetGroup",void 0);p([g({type:Zd,context:2,implicit:!0})],eu.prototype,"targetCert",void 0);eu=p([U({type:B.Choice})],eu);Ym=pv=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,pv.prototype)}};Ym=pv=p([U({type:B.Sequence,itemType:eu})],Ym)});var gv,KT,WT=T(()=>{"use strict";ee();J();mv();KT=gv=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,gv.prototype)}};KT=gv=p([U({type:B.Sequence,itemType:Ym})],KT)});var Jm,GT=T(()=>{"use strict";ee();J();Ct();Jm=class{roleAuthority;roleName;constructor(e={}){Object.assign(this,e)}};p([g({type:Xt,implicit:!0,context:0,optional:!0})],Jm.prototype,"roleAuthority",void 0);p([g({type:We,implicit:!0,context:1})],Jm.prototype,"roleName",void 0)});var Ul,XT=T(()=>{"use strict";ee();J();Ct();Ul=class{service=new We;ident=new We;authInfo;constructor(e={}){Object.assign(this,e)}};p([g({type:We})],Ul.prototype,"service",void 0);p([g({type:We})],Ul.prototype,"ident",void 0);p([g({type:ze,optional:!0})],Ul.prototype,"authInfo",void 0)});var yv=T(()=>{"use strict";HT();FT();ov();av();sv();qT();uv();fv();zT();cv();$T();Nl();Ol();VT();WT();GT();lv();XT();mv();iv()});var xv,jl,gc,yc,Qm=T(()=>{"use strict";ee();J();Ct();yv();jl=class{otherCertFormat="";otherCert=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};p([g({type:_.ObjectIdentifier})],jl.prototype,"otherCertFormat",void 0);p([g({type:_.Any})],jl.prototype,"otherCert",void 0);gc=class{certificate;v2AttrCert;other;constructor(e={}){Object.assign(this,e)}};p([g({type:Ks})],gc.prototype,"certificate",void 0);p([g({type:mc,context:2,implicit:!0})],gc.prototype,"v2AttrCert",void 0);p([g({type:jl,context:3,implicit:!0})],gc.prototype,"other",void 0);gc=p([U({type:B.Choice})],gc);yc=xv=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,xv.prototype)}};yc=xv=p([U({type:B.Set,itemType:gc})],yc)});var Xs,YT=T(()=>{"use strict";ee();J();Xs=class{contentType="";content=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};p([g({type:_.ObjectIdentifier})],Xs.prototype,"contentType",void 0);p([g({type:_.Any,context:0})],Xs.prototype,"content",void 0)});var tu,xc,bv=T(()=>{"use strict";ee();J();tu=class{single;any;constructor(e={}){Object.assign(this,e)}};p([g({type:ze})],tu.prototype,"single",void 0);p([g({type:_.Any})],tu.prototype,"any",void 0);tu=p([U({type:B.Choice})],tu);xc=class{eContentType="";eContent;constructor(e={}){Object.assign(this,e)}};p([g({type:_.ObjectIdentifier})],xc.prototype,"eContentType",void 0);p([g({type:tu,context:0,optional:!0})],xc.prototype,"eContent",void 0)});var Hl,jo,vv=T(()=>{"use strict";ee();J();$n();Hl=class{value;constructedValue;constructor(e={}){Object.assign(this,e)}};p([g({type:ze,context:0,implicit:!0,optional:!0})],Hl.prototype,"value",void 0);p([g({type:ze,converter:I3,context:0,implicit:!0,optional:!0,repeated:"sequence"})],Hl.prototype,"constructedValue",void 0);Hl=p([U({type:B.Choice})],Hl);jo=class{contentType="";contentEncryptionAlgorithm=new Rl;encryptedContent;constructor(e={}){Object.assign(this,e)}};p([g({type:_.ObjectIdentifier})],jo.prototype,"contentType",void 0);p([g({type:Rl})],jo.prototype,"contentEncryptionAlgorithm",void 0);p([g({type:Hl,optional:!0})],jo.prototype,"encryptedContent",void 0)});var Ho,wv=T(()=>{"use strict";ee();J();Ho=class{keyAttrId="";keyAttr;constructor(e={}){Object.assign(this,e)}};p([g({type:_.ObjectIdentifier})],Ho.prototype,"keyAttrId",void 0);p([g({type:_.Any,optional:!0})],Ho.prototype,"keyAttr",void 0)});var Sv,ru,su,Fl,Zm,ql,bc,Li,_v=T(()=>{"use strict";ee();J();Ct();$n();Al();wv();ru=class{subjectKeyIdentifier=new us;date;other;constructor(e={}){Object.assign(this,e)}};p([g({type:us})],ru.prototype,"subjectKeyIdentifier",void 0);p([g({type:_.GeneralizedTime,optional:!0})],ru.prototype,"date",void 0);p([g({type:Ho,optional:!0})],ru.prototype,"other",void 0);su=class{rKeyId;issuerAndSerialNumber;constructor(e={}){Object.assign(this,e)}};p([g({type:ru,context:0,implicit:!0,optional:!0})],su.prototype,"rKeyId",void 0);p([g({type:un,optional:!0})],su.prototype,"issuerAndSerialNumber",void 0);su=p([U({type:B.Choice})],su);Fl=class{rid=new su;encryptedKey=new ze;constructor(e={}){Object.assign(this,e)}};p([g({type:su})],Fl.prototype,"rid",void 0);p([g({type:ze})],Fl.prototype,"encryptedKey",void 0);Zm=Sv=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,Sv.prototype)}};Zm=Sv=p([U({type:B.Sequence,itemType:Fl})],Zm);ql=class{algorithm=new ue;publicKey=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};p([g({type:ue})],ql.prototype,"algorithm",void 0);p([g({type:_.BitString})],ql.prototype,"publicKey",void 0);bc=class{subjectKeyIdentifier;originatorKey;issuerAndSerialNumber;constructor(e={}){Object.assign(this,e)}};p([g({type:us,context:0,implicit:!0,optional:!0})],bc.prototype,"subjectKeyIdentifier",void 0);p([g({type:ql,context:1,implicit:!0,optional:!0})],bc.prototype,"originatorKey",void 0);p([g({type:un,optional:!0})],bc.prototype,"issuerAndSerialNumber",void 0);bc=p([U({type:B.Choice})],bc);Li=class{version=Pr.v3;originator=new bc;ukm;keyEncryptionAlgorithm=new fs;recipientEncryptedKeys=new Zm;constructor(e={}){Object.assign(this,e)}};p([g({type:_.Integer})],Li.prototype,"version",void 0);p([g({type:bc,context:0})],Li.prototype,"originator",void 0);p([g({type:ze,context:1,optional:!0})],Li.prototype,"ukm",void 0);p([g({type:fs})],Li.prototype,"keyEncryptionAlgorithm",void 0);p([g({type:Zm})],Li.prototype,"recipientEncryptedKeys",void 0)});var nu,Fo,Ev=T(()=>{"use strict";ee();J();Ct();$n();Al();nu=class{subjectKeyIdentifier;issuerAndSerialNumber;constructor(e={}){Object.assign(this,e)}};p([g({type:us,context:0,implicit:!0})],nu.prototype,"subjectKeyIdentifier",void 0);p([g({type:un})],nu.prototype,"issuerAndSerialNumber",void 0);nu=p([U({type:B.Choice})],nu);Fo=class{version=Pr.v0;rid=new nu;keyEncryptionAlgorithm=new fs;encryptedKey=new ze;constructor(e={}){Object.assign(this,e)}};p([g({type:_.Integer})],Fo.prototype,"version",void 0);p([g({type:nu})],Fo.prototype,"rid",void 0);p([g({type:fs})],Fo.prototype,"keyEncryptionAlgorithm",void 0);p([g({type:ze})],Fo.prototype,"encryptedKey",void 0)});var vc,qo,Cv=T(()=>{"use strict";ee();J();wv();$n();vc=class{keyIdentifier=new ze;date;other;constructor(e={}){Object.assign(this,e)}};p([g({type:ze})],vc.prototype,"keyIdentifier",void 0);p([g({type:_.GeneralizedTime,optional:!0})],vc.prototype,"date",void 0);p([g({type:Ho,optional:!0})],vc.prototype,"other",void 0);qo=class{version=Pr.v4;kekid=new vc;keyEncryptionAlgorithm=new fs;encryptedKey=new ze;constructor(e={}){Object.assign(this,e)}};p([g({type:_.Integer})],qo.prototype,"version",void 0);p([g({type:vc})],qo.prototype,"kekid",void 0);p([g({type:fs})],qo.prototype,"keyEncryptionAlgorithm",void 0);p([g({type:ze})],qo.prototype,"encryptedKey",void 0)});var zo,Tv=T(()=>{"use strict";ee();J();$n();zo=class{version=Pr.v0;keyDerivationAlgorithm;keyEncryptionAlgorithm=new fs;encryptedKey=new ze;constructor(e={}){Object.assign(this,e)}};p([g({type:_.Integer})],zo.prototype,"version",void 0);p([g({type:Km,context:0,optional:!0})],zo.prototype,"keyDerivationAlgorithm",void 0);p([g({type:fs})],zo.prototype,"keyEncryptionAlgorithm",void 0);p([g({type:ze})],zo.prototype,"encryptedKey",void 0)});var zl,Di,Av=T(()=>{"use strict";ee();J();_v();Ev();Cv();Tv();zl=class{oriType="";oriValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};p([g({type:_.ObjectIdentifier})],zl.prototype,"oriType",void 0);p([g({type:_.Any})],zl.prototype,"oriValue",void 0);Di=class{ktri;kari;kekri;pwri;ori;constructor(e={}){Object.assign(this,e)}};p([g({type:Fo,optional:!0})],Di.prototype,"ktri",void 0);p([g({type:Li,context:1,implicit:!0,optional:!0})],Di.prototype,"kari",void 0);p([g({type:qo,context:2,implicit:!0,optional:!0})],Di.prototype,"kekri",void 0);p([g({type:zo,context:3,implicit:!0,optional:!0})],Di.prototype,"pwri",void 0);p([g({type:zl,context:4,implicit:!0,optional:!0})],Di.prototype,"ori",void 0);Di=p([U({type:B.Choice})],Di)});var Iv,$l,Rv=T(()=>{"use strict";ee();J();Av();$l=Iv=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,Iv.prototype)}};$l=Iv=p([U({type:B.Set,itemType:Di})],$l)});var kv,JT,qse,zse,iu,eg,ou,tg=T(()=>{"use strict";ee();J();Ct();JT=`${Lo}.16`,qse=`${JT}.2`,zse=`${JT}.4`,iu=class{otherRevInfoFormat="";otherRevInfo=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};p([g({type:_.ObjectIdentifier})],iu.prototype,"otherRevInfoFormat",void 0);p([g({type:_.Any})],iu.prototype,"otherRevInfo",void 0);eg=class{other=new iu;constructor(e={}){Object.assign(this,e)}};p([g({type:iu,context:1,implicit:!0})],eg.prototype,"other",void 0);eg=p([U({type:B.Choice})],eg);ou=kv=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,kv.prototype)}};ou=kv=p([U({type:B.Set,itemType:eg})],ou)});var au,Pv=T(()=>{"use strict";ee();J();Qm();tg();au=class{certs;crls;constructor(e={}){Object.assign(this,e)}};p([g({type:yc,context:0,implicit:!0,optional:!0})],au.prototype,"certs",void 0);p([g({type:ou,context:1,implicit:!0,optional:!0})],au.prototype,"crls",void 0)});var Bv,Nv,wc,QT=T(()=>{"use strict";ee();J();$n();Wm();Rv();Pv();vv();Nv=Bv=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,Bv.prototype)}};Nv=Bv=p([U({type:B.Set,itemType:fn})],Nv);wc=class{version=Pr.v0;originatorInfo;recipientInfos=new $l;encryptedContentInfo=new jo;unprotectedAttrs;constructor(e={}){Object.assign(this,e)}};p([g({type:_.Integer})],wc.prototype,"version",void 0);p([g({type:au,context:0,implicit:!0,optional:!0})],wc.prototype,"originatorInfo",void 0);p([g({type:$l})],wc.prototype,"recipientInfos",void 0);p([g({type:jo})],wc.prototype,"encryptedContentInfo",void 0);p([g({type:Nv,context:1,implicit:!0,optional:!0})],wc.prototype,"unprotectedAttrs",void 0)});var ZT,e4=T(()=>{"use strict";ZT="1.2.840.113549.1.7.2"});var Ov,rg,Mi,t4=T(()=>{"use strict";ee();J();Qm();$n();bv();tg();Gm();rg=Ov=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,Ov.prototype)}};rg=Ov=p([U({type:B.Set,itemType:fc})],rg);Mi=class{version=Pr.v0;digestAlgorithms=new rg;encapContentInfo=new xc;certificates;crls;signerInfos=new kl;constructor(e={}){Object.assign(this,e)}};p([g({type:_.Integer})],Mi.prototype,"version",void 0);p([g({type:rg})],Mi.prototype,"digestAlgorithms",void 0);p([g({type:xc})],Mi.prototype,"encapContentInfo",void 0);p([g({type:yc,context:0,implicit:!0,optional:!0})],Mi.prototype,"certificates",void 0);p([g({type:ou,context:1,implicit:!0,optional:!0})],Mi.prototype,"crls",void 0);p([g({type:kl})],Mi.prototype,"signerInfos",void 0)});var Vl=T(()=>{"use strict";jT();Wm();Qm();YT();bv();vv();QT();Al();Cv();_v();Ev();e4();Pv();Tv();Av();Rv();tg();t4();ev();Gm();$n()});var Sc,Kl,sg,Wl,Gl,Xl,Lv,Dv,Mv,Uv=T(()=>{"use strict";Sc="1.2.840.10045.2.1",Kl="1.2.840.10045.4.1",sg="1.2.840.10045.4.3.1",Wl="1.2.840.10045.4.3.2",Gl="1.2.840.10045.4.3.3",Xl="1.2.840.10045.4.3.4",Lv="1.2.840.10045.3.1.7",Dv="1.3.132.0.34",Mv="1.3.132.0.35"});function Yl(r){return new ue({algorithm:r})}var s4,jne,n4,i4,o4,a4=T(()=>{"use strict";Ct();Uv();s4=Yl(Kl),jne=Yl(sg),n4=Yl(Wl),i4=Yl(Gl),o4=Yl(Xl)});var Jl,jv,cu,Hv,Vn,Fv=T(()=>{"use strict";ee();J();Jl=class{fieldType;parameters;constructor(e={}){Object.assign(this,e)}};p([g({type:_.ObjectIdentifier})],Jl.prototype,"fieldType",void 0);p([g({type:_.Any})],Jl.prototype,"parameters",void 0);Jl=p([U({type:B.Sequence})],Jl);jv=class extends ze{},cu=class{a;b;seed;constructor(e={}){Object.assign(this,e)}};p([g({type:_.OctetString})],cu.prototype,"a",void 0);p([g({type:_.OctetString})],cu.prototype,"b",void 0);p([g({type:_.BitString,optional:!0})],cu.prototype,"seed",void 0);cu=p([U({type:B.Sequence})],cu);(function(r){r[r.ecpVer1=1]="ecpVer1"})(Hv||(Hv={}));Vn=class{version=Hv.ecpVer1;fieldID;curve;base;order;cofactor;constructor(e={}){Object.assign(this,e)}};p([g({type:_.Integer})],Vn.prototype,"version",void 0);p([g({type:Jl})],Vn.prototype,"fieldID",void 0);p([g({type:cu})],Vn.prototype,"curve",void 0);p([g({type:jv})],Vn.prototype,"base",void 0);p([g({type:_.Integer,converter:Et})],Vn.prototype,"order",void 0);p([g({type:_.Integer,optional:!0})],Vn.prototype,"cofactor",void 0);Vn=p([U({type:B.Sequence})],Vn)});var Kn,qv=T(()=>{"use strict";ee();J();Fv();Kn=class{namedCurve;implicitCurve;specifiedCurve;constructor(e={}){Object.assign(this,e)}};p([g({type:_.ObjectIdentifier})],Kn.prototype,"namedCurve",void 0);p([g({type:_.Null})],Kn.prototype,"implicitCurve",void 0);p([g({type:Vn})],Kn.prototype,"specifiedCurve",void 0);Kn=p([U({type:B.Choice})],Kn)});var du,c4=T(()=>{"use strict";ee();J();qv();du=class{version=1;privateKey=new ze;parameters;publicKey;constructor(e={}){Object.assign(this,e)}};p([g({type:_.Integer})],du.prototype,"version",void 0);p([g({type:ze})],du.prototype,"privateKey",void 0);p([g({type:Kn,context:0,optional:!0})],du.prototype,"parameters",void 0);p([g({type:_.BitString,context:1,optional:!0})],du.prototype,"publicKey",void 0)});var _c,d4=T(()=>{"use strict";ee();J();_c=class{r=new ArrayBuffer(0);s=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};p([g({type:_.Integer,converter:Et})],_c.prototype,"r",void 0);p([g({type:_.Integer,converter:Et})],_c.prototype,"s",void 0)});var zv=T(()=>{"use strict";a4();qv();c4();d4();Uv();Fv()});var ps,Wn,u4,f4,$o,l4,h4,uu,p4,ng,fu,lu,$v,Vv,Ec,ig,Cc,Tc,Ac,m4,g4,y4,x4,Vo,Ql=T(()=>{"use strict";ps="1.2.840.113549.1.1",Wn=`${ps}.1`,u4=`${ps}.7`,f4=`${ps}.9`,$o=`${ps}.10`,l4=`${ps}.2`,h4=`${ps}.4`,uu=`${ps}.5`,p4=`${ps}.14`,ng=`${ps}.11`,fu=`${ps}.12`,lu=`${ps}.13`,$v=`${ps}.15`,Vv=`${ps}.16`,Ec="1.3.14.3.2.26",ig="2.16.840.1.101.3.4.2.4",Cc="2.16.840.1.101.3.4.2.1",Tc="2.16.840.1.101.3.4.2.2",Ac="2.16.840.1.101.3.4.2.3",m4="2.16.840.1.101.3.4.2.5",g4="2.16.840.1.101.3.4.2.6",y4="1.2.840.113549.2.2",x4="1.2.840.113549.2.5",Vo=`${ps}.8`});function wr(r){return new ue({algorithm:r,parameters:null})}var hie,pie,Ui,mie,gie,yie,xie,bie,vie,og,Kv,wie,Sie,_ie,Eie,Cie,Tie,Aie,Iie,Rie,kie,ag=T(()=>{"use strict";J();Ct();Ql();hie=wr(y4),pie=wr(x4),Ui=wr(Ec),mie=wr(ig),gie=wr(Cc),yie=wr(Tc),xie=wr(Ac),bie=wr(m4),vie=wr(g4),og=new ue({algorithm:Vo,parameters:pe.serialize(Ui)}),Kv=new ue({algorithm:f4,parameters:pe.serialize(zd.toASN(new Uint8Array([218,57,163,238,94,107,75,13,50,85,191,239,149,96,24,144,175,216,7,9]).buffer))}),wie=wr(Wn),Sie=wr(l4),_ie=wr(h4),Eie=wr(uu),Cie=wr($v),Tie=wr(Vv),Aie=wr(fu),Iie=wr(lu),Rie=wr($v),kie=wr(Vv)});var hu,Mie,b4=T(()=>{"use strict";ee();J();Ct();Ql();ag();hu=class{hashAlgorithm=new ue(Ui);maskGenAlgorithm=new ue({algorithm:Vo,parameters:pe.serialize(Ui)});pSourceAlgorithm=new ue(Kv);constructor(e={}){Object.assign(this,e)}};p([g({type:ue,context:0,defaultValue:Ui})],hu.prototype,"hashAlgorithm",void 0);p([g({type:ue,context:1,defaultValue:og})],hu.prototype,"maskGenAlgorithm",void 0);p([g({type:ue,context:2,defaultValue:Kv})],hu.prototype,"pSourceAlgorithm",void 0);Mie=new ue({algorithm:u4,parameters:pe.serialize(new hu)})});var Gn,$ie,v4=T(()=>{"use strict";ee();J();Ct();Ql();ag();Gn=class{hashAlgorithm=new ue(Ui);maskGenAlgorithm=new ue({algorithm:Vo,parameters:pe.serialize(Ui)});saltLength=20;trailerField=1;constructor(e={}){Object.assign(this,e)}};p([g({type:ue,context:0,defaultValue:Ui})],Gn.prototype,"hashAlgorithm",void 0);p([g({type:ue,context:1,defaultValue:og})],Gn.prototype,"maskGenAlgorithm",void 0);p([g({type:_.Integer,context:2,defaultValue:20})],Gn.prototype,"saltLength",void 0);p([g({type:_.Integer,context:3,defaultValue:1})],Gn.prototype,"trailerField",void 0);$ie=new ue({algorithm:$o,parameters:pe.serialize(new Gn)})});var Ic,w4=T(()=>{"use strict";ee();Ct();J();Ic=class{digestAlgorithm=new ue;digest=new ze;constructor(e={}){Object.assign(this,e)}};p([g({type:ue})],Ic.prototype,"digestAlgorithm",void 0);p([g({type:ze})],Ic.prototype,"digest",void 0)});var S4=T(()=>{"use strict";b4();v4();w4()});var Wv,pu,cg,Gv=T(()=>{"use strict";ee();J();pu=class{prime=new ArrayBuffer(0);exponent=new ArrayBuffer(0);coefficient=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};p([g({type:_.Integer,converter:Et})],pu.prototype,"prime",void 0);p([g({type:_.Integer,converter:Et})],pu.prototype,"exponent",void 0);p([g({type:_.Integer,converter:Et})],pu.prototype,"coefficient",void 0);cg=Wv=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,Wv.prototype)}};cg=Wv=p([U({type:B.Sequence,itemType:pu})],cg)});var Ys,_4=T(()=>{"use strict";ee();J();Gv();Ys=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)}};p([g({type:_.Integer})],Ys.prototype,"version",void 0);p([g({type:_.Integer,converter:Et})],Ys.prototype,"modulus",void 0);p([g({type:_.Integer,converter:Et})],Ys.prototype,"publicExponent",void 0);p([g({type:_.Integer,converter:Et})],Ys.prototype,"privateExponent",void 0);p([g({type:_.Integer,converter:Et})],Ys.prototype,"prime1",void 0);p([g({type:_.Integer,converter:Et})],Ys.prototype,"prime2",void 0);p([g({type:_.Integer,converter:Et})],Ys.prototype,"exponent1",void 0);p([g({type:_.Integer,converter:Et})],Ys.prototype,"exponent2",void 0);p([g({type:_.Integer,converter:Et})],Ys.prototype,"coefficient",void 0);p([g({type:cg,optional:!0})],Ys.prototype,"otherPrimeInfos",void 0)});var mu,E4=T(()=>{"use strict";ee();J();mu=class{modulus=new ArrayBuffer(0);publicExponent=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};p([g({type:_.Integer,converter:Et})],mu.prototype,"modulus",void 0);p([g({type:_.Integer,converter:Et})],mu.prototype,"publicExponent",void 0)});var dg=T(()=>{"use strict";S4();ag();Ql();Gv();_4();E4()});var Xv,Br,Yv=T(()=>{"use strict";(function(r){r[r.Transient=0]="Transient",r[r.Singleton=1]="Singleton",r[r.ResolutionScoped=2]="ResolutionScoped",r[r.ContainerScoped=3]="ContainerScoped"})(Xv||(Xv={}));Br=Xv});var C4=T(()=>{"use strict";Yv()});function Zl(r,e){Jv(r,e);function t(){this.constructor=r}r.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}function T4(r,e,t,s){function n(i){return i instanceof t?i:new t(function(o){o(i)})}return new(t||(t=Promise))(function(i,o){function a(u){try{d(s.next(u))}catch(f){o(f)}}function c(u){try{d(s.throw(u))}catch(f){o(f)}}function d(u){u.done?i(u.value):n(u.value).then(a,c)}d((s=s.apply(r,e||[])).next())})}function A4(r,e){var t={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(;t;)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 t.label++,{value:d[1],done:!1};case 5:t.label++,n=d[1],d=[0];continue;case 7:d=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(d[0]===6||d[0]===2)){t=0;continue}if(d[0]===3&&(!i||d[1]>i[0]&&d[1]<i[3])){t.label=d[1];break}if(d[0]===6&&t.label<i[1]){t.label=i[1],i=d;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(d);break}i[2]&&t.ops.pop(),t.trys.pop();continue}d=e.call(r,t)}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 eh(r){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&r[e],s=0;if(t)return t.call(r);if(r&&typeof r.length=="number")return{next:function(){return r&&s>=r.length&&(r=void 0),{value:r&&r[s++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function gu(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var s=t.call(r),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&&(t=s.return)&&t.call(s)}finally{if(o)throw o.error}}return i}function Xn(){for(var r=[],e=0;e<arguments.length;e++)r=r.concat(gu(arguments[e]));return r}var Jv,yu=T(()=>{"use strict";Jv=function(r,e){return Jv=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,s){t.__proto__=s}||function(t,s){for(var n in s)s.hasOwnProperty(n)&&(t[n]=s[n])},Jv(r,e)}});function Qv(r){var e=Reflect.getMetadata("design:paramtypes",r)||[],t=Reflect.getOwnMetadata(kU,r)||{};return Object.keys(t).forEach(function(s){e[+s]=t[s]}),e}var kU,Rc=T(()=>{"use strict";kU="injectionTokens"});function th(r){return!!r.useClass}var Zv=T(()=>{"use strict"});function xu(r){return!!r.useFactory}var ew=T(()=>{"use strict"});var ug,fg=T(()=>{"use strict";yu();ug=(function(){function r(e){this.wrap=e,this.reflectMethods=["get","getPrototypeOf","setPrototypeOf","getOwnPropertyDescriptor","defineProperty","has","set","deleteProperty","apply","construct","ownKeys"]}return r.prototype.createProxy=function(e){var t=this,s={},n=!1,i,o=function(){return n||(i=e(t.wrap()),n=!0),i};return new Proxy(s,this.createHandler(o))},r.prototype.createHandler=function(e){var t={},s=function(n){t[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,Xn(i))}};return this.reflectMethods.forEach(s),t},r})()});function Ko(r){return typeof r=="string"||typeof r=="symbol"}function tw(r){return typeof r=="object"&&"token"in r&&"multiple"in r}function lg(r){return typeof r=="object"&&"token"in r&&"transform"in r}function I4(r){return typeof r=="function"||r instanceof ug}var hg=T(()=>{"use strict";fg()});function kc(r){return!!r.useToken}var rw=T(()=>{"use strict"});function Pc(r){return r.useValue!=null}var sw=T(()=>{"use strict"});var nw=T(()=>{"use strict";Zv();ew();hg();rw();sw()});function R4(r){return th(r)||Pc(r)||kc(r)||xu(r)}var k4=T(()=>{"use strict";Zv();sw();rw();ew()});var PU,rh,iw=T(()=>{"use strict";PU=(function(){function r(){this._registryMap=new Map}return r.prototype.entries=function(){return this._registryMap.entries()},r.prototype.getAll=function(e){return this.ensure(e),this._registryMap.get(e)},r.prototype.get=function(e){this.ensure(e);var t=this._registryMap.get(e);return t[t.length-1]||null},r.prototype.set=function(e,t){this.ensure(e),this._registryMap.get(e).push(t)},r.prototype.setAll=function(e,t){this._registryMap.set(e,t)},r.prototype.has=function(e){return this.ensure(e),this._registryMap.get(e).length>0},r.prototype.clear=function(){this._registryMap.clear()},r.prototype.ensure=function(e){this._registryMap.has(e)||this._registryMap.set(e,[])},r})(),rh=PU});var BU,P4,B4=T(()=>{"use strict";yu();iw();BU=(function(r){Zl(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e})(rh),P4=BU});var NU,sh,N4=T(()=>{"use strict";NU=(function(){function r(){this.scopedResolutions=new Map}return r})(),sh=NU});function OU(r,e){if(r===null)return"at position #"+e;var t=r.split(",")[e].trim();return'"'+t+'" at position #'+e}function LU(r,e,t){return t===void 0&&(t=" "),Xn([r],e.message.split(`
28
+ `).map(function(s){return t+s})).join(`
29
+ `)}function ow(r,e,t){var s=gu(r.toString().match(/constructor\(([\w, ]+)\)/)||[],2),n=s[1],i=n===void 0?null:n,o=OU(i,e);return LU("Cannot inject the dependency "+o+' of "'+r.name+'" constructor. Reason:',t)}var aw=T(()=>{"use strict";yu()});function O4(r){if(typeof r.dispose!="function")return!1;var e=r.dispose;return!(e.length>0)}var L4=T(()=>{"use strict"});var DU,MU,UU,D4,M4=T(()=>{"use strict";yu();iw();DU=(function(r){Zl(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e})(rh),MU=(function(r){Zl(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e})(rh),UU=(function(){function r(){this.preResolution=new DU,this.postResolution=new MU}return r})(),D4=UU});var cw,jU,Kt,Wo=T(()=>{"use strict";yu();nw();k4();hg();B4();Yv();N4();aw();fg();L4();M4();cw=new Map,jU=(function(){function r(e){this.parent=e,this._registry=new P4,this.interceptors=new D4,this.disposed=!1,this.disposables=new Set}return r.prototype.register=function(e,t,s){s===void 0&&(s={lifecycle:Br.Transient}),this.ensureNotDisposed();var n;if(R4(t)?n=t:n={useClass:t},kc(n))for(var i=[e],o=n;o!=null;){var a=o.useToken;if(i.includes(a))throw new Error("Token registration cycle detected! "+Xn(i,[a]).join(" -> "));i.push(a);var c=this._registry.get(a);c&&kc(c.provider)?o=c.provider:o=null}if((s.lifecycle===Br.Singleton||s.lifecycle==Br.ContainerScoped||s.lifecycle==Br.ResolutionScoped)&&(Pc(n)||xu(n)))throw new Error('Cannot use lifecycle "'+Br[s.lifecycle]+'" with ValueProviders or FactoryProviders');return this._registry.set(e,{provider:n,options:s}),this},r.prototype.registerType=function(e,t){return this.ensureNotDisposed(),Ko(t)?this.register(e,{useToken:t}):this.register(e,{useClass:t})},r.prototype.registerInstance=function(e,t){return this.ensureNotDisposed(),this.register(e,{useValue:t})},r.prototype.registerSingleton=function(e,t){if(this.ensureNotDisposed(),Ko(e)){if(Ko(t))return this.register(e,{useToken:t},{lifecycle:Br.Singleton});if(t)return this.register(e,{useClass:t},{lifecycle:Br.Singleton});throw new Error('Cannot register a type name as a singleton without a "to" token')}var s=e;return t&&!Ko(t)&&(s=t),this.register(e,{useClass:s},{lifecycle:Br.Singleton})},r.prototype.resolve=function(e,t,s){t===void 0&&(t=new sh),s===void 0&&(s=!1),this.ensureNotDisposed();var n=this.getRegistration(e);if(!n&&Ko(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,t);return this.executePostResolutionInterceptor(e,i,"Single"),i}if(I4(e)){var i=this.construct(e,t);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.")},r.prototype.executePreResolutionInterceptor=function(e,t){var s,n;if(this.interceptors.preResolution.has(e)){var i=[];try{for(var o=eh(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,t)}}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)}},r.prototype.executePostResolutionInterceptor=function(e,t,s){var n,i;if(this.interceptors.postResolution.has(e)){var o=[];try{for(var a=eh(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,t,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)}},r.prototype.resolveRegistration=function(e,t){if(this.ensureNotDisposed(),e.options.lifecycle===Br.ResolutionScoped&&t.scopedResolutions.has(e))return t.scopedResolutions.get(e);var s=e.options.lifecycle===Br.Singleton,n=e.options.lifecycle===Br.ContainerScoped,i=s||n,o;return Pc(e.provider)?o=e.provider.useValue:kc(e.provider)?o=i?e.instance||(e.instance=this.resolve(e.provider.useToken,t)):this.resolve(e.provider.useToken,t):th(e.provider)?o=i?e.instance||(e.instance=this.construct(e.provider.useClass,t)):this.construct(e.provider.useClass,t):xu(e.provider)?o=e.provider.useFactory(this):o=this.construct(e.provider,t),e.options.lifecycle===Br.ResolutionScoped&&t.scopedResolutions.set(e,o),o},r.prototype.resolveAll=function(e,t,s){var n=this;t===void 0&&(t=new sh),s===void 0&&(s=!1),this.ensureNotDisposed();var i=this.getAllRegistrations(e);if(!i&&Ko(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,t)});return this.executePostResolutionInterceptor(e,o,"All"),o}var a=[this.construct(e,t)];return this.executePostResolutionInterceptor(e,a,"All"),a},r.prototype.isRegistered=function(e,t){return t===void 0&&(t=!1),this.ensureNotDisposed(),this._registry.has(e)||t&&(this.parent||!1)&&this.parent.isRegistered(e,!0)},r.prototype.reset=function(){this.ensureNotDisposed(),this._registry.clear(),this.interceptors.preResolution.clear(),this.interceptors.postResolution.clear()},r.prototype.clearInstances=function(){var e,t;this.ensureNotDisposed();try{for(var s=eh(this._registry.entries()),n=s.next();!n.done;n=s.next()){var i=gu(n.value,2),o=i[0],a=i[1];this._registry.setAll(o,a.filter(function(c){return!Pc(c.provider)}).map(function(c){return c.instance=void 0,c}))}}catch(c){e={error:c}}finally{try{n&&!n.done&&(t=s.return)&&t.call(s)}finally{if(e)throw e.error}}},r.prototype.createChildContainer=function(){var e,t;this.ensureNotDisposed();var s=new r(this);try{for(var n=eh(this._registry.entries()),i=n.next();!i.done;i=n.next()){var o=gu(i.value,2),a=o[0],c=o[1];c.some(function(d){var u=d.options;return u.lifecycle===Br.ContainerScoped})&&s._registry.setAll(a,c.map(function(d){return d.options.lifecycle===Br.ContainerScoped?{provider:d.provider,options:d.options}:d}))}}catch(d){e={error:d}}finally{try{i&&!i.done&&(t=n.return)&&t.call(n)}finally{if(e)throw e.error}}return s},r.prototype.beforeResolution=function(e,t,s){s===void 0&&(s={frequency:"Always"}),this.interceptors.preResolution.set(e,{callback:t,options:s})},r.prototype.afterResolution=function(e,t,s){s===void 0&&(s={frequency:"Always"}),this.interceptors.postResolution.set(e,{callback:t,options:s})},r.prototype.dispose=function(){return T4(this,void 0,void 0,function(){var e;return A4(this,function(t){switch(t.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 t.sent(),[2]}})})},r.prototype.getRegistration=function(e){return this.isRegistered(e)?this._registry.get(e):this.parent?this.parent.getRegistration(e):null},r.prototype.getAllRegistrations=function(e){return this.isRegistered(e)?this._registry.getAll(e):this.parent?this.parent.getAllRegistrations(e):null},r.prototype.construct=function(e,t){var s=this;if(e instanceof ug)return e.createProxy(function(i){return s.resolve(i,t)});var n=(function(){var i=cw.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(t,e));return new(e.bind.apply(e,Xn([void 0],o)))})();return O4(n)&&this.disposables.add(n),n},r.prototype.resolveParams=function(e,t){var s=this;return function(n,i){var o,a,c;try{return tw(n)?lg(n)?n.multiple?(o=s.resolve(n.transform)).transform.apply(o,Xn([s.resolveAll(n.token,new sh,n.isOptional)],n.transformArgs)):(a=s.resolve(n.transform)).transform.apply(a,Xn([s.resolve(n.token,e,n.isOptional)],n.transformArgs)):n.multiple?s.resolveAll(n.token,new sh,n.isOptional):s.resolve(n.token,e,n.isOptional):lg(n)?(c=s.resolve(n.transform,e)).transform.apply(c,Xn([s.resolve(n.token,e)],n.transformArgs)):s.resolve(n,e)}catch(d){throw new Error(ow(t,i,d))}}},r.prototype.ensureNotDisposed=function(){if(this.disposed)throw new Error("This container has been disposed, you cannot interact with a disposed container")},r})(),Kt=new jU});var U4=T(()=>{"use strict";Rc();Wo();hg();aw()});var j4=T(()=>{"use strict";Rc()});function HU(r){return function(e){cw.set(e,Qv(e)),r&&r.token&&(Array.isArray(r.token)?r.token.forEach(function(t){Kt.register(t,e)}):Kt.register(r.token,e))}}var Go,pg=T(()=>{"use strict";Rc();Wo();Wo();Go=HU});var H4=T(()=>{"use strict";Wo()});var F4=T(()=>{"use strict";pg();Wo()});var q4=T(()=>{"use strict";Rc()});var z4=T(()=>{"use strict";Rc()});var $4=T(()=>{"use strict";Rc()});var V4=T(()=>{"use strict";pg();Wo()});var K4=T(()=>{"use strict";U4();j4();pg();H4();F4();q4();z4();$4();V4()});var W4=T(()=>{"use strict"});var G4=T(()=>{"use strict"});var X4=T(()=>{"use strict"});var Y4=T(()=>{"use strict";W4();G4();X4()});var J4=T(()=>{"use strict";C4();K4();Y4();nw();fg();Wo();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 uw,Bc,Q4,fw=T(()=>{"use strict";ee();J();Bc=class{attrId="";attrValues=[];constructor(e={}){Object.assign(e)}};p([g({type:_.ObjectIdentifier})],Bc.prototype,"attrId",void 0);p([g({type:_.Any,repeated:"set"})],Bc.prototype,"attrValues",void 0);Q4=uw=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,uw.prototype)}};Q4=uw=p([U({type:B.Sequence,itemType:Bc})],Q4)});var lw,Z4,e8=T(()=>{"use strict";ee();J();Vl();Z4=lw=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,lw.prototype)}};Z4=lw=p([U({type:B.Sequence,itemType:Xs})],Z4)});var FU,qU,t8,bu,Ace,Ice,Rce,kce,Pce,Bce,Nc,hw=T(()=>{"use strict";FU="1.2.840.113549",qU=`${FU}.1`,t8=`${qU}.12`,bu=`${t8}.1`,Ace=`${bu}.1`,Ice=`${bu}.2`,Rce=`${bu}.3`,kce=`${bu}.4`,Pce=`${bu}.5`,Bce=`${bu}.6`,Nc=`${t8}.10.1`});var Lce,Dce,Mce,Uce,jce,Hce,mg,gg=T(()=>{"use strict";hw();Lce=`${Nc}.1`,Dce=`${Nc}.2`,Mce=`${Nc}.3`,Uce=`${Nc}.4`,jce=`${Nc}.5`,Hce=`${Nc}.6`,mg="1.2.840.113549.1.9"});var yg,r8,Vce,Kce,s8=T(()=>{"use strict";ee();J();gg();yg=class{certId="";certValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};p([g({type:_.ObjectIdentifier})],yg.prototype,"certId",void 0);p([g({type:_.Any,context:0})],yg.prototype,"certValue",void 0);r8=`${mg}.22`,Vce=`${r8}.1`,Kce=`${r8}.2`});var xg,zU,Jce,n8=T(()=>{"use strict";ee();J();gg();xg=class{crlId="";crltValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};p([g({type:_.ObjectIdentifier})],xg.prototype,"crlId",void 0);p([g({type:_.Any,context:0})],xg.prototype,"crltValue",void 0);zU=`${mg}.23`,Jce=`${zU}.1`});var bg,Xo,i8=T(()=>{"use strict";ee();J();Ct();bg=class extends ze{},Xo=class{encryptionAlgorithm=new ue;encryptedData=new bg;constructor(e={}){Object.assign(this,e)}};p([g({type:ue})],Xo.prototype,"encryptionAlgorithm",void 0);p([g({type:bg})],Xo.prototype,"encryptedData",void 0)});var pw,mw,vg,gw,Yo,o8=T(()=>{"use strict";ee();J();Ct();(function(r){r[r.v1=0]="v1"})(mw||(mw={}));vg=class extends ze{},gw=pw=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,pw.prototype)}};gw=pw=p([U({type:B.Sequence,itemType:Ir})],gw);Yo=class{version=mw.v1;privateKeyAlgorithm=new ue;privateKey=new vg;attributes;constructor(e={}){Object.assign(this,e)}};p([g({type:_.Integer})],Yo.prototype,"version",void 0);p([g({type:ue})],Yo.prototype,"privateKeyAlgorithm",void 0);p([g({type:vg})],Yo.prototype,"privateKey",void 0);p([g({type:gw,implicit:!0,context:0,optional:!0})],Yo.prototype,"attributes",void 0)});var wg=T(()=>{"use strict";i8();o8()});var a8,c8=T(()=>{"use strict";ee();wg();J();a8=class extends Yo{};a8=p([U({type:B.Sequence})],a8)});var d8,u8=T(()=>{"use strict";ee();wg();J();d8=class extends Xo{};d8=p([U({type:B.Sequence})],d8)});var Sg,f8=T(()=>{"use strict";ee();J();Sg=class{secretTypeId="";secretValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};p([g({type:_.ObjectIdentifier})],Sg.prototype,"secretTypeId",void 0);p([g({type:_.Any,context:0})],Sg.prototype,"secretValue",void 0)});var l8=T(()=>{"use strict";s8();n8();c8();u8();f8();gg()});var Jo,yw=T(()=>{"use strict";ee();dg();J();Jo=class{mac=new Ic;macSalt=new ze;iterations=1;constructor(e={}){Object.assign(this,e)}};p([g({type:Ic})],Jo.prototype,"mac",void 0);p([g({type:ze})],Jo.prototype,"macSalt",void 0);p([g({type:_.Integer,defaultValue:1})],Jo.prototype,"iterations",void 0)});var Oc,h8=T(()=>{"use strict";ee();J();Vl();yw();Oc=class{version=3;authSafe=new Xs;macData=new Jo;constructor(e={}){Object.assign(this,e)}};p([g({type:_.Integer})],Oc.prototype,"version",void 0);p([g({type:Xs})],Oc.prototype,"authSafe",void 0);p([g({type:Jo,optional:!0})],Oc.prototype,"macData",void 0)});var xw,vu,p8,m8=T(()=>{"use strict";ee();J();fw();vu=class{bagId="";bagValue=new ArrayBuffer(0);bagAttributes;constructor(e={}){Object.assign(this,e)}};p([g({type:_.ObjectIdentifier})],vu.prototype,"bagId",void 0);p([g({type:_.Any,context:0})],vu.prototype,"bagValue",void 0);p([g({type:Bc,repeated:"set",optional:!0})],vu.prototype,"bagAttributes",void 0);p8=xw=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,xw.prototype)}};p8=xw=p([U({type:B.Sequence,itemType:vu})],p8)});var g8=T(()=>{"use strict";fw();e8();l8();yw();hw();h8();m8()});var bw,vw,ww,ar,Zde,k8,ih,P8,B8,eue,tue,rue,sue,nue,iue,oue,aue,Rw,cue,due,uue,oh,fue,lue,hue,pue,mue,gue,yue,xue,ah,bue,vue,wue,Sue,_ue,Eue,Cue,Tue,Aue,Iue,Rue,kue,Pue,_g,y8,x8,b8,Sw,v8,w8,_w,S8,Ew,Eg,_8,E8,Cw,C8,Tw,T8,nh,A8,I8,Aw,Iw,R8,kw=T(()=>{"use strict";ee();J();Vl();g8();wg();Ct();yv();ar="1.2.840.113549.1.9",Zde=`${ar}.0`,k8=`${ar}.24`,ih=`${ar}.25`,P8=`${ar}.26`,B8=`${ar}.27`,eue=`${k8}.1`,tue=`${k8}.2`,rue=`${ar}.1`,sue=`${ar}.2`,nue=`${ar}.3`,iue=`${ar}.4`,oue=`${ar}.5`,aue=`${ar}.6`,Rw=`${ar}.7`,cue=`${ar}.8`,due=`${ar}.9`,uue=`${ar}.13`,oh=`${ar}.14`,fue=`${ar}.15`,lue=`${ar}.20`,hue=`${ar}.21`,pue=`${ih}.1`,mue=`${ih}.2`,gue=`${ih}.3`,yue=`${ih}.4`,xue=`${ih}.5`,ah="1.3.6.1.5.5.7.9",bue=`${ah}.1`,vue=`${ah}.2`,wue=`${ah}.3`,Sue=`${ah}.4`,_ue=`${ah}.5`,Eue=`${P8}.1`,Cue=`${P8}.2`,Tue=`${B8}.1`,Aue=`${B8}.2`,Iue=`${ar}.16`,Rue=`${ar}.22`,kue=`${ar}.23`,Pue=`${hv}.65`,_g=class extends hr{ia5String;constructor(e={}){super(e)}toString(){return{}.toString(),this.ia5String||super.toString()}};p([g({type:_.IA5String})],_g.prototype,"ia5String",void 0);_g=p([U({type:B.Choice})],_g);y8=class extends Xs{};y8=p([U({type:B.Sequence})],y8);x8=class extends Oc{};x8=p([U({type:B.Sequence})],x8);b8=class extends Xo{};b8=p([U({type:B.Sequence})],b8);Sw=class{value;constructor(e=""){this.value=e}toString(){return this.value}};p([g({type:_.IA5String})],Sw.prototype,"value",void 0);Sw=p([U({type:B.Choice})],Sw);v8=class extends _g{};v8=p([U({type:B.Choice})],v8);w8=class extends hr{};w8=p([U({type:B.Choice})],w8);_w=class{value;constructor(e=new Date){this.value=e}};p([g({type:_.GeneralizedTime})],_w.prototype,"value",void 0);_w=p([U({type:B.Choice})],_w);S8=class extends hr{};S8=p([U({type:B.Choice})],S8);Ew=class{value;constructor(e="M"){this.value=e}toString(){return this.value}};p([g({type:_.PrintableString})],Ew.prototype,"value",void 0);Ew=p([U({type:B.Choice})],Ew);Eg=class{value;constructor(e=""){this.value=e}toString(){return this.value}};p([g({type:_.PrintableString})],Eg.prototype,"value",void 0);Eg=p([U({type:B.Choice})],Eg);_8=class extends Eg{};_8=p([U({type:B.Choice})],_8);E8=class extends hr{};E8=p([U({type:B.Choice})],E8);Cw=class{value;constructor(e=""){this.value=e}toString(){return this.value}};p([g({type:_.ObjectIdentifier})],Cw.prototype,"value",void 0);Cw=p([U({type:B.Choice})],Cw);C8=class extends or{};C8=p([U({type:B.Choice})],C8);Tw=class{value;constructor(e=0){this.value=e}toString(){return this.value.toString()}};p([g({type:_.Integer})],Tw.prototype,"value",void 0);Tw=p([U({type:B.Choice})],Tw);T8=class extends ls{};T8=p([U({type:B.Sequence})],T8);nh=class extends hr{};nh=p([U({type:B.Choice})],nh);A8=bw=class extends Ts{constructor(e){super(e),Object.setPrototypeOf(this,bw.prototype)}};A8=bw=p([U({type:B.Sequence})],A8);I8=vw=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,vw.prototype)}};I8=vw=p([U({type:B.Set,itemType:fn})],I8);Aw=class{value;constructor(e=""){this.value=e}toString(){return this.value}};p([g({type:_.BmpString})],Aw.prototype,"value",void 0);Aw=p([U({type:B.Choice})],Aw);Iw=class extends ue{};Iw=p([U({type:B.Sequence})],Iw);R8=ww=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,ww.prototype)}};R8=ww=p([U({type:B.Sequence,itemType:Iw})],R8)});var Pw,ch,Bw=T(()=>{"use strict";ee();J();Ct();ch=Pw=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,Pw.prototype)}};ch=Pw=p([U({type:B.Sequence,itemType:Ir})],ch)});var Yn,Nw=T(()=>{"use strict";ee();J();Ct();Bw();Yn=class{version=0;subject=new Ft;subjectPKInfo=new Rr;attributes=new ch;constructor(e={}){Object.assign(this,e)}};p([g({type:_.Integer})],Yn.prototype,"version",void 0);p([g({type:Ft})],Yn.prototype,"subject",void 0);p([g({type:Rr})],Yn.prototype,"subjectPKInfo",void 0);p([g({type:ch,implicit:!0,context:0,optional:!0})],Yn.prototype,"attributes",void 0)});var Qo,N8=T(()=>{"use strict";ee();J();Ct();Nw();Qo=class{certificationRequestInfo=new Yn;certificationRequestInfoRaw;signatureAlgorithm=new ue;signature=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};p([g({type:Yn,raw:!0})],Qo.prototype,"certificationRequestInfo",void 0);p([g({type:ue})],Qo.prototype,"signatureAlgorithm",void 0);p([g({type:_.BitString})],Qo.prototype,"signature",void 0)});var O8=T(()=>{"use strict";Bw();N8();Nw()});function GU(r){return new RegExp(WU).test(r)}function XU(r,e){return`\\${Ue.ToHex(Ue.FromUtf8String(e)).toUpperCase()}`}function YU(r){return r.replace(/([,+"\\<>;])/g,"\\$1").replace(/^([ #])/,"\\$1").replace(/([ ]$)/,"\\$1").replace(/([\r\n\t])/,XU)}function ij(r,e){return r.algorithm=new ue({algorithm:Wn,parameters:null}),e=pe.serialize(r),e}function Tg(r,e,t){if(t.length===1)r[e]=t[0].toTextObject();else{let s=new Rt("");t.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)}),r[e]=s}}function Ag(r,e,t,s){let n=e[s];n&&(Array.isArray(n)?n:[n]).forEach(o=>{typeof o=="string"&&(o=new Jn("url",o)),r.push(new Pi({accessMethod:t,accessLocation:pe.parse(o.rawData,We)}))})}function oj(r,e=pr.get()){let t=xe.toUint8Array(Ue.FromHex(r||"")),s=t&&t.length&&t.some(i=>i>0)?new Uint8Array(t):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 wfe,Bh,zw,Lc,Ig,gs,L8,D8,M8,U8,j8,H8,F8,q8,z8,$8,V8,K8,W8,G8,X8,Y8,J8,Q8,Z8,eA,tA,rA,sA,nA,iA,oA,aA,cA,tr,Ih,bA,vA,Rt,$w,Qn,Hi,wu,Zo,Is,wA,Rh,pr,WU,kg,ms,ln,SA,dA,JU,uA,fA,lA,Ow,Lw,Dw,Mw,Uw,jw,Hw,Cg,Jn,Fi,Ah,kh,QU,ZU,ej,Eu,tj,rj,sj,nj,hA,Nr,ea,ji,Pg,Bg,pA,Ng,mA,Og,Lg,Dg,rs,Mg,Ug,jg,Hg,Cu,Fg,Ph,Tu,Nh,Vw,Rg,Kw,Ww,qi,Fw,gA,qw,yA,Gw,dh,uh,fh,lh,hh,ph,mh,Su,Xw,gh,yh,xh,bh,vh,wh,Sh,_h,Eh,Ch,_u,Th,qg,zg,aj,cj,dj,uj,fj,xA,lj,hj,pj,mj,gj,yj,xj,_A=T(()=>{"use strict";wfe=Ge(I6());J();Ct();Ct();Jb();ee();Vl();zv();zv();dg();dg();J4();kw();kw();O8();Bh="crypto.algorithm",zw=class{getAlgorithms(){return Kt.resolveAll(Bh)}toAsnAlgorithm(e){({...e});for(let t of this.getAlgorithms()){let s=t.toAsnAlgorithm(e);if(s)return s}if(/^[0-9.]+$/.test(e.name)){let t=new ue({algorithm:e.name});if("parameters"in e){let s=e;t.parameters=s.parameters}return t}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}}},Lc="crypto.algorithmProvider";Kt.registerSingleton(Lc,zw);gs="1.3.36.3.3.2.8.1.1",L8=`${gs}.1`,D8=`${gs}.2`,M8=`${gs}.3`,U8=`${gs}.4`,j8=`${gs}.5`,H8=`${gs}.6`,F8=`${gs}.7`,q8=`${gs}.8`,z8=`${gs}.9`,$8=`${gs}.10`,V8=`${gs}.11`,K8=`${gs}.12`,W8=`${gs}.13`,G8=`${gs}.14`,X8="brainpoolP160r1",Y8="brainpoolP160t1",J8="brainpoolP192r1",Q8="brainpoolP192t1",Z8="brainpoolP224r1",eA="brainpoolP224t1",tA="brainpoolP256r1",rA="brainpoolP256t1",sA="brainpoolP320r1",nA="brainpoolP320t1",iA="brainpoolP384r1",oA="brainpoolP384t1",aA="brainpoolP512r1",cA="brainpoolP512t1",tr="ECDSA",Ih=Ig=class{toAsnAlgorithm(e){switch(e.name.toLowerCase()){case tr.toLowerCase():if("hash"in e)switch((typeof e.hash=="string"?e.hash:e.hash.name).toLowerCase()){case"sha-1":return s4;case"sha-256":return n4;case"sha-384":return i4;case"sha-512":return o4}else if("namedCurve"in e){let t="";switch(e.namedCurve){case"P-256":t=Lv;break;case"K-256":t=Ig.SECP256K1;break;case"P-384":t=Dv;break;case"P-521":t=Mv;break;case X8:t=L8;break;case Y8:t=D8;break;case J8:t=M8;break;case Q8:t=U8;break;case Z8:t=j8;break;case eA:t=H8;break;case tA:t=F8;break;case rA:t=q8;break;case sA:t=z8;break;case nA:t=$8;break;case iA:t=V8;break;case oA:t=K8;break;case aA:t=W8;break;case cA:t=G8;break}if(t)return new ue({algorithm:Sc,parameters:pe.serialize(new Kn({namedCurve:t}))})}}return null}toWebAlgorithm(e){switch(e.algorithm){case Kl:return{name:tr,hash:{name:"SHA-1"}};case Wl:return{name:tr,hash:{name:"SHA-256"}};case Gl:return{name:tr,hash:{name:"SHA-384"}};case Xl:return{name:tr,hash:{name:"SHA-512"}};case Sc:{if(!e.parameters)throw new TypeError("Cannot get required parameters from EC algorithm");switch(pe.parse(e.parameters,Kn).namedCurve){case Lv:return{name:tr,namedCurve:"P-256"};case Ig.SECP256K1:return{name:tr,namedCurve:"K-256"};case Dv:return{name:tr,namedCurve:"P-384"};case Mv:return{name:tr,namedCurve:"P-521"};case L8:return{name:tr,namedCurve:X8};case D8:return{name:tr,namedCurve:Y8};case M8:return{name:tr,namedCurve:J8};case U8:return{name:tr,namedCurve:Q8};case j8:return{name:tr,namedCurve:Z8};case H8:return{name:tr,namedCurve:eA};case F8:return{name:tr,namedCurve:tA};case q8:return{name:tr,namedCurve:rA};case z8:return{name:tr,namedCurve:sA};case $8:return{name:tr,namedCurve:nA};case V8:return{name:tr,namedCurve:iA};case K8:return{name:tr,namedCurve:oA};case W8:return{name:tr,namedCurve:aA};case G8:return{name:tr,namedCurve:cA}}}}return null}};Ih.SECP256K1="1.3.132.0.10";Ih=Ig=p([Go()],Ih);Kt.registerSingleton(Bh,Ih);bA=Symbol("name"),vA=Symbol("value"),Rt=class{constructor(e,t={},s=""){this[bA]=e,this[vA]=s;for(let n in t)this[n]=t[n]}};Rt.NAME=bA;Rt.VALUE=vA;$w=class{static toTextObject(e){let t=new Rt("Algorithm Identifier",{},Qn.toString(e.algorithm));if(e.parameters)if(e.algorithm===Sc){let s=new Ih().toWebAlgorithm(e);s&&"namedCurve"in s?t["Named Curve"]=s.namedCurve:t.Parameters=e.parameters}else t.Parameters=e.parameters;return t}},Qn=class{static toString(e){let t=this.items[e];return t||e}};Qn.items={[Ec]:"sha1",[ig]:"sha224",[Cc]:"sha256",[Tc]:"sha384",[Ac]:"sha512",[Wn]:"rsaEncryption",[uu]:"sha1WithRSAEncryption",[p4]:"sha224WithRSAEncryption",[ng]:"sha256WithRSAEncryption",[fu]:"sha384WithRSAEncryption",[lu]:"sha512WithRSAEncryption",[Sc]:"ecPublicKey",[Kl]:"ecdsaWithSHA1",[sg]:"ecdsaWithSHA224",[Wl]:"ecdsaWithSHA256",[Gl]:"ecdsaWithSHA384",[Xl]:"ecdsaWithSHA512",[nT]:"TLS WWW server authentication",[iT]:"TLS WWW client authentication",[oT]:"Code Signing",[aT]:"E-mail Protection",[cT]:"Time Stamping",[dT]:"OCSP Signing",[ZT]:"Signed Data"};Hi=class{static serialize(e){return this.serializeObj(e).join(`
30
+ `)}static pad(e=0){return"".padStart(2*e," ")}static serializeObj(e,t=0){let s=[],n=this.pad(t++),i="",o=e[Rt.VALUE];o&&(i=` ${o}`),s.push(`${n}${e[Rt.NAME]}:${i}`),n=this.pad(t);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,t));else if(c instanceof Rt)c[Rt.NAME]=a,s.push(...this.serializeObj(c,t));else if(xe.isBufferSource(c))a?(s.push(`${n}${d}`),s.push(...this.serializeBufferSource(c,t+1))):s.push(...this.serializeBufferSource(c,t));else if("toTextObject"in c){let u=c.toTextObject();u[Rt.NAME]=a,s.push(...this.serializeObj(u,t))}else throw new TypeError("Cannot serialize data in text format. Unsupported type.")}return s}static serializeBufferSource(e,t=0){let s=this.pad(t),n=xe.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)}};Hi.oidSerializer=Qn;Hi.algorithmSerializer=$w;Zo=class r{get rawData(){return ht(this,wu,"f")||Gt(this,wu,pe.serialize(this.asn),"f"),ht(this,wu,"f")}constructor(...e){wu.set(this,void 0),xe.isBufferSource(e[0])?(this.asn=pe.parse(e[0],e[1]),Gt(this,wu,xe.toArrayBuffer(e[0]),"f"),this.onInit(this.asn)):(this.asn=e[0],this.onInit(this.asn))}equal(e){return e instanceof r?k6(e.rawData,this.rawData):!1}toString(e="text"){switch(e){case"asn":return pe.toString(this.rawData);case"text":return Hi.serialize(this.toTextObject());case"hex":return Ue.ToHex(this.rawData);case"base64":return Ue.ToBase64(this.rawData);case"base64url":return Ue.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)}};wu=new WeakMap;Zo.NAME="ASN";Is=class r extends Zo{constructor(...e){let t;xe.isBufferSource(e[0])?t=xe.toArrayBuffer(e[0]):t=pe.serialize(new Kr({extnID:e[0],critical:e[1],extnValue:new ze(xe.toArrayBuffer(e[2]))})),super(t,Kr)}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]===r.NAME&&(e[Rt.NAME]=Qn.toString(this.type)),e}},Rh=class r{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[wA]="CryptoProvider",typeof self<"u"&&typeof crypto<"u"?this.set(r.DEFAULT,crypto):typeof global<"u"&&global.crypto&&global.crypto.subtle&&this.set(r.DEFAULT,global.crypto)}clear(){this.items.clear()}delete(e){return this.items.delete(e)}forEach(e,t){return this.items.forEach(e,t)}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=r.DEFAULT){let t=this.items.get(e.toLowerCase());if(!t)throw new Error(`Cannot get Crypto by name '${e}'`);return t}set(e,t){if(typeof e=="string"){if(!t)throw new TypeError("Argument 'value' is required");this.items.set(e.toLowerCase(),t)}else this.items.set(r.DEFAULT,e);return this}};wA=Symbol.toStringTag;Rh.DEFAULT="default";pr=new Rh,WU=/^[0-2](?:\.[1-9][0-9]*)+$/;kg=class{constructor(e={}){this.items={};for(let t in e)this.register(t,e[t])}get(e){return this.items[e]||null}findId(e){return GU(e)?e:this.get(e)}register(e,t){this.items[e]=t,this.items[t]=e}},ms=new kg;ms.register("CN","2.5.4.3");ms.register("L","2.5.4.7");ms.register("ST","2.5.4.8");ms.register("O","2.5.4.10");ms.register("OU","2.5.4.11");ms.register("C","2.5.4.6");ms.register("DC","0.9.2342.19200300.100.1.25");ms.register("E","1.2.840.113549.1.9.1");ms.register("G","2.5.4.42");ms.register("I","2.5.4.43");ms.register("SN","2.5.4.4");ms.register("T","2.5.4.12");ln=class r{static isASCII(e){for(let t=0;t<e.length;t++)if(e.charCodeAt(t)>255)return!1;return!0}static isPrintableString(e){return/^[A-Za-z0-9 '()+,-./:=?]*$/g.test(e)}constructor(e,t={}){this.extraNames=new kg,this.asn=new Ft;for(let s in t)if(Object.prototype.hasOwnProperty.call(t,s)){let n=t[s];this.extraNames.register(s,n)}typeof e=="string"?this.asn=this.fromString(e):e instanceof Ft?this.asn=e:xe.isBufferSource(e)?this.asn=pe.parse(e,Ft):this.asn=this.fromJSON(e)}getField(e){let t=this.extraNames.findId(e)||ms.findId(e),s=[];for(let n of this.asn)for(let i of n)i.type===t&&s.push(i.value.toString());return s}getName(e){return this.extraNames.get(e)||ms.get(e)}toString(){return this.asn.map(e=>e.map(t=>{let s=this.getName(t.type)||t.type,n=t.value.anyValue?`#${Ue.ToHex(t.value.anyValue)}`:YU(t.value.toString());return`${s}=${n}`}).join("+")).join(", ")}toJSON(){var e;let t=[];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?`#${Ue.ToHex(i.value.anyValue)}`:i.value.toString())}t.push(n)}return t}fromString(e){let t=new Ft,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==="+"?t[t.length-1].push(u):t.push(new No([u])),i=d}return t}fromJSON(e){let t=new Ft;for(let s of e){let n=new No;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)}}t.push(n)}return t}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,t){let s=new ec({type:e});if(typeof t=="object")for(let n in t)switch(n){case"ia5String":s.value.ia5String=t[n];break;case"utf8String":s.value.utf8String=t[n];break;case"universalString":s.value.universalString=t[n];break;case"bmpString":s.value.bmpString=t[n];break;case"printableString":s.value.printableString=t[n];break}else if(t[0]==="#")s.value.anyValue=Ue.FromHex(t.slice(1));else{let n=this.processStringValue(t);e===this.getName("E")||e===this.getName("DC")?s.value.ia5String=n:r.isPrintableString(n)?s.value.printableString=n:s.value.utf8String=n}return s}processStringValue(e){let t=/"(.*?[^\\])?"/.exec(e);return t&&(e=t[1]),e.replace(/\\0a/ig,`
31
+ `).replace(/\\0d/ig,"\r").replace(/\\0g/ig," ").replace(/\\(.)/g,"$1")}toArrayBuffer(){return pe.serialize(this.asn)}async getThumbprint(...e){var t;let s,n="SHA-1";return e.length>=1&&!(!((t=e[0])===null||t===void 0)&&t.subtle)?(n=e[0]||n,s=e[1]||pr.get()):s=e[0]||pr.get(),await s.subtle.digest(n,this.toArrayBuffer())}},SA="Cannot initialize GeneralName from ASN.1 data.",dA=`${SA} Unsupported string format in use.`,JU=`${SA} Value doesn't match to GUID regular expression.`,uA=/^([0-9a-f]{8})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{12})$/i,fA="1.3.6.1.4.1.311.25.1",lA="1.3.6.1.4.1.311.20.2.3",Ow="dns",Lw="dn",Dw="email",Mw="ip",Uw="url",jw="guid",Hw="upn",Cg="id",Jn=class extends Zo{constructor(...e){let t;if(e.length===2)switch(e[0]){case Lw:{let s=new ln(e[1]).toArrayBuffer(),n=pe.parse(s,Ft);t=new We({directoryName:n});break}case Ow:t=new We({dNSName:e[1]});break;case Dw:t=new We({rfc822Name:e[1]});break;case jw:{let s=new RegExp(uA,"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?Ue.ToHex(new Uint8Array(Ue.FromHex(i)).reverse()):i).join("");t=new We({otherName:new Oo({typeId:fA,value:pe.serialize(new ze(Ue.FromHex(n)))})});break}case Mw:t=new We({iPAddress:e[1]});break;case Cg:t=new We({registeredID:e[1]});break;case Hw:{t=new We({otherName:new Oo({typeId:lA,value:pe.serialize(c1.toASN(e[1]))})});break}case Uw:t=new We({uniformResourceIdentifier:e[1]});break;default:throw new Error("Cannot create GeneralName. Unsupported type of the name")}else xe.isBufferSource(e[0])?t=pe.parse(e[0],We):t=e[0];super(t)}onInit(e){if(e.dNSName!=null)this.type=Ow,this.value=e.dNSName;else if(e.rfc822Name!=null)this.type=Dw,this.value=e.rfc822Name;else if(e.iPAddress!=null)this.type=Mw,this.value=e.iPAddress;else if(e.uniformResourceIdentifier!=null)this.type=Uw,this.value=e.uniformResourceIdentifier;else if(e.registeredID!=null)this.type=Cg,this.value=e.registeredID;else if(e.directoryName!=null)this.type=Lw,this.value=new ln(e.directoryName).toString();else if(e.otherName!=null)if(e.otherName.typeId===fA){this.type=jw;let t=pe.parse(e.otherName.value,ze),s=new RegExp(uA,"i").exec(Ue.ToHex(t));if(!s)throw new Error(JU);this.value=s.slice(1).map((n,i)=>i<3?Ue.ToHex(new Uint8Array(Ue.FromHex(n)).reverse()):n).join("-")}else if(e.otherName.typeId===lA)this.type=Hw,this.value=pe.parse(e.otherName.value,hr).toString();else throw new Error(dA);else throw new Error(dA)}toJSON(){return{type:this.type,value:this.value}}toTextObject(){let e;switch(this.type){case Lw:case Ow:case jw:case Mw:case Cg:case Hw:case Uw:e=this.type.toUpperCase();break;case Dw:e="Email";break;default:throw new Error("Unsupported GeneralName type")}let t=this.value;return this.type===Cg&&(t=Qn.toString(t)),new Rt(e,void 0,t)}},Fi=class extends Zo{constructor(e){let t;if(e instanceof Xt)t=e;else if(Array.isArray(e)){let s=[];for(let n of e)if(n instanceof We)s.push(n);else{let i=pe.parse(new Jn(n.type,n.value).rawData,We);s.push(i)}t=new Xt(s)}else if(xe.isBufferSource(e))t=pe.parse(e,Xt);else throw new Error("Cannot initialize GeneralNames. Incorrect incoming arguments");super(t)}onInit(e){let t=[];for(let s of e){let n=null;try{n=new Jn(s)}catch{continue}t.push(n)}this.items=t}toJSON(){return this.items.map(e=>e.toJSON())}toTextObject(){let e=super.toTextObjectEmpty();for(let t of this.items){let s=t.toTextObject(),n=e[s[Rt.NAME]];Array.isArray(n)||(n=[],e[s[Rt.NAME]]=n),n.push(s)}return e}};Fi.NAME="GeneralNames";Ah="-{5}",kh="\\n",QU=`[^${kh}]+`,ZU=`${Ah}BEGIN (${QU}(?=${Ah}))${Ah}`,ej=`${Ah}END \\1${Ah}`,Eu="\\n",tj=`[^:${kh}]+`,rj=`(?:[^${kh}]+${Eu}(?: +[^${kh}]+${Eu})*)`,sj="[a-zA-Z0-9=+/]+",nj=`(?:${sj}${Eu})+`,hA=`${ZU}${Eu}(?:((?:${tj}: ${rj})+))?${Eu}?(${nj})${ej}`,Nr=class{static isPem(e){return typeof e=="string"&&new RegExp(hA,"g").test(e.replace(/\r/g,""))}static decodeWithHeaders(e){e=e.replace(/\r/g,"");let t=new RegExp(hA,"g"),s=[],n=null;for(;n=t.exec(e);){let i=n[3].replace(new RegExp(`[${kh}]+`,"g"),""),o={type:n[1],headers:[],rawData:Ue.FromBase64(i)},a=n[2];if(a){let c=a.split(new RegExp(Eu,"g")),d=null;for(let u of c){let[f,h]=u.split(/:(.*)/);if(h===void 0){if(!d)throw new Error("Cannot parse PEM string. Incorrect header value");d.value+=f.trim()}else d&&o.headers.push(d),d={key:f,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 t=this.decode(e);if(!t.length)throw new RangeError("PEM string doesn't contain any objects");return t[0]}static encode(e,t){if(Array.isArray(e)){let s=new Array;return t?e.forEach(n=>{if(!xe.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:t,rawData:xe.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(`
32
+ `)}else{if(!t)throw new Error("Required argument 'tag' is missed");return this.encodeStruct({type:t,rawData:xe.toArrayBuffer(e)})}}static encodeStruct(e){var t;let s=e.type.toLocaleUpperCase(),n=[];if(n.push(`-----BEGIN ${s}-----`),!((t=e.headers)===null||t===void 0)&&t.length){for(let d of e.headers)n.push(`${d.key}: ${d.value}`);n.push("")}let i=Ue.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(`
33
+ `)}};Nr.CertificateTag="CERTIFICATE";Nr.CrlTag="CRL";Nr.CertificateRequestTag="CERTIFICATE REQUEST";Nr.PublicKeyTag="PUBLIC KEY";Nr.PrivateKeyTag="PRIVATE KEY";ea=class r extends Zo{static isAsnEncoded(e){return xe.isBufferSource(e)||typeof e=="string"}static toArrayBuffer(e){if(typeof e=="string"){if(Nr.isPem(e))return Nr.decode(e)[0];if(Ue.isHex(e))return Ue.FromHex(e);if(Ue.isBase64(e))return Ue.FromBase64(e);if(Ue.isBase64Url(e))return Ue.FromBase64Url(e);throw new TypeError("Unsupported format of 'raw' argument. Must be one of DER, PEM, HEX, Base64, or Base4Url")}else{let t=xe.toUint8Array(e);if(t.length>0&&t[0]===48)return xe.toArrayBuffer(e);let s=Ue.ToBinary(e);if(Nr.isPem(s))return Nr.decode(s)[0];if(Ue.isHex(s))return Ue.FromHex(s);if(Ue.isBase64(s))return Ue.FromBase64(s);if(Ue.isBase64Url(s))return Ue.FromBase64Url(s);throw new TypeError("Unsupported format of 'raw' argument. Must be one of DER, PEM, HEX, Base64, or Base4Url")}}constructor(...e){r.isAsnEncoded(e[0])?super(r.toArrayBuffer(e[0]),e[1]):super(e[0])}toString(e="pem"){return e==="pem"?Nr.encode(this.rawData,this.tag):super.toString(e)}},ji=class r extends ea{static async create(e,t=pr.get()){if(e instanceof r)return e;if(Rh.isCryptoKey(e)){if(e.type!=="public")throw new TypeError("Public key is required");let s=await t.subtle.exportKey("spki",e);return new r(s)}else{if(e.publicKey)return e.publicKey;if(xe.isBufferSource(e))return new r(e);throw new TypeError("Unsupported PublicKeyType")}}constructor(e){ea.isAsnEncoded(e)?super(e,Rr):super(e),this.tag=Nr.PublicKeyTag}async export(...e){let t,s=["verify"],n={hash:"SHA-256",...this.algorithm};e.length>1?(n=e[0]||n,s=e[1]||s,t=e[2]||pr.get()):t=e[0]||pr.get();let i=this.rawData,o=pe.parse(this.rawData,Rr);return o.algorithm.algorithm===$o&&(i=ij(o,i)),t.subtle.importKey("spki",i,n,!0,s)}onInit(e){let t=Kt.resolve(Lc),s=this.algorithm=t.toWebAlgorithm(e.algorithm);if(e.algorithm.algorithm===Wn){let n=pe.parse(e.subjectPublicKey,mu),i=xe.toUint8Array(n.modulus);s.publicExponent=xe.toUint8Array(n.publicExponent),s.modulusLength=(i[0]?i:i.slice(1)).byteLength<<3}}async getThumbprint(...e){var t;let s,n="SHA-1";return e.length>=1&&!(!((t=e[0])===null||t===void 0)&&t.subtle)?(n=e[0]||n,s=e[1]||pr.get()):s=e[0]||pr.get(),await s.subtle.digest(n,this.rawData)}async getKeyIdentifier(...e){let t,s="SHA-1";e.length===1?typeof e[0]=="string"?(s=e[0],t=pr.get()):t=e[0]:e.length===2?(s=e[0],t=e[1]):t=pr.get();let n=pe.parse(this.rawData,Rr);return await t.subtle.digest(s,n.subjectPublicKey)}toTextObject(){let e=this.toTextObjectEmpty(),t=pe.parse(this.rawData,Rr);switch(e.Algorithm=Hi.serializeAlgorithm(t.algorithm),t.algorithm.algorithm){case Sc:e["EC Point"]=t.subjectPublicKey;break;case Wn:default:e["Raw Data"]=t.subjectPublicKey}return e}};Pg=class r extends Is{static async create(e,t=!1,s=pr.get()){if("name"in e&&"serialNumber"in e)return new r(e,t);let i=await(await ji.create(e,s)).getKeyIdentifier(s);return new r(Ue.ToHex(i),t)}constructor(...e){if(xe.isBufferSource(e[0]))super(e[0]);else if(typeof e[0]=="string"){let t=new Fn({keyIdentifier:new nc(Ue.FromHex(e[0]))});super(Rm,e[1],pe.serialize(t))}else{let t=e[0],s=t.name instanceof Fi?pe.parse(t.name.rawData,Xt):t.name,n=new Fn({authorityCertIssuer:s,authorityCertSerialNumber:Ue.FromHex(t.serialNumber)});super(Rm,e[1],pe.serialize(n))}}onInit(e){super.onInit(e);let t=pe.parse(e.extnValue,Fn);t.keyIdentifier&&(this.keyId=Ue.ToHex(t.keyIdentifier)),(t.authorityCertIssuer||t.authorityCertSerialNumber)&&(this.certId={name:t.authorityCertIssuer||[],serialNumber:t.authorityCertSerialNumber?Ue.ToHex(t.authorityCertSerialNumber):""})}toTextObject(){let e=this.toTextObjectWithoutValue(),t=pe.parse(this.value,Fn);return t.authorityCertIssuer&&(e["Authority Issuer"]=new Fi(t.authorityCertIssuer).toTextObject()),t.authorityCertSerialNumber&&(e["Authority Serial Number"]=t.authorityCertSerialNumber),t.keyIdentifier&&(e[""]=t.keyIdentifier),e}};Pg.NAME="Authority Key Identifier";Bg=class extends Is{constructor(...e){if(xe.isBufferSource(e[0])){super(e[0]);let t=pe.parse(this.value,ic);this.ca=t.cA,this.pathLength=t.pathLenConstraint}else{let t=new ic({cA:e[0],pathLenConstraint:e[1]});super(km,e[2],pe.serialize(t)),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}};Bg.NAME="Basic Constraints";(function(r){r.serverAuth="1.3.6.1.5.5.7.3.1",r.clientAuth="1.3.6.1.5.5.7.3.2",r.codeSigning="1.3.6.1.5.5.7.3.3",r.emailProtection="1.3.6.1.5.5.7.3.4",r.timeStamping="1.3.6.1.5.5.7.3.8",r.ocspSigning="1.3.6.1.5.5.7.3.9"})(pA||(pA={}));Ng=class extends Is{constructor(...e){if(xe.isBufferSource(e[0])){super(e[0]);let t=pe.parse(this.value,_l);this.usages=t.map(s=>s)}else{let t=new _l(e[0]);super(Lm,e[1],pe.serialize(t)),this.usages=e[0]}}toTextObject(){let e=this.toTextObjectWithoutValue();return e[""]=this.usages.map(t=>Qn.toString(t)).join(", "),e}};Ng.NAME="Extended Key Usages";(function(r){r[r.digitalSignature=1]="digitalSignature",r[r.nonRepudiation=2]="nonRepudiation",r[r.keyEncipherment=4]="keyEncipherment",r[r.dataEncipherment=8]="dataEncipherment",r[r.keyAgreement=16]="keyAgreement",r[r.keyCertSign=32]="keyCertSign",r[r.cRLSign=64]="cRLSign",r[r.encipherOnly=128]="encipherOnly",r[r.decipherOnly=256]="decipherOnly"})(mA||(mA={}));Og=class extends Is{constructor(...e){if(xe.isBufferSource(e[0])){super(e[0]);let t=pe.parse(this.value,Wd);this.usages=t.toNumber()}else{let t=new Wd(e[0]);super(Dm,e[1],pe.serialize(t)),this.usages=e[0]}}toTextObject(){let e=this.toTextObjectWithoutValue(),t=pe.parse(this.value,Wd);return e[""]=t.toJSON().join(", "),e}};Og.NAME="Key Usages";Lg=class r extends Is{static async create(e,t=!1,s=pr.get()){let i=await(await ji.create(e,s)).getKeyIdentifier(s);return new r(Ue.ToHex(i),t)}constructor(...e){if(xe.isBufferSource(e[0])){super(e[0]);let t=pe.parse(this.value,us);this.keyId=Ue.ToHex(t)}else{let t=typeof e[0]=="string"?Ue.FromHex(e[0]):e[0],s=new us(t);super(K1,e[1],pe.serialize(s)),this.keyId=Ue.ToHex(t)}}toTextObject(){let e=this.toTextObjectWithoutValue(),t=pe.parse(this.value,us);return e[""]=t,e}};Lg.NAME="Subject Key Identifier";Dg=class extends Is{constructor(...e){xe.isBufferSource(e[0])?super(e[0]):super(z1,e[1],new Fi(e[0]||[]).rawData)}onInit(e){super.onInit(e);let t=pe.parse(e.extnValue,Hm);this.names=new Fi(t)}toTextObject(){let e=this.toTextObjectWithoutValue(),t=this.names.toTextObject();for(let s in t)e[s]=t[s];return e}};Dg.NAME="Subject Alternative Name";rs=class{static register(e,t){this.items.set(e,t)}static create(e){let t=new Is(e),s=this.items.get(t.type);return s?new s(e):t}};rs.items=new Map;Mg=class extends Is{constructor(...e){var t;if(xe.isBufferSource(e[0])){super(e[0]);let s=pe.parse(this.value,xl);this.policies=s.map(n=>n.policyIdentifier)}else{let s=e[0],n=(t=e[1])!==null&&t!==void 0?t:!1,i=new xl(s.map(o=>new oc({policyIdentifier:o})));super(Bm,n,pe.serialize(i)),this.policies=s}}toTextObject(){let e=this.toTextObjectWithoutValue();return e.Policy=this.policies.map(t=>new Rt("",{},Qn.toString(t))),e}};Mg.NAME="Certificate Policies";rs.register(Bm,Mg);Ug=class extends Is{constructor(...e){var t;if(xe.isBufferSource(e[0]))super(e[0]);else if(Array.isArray(e[0])&&typeof e[0][0]=="string"){let n=e[0].map(o=>new qn({distributionPoint:new Ni({fullName:[new We({uniformResourceIdentifier:o})]})})),i=new Mo(n);super(Nm,e[1],pe.serialize(i))}else{let s=new Mo(e[0]);super(Nm,e[1],pe.serialize(s))}(t=this.distributionPoints)!==null&&t!==void 0||(this.distributionPoints=[])}onInit(e){super.onInit(e);let t=pe.parse(e.extnValue,Mo);this.distributionPoints=t}toTextObject(){let e=this.toTextObjectWithoutValue();return e["Distribution Point"]=this.distributionPoints.map(t=>{var s;let n={};return t.distributionPoint&&(n[""]=(s=t.distributionPoint.fullName)===null||s===void 0?void 0:s.map(i=>new Jn(i).toString()).join(", ")),t.reasons&&(n.Reasons=t.reasons.toString()),t.cRLIssuer&&(n["CRL Issuer"]=t.cRLIssuer.map(i=>i.toString()).join(", ")),n}),e}};Ug.NAME="CRL Distribution Points";jg=class extends Is{constructor(...e){var t,s,n,i;if(xe.isBufferSource(e[0]))super(e[0]);else if(e[0]instanceof sc){let o=new sc(e[0]);super(Im,e[1],pe.serialize(o))}else{let o=e[0],a=new sc;Ag(a,o,_1,"ocsp"),Ag(a,o,E1,"caIssuers"),Ag(a,o,C1,"timeStamping"),Ag(a,o,T1,"caRepository"),super(Im,e[1],pe.serialize(a))}(t=this.ocsp)!==null&&t!==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=[],pe.parse(e.extnValue,sc).forEach(s=>{switch(s.accessMethod){case _1:this.ocsp.push(new Jn(s.accessLocation));break;case E1:this.caIssuers.push(new Jn(s.accessLocation));break;case C1:this.timeStamping.push(new Jn(s.accessLocation));break;case T1:this.caRepository.push(new Jn(s.accessLocation));break}})}toTextObject(){let e=this.toTextObjectWithoutValue();return this.ocsp.length&&Tg(e,"OCSP",this.ocsp),this.caIssuers.length&&Tg(e,"CA Issuers",this.caIssuers),this.timeStamping.length&&Tg(e,"Time Stamping",this.timeStamping),this.caRepository.length&&Tg(e,"CA Repository",this.caRepository),e}};jg.NAME="Authority Info Access";Hg=class extends Is{constructor(...e){xe.isBufferSource(e[0])?super(e[0]):super(j1,e[1],new Fi(e[0]||[]).rawData)}onInit(e){super.onInit(e);let t=pe.parse(e.extnValue,Xt);this.names=new Fi(t)}toTextObject(){let e=this.toTextObjectWithoutValue(),t=this.names.toTextObject();for(let s in t)e[s]=t[s];return e}};Hg.NAME="Issuer Alternative Name";Cu=class r extends Zo{constructor(...e){let t;if(xe.isBufferSource(e[0]))t=xe.toArrayBuffer(e[0]);else{let s=e[0],n=Array.isArray(e[1])?e[1].map(i=>xe.toArrayBuffer(i)):[];t=pe.serialize(new Ir({type:s,values:n}))}super(t,Ir)}onInit(e){this.type=e.type,this.values=e.values}toTextObject(){let e=this.toTextObjectWithoutValue();return e.Value=this.values.map(t=>new Rt("",{"":t})),e}toTextObjectWithoutValue(){let e=this.toTextObjectEmpty();return e[Rt.NAME]===r.NAME&&(e[Rt.NAME]=Qn.toString(this.type)),e}};Cu.NAME="Attribute";Fg=class extends Cu{constructor(...e){var t;if(xe.isBufferSource(e[0]))super(e[0]);else{let s=new nh({printableString:e[0]});super(Rw,[pe.serialize(s)])}(t=this.password)!==null&&t!==void 0||(this.password="")}onInit(e){if(super.onInit(e),this.values[0]){let t=pe.parse(this.values[0],nh);this.password=t.toString()}}toTextObject(){let e=this.toTextObjectWithoutValue();return e[Rt.VALUE]=this.password,e}};Fg.NAME="Challenge Password";Ph=class extends Cu{constructor(...e){var t;if(xe.isBufferSource(e[0]))super(e[0]);else{let s=e[0],n=new Ts;for(let i of s)n.push(pe.parse(i.rawData,Kr));super(oh,[pe.serialize(n)])}(t=this.items)!==null&&t!==void 0||(this.items=[])}onInit(e){if(super.onInit(e),this.values[0]){let t=pe.parse(this.values[0],Ts);this.items=t.map(s=>rs.create(pe.serialize(s)))}}toTextObject(){let e=this.toTextObjectWithoutValue(),t=this.items.map(s=>s.toTextObject());for(let s of t)e[s[Rt.NAME]]=s;return e}};Ph.NAME="Extensions";Tu=class{static register(e,t){this.items.set(e,t)}static create(e){let t=new Cu(e),s=this.items.get(t.type);return s?new s(e):t}};Tu.items=new Map;Nh="crypto.signatureFormatter",Vw=class{toAsnSignature(e,t){return xe.toArrayBuffer(t)}toWebSignature(e,t){return xe.toArrayBuffer(t)}},Kw=Rg=class{static createPssParams(e,t){let s=Rg.getHashAlgorithm(e);return s?new Gn({hashAlgorithm:s,maskGenAlgorithm:new ue({algorithm:Vo,parameters:pe.serialize(s)}),saltLength:t}):null}static getHashAlgorithm(e){let t=Kt.resolve(Lc);return typeof e=="string"?t.toAsnAlgorithm({name:e}):typeof e=="object"&&e&&"name"in e?t.toAsnAlgorithm(e):null}toAsnAlgorithm(e){switch(e.name.toLowerCase()){case"rsassa-pkcs1-v1_5":if("hash"in e){let t;if(typeof e.hash=="string")t=e.hash;else if(e.hash&&typeof e.hash=="object"&&"name"in e.hash&&typeof e.hash.name=="string")t=e.hash.name.toUpperCase();else throw new Error("Cannot get hash algorithm name");switch(t.toLowerCase()){case"sha-1":return new ue({algorithm:uu,parameters:null});case"sha-256":return new ue({algorithm:ng,parameters:null});case"sha-384":return new ue({algorithm:fu,parameters:null});case"sha-512":return new ue({algorithm:lu,parameters:null})}}else return new ue({algorithm:Wn,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 t=Rg.createPssParams(e.hash,e.saltLength);if(!t)throw new Error("Cannot create PSS parameters");return new ue({algorithm:$o,parameters:pe.serialize(t)})}else return new ue({algorithm:$o,parameters:null})}return null}toWebAlgorithm(e){switch(e.algorithm){case Wn:return{name:"RSASSA-PKCS1-v1_5"};case uu:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-1"}};case ng:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case fu:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-384"}};case lu:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-512"}};case $o:if(e.parameters){let t=pe.parse(e.parameters,Gn);return{name:"RSA-PSS",hash:Kt.resolve(Lc).toWebAlgorithm(t.hashAlgorithm),saltLength:t.saltLength}}else return{name:"RSA-PSS"}}return null}};Kw=Rg=p([Go()],Kw);Kt.registerSingleton(Bh,Kw);Ww=class{toAsnAlgorithm(e){switch(e.name.toLowerCase()){case"sha-1":return new ue({algorithm:Ec});case"sha-256":return new ue({algorithm:Cc});case"sha-384":return new ue({algorithm:Tc});case"sha-512":return new ue({algorithm:Ac})}return null}toWebAlgorithm(e){switch(e.algorithm){case Ec:return{name:"SHA-1"};case Cc:return{name:"SHA-256"};case Tc:return{name:"SHA-384"};case Ac:return{name:"SHA-512"}}return null}};Ww=p([Go()],Ww);Kt.registerSingleton(Bh,Ww);qi=class r{addPadding(e,t){let s=xe.toUint8Array(t),n=new Uint8Array(e);return n.set(s,e-s.length),n.buffer}removePadding(e,t=!1){let s=xe.toUint8Array(e);for(let n=0;n<s.length;n++)if(s[n]){s=s.slice(n);break}if(t&&s[0]>127){let n=new Uint8Array(s.length+1);return n.set(s,1),n.buffer}return s.buffer}toAsnSignature(e,t){if(e.name==="ECDSA"){let s=e.namedCurve,n=r.namedCurveSize.get(s)||r.defaultNamedCurveSize,i=new _c,o=xe.toUint8Array(t);return i.r=this.removePadding(o.slice(0,n),!0),i.s=this.removePadding(o.slice(n,n+n),!0),pe.serialize(i)}return null}toWebSignature(e,t){if(e.name==="ECDSA"){let s=pe.parse(t,_c),n=e.namedCurve,i=r.namedCurveSize.get(n)||r.defaultNamedCurveSize,o=this.addPadding(i,this.removePadding(s.r)),a=this.addPadding(i,this.removePadding(s.s));return R6(o,a)}return null}};qi.namedCurveSize=new Map;qi.defaultNamedCurveSize=32;Fw="1.3.101.110",gA="1.3.101.111",qw="1.3.101.112",yA="1.3.101.113",Gw=class{toAsnAlgorithm(e){let t=null;switch(e.name.toLowerCase()){case"ed25519":t=qw;break;case"x25519":t=Fw;break;case"eddsa":switch(e.namedCurve.toLowerCase()){case"ed25519":t=qw;break;case"ed448":t=yA;break}break;case"ecdh-es":switch(e.namedCurve.toLowerCase()){case"x25519":t=Fw;break;case"x448":t=gA;break}}return t?new ue({algorithm:t}):null}toWebAlgorithm(e){switch(e.algorithm){case qw:return{name:"Ed25519"};case yA:return{name:"EdDSA",namedCurve:"Ed448"};case Fw:return{name:"X25519"};case gA:return{name:"ECDH-ES",namedCurve:"X448"}}return null}};Gw=p([Go()],Gw);Kt.registerSingleton(Bh,Gw);Xw=class extends ea{get subjectName(){return ht(this,uh,"f")||Gt(this,uh,new ln(this.asn.certificationRequestInfo.subject),"f"),ht(this,uh,"f")}get subject(){return ht(this,fh,"f")||Gt(this,fh,this.subjectName.toString(),"f"),ht(this,fh,"f")}get signatureAlgorithm(){if(!ht(this,lh,"f")){let e=Kt.resolve(Lc);Gt(this,lh,e.toWebAlgorithm(this.asn.signatureAlgorithm),"f")}return ht(this,lh,"f")}get signature(){return ht(this,hh,"f")||Gt(this,hh,this.asn.signature,"f"),ht(this,hh,"f")}get publicKey(){return ht(this,ph,"f")||Gt(this,ph,new ji(this.asn.certificationRequestInfo.subjectPKInfo),"f"),ht(this,ph,"f")}get attributes(){return ht(this,mh,"f")||Gt(this,mh,this.asn.certificationRequestInfo.attributes.map(e=>Tu.create(pe.serialize(e))),"f"),ht(this,mh,"f")}get extensions(){if(!ht(this,Su,"f")){Gt(this,Su,[],"f");let e=this.getAttribute(oh);e instanceof Ph&&Gt(this,Su,e.items,"f")}return ht(this,Su,"f")}get tbs(){return ht(this,dh,"f")||Gt(this,dh,this.asn.certificationRequestInfoRaw||pe.serialize(this.asn.certificationRequestInfo),"f"),ht(this,dh,"f")}constructor(e){let t=ea.isAsnEncoded(e)?[e,Qo]:[e];super(t[0],t[1]),dh.set(this,void 0),uh.set(this,void 0),fh.set(this,void 0),lh.set(this,void 0),hh.set(this,void 0),ph.set(this,void 0),mh.set(this,void 0),Su.set(this,void 0),this.tag=Nr.CertificateRequestTag}onInit(e){}getAttribute(e){for(let t of this.attributes)if(t.type===e)return t;return null}getAttributes(e){return this.attributes.filter(t=>t.type===e)}getExtension(e){for(let t of this.extensions)if(t.type===e)return t;return null}getExtensions(e){return this.extensions.filter(t=>t.type===e)}async verify(e=pr.get()){let t={...this.publicKey.algorithm,...this.signatureAlgorithm},s=await this.publicKey.export(t,["verify"],e),n=Kt.resolveAll(Nh).reverse(),i=null;for(let a of n)if(i=a.toWebSignature(t,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(),t=pe.parse(this.rawData,Qo),s=t.certificationRequestInfo,n=new Rt("",{Version:`${zn[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:Hi.serializeAlgorithm(t.signatureAlgorithm),"":t.signature}),e}};dh=new WeakMap,uh=new WeakMap,fh=new WeakMap,lh=new WeakMap,hh=new WeakMap,ph=new WeakMap,mh=new WeakMap,Su=new WeakMap;Xw.NAME="PKCS#10 Certificate Request";qg=class extends ea{get publicKey(){return ht(this,Th,"f")||Gt(this,Th,new ji(this.asn.tbsCertificate.subjectPublicKeyInfo),"f"),ht(this,Th,"f")}get serialNumber(){if(!ht(this,yh,"f")){let e=this.asn.tbsCertificate,t=new Uint8Array(e.serialNumber);t.length>1&&t[0]===0&&t[1]>127&&(t=t.slice(1)),Gt(this,yh,Ue.ToHex(t),"f")}return ht(this,yh,"f")}get subjectName(){return ht(this,xh,"f")||Gt(this,xh,new ln(this.asn.tbsCertificate.subject),"f"),ht(this,xh,"f")}get subject(){return ht(this,bh,"f")||Gt(this,bh,this.subjectName.toString(),"f"),ht(this,bh,"f")}get issuerName(){return ht(this,vh,"f")||Gt(this,vh,new ln(this.asn.tbsCertificate.issuer),"f"),ht(this,vh,"f")}get issuer(){return ht(this,wh,"f")||Gt(this,wh,this.issuerName.toString(),"f"),ht(this,wh,"f")}get notBefore(){if(!ht(this,Sh,"f")){let e=this.asn.tbsCertificate.validity.notBefore.utcTime||this.asn.tbsCertificate.validity.notBefore.generalTime;if(!e)throw new Error("Cannot get 'notBefore' value");Gt(this,Sh,e,"f")}return ht(this,Sh,"f")}get notAfter(){if(!ht(this,_h,"f")){let e=this.asn.tbsCertificate.validity.notAfter.utcTime||this.asn.tbsCertificate.validity.notAfter.generalTime;if(!e)throw new Error("Cannot get 'notAfter' value");Gt(this,_h,e,"f")}return ht(this,_h,"f")}get signatureAlgorithm(){if(!ht(this,Eh,"f")){let e=Kt.resolve(Lc);Gt(this,Eh,e.toWebAlgorithm(this.asn.signatureAlgorithm),"f")}return ht(this,Eh,"f")}get signature(){return ht(this,Ch,"f")||Gt(this,Ch,this.asn.signatureValue,"f"),ht(this,Ch,"f")}get extensions(){return ht(this,_u,"f")||(Gt(this,_u,[],"f"),this.asn.tbsCertificate.extensions&&Gt(this,_u,this.asn.tbsCertificate.extensions.map(e=>rs.create(pe.serialize(e))),"f")),ht(this,_u,"f")}get tbs(){return ht(this,gh,"f")||Gt(this,gh,this.asn.tbsCertificateRaw||pe.serialize(this.asn.tbsCertificate),"f"),ht(this,gh,"f")}constructor(e){let t=ea.isAsnEncoded(e)?[e,Ks]:[e];super(t[0],t[1]),gh.set(this,void 0),yh.set(this,void 0),xh.set(this,void 0),bh.set(this,void 0),vh.set(this,void 0),wh.set(this,void 0),Sh.set(this,void 0),_h.set(this,void 0),Eh.set(this,void 0),Ch.set(this,void 0),_u.set(this,void 0),Th.set(this,void 0),this.tag=Nr.CertificateTag}onInit(e){}getExtension(e){for(let t of this.extensions)if(typeof e=="string"){if(t.type===e)return t}else if(t instanceof e)return t;return null}getExtensions(e){return this.extensions.filter(t=>typeof e=="string"?t.type===e:t instanceof e)}async verify(e={},t=pr.get()){let s,n,i=e.publicKey;try{if(!i)s={...this.publicKey.algorithm,...this.signatureAlgorithm},n=await this.publicKey.export(s,["verify"],t);else if("publicKey"in i)s={...i.publicKey.algorithm,...this.signatureAlgorithm},n=await i.publicKey.export(s,["verify"],t);else if(i instanceof ji)s={...i.algorithm,...this.signatureAlgorithm},n=await i.export(s,["verify"],t);else if(xe.isBufferSource(i)){let d=new ji(i);s={...d.algorithm,...this.signatureAlgorithm},n=await d.export(s,["verify"],t)}else s={...i.algorithm,...this.signatureAlgorithm},n=i}catch{return!1}let o=Kt.resolveAll(Nh).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 t.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 t,s="SHA-1";return e[0]&&(e[0].subtle?t=e[0]:(s=e[0]||s,t=e[1])),t??(t=pr.get()),await t.subtle.digest(s,this.rawData)}async isSelfSigned(e=pr.get()){return this.subject===this.issuer&&await this.verify({signatureOnly:!0},e)}toTextObject(){let e=this.toTextObjectEmpty(),t=pe.parse(this.rawData,Ks),s=t.tbsCertificate,n=new Rt("",{Version:`${zn[s.version]} (${s.version})`,"Serial Number":s.serialNumber,"Signature Algorithm":Hi.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:Hi.serializeAlgorithm(t.signatureAlgorithm),"":t.signatureValue}),e}};gh=new WeakMap,yh=new WeakMap,xh=new WeakMap,bh=new WeakMap,vh=new WeakMap,wh=new WeakMap,Sh=new WeakMap,_h=new WeakMap,Eh=new WeakMap,Ch=new WeakMap,_u=new WeakMap,Th=new WeakMap;qg.NAME="Certificate";zg=class{static async createSelfSigned(e,t=pr.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},t)}static async create(e,t=pr.get()){var s;let n;e.publicKey instanceof ji?n=e.publicKey.rawData:"publicKey"in e.publicKey?n=e.publicKey.publicKey.rawData:xe.isBufferSource(e.publicKey)?n=e.publicKey:n=await t.subtle.exportKey("spki",e.publicKey);let i=oj(e.serialNumber,t),o=e.notBefore||new Date,a=e.notAfter||new Date(o.getTime()+31536e6),c=new Ks({tbsCertificate:new kr({version:zn.v3,serialNumber:i,validity:new Oi({notBefore:o,notAfter:a}),extensions:new Ts(((s=e.extensions)===null||s===void 0?void 0:s.map(C=>pe.parse(C.rawData,Kr)))||[]),subjectPublicKeyInfo:pe.parse(n,Rr)})});if(e.subject){let C=e.subject instanceof ln?e.subject:new ln(e.subject);c.tbsCertificate.subject=pe.parse(C.toArrayBuffer(),Ft)}if(e.issuer){let C=e.issuer instanceof ln?e.issuer:new ln(e.issuer);c.tbsCertificate.issuer=pe.parse(C.toArrayBuffer(),Ft)}let d={hash:"SHA-256"},u="signingKey"in e?{...d,...e.signingAlgorithm,...e.signingKey.algorithm}:{...d,...e.signingAlgorithm},f=Kt.resolve(Lc);c.tbsCertificate.signature=c.signatureAlgorithm=f.toAsnAlgorithm(u);let h=pe.serialize(c.tbsCertificate),y="signingKey"in e?await t.subtle.sign(u,e.signingKey,h):e.signature,v=Kt.resolveAll(Nh).reverse(),S=null;for(let C of v)if(S=C.toAsnSignature(u,y),S)break;if(!S)throw Error("Cannot convert ASN.1 signature value to WebCrypto format");return c.signatureValue=S,new qg(pe.serialize(c))}};(function(r){r[r.unspecified=0]="unspecified",r[r.keyCompromise=1]="keyCompromise",r[r.cACompromise=2]="cACompromise",r[r.affiliationChanged=3]="affiliationChanged",r[r.superseded=4]="superseded",r[r.cessationOfOperation=5]="cessationOfOperation",r[r.certificateHold=6]="certificateHold",r[r.removeFromCRL=8]="removeFromCRL",r[r.privilegeWithdrawn=9]="privilegeWithdrawn",r[r.aACompromise=10]="aACompromise"})(xA||(xA={}));aj=new WeakMap,cj=new WeakMap,dj=new WeakMap,uj=new WeakMap,fj=new WeakMap;lj=new WeakMap,hj=new WeakMap,pj=new WeakMap,mj=new WeakMap,gj=new WeakMap,yj=new WeakMap,xj=new WeakMap;rs.register(km,Bg);rs.register(Lm,Ng);rs.register(Dm,Og);rs.register(K1,Lg);rs.register(Rm,Pg);rs.register(z1,Dg);rs.register(Nm,Ug);rs.register(Im,jg);rs.register(j1,Hg);Tu.register(Rw,Fg);Tu.register(oh,Ph);Kt.registerSingleton(Nh,Vw);Kt.registerSingleton(Nh,qi);qi.namedCurveSize.set("P-256",32);qi.namedCurveSize.set("K-256",32);qi.namedCurveSize.set("P-384",48);qi.namedCurveSize.set("P-521",66)});var CA=re((Lfe,EA)=>{"use strict";function vj(r){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(r)}EA.exports=vj});var Oh=re((Dfe,OA)=>{"use strict";var TA=require("util"),kA=CA(),AA=/[\{\[]/,IA=/[\}\]]/,RA=["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"],PA={};for($g=0;$g<RA.length;$g++)PA[RA[$g]]=!0;var $g,wj=function(r){return kA(r)&&!PA.hasOwnProperty(r)},BA={s:function(r){return""+r},d:function(r){return""+Number(r)},o:function(r){return JSON.stringify(r)}},NA=function(){var r=[],e=0,t={},s=function(o){for(var a="";a.length<e*2;)a+=" ";r.push(a+o)},n=function(o){if(IA.test(o.trim()[0])&&AA.test(o[o.length-1])){e--,s(o),e++;return}if(AA.test(o[o.length-1])){s(o),e++;return}if(IA.test(o.trim()[0])){e--,s(o);return}s(o)},i=function(o){if(!o)return i;if(arguments.length===1&&o.indexOf(`
34
+ `)>-1)for(var a=o.trim().split(`
35
+ `),c=0;c<a.length;c++)n(a[c].trim());else n(TA.format.apply(TA,arguments));return i};return i.scope={},i.formats=BA,i.sym=function(o){return(!o||!wj(o))&&(o="tmp"),t[o]||(t[o]=0),o+(t[o]++||"")},i.property=function(o,a){return arguments.length===1&&(a=o,o=""),a=a+"",kA(a)?o?o+"."+a:a:o?o+"["+JSON.stringify(a)+"]":JSON.stringify(a)},i.toString=function(){return r.join(`
36
+ `)},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};NA.formats=BA;OA.exports=NA});var DA=re((Mfe,LA)=>{"use strict";var Kg=class{constructor(){this.next=null,this.buffer=null}};LA.exports=class Vg{constructor(){this.head=null,this.tail=null,this.length=0,this.count=0}push(e){let t=new Kg;t.buffer=e,this.length>0?this.tail.next=t:this.head=t,this.tail=t,this.length+=e.length,this.count+=1}unshift(e){let t=new Kg;t.buffer=e,t.next=this.head,this.isEmpty()&&(this.tail=t),this.head=t,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,t){if(e<0||e>=this.length)return new Vg;if(t<0||t>this.length||t<e)return new Vg;let s=new Vg,n=this.head,i=e,o=t;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 HA=re((Ufe,jA)=>{"use strict";var Wg=Oh(),Sj=DA(),Dc=class r{constructor(){this.queue=new Sj,this.offset=0}get length(){return this.queue.length-this.offset}append(e){if(Buffer.isBuffer(e)){if(this.offset>0){let t=this.queue.shift();this.queue.unshift(t.slice(this.offset)),this.offset=0}this.queue.push(e)}else if(Array.isArray(e))for(let t=0;t<e.length;t+=1)this.append(e[t]);else if(e instanceof r){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 t=e.queue.head;for(;t;)this.queue.push(t.buffer),t=t.next}}get(e){let t=e;for(;t>=this.length;)t-=this.length;for(;t<0;)t+=this.length;let s=this.queue.head,{offset:n}=this;for(;s;){if(s.buffer.length-n>t)return s.buffer[t+n];t-=s.buffer.length-n,n=0,s=s.next}}slice(e,t){for(typeof e!="number"&&(e=0),typeof t!="number"&&(t=this.length);e<0;)e+=this.length;for(;t<0;)t+=this.length;if(t=Math.min(t,this.length),e>=this.length||t===0)return Buffer.alloc(0);let s=e;e=Math.min(s,t),t=Math.max(s,t);let n=this.queue.slice(e+this.offset,t+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,t,s){return this.slice(t,s).toString(e)}consume(e){let t=e;for(;this.length>0;){let s=this.queue.first.length-this.offset;if(t>=s)this.queue.shift(),t-=s,this.offset=0;else{this.offset+=t;break}}}indexOf(e,t=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(t)||(t=0);t>=this.length;)t-=this.length;for(;t<0;)t+=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),t>=s.buffer.length-o){t-=s.buffer.length-o,i();continue}t<s.buffer.length&&(o+=t);let a=s.buffer.indexOf(e,o);if(a>-1)return a+n-this.offset;i(),o>this.offset&&(t=0)}return-1}},MA={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(MA).forEach(r=>{let e=Wg();e(`
37
+ function bufferlist_${r}(offset = 0) {
38
+ const start = offset + this.offset;
39
+ const head = this.queue.first;
40
+ const size = ${e.formats.d(MA[r])};
41
+ const isFirtsChunkEnough = head.length - start >= size;
42
+
43
+ return isFirtsChunkEnough
44
+ ? head.${r}(start)
45
+ : this.slice(offset, offset + size).${r}(0)
46
+ }
47
+ `),Dc.prototype[r]=e.toFunction()});var _j=["readIntBE","readIntLE","readUIntBE","readUIntLE"];_j.forEach(r=>{let e=Wg();e(`
48
+ function bufferlist_${r}(size, offset = 0) {
49
+ const start = offset + this.offset;
50
+ const head = this.queue.first;
51
+ const isFirtsChunkEnough = head.length - start >= size;
52
+
53
+ return isFirtsChunkEnough
54
+ ? head.${r}(start, size)
55
+ : this.slice(offset, offset + size).${r}(0, size)
56
+ }
57
+ `),Dc.prototype[r]=e.toFunction()});var UA={writeDoubleBE:8,writeDoubleLE:8,writeFloatBE:4,writeFloatLE:4,writeInt32BE:4,writeInt32LE:4,writeUInt32BE:4,writeUInt32LE:4,writeInt16BE:2,writeInt16LE:2,writeUInt16BE:2,writeUInt16LE:2,writeInt8:1,writeUInt8:1};Object.keys(UA).forEach(r=>{let e=Wg();e(`
58
+ function bufferlist_${r}(value) {
59
+ const size = ${e.formats.d(UA[r])};
60
+ const buf = Buffer.allocUnsafe(size);
61
+ buf.${r}(value, 0);
62
+ this.append(buf);
63
+ }
64
+ `),Dc.prototype[r]=e.toFunction()});var Ej=["writeIntBE","writeIntLE","writeUIntBE","writeUIntLE"];Ej.forEach(r=>{let e=Wg();e(`
65
+ function bufferlist_${r}(value, size) {
66
+ const buf = Buffer.allocUnsafe(size);
67
+ buf.${r}(value, 0, size);
68
+ this.append(buf);
69
+ }
70
+ `),Dc.prototype[r]=e.toFunction()});jA.exports=Dc});var Au=re((Hfe,FA)=>{"use strict";FA.exports=class extends Error{constructor(e,t){let s=`requested ${e} bytes but only ${t} available`;super(s),this.name="NotEnoughDataError"}}});var Lh=re((Ffe,$A)=>{"use strict";var{Transform:Cj}=require("stream"),Gg=Oh(),Tj=HA(),Aj=Au(),qA=Symbol("buffer"),Mc=class extends Cj{constructor(e={}){super(e),this[qA]=new Tj}get buffer(){return this[qA]}get length(){return this.buffer.length}append(e){this.buffer.append(e)}get(e){return this.buffer.get(e)}slice(e,t){return this.buffer.slice(e,t)}consume(e){this.buffer.consume(e)}toString(e,t,s){return this.buffer.toString(e,t,s)}indexOf(e,t=0){return this.buffer.indexOf(e,t)}readBuffer(e){Yw(e,this.length);let t=this.slice(0,e);return this.consume(e),t}writeBuffer(e){this.append(e)}},zA={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},Ij=["readIntBE","readIntLE","readUIntBE","readUIntLE"];Object.keys(zA).forEach(r=>{let e=Gg();e(`
71
+ function binary_${r}() {
72
+ const bytes = ${e.formats.d(zA[r])};
73
+ assertSize(bytes, this.length);
74
+
75
+ const res = this.buffer.${r}(0);
76
+ this.consume(bytes);
77
+
78
+ return res;
79
+ }
80
+ `),Mc.prototype[r]=e.toFunction({assertSize:Yw})});Ij.forEach(r=>{let e=Gg();e(`
81
+ function binary_${r}(size) {
82
+ assertSize(size, this.length);
83
+
84
+ const res = this.buffer.${r}(size, 0);
85
+ this.consume(size);
86
+ return res;
87
+ }
88
+ `),Mc.prototype[r]=e.toFunction({assertSize:Yw})});var Rj=["writeDoubleBE","writeDoubleLE","writeFloatBE","writeFloatLE","writeInt32BE","writeInt32LE","writeUInt32BE","writeUInt32LE","writeInt16BE","writeInt16LE","writeUInt16BE","writeUInt16LE","writeInt8","writeUInt8"];Rj.forEach(r=>{let e=Gg();e(`
89
+ function binary_${r}(value) {
90
+ this.buffer.${r}(value);
91
+ }
92
+ `),Mc.prototype[r]=e.toFunction()});var kj=["writeIntBE","writeIntLE","writeUIntBE","writeUIntLE"];kj.forEach(r=>{let e=Gg();e(`
93
+ function binary_${r}(value, size) {
94
+ this.buffer.${r}(value, size);
95
+ }
96
+ `),Mc.prototype[r]=e.toFunction()});function Yw(r,e){if(r>e)throw new Aj(r,e)}$A.exports=Mc});var KA=re((qfe,VA)=>{"use strict";VA.exports=function(e){return e!=null&&typeof e=="object"&&Array.isArray(e)===!1}});var XA=re((zfe,GA)=>{"use strict";var Pj=KA();function WA(r){return Pj(r)===!0&&Object.prototype.toString.call(r)==="[object Object]"}GA.exports=function(e){var t,s;return!(WA(e)===!1||(t=e.constructor,typeof t!="function")||(s=t.prototype,WA(s)===!1)||s.hasOwnProperty("isPrototypeOf")===!1)}});var Zn=re(($fe,YA)=>{"use strict";var Bj=XA();YA.exports={isType:Nj,isUserType:Bj,isFunction:Dh,isDecodeType:Oj,isEncodeType:Lj};function Nj(r){return Jw(r)&&Dh(r.encode)&&Dh(r.decode)}function Dh(r){return typeof r=="function"}function Jw(r){return typeof r=="object"&&r!==null}function Oj(r){return Jw(r)&&Dh(r.decode)}function Lj(r){return Jw(r)&&Dh(r.encode)}});var ta=re((Vfe,JA)=>{"use strict";var Dj=Symbol("skip"),Mj=Symbol("bytes");JA.exports={skip:Dj,bytes:Mj}});var ra=re((Kfe,ZA)=>{"use strict";var QA=ta();ZA.exports=class Xg{constructor(){this[QA.bytes]=0,this.node=void 0,this.current=void 0}get bytes(){return this[QA.bytes]}static clone(e){let t=new Xg;return e instanceof Xg&&(t.node=e.node,t.current=e.current),t}static clean(e){e instanceof Xg&&(e.node=void 0,e.current=void 0)}}});var Iu=re((Wfe,n5)=>{"use strict";var{isType:Uj,isUserType:jj,isDecodeType:Hj}=Zn(),Fj=Lh(),Qw=ta(),e5=ra();n5.exports={decode:t5,decodeCommon:r5};function t5(r,e){let t=r;Buffer.isBuffer(r)&&(t=new Fj,t.append(r));let s=new e5,n=r5(t,e,s);return t5.bytes=s.bytes,e5.clean(s),n}function r5(r,e,t){if(Uj(e)){let s=e.decode.call(t,r);return t[Qw.bytes]+=e.decode.bytes,s}return s5(r,e,t)}function s5(r,e,t){qj(e);let s=Object.create(null);t.node===void 0&&(t.node=s),t.current=s;let n=Object.keys(e);for(let i=0;i<n.length;i+=1){let o=n[i],a=e[o];if(!Hj(a)){s[o]=s5(r,a,t),t.current=s;continue}let c=a.decode.call(t,r);t[Qw.bytes]+=a.decode.bytes,a[Qw.skip]!==!0&&(s[o]=c)}return s}function qj(r){if(!jj(r))throw new TypeError("Argument #2 should be a plain object.")}});var Mh=re((Gfe,u5)=>{"use strict";var{isUserType:zj,isEncodeType:$j,isType:Vj}=Zn(),o5=ta(),i5=ra(),Zw=Lh();u5.exports={encode:a5,encodeCommon:c5};function a5(r,e,t){let s=new i5;if(e instanceof Zw){let n=t;t=e,e=n}return t instanceof Zw||(t=new Zw),c5(r,t,e,s),a5.bytes=s.bytes,i5.clean(s),t}function c5(r,e,t,s){Vj(t)?(t.encode.call(s,r,e),s[o5.bytes]+=t.encode.bytes):d5(r,e,t,s)}function d5(r,e,t,s){Kj(t),s.node===void 0&&(s.node=r),s.current=r;let n=Object.keys(t);for(let i=0;i<n.length;i+=1){let o=n[i],a=t[o],c=r[o];if(!$j(a)){d5(c,e,a,s),s.current=r;continue}a.encode.call(s,c,e),s[o5.bytes]+=a.encode.bytes}}function Kj(r){if(!zj(r))throw new TypeError("Argument `schema` should be a plain object.")}});var Uh=re((Xfe,g5)=>{"use strict";var{isUserType:Wj,isType:l5}=Zn(),f5=ra(),h5=ta();g5.exports={encodingLength:Gj,encodingLengthCommon:p5};function Gj(r,e){let t=new f5;return p5(r,e,t),f5.clean(t),t.bytes}function p5(r,e,t){l5(e)?t[h5.bytes]+=e.encodingLength.call(t,r):m5(r,e,t)}function m5(r,e,t){if(!Wj(e))throw new TypeError("Argument `schema` should be a plain object.");t.node===void 0&&(t.node=r),t.current=r;let s=Object.keys(e);for(let n=0;n<s.length;n+=1){let i=s[n],o=e[i],a=r[i];if(!l5(o)){m5(a,o,t),t.current=r;continue}t[h5.bytes]+=o.encodingLength.call(t,a)}}});var E5=re((Yfe,_5)=>{"use strict";var{decodeCommon:S5}=Iu(),{encodeCommon:Xj}=Mh(),{encodingLengthCommon:y5}=Uh(),{isType:x5,isUserType:Yj,isFunction:Jj}=Zn(),sa=ra();_5.exports=Qj;function Qj(r,e,t="count"){if(!x5(r)&&!Yj(r))throw new TypeError("Argument #1 should be a valid type.");let s=t==="bytes",n=typeof e=="number",i=x5(e),o=Jj(e);if(!n&&!i&&!o)throw new TypeError("Unknown type of argument #1.");return{encode:a,decode:c,encodingLength:d};function a(u,f){b5(u);let h=sa.clone(this);a.bytes=0;let y=0;if(i?y=u.length:n?y=e:o&&(y=e(h),v5(y)),s||w5(y,u.length),s){let v=sa.clone(h);for(let S of u)y5(S,r,v);i&&(y=v.bytes),w5(v.bytes,y),sa.clean(v)}i&&(e.encode.call(h,y,f),a.bytes+=e.encode.bytes),u.forEach(v=>{Xj(v,f,r,h)}),a.bytes+=h.bytes,sa.clean(h)}function c(u){let f=0;c.bytes=0;let h=sa.clone(this);n?f=e:i?(f=e.decode.call(h,u),c.bytes+=e.decode.bytes):o&&(f=e(h)),v5(f);let y;return s?y=Zj(r,f,u,h):y=eH(r,f,u,h),c.bytes+=h.bytes,sa.clean(h),y}function d(u){b5(u);let f=sa.clone(this),h=0;if(n&&s)return e;i&&!s&&(h=e.encodingLength(u.length));for(let y of u)y5(y,r,f);return sa.clean(f),h+=f.bytes,i&&s&&(h+=e.encodingLength(h)),h}}function b5(r){if(!Array.isArray(r))throw new TypeError("Argument #1 should be an Array.")}function v5(r){if(typeof r!="number")throw new TypeError("Length of an array should be a number.")}function w5(r,e){if(r!==e)throw new Error(`Argument #1 required length ${r} instead of ${e}`)}function Zj(r,e,t,s){let n=[],i=s.bytes,o=0;for(;o<e;)n.push(S5(t,r,s)),o=s.bytes-i;if(o>e)throw new Error("Incorrect length of an array.");return n}function eH(r,e,t,s){let n=new Array(e);for(let i=0;i<e;i+=1)n[i]=S5(t,r,s);return n}});var I5=re((Jfe,A5)=>{"use strict";var{isType:tH,isFunction:rH}=Zn(),sH=Au(),nH=Lh();A5.exports=iH;function iH(r){let e=typeof r=="number",t=tH(r),s=rH(r),n=r===null;if(!e&&!t&&!s&&!n)throw new TypeError("Unknown type of argument #1.");return{encode:i,decode:o,encodingLength:a};function i(c,d){C5(c),i.bytes=0;let u=this;if(e&&T5(r,c.length),t&&(r.encode.call(u,c.length,d),i.bytes+=r.encode.bytes),s){let f=r(u);eS(f),T5(f,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=r;else if(t)d=r.decode.call(u,c),o.bytes+=r.decode.bytes,eS(d);else if(s)d=r(u),eS(d);else if(n&&(d=c.indexOf(0),d===-1))throw new sH(c.length+1,c.length);let f=c.readBuffer(d);return o.bytes+=d,n&&(o.bytes+=1,c.consume(1)),f}function a(c){C5(c);let d=0;return e?r:(n?d=1:t&&(d=r.encodingLength(c.length)),d+c.length)}}function C5(r){if(!Buffer.isBuffer(r)&&!(r instanceof nH))throw new TypeError("Argument 1 should be a Buffer or a BinaryStream.")}function T5(r,e){if(r!==e)throw new Error(`Buffer required length ${r} instead of ${e}`)}function eS(r){if(typeof r!="number")throw new TypeError("Length of a buffer should be a number.")}});var k5=re((Qfe,R5)=>{"use strict";var{isType:oH}=Zn();R5.exports=aH;function aH(r){if(!oH(r))throw new TypeError("Argument #1 should be valid type.");function e(s){let n=this,i=r.decode.call(n,s);return e.bytes=r.decode.bytes,!!i}function t(s,n){let i=this;r.encode.call(i,s?1:0,n),t.bytes=r.encode.bytes}return{encode:t,decode:e,encodingLength:r.encodingLength}}});var B5=re((Zfe,P5)=>{"use strict";var{decodeCommon:cH}=Iu(),{encodeCommon:dH}=Mh(),{encodingLengthCommon:uH}=Uh(),{isType:fH,isFunction:Yg}=Zn(),lH=ta(),na=ra();P5.exports=hH;function hH(r,e=1){if(!fH(r))throw new TypeError("Invalid data type.");if(!Number.isInteger(e)&&!Yg(e))throw new TypeError("Argument #2 should be a valid integer or function.");return{[lH.skip]:!0,encodingLength:t,decode:s,encode:n};function t(i){let o=na.clone(this),a=Yg(e)?e(o):e;return uH(i,r,o),na.clean(o),o.bytes*a}function s(i){let o=na.clone(this);s.bytes=0;let a=Yg(e)?e(o):e;if(a===0){na.clean(o);return}for(let c=a;c>0;c-=1)cH(i,r,o);s.bytes=o.bytes,na.clean(o)}function n(i,o){n.bytes=0;let a=na.clone(this),c=Yg(e)?e(a):e;if(c===0){na.clean(a);return}for(let d=c;d>0;d-=1)dH(0,o,r,a);n.bytes=a.bytes,na.clean(a)}}});var L5=re((ele,O5)=>{"use strict";var{isType:pH}=Zn(),mH=Au();O5.exports=gH;function gH(r,e="ascii"){if(!Buffer.isEncoding(e))throw new Error("Argument #2 should be an encoding name.");if(typeof r=="number")return{encode:bH(r,e),decode:vH(r,e),encodingLength:()=>r};if(pH(r))return{encode:wH(r,e),decode:SH(r,e),encodingLength:_H(r,e)};if(r===null)return{encode:yH(e),decode:xH(e),encodingLength(t){return Buffer.byteLength(t,e)+1}};if(typeof r=="function")return{encode:EH(r,e),decode:CH(r,e),encodingLength(t){return Buffer.byteLength(t,e)}};throw new TypeError("Unknown type of argument #1.")}function yH(r){return function e(t,s){let n=Buffer.from(t.toString(),r);s.writeBuffer(n),s.writeInt8(0),e.bytes=n.length+1}}function xH(r){return function e(t){let s=t.indexOf(0);if(s===-1)throw new mH(t.length+1,t.length);let n=s+1,i=t.readBuffer(n);return e.bytes=n,i.toString(r,0,s)}}function bH(r,e){return function t(s,n){if(s=s.toString(),Buffer.byteLength(s,e)!==r)throw new Error(`Size of string should be ${r} in bytes.`);let i=Buffer.from(s,e);n.writeBuffer(i),t.bytes=i.length}}function vH(r,e){return function t(s){let n=s.readBuffer(r);return t.bytes=r,n.toString(e)}}function wH(r,e){return function t(s,n){s=s.toString();let i=this;r.encode.call(i,Buffer.byteLength(s,e),n),t.bytes=r.encode.bytes;let o=Buffer.from(s,e);n.writeBuffer(o),t.bytes+=o.length}}function SH(r,e){return function t(s){let n=r.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 t.bytes=r.decode.bytes+i.length,i.toString(e)}}function _H(r,e){return function(s){let n=Buffer.byteLength(s,e);return r.encodingLength(n)+n}}function EH(r,e){return function t(s,n){t.bytes=0;let o=r(this),a=Buffer.from(s.toString(),e);N5(o),TH(o,a.length),n.writeBuffer(a),t.bytes+=a.length}}function CH(r,e){return function t(s){let n=r(this);N5(n);let i=s.readBuffer(n);return t.bytes=n,i.toString(e)}}function N5(r){if(typeof r!="number")throw new TypeError("Length of a buffer should be a number.")}function TH(r,e){if(r!==e)throw new Error(`Buffer required length ${r} instead of ${e}`)}});var M5=re((tle,D5)=>{"use strict";var Jg=Oh();D5.exports={doublebe:ys(8,"writeDoubleBE","readDoubleBE"),doublele:ys(8,"writeDoubleLE","readDoubleLE"),floatbe:ys(4,"writeFloatBE","readFloatBE"),floatle:ys(4,"writeFloatLE","readFloatLE"),int8:ys(1,"writeInt8","readInt8"),uint8:ys(1,"writeUInt8","readUInt8"),int16be:ys(2,"writeInt16BE","readInt16BE"),uint16be:ys(2,"writeUInt16BE","readUInt16BE"),int16le:ys(2,"writeInt16LE","readInt16LE"),uint16le:ys(2,"writeUInt16LE","readUInt16LE"),int32be:ys(4,"writeInt32BE","readInt32BE"),uint32be:ys(4,"writeUInt32BE","readUInt32BE"),int32le:ys(4,"writeInt32LE","readInt32LE"),uint32le:ys(4,"writeUInt32LE","readUInt32LE"),int24be:Js(3,"writeIntBE","readIntBE"),uint24be:Js(3,"writeUIntBE","readUIntBE"),int24le:Js(3,"writeIntLE","readIntLE"),uint24le:Js(3,"writeUIntLE","readUIntLE"),int40be:Js(5,"writeIntBE","readIntBE"),uint40be:Js(5,"writeUIntBE","readUIntBE"),int40le:Js(5,"writeIntLE","readIntLE"),uint40le:Js(5,"writeUIntLE","readUIntLE"),int48be:Js(6,"writeIntBE","readIntBE"),uint48be:Js(6,"writeUIntBE","readUIntBE"),int48le:Js(6,"writeIntLE","readIntLE"),uint48le:Js(6,"writeUIntLE","readUIntLE")};function ys(r,e,t){let s=Jg(),n=Jg();return s(`
97
+ function decode_${t}(rstream) {
98
+ decode_${t}.bytes = ${s.formats.d(r)};
99
+ return rstream.${t}()
100
+ }
101
+ `),n(`
102
+ function encode_${e}(value, wstream) {
103
+ wstream.${e}(value);
104
+ encode_${e}.bytes = ${s.formats.d(r)};
105
+ }
106
+ `),{encodingLength:()=>r,encode:n.toFunction(),decode:s.toFunction()}}function Js(r,e,t){let s=Jg(),n=Jg();return s(`
107
+ function decode_${t}(rstream) {
108
+ decode_${t}.bytes = ${s.formats.d(r)};
109
+ return rstream.${t}(${s.formats.d(r)})
110
+ }
111
+ `),n(`
112
+ function encode_${e}(value, wstream) {
113
+ wstream.${e}(value, ${s.formats.d(r)});
114
+ encode_${e}.bytes = ${s.formats.d(r)};
115
+ }
116
+ `),{encodingLength:()=>r,encode:n.toFunction(),decode:s.toFunction()}}});var j5=re((rle,U5)=>{"use strict";var{isType:AH,isFunction:tS,isUserType:IH}=Zn(),rS=ta(),{decodeCommon:RH}=Iu(),{encodeCommon:kH}=Mh(),{encodingLengthCommon:PH}=Uh(),ia=ra();U5.exports=BH;function BH(r,e){if(!AH(e)&&!IH(e))throw new TypeError("Argument #2 should be a valid type.");let t={encode:s,decode:n,encodingLength:i,[rS.skip]:!1};return t;function s(o,a){let c=ia.clone(this);s.bytes=0;let d=tS(r)?!!r(c):!!r;if(t[rS.skip]=!d,!d){ia.clean(c);return}kH(o,a,e,c),s.bytes=c.bytes,ia.clean(c)}function n(o){let a=ia.clone(this);n.bytes=0;let c=tS(r)?!!r(a):!!r;if(t[rS.skip]=!c,!c){ia.clean(a);return}let d=RH(o,e,a);return n.bytes=a.bytes,ia.clean(a),d}function i(o){let a=ia.clone(this);return(tS(r)?r(a):r)&&PH(o,e,a),ia.clean(a),a.bytes}}});var q5=re((sle,F5)=>{"use strict";var Qg=ta(),{decodeCommon:NH}=Iu(),H5=ra();F5.exports=OH;function OH(...r){if(r.length===0)throw new TypeError("You should set at least one condition type.");let e={decode:t,encode:()=>{},[Qg.skip]:!0};return e;function t(s){t.bytes=0;let n=H5.clone(this);for(let i of r){let o=NH(s,i,n);if(i[Qg.skip]!==!0)return t.bytes=n.bytes,H5.clean(n),e[Qg.skip]=!1,o}e[Qg.skip]=!0}}});var K5=re((nle,V5)=>{"use strict";var $5=Oh(),LH=Au(),jh=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,t){return this.stream.slice(e,t)}toString(e,t,s){return this.stream.toString(e,t,s)}readBuffer(e){sS(this.index+e,this.length);let t=this.stream.slice(this.index,this.index+e);return this.index+=e,t}indexOf(e,t=0){return this.stream.indexOf(e,this.index+t)-this.index}},z5={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(z5).forEach(r=>{let e=$5(),t=z5[r];e(`
117
+ function transaction_${r}() {
118
+ assertSize(this.index + ${e.formats.d(t)}, this.length);
119
+ const value = this.stream.buffer.${r}(this.index);
120
+ this.index += ${e.formats.d(t)};
121
+ return value;
122
+ }
123
+ `),jh.prototype[r]=e.toFunction({assertSize:sS})});["readIntBE","readIntLE","readUIntBE","readUIntLE"].forEach(r=>{let e=$5();e(`
124
+ function transaction_${r}(bytes) {
125
+ assertSize(this.index + bytes, this.length);
126
+ const value = this.stream.buffer.${r}(bytes, this.index);
127
+ this.index += bytes;
128
+ return value;
129
+ }
130
+ `),jh.prototype[r]=e.toFunction({assertSize:sS})});V5.exports=jh;function sS(r,e){if(r>e)throw new LH(r,e)}});var Zt=re((ile,eI)=>{"use strict";var nS=Lh(),DH=E5(),MH=I5(),UH=k5(),jH=B5(),HH=L5(),W5=M5(),FH=j5(),qH=q5(),{encode:Y5}=Mh(),{decode:J5}=Iu(),{encodingLength:zH}=Uh(),$H=K5(),Q5=Au(),Z5={array:DH,bool:UH,buffer:MH,reserved:jH,string:HH,when:FH,select:qH};for(let r of Object.keys(W5))Z5[r]=W5[r];var Zg=Symbol("schema");function G5(r){let e=new nS({readableObjectMode:!1,writableObjectMode:!0,transform:VH});return e[Zg]=r,e}function X5(r){let e=null,t=Buffer.isBuffer(r);t||(e=r);let s=new nS({transform:KH,readableObjectMode:!0,writableObjectMode:!1});return s[Zg]=e,t&&s.append(r),s}function VH(r,e,t){try{Y5(r,this[Zg],this);let s=this.slice();this.consume(s.length),t(null,s)}catch(s){t(s)}}function KH(r,e,t){this.append(r);try{for(;this.length>0;){let s=new $H(this),n=J5(s,this[Zg]);s.commit(),this.push(n)}t()}catch(s){s instanceof Q5?t():t(s)}}eI.exports={createEncodeStream:G5,createDecodeStream:X5,encode:Y5,decode:J5,encodingLength:zH,createEncode:G5,createDecode:X5,types:Z5,BinaryStream:nS,NotEnoughDataError:Q5}});var zi,Uc,tI=T(()=>{"use strict";zi=Ge(require("crypto"),1),Uc=zi&&typeof zi=="object"&&"webcrypto"in zi?zi.webcrypto:zi&&typeof zi=="object"&&"randomBytes"in zi?zi:void 0});function jc(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function Hh(r){if(!Number.isSafeInteger(r)||r<0)throw new Error("positive integer expected, got "+r)}function hn(r,...e){if(!jc(r))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(r.length))throw new Error("Uint8Array expected of length "+e+", got length="+r.length)}function ey(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");Hh(r.outputLen),Hh(r.blockLen)}function ku(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function sI(r,e){hn(r);let t=e.outputLen;if(r.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function Vi(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function ty(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function pn(r,e){return r<<32-e|r>>>e}function Ki(r){if(hn(r),nI)return r.toHex();let e="";for(let t=0;t<r.length;t++)e+=WH[r[t]];return e}function rI(r){if(r>=$i._0&&r<=$i._9)return r-$i._0;if(r>=$i.A&&r<=$i.F)return r-($i.A-10);if(r>=$i.a&&r<=$i.f)return r-($i.a-10)}function Hc(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(nI)return Uint8Array.fromHex(r);let e=r.length,t=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);let s=new Uint8Array(t);for(let n=0,i=0;n<t;n++,i+=2){let o=rI(r.charCodeAt(i)),a=rI(r.charCodeAt(i+1));if(o===void 0||a===void 0){let c=r[i]+r[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}s[n]=o*16+a}return s}function iI(r){if(typeof r!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(r))}function Fh(r){return typeof r=="string"&&(r=iI(r)),hn(r),r}function mn(...r){let e=0;for(let s=0;s<r.length;s++){let n=r[s];hn(n),e+=n.length}let t=new Uint8Array(e);for(let s=0,n=0;s<r.length;s++){let i=r[s];t.set(i,n),n+=i.length}return t}function ry(r){let e=s=>r().update(Fh(s)).digest(),t=r();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>r(),e}function sy(r=32){if(Uc&&typeof Uc.getRandomValues=="function")return Uc.getRandomValues(new Uint8Array(r));if(Uc&&typeof Uc.randomBytes=="function")return Uint8Array.from(Uc.randomBytes(r));throw new Error("crypto.getRandomValues must be defined")}var nI,WH,$i,Ru,Fc=T(()=>{"use strict";tI();nI=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",WH=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));$i={_0:48,_9:57,A:65,F:70,a:97,f:102};Ru=class{}});function qh(r,e=""){if(typeof r!="boolean"){let t=e&&`"${e}"`;throw new Error(t+"expected boolean, got type="+typeof r)}return r}function oa(r,e,t=""){let s=jc(r),n=r?.length,i=e!==void 0;if(!s||i&&n!==e){let o=t&&`"${t}" `,a=i?` of length ${e}`:"",c=s?`length=${n}`:`type=${typeof r}`;throw new Error(o+"expected Uint8Array"+a+", got "+c)}return r}function zh(r){let e=r.toString(16);return e.length&1?"0"+e:e}function oI(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?aS:BigInt("0x"+r)}function Pu(r){return oI(Ki(r))}function cS(r){return hn(r),oI(Ki(Uint8Array.from(r).reverse()))}function ny(r,e){return Hc(r.toString(16).padStart(e*2,"0"))}function dS(r,e){return ny(r,e).reverse()}function Wr(r,e,t){let s;if(typeof e=="string")try{s=Hc(e)}catch(i){throw new Error(r+" must be hex string or Uint8Array, cause: "+i)}else if(jc(e))s=Uint8Array.from(e);else throw new Error(r+" must be hex string or Uint8Array");let n=s.length;if(typeof t=="number"&&n!==t)throw new Error(r+" of length "+t+" expected, got "+n);return s}function aI(r,e,t){return iS(r)&&iS(e)&&iS(t)&&e<=r&&r<t}function cI(r,e,t,s){if(!aI(e,t,s))throw new Error("expected valid "+r+": "+t+" <= n < "+s+", got "+e)}function iy(r){let e;for(e=0;r>aS;r>>=oS,e+=1);return e}function dI(r,e,t){if(typeof r!="number"||r<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 t!="function")throw new Error("hmacFn must be a function");let s=y=>new Uint8Array(y),n=y=>Uint8Array.of(y),i=s(r),o=s(r),a=0,c=()=>{i.fill(1),o.fill(0),a=0},d=(...y)=>t(o,i,...y),u=(y=s(0))=>{o=d(n(0),y),i=d(),y.length!==0&&(o=d(n(1),y),i=d())},f=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let y=0,v=[];for(;y<e;){i=d();let S=i.slice();v.push(S),y+=i.length}return mn(...v)};return(y,v)=>{c(),u(y);let S;for(;!(S=v(f()));)u();return c(),S}}function $h(r,e,t={}){if(!r||typeof r!="object")throw new Error("expected valid options object");function s(n,i,o){let a=r[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(t).forEach(([n,i])=>s(n,i,!0))}function uS(r){let e=new WeakMap;return(t,...s)=>{let n=e.get(t);if(n!==void 0)return n;let i=r(t,...s);return e.set(t,i),i}}var aS,oS,iS,aa,oy=T(()=>{"use strict";Fc();Fc();aS=BigInt(0),oS=BigInt(1);iS=r=>typeof r=="bigint"&&aS<=r;aa=r=>(oS<<BigInt(r))-oS});function gn(r,e){let t=r%e;return t>=xs?t:e+t}function uI(r,e){if(r===xs)throw new Error("invert: expected non-zero number");if(e<=xs)throw new Error("invert: expected positive modulus, got "+e);let t=gn(r,e),s=e,n=xs,i=Gr,o=Gr,a=xs;for(;t!==xs;){let d=s/t,u=s%t,f=n-o*d,h=i-a*d;s=t,t=u,n=o,i=a,o=f,a=h}if(s!==Gr)throw new Error("invert: does not exist");return gn(n,e)}function fS(r,e,t){if(!r.eql(r.sqr(e),t))throw new Error("Cannot find square root")}function yI(r,e){let t=(r.ORDER+Gr)/hI,s=r.pow(e,t);return fS(r,s,e),s}function YH(r,e){let t=(r.ORDER-pI)/mI,s=r.mul(e,qc),n=r.pow(s,t),i=r.mul(e,n),o=r.mul(r.mul(i,qc),n),a=r.mul(i,r.sub(o,r.ONE));return fS(r,a,e),a}function JH(r){let e=ei(r),t=xI(r),s=t(e,e.neg(e.ONE)),n=t(e,s),i=t(e,e.neg(s)),o=(r+GH)/gI;return(a,c)=>{let d=a.pow(c,o),u=a.mul(d,s),f=a.mul(d,n),h=a.mul(d,i),y=a.eql(a.sqr(u),c),v=a.eql(a.sqr(f),c);d=a.cmov(d,u,y),u=a.cmov(h,f,v);let S=a.eql(a.sqr(u),c),C=a.cmov(d,u,S);return fS(a,C,c),C}}function xI(r){if(r<lI)throw new Error("sqrt is not defined for small field");let e=r-Gr,t=0;for(;e%qc===xs;)e/=qc,t++;let s=qc,n=ei(r);for(;fI(n,s)===1;)if(s++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return yI;let i=n.pow(s,e),o=(e+Gr)/qc;return function(c,d){if(c.is0(d))return d;if(fI(c,d)!==1)throw new Error("Cannot find square root");let u=t,f=c.mul(c.ONE,i),h=c.pow(d,e),y=c.pow(d,o);for(;!c.eql(h,c.ONE);){if(c.is0(h))return c.ZERO;let v=1,S=c.sqr(h);for(;!c.eql(S,c.ONE);)if(v++,S=c.sqr(S),v===u)throw new Error("Cannot find square root");let C=Gr<<BigInt(u-v-1),O=c.pow(f,C);u=v,f=c.sqr(O),h=c.mul(h,f),y=c.mul(y,O)}return y}}function QH(r){return r%hI===lI?yI:r%mI===pI?YH:r%gI===XH?JH(r):xI(r)}function lS(r){let e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},t=ZH.reduce((s,n)=>(s[n]="function",s),e);return $h(r,t),r}function eF(r,e,t){if(t<xs)throw new Error("invalid exponent, negatives unsupported");if(t===xs)return r.ONE;if(t===Gr)return e;let s=r.ONE,n=e;for(;t>xs;)t&Gr&&(s=r.mul(s,n)),n=r.sqr(n),t>>=Gr;return s}function ay(r,e,t=!1){let s=new Array(e.length).fill(t?r.ZERO:void 0),n=e.reduce((o,a,c)=>r.is0(a)?o:(s[c]=o,r.mul(o,a)),r.ONE),i=r.inv(n);return e.reduceRight((o,a,c)=>r.is0(a)?o:(s[c]=r.mul(o,s[c]),r.mul(o,a)),i),s}function fI(r,e){let t=(r.ORDER-Gr)/qc,s=r.pow(e,t),n=r.eql(s,r.ONE),i=r.eql(s,r.ZERO),o=r.eql(s,r.neg(r.ONE));if(!n&&!i&&!o)throw new Error("invalid Legendre symbol result");return n?1:i?0:-1}function cy(r,e){e!==void 0&&Hh(e);let t=e!==void 0?e:r.toString(2).length,s=Math.ceil(t/8);return{nBitLength:t,nByteLength:s}}function ei(r,e,t=!1,s={}){if(r<=xs)throw new Error("invalid field: expected ORDER > 0, got "+r);let n,i,o=!1,a;if(typeof e=="object"&&e!=null){if(s.sqrt||t)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"&&(t=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}=cy(r,n);if(d>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let u,f=Object.freeze({ORDER:r,isLE:t,BITS:c,BYTES:d,MASK:aa(c),ZERO:xs,ONE:Gr,allowedLengths:a,create:h=>gn(h,r),isValid:h=>{if(typeof h!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof h);return xs<=h&&h<r},is0:h=>h===xs,isValidNot0:h=>!f.is0(h)&&f.isValid(h),isOdd:h=>(h&Gr)===Gr,neg:h=>gn(-h,r),eql:(h,y)=>h===y,sqr:h=>gn(h*h,r),add:(h,y)=>gn(h+y,r),sub:(h,y)=>gn(h-y,r),mul:(h,y)=>gn(h*y,r),pow:(h,y)=>eF(f,h,y),div:(h,y)=>gn(h*uI(y,r),r),sqrN:h=>h*h,addN:(h,y)=>h+y,subN:(h,y)=>h-y,mulN:(h,y)=>h*y,inv:h=>uI(h,r),sqrt:i||(h=>(u||(u=QH(r)),u(f,h))),toBytes:h=>t?dS(h,d):ny(h,d),fromBytes:(h,y=!0)=>{if(a){if(!a.includes(h.length)||h.length>d)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+h.length);let S=new Uint8Array(d);S.set(h,t?0:S.length-h.length),h=S}if(h.length!==d)throw new Error("Field.fromBytes: expected "+d+" bytes, got "+h.length);let v=t?cS(h):Pu(h);if(o&&(v=gn(v,r)),!y&&!f.isValid(v))throw new Error("invalid field element: outside of range 0..ORDER");return v},invertBatch:h=>ay(f,h),cmov:(h,y,v)=>v?y:h});return Object.freeze(f)}function bI(r){if(typeof r!="bigint")throw new Error("field order must be bigint");let e=r.toString(2).length;return Math.ceil(e/8)}function hS(r){let e=bI(r);return e+Math.ceil(e/2)}function vI(r,e,t=!1){let s=r.length,n=bI(e),i=hS(e);if(s<16||s<i||s>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+s);let o=t?cS(r):Pu(r),a=gn(o,e-Gr)+Gr;return t?dS(a,n):ny(a,n)}var xs,Gr,qc,lI,hI,pI,GH,mI,XH,gI,ZH,dy=T(()=>{"use strict";oy();xs=BigInt(0),Gr=BigInt(1),qc=BigInt(2),lI=BigInt(3),hI=BigInt(4),pI=BigInt(5),GH=BigInt(7),mI=BigInt(8),XH=BigInt(9),gI=BigInt(16);ZH=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"]});function tF(r,e,t,s){if(typeof r.setBigUint64=="function")return r.setBigUint64(e,t,s);let n=BigInt(32),i=BigInt(4294967295),o=Number(t>>n&i),a=Number(t&i),c=s?4:0,d=s?0:4;r.setUint32(e+c,o,s),r.setUint32(e+d,a,s)}function wI(r,e,t){return r&e^~r&t}function SI(r,e,t){return r&e^r&t^e&t}var Vh,Wi,Or,Lr,_I=T(()=>{"use strict";Fc();Vh=class extends Ru{constructor(e,t,s,n){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=s,this.isLE=n,this.buffer=new Uint8Array(e),this.view=ty(this.buffer)}update(e){ku(this),e=Fh(e),hn(e);let{view:t,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=ty(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(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){ku(this),sI(e,this),this.finished=!0;let{buffer:t,view:s,blockLen:n,isLE:i}=this,{pos:o}=this;t[o++]=128,Vi(this.buffer.subarray(o)),this.padOffset>n-o&&(this.process(s,0),o=0);for(let f=o;f<n;f++)t[f]=0;tF(s,n-8,BigInt(this.length*8),i),this.process(s,0);let a=ty(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 f=0;f<d;f++)a.setUint32(4*f,u[f],i)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let s=e.slice(0,t);return this.destroy(),s}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:t,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%t&&e.buffer.set(s),e}clone(){return this._cloneInto()}},Wi=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Or=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]),Lr=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209])});function rF(r,e=!1){return e?{h:Number(r&uy),l:Number(r>>EI&uy)}:{h:Number(r>>EI&uy)|0,l:Number(r&uy)|0}}function CI(r,e=!1){let t=r.length,s=new Uint32Array(t),n=new Uint32Array(t);for(let i=0;i<t;i++){let{h:o,l:a}=rF(r[i],e);[s[i],n[i]]=[o,a]}return[s,n]}function ti(r,e,t,s){let n=(e>>>0)+(s>>>0);return{h:r+t+(n/2**32|0)|0,l:n|0}}var uy,EI,pS,mS,zc,$c,Kh,Wh,TI,AI,II,RI,kI,PI,BI=T(()=>{"use strict";uy=BigInt(4294967295),EI=BigInt(32);pS=(r,e,t)=>r>>>t,mS=(r,e,t)=>r<<32-t|e>>>t,zc=(r,e,t)=>r>>>t|e<<32-t,$c=(r,e,t)=>r<<32-t|e>>>t,Kh=(r,e,t)=>r<<64-t|e>>>t-32,Wh=(r,e,t)=>r>>>t-32|e<<64-t;TI=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),AI=(r,e,t,s)=>e+t+s+(r/2**32|0)|0,II=(r,e,t,s)=>(r>>>0)+(e>>>0)+(t>>>0)+(s>>>0),RI=(r,e,t,s,n)=>e+t+s+n+(r/2**32|0)|0,kI=(r,e,t,s,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(s>>>0)+(n>>>0),PI=(r,e,t,s,n,i)=>e+t+s+n+i+(r/2**32|0)|0});var nF,ca,gS,NI,iF,oF,da,ua,fy,yS,OI,LI,DI,MI=T(()=>{"use strict";_I();BI();Fc();nF=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]),ca=new Uint32Array(64),gS=class extends Vh{constructor(e=32){super(64,e,8,!1),this.A=Wi[0]|0,this.B=Wi[1]|0,this.C=Wi[2]|0,this.D=Wi[3]|0,this.E=Wi[4]|0,this.F=Wi[5]|0,this.G=Wi[6]|0,this.H=Wi[7]|0}get(){let{A:e,B:t,C:s,D:n,E:i,F:o,G:a,H:c}=this;return[e,t,s,n,i,o,a,c]}set(e,t,s,n,i,o,a,c){this.A=e|0,this.B=t|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,t){for(let f=0;f<16;f++,t+=4)ca[f]=e.getUint32(t,!1);for(let f=16;f<64;f++){let h=ca[f-15],y=ca[f-2],v=pn(h,7)^pn(h,18)^h>>>3,S=pn(y,17)^pn(y,19)^y>>>10;ca[f]=S+ca[f-7]+v+ca[f-16]|0}let{A:s,B:n,C:i,D:o,E:a,F:c,G:d,H:u}=this;for(let f=0;f<64;f++){let h=pn(a,6)^pn(a,11)^pn(a,25),y=u+h+wI(a,c,d)+nF[f]+ca[f]|0,S=(pn(s,2)^pn(s,13)^pn(s,22))+SI(s,n,i)|0;u=d,d=c,c=a,a=o+y|0,o=i,i=n,n=s,s=y+S|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(){Vi(ca)}destroy(){this.set(0,0,0,0,0,0,0,0),Vi(this.buffer)}},NI=CI(["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(r=>BigInt(r))),iF=NI[0],oF=NI[1],da=new Uint32Array(80),ua=new Uint32Array(80),fy=class extends Vh{constructor(e=64){super(128,e,16,!1),this.Ah=Lr[0]|0,this.Al=Lr[1]|0,this.Bh=Lr[2]|0,this.Bl=Lr[3]|0,this.Ch=Lr[4]|0,this.Cl=Lr[5]|0,this.Dh=Lr[6]|0,this.Dl=Lr[7]|0,this.Eh=Lr[8]|0,this.El=Lr[9]|0,this.Fh=Lr[10]|0,this.Fl=Lr[11]|0,this.Gh=Lr[12]|0,this.Gl=Lr[13]|0,this.Hh=Lr[14]|0,this.Hl=Lr[15]|0}get(){let{Ah:e,Al:t,Bh:s,Bl:n,Ch:i,Cl:o,Dh:a,Dl:c,Eh:d,El:u,Fh:f,Fl:h,Gh:y,Gl:v,Hh:S,Hl:C}=this;return[e,t,s,n,i,o,a,c,d,u,f,h,y,v,S,C]}set(e,t,s,n,i,o,a,c,d,u,f,h,y,v,S,C){this.Ah=e|0,this.Al=t|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=f|0,this.Fl=h|0,this.Gh=y|0,this.Gl=v|0,this.Hh=S|0,this.Hl=C|0}process(e,t){for(let z=0;z<16;z++,t+=4)da[z]=e.getUint32(t),ua[z]=e.getUint32(t+=4);for(let z=16;z<80;z++){let Q=da[z-15]|0,oe=ua[z-15]|0,se=zc(Q,oe,1)^zc(Q,oe,8)^pS(Q,oe,7),we=$c(Q,oe,1)^$c(Q,oe,8)^mS(Q,oe,7),me=da[z-2]|0,Y=ua[z-2]|0,Ze=zc(me,Y,19)^Kh(me,Y,61)^pS(me,Y,6),Tt=$c(me,Y,19)^Wh(me,Y,61)^mS(me,Y,6),Fe=II(we,Tt,ua[z-7],ua[z-16]),V=RI(Fe,se,Ze,da[z-7],da[z-16]);da[z]=V|0,ua[z]=Fe|0}let{Ah:s,Al:n,Bh:i,Bl:o,Ch:a,Cl:c,Dh:d,Dl:u,Eh:f,El:h,Fh:y,Fl:v,Gh:S,Gl:C,Hh:O,Hl:K}=this;for(let z=0;z<80;z++){let Q=zc(f,h,14)^zc(f,h,18)^Kh(f,h,41),oe=$c(f,h,14)^$c(f,h,18)^Wh(f,h,41),se=f&y^~f&S,we=h&v^~h&C,me=kI(K,oe,we,oF[z],ua[z]),Y=PI(me,O,Q,se,iF[z],da[z]),Ze=me|0,Tt=zc(s,n,28)^Kh(s,n,34)^Kh(s,n,39),Fe=$c(s,n,28)^Wh(s,n,34)^Wh(s,n,39),V=s&i^s&a^i&a,D=n&o^n&c^o&c;O=S|0,K=C|0,S=y|0,C=v|0,y=f|0,v=h|0,{h:f,l:h}=ti(d|0,u|0,Y|0,Ze|0),d=a|0,u=c|0,a=i|0,c=o|0,i=s|0,o=n|0;let F=TI(Ze,Fe,D);s=AI(F,Y,Tt,V),n=F|0}({h:s,l:n}=ti(this.Ah|0,this.Al|0,s|0,n|0)),{h:i,l:o}=ti(this.Bh|0,this.Bl|0,i|0,o|0),{h:a,l:c}=ti(this.Ch|0,this.Cl|0,a|0,c|0),{h:d,l:u}=ti(this.Dh|0,this.Dl|0,d|0,u|0),{h:f,l:h}=ti(this.Eh|0,this.El|0,f|0,h|0),{h:y,l:v}=ti(this.Fh|0,this.Fl|0,y|0,v|0),{h:S,l:C}=ti(this.Gh|0,this.Gl|0,S|0,C|0),{h:O,l:K}=ti(this.Hh|0,this.Hl|0,O|0,K|0),this.set(s,n,i,o,a,c,d,u,f,h,y,v,S,C,O,K)}roundClean(){Vi(da,ua)}destroy(){Vi(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},yS=class extends fy{constructor(){super(48),this.Ah=Or[0]|0,this.Al=Or[1]|0,this.Bh=Or[2]|0,this.Bl=Or[3]|0,this.Ch=Or[4]|0,this.Cl=Or[5]|0,this.Dh=Or[6]|0,this.Dl=Or[7]|0,this.Eh=Or[8]|0,this.El=Or[9]|0,this.Fh=Or[10]|0,this.Fl=Or[11]|0,this.Gh=Or[12]|0,this.Gl=Or[13]|0,this.Hh=Or[14]|0,this.Hl=Or[15]|0}},OI=ry(()=>new gS),LI=ry(()=>new fy),DI=ry(()=>new yS)});var ly,xS,UI=T(()=>{"use strict";Fc();ly=class extends Ru{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,ey(e);let s=Fh(t);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),Vi(i)}update(e){return ku(this),this.iHash.update(e),this}digestInto(e){ku(this),hn(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:t,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=t._cloneInto(e.oHash),e.iHash=s._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},xS=(r,e,t)=>new ly(r,e).update(t).digest();xS.create=(r,e)=>new ly(r,e)});function Gh(r,e){let t=e.negate();return r?t:e}function py(r,e){let t=ay(r.Fp,e.map(s=>s.Z));return e.map((s,n)=>r.fromAffine(s.toAffine(t[n])))}function qI(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function bS(r,e){qI(r,e);let t=Math.ceil(e/r)+1,s=2**(r-1),n=2**r,i=aa(r),o=BigInt(r);return{windows:t,windowSize:s,mask:i,maxNumber:n,shiftBy:o}}function jI(r,e,t){let{windowSize:s,mask:n,maxNumber:i,shiftBy:o}=t,a=Number(r&n),c=r>>o;a>s&&(a-=i,c+=Vc);let d=e*s,u=d+Math.abs(a)-1,f=a===0,h=a<0,y=e%2!==0;return{nextN:c,offset:u,isZero:f,isNeg:h,isNegF:y,offsetF:d}}function aF(r,e){if(!Array.isArray(r))throw new Error("array expected");r.forEach((t,s)=>{if(!(t instanceof e))throw new Error("invalid point at index "+s)})}function cF(r,e){if(!Array.isArray(r))throw new Error("array of scalars expected");r.forEach((t,s)=>{if(!e.isValid(t))throw new Error("invalid scalar at index "+s)})}function wS(r){return zI.get(r)||1}function HI(r){if(r!==Bu)throw new Error("invalid wNAF")}function $I(r,e,t,s){let n=e,i=r.ZERO,o=r.ZERO;for(;t>Bu||s>Bu;)t&Vc&&(i=i.add(n)),s&Vc&&(o=o.add(n)),n=n.double(),t>>=Vc,s>>=Vc;return{p1:i,p2:o}}function VI(r,e,t,s){aF(t,r),cF(s,e);let n=t.length,i=s.length;if(n!==i)throw new Error("arrays of points and scalars must have equal length");let o=r.ZERO,a=iy(BigInt(n)),c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);let d=aa(c),u=new Array(Number(d)+1).fill(o),f=Math.floor((e.BITS-1)/c)*c,h=o;for(let y=f;y>=0;y-=c){u.fill(o);for(let S=0;S<i;S++){let C=s[S],O=Number(C>>BigInt(y)&d);u[O]=u[O].add(t[S])}let v=o;for(let S=u.length-1,C=o;S>0;S--)C=C.add(u[S]),v=v.add(C);if(h=h.add(v),y!==0)for(let S=0;S<c;S++)h=h.double()}return h}function FI(r,e,t){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return lS(e),e}else return ei(r,{isLE:t})}function KI(r,e,t={},s){if(s===void 0&&(s=r==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${r} CURVE object`);for(let c of["p","n","h"]){let d=e[c];if(!(typeof d=="bigint"&&d>Bu))throw new Error(`CURVE.${c} must be positive bigint`)}let n=FI(e.p,t.Fp,s),i=FI(e.n,t.Fn,s),a=["Gx","Gy","a",r==="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 Bu,Vc,vS,zI,hy,WI=T(()=>{"use strict";oy();dy();Bu=BigInt(0),Vc=BigInt(1);vS=new WeakMap,zI=new WeakMap;hy=class{constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,s=this.ZERO){let n=e;for(;t>Bu;)t&Vc&&(s=s.add(n)),n=n.double(),t>>=Vc;return s}precomputeWindow(e,t){let{windows:s,windowSize:n}=bS(t,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,t,s){if(!this.Fn.isValid(s))throw new Error("invalid scalar");let n=this.ZERO,i=this.BASE,o=bS(e,this.bits);for(let a=0;a<o.windows;a++){let{nextN:c,offset:d,isZero:u,isNeg:f,isNegF:h,offsetF:y}=jI(s,a,o);s=c,u?i=i.add(Gh(h,t[y])):n=n.add(Gh(f,t[d]))}return HI(s),{p:n,f:i}}wNAFUnsafe(e,t,s,n=this.ZERO){let i=bS(e,this.bits);for(let o=0;o<i.windows&&s!==Bu;o++){let{nextN:a,offset:c,isZero:d,isNeg:u}=jI(s,o,i);if(s=a,!d){let f=t[c];n=n.add(u?f.negate():f)}}return HI(s),n}getPrecomputes(e,t,s){let n=vS.get(t);return n||(n=this.precomputeWindow(t,e),e!==1&&(typeof s=="function"&&(n=s(n)),vS.set(t,n))),n}cached(e,t,s){let n=wS(e);return this.wNAF(n,this.getPrecomputes(n,e,s),t)}unsafe(e,t,s,n){let i=wS(e);return i===1?this._unsafeLadder(e,t,n):this.wNAFUnsafe(i,this.getPrecomputes(i,e,s),t,n)}createCache(e,t){qI(t,this.bits),zI.set(e,t),vS.delete(e)}hasCache(e){return wS(e)!==1}}});function dF(r,e,t){let[[s,n],[i,o]]=e,a=GI(o*r,t),c=GI(-n*r,t),d=r-a*s-c*i,u=-a*n-c*o,f=d<Xi,h=u<Xi;f&&(d=-d),h&&(u=-u);let y=aa(Math.ceil(iy(t)/2))+Ou;if(d<Xi||d>=y||u<Xi||u>=y)throw new Error("splitScalar (endomorphism): failed, k="+r);return{k1neg:f,k1:d,k2neg:h,k2:u}}function _S(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function SS(r,e){let t={};for(let s of Object.keys(e))t[s]=r[s]===void 0?e[s]:r[s];return qh(t.lowS,"lowS"),qh(t.prehash,"prehash"),t.format!==void 0&&_S(t.format),t}function Nu(r,e){let{BYTES:t}=r,s;if(typeof e=="bigint")s=e;else{let n=Wr("private key",e);try{s=r.fromBytes(n)}catch{throw new Error(`invalid private key: expected ui8a of size ${t}, got ${typeof e}`)}}if(!r.isValidNot0(s))throw new Error("invalid private key: out of range [1..N-1]");return s}function fF(r,e={}){let t=KI("weierstrass",r,e),{Fp:s,Fn:n}=t,i=t.CURVE,{h:o,n:a}=i;$h(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=JI(s,n);function u(){if(!s.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function f(Fe,V,D){let{x:F,y:le}=V.toAffine(),Ae=s.toBytes(F);if(qh(D,"isCompressed"),D){u();let Oe=!s.isOdd(le);return mn(YI(Oe),Ae)}else return mn(Uint8Array.of(4),Ae,s.toBytes(le))}function h(Fe){oa(Fe,void 0,"Point");let{publicKey:V,publicKeyUncompressed:D}=d,F=Fe.length,le=Fe[0],Ae=Fe.subarray(1);if(F===V&&(le===2||le===3)){let Oe=s.fromBytes(Ae);if(!s.isValid(Oe))throw new Error("bad point: is not on curve, wrong x");let A=S(Oe),R;try{R=s.sqrt(A)}catch(L){let ae=L instanceof Error?": "+L.message:"";throw new Error("bad point: is not on curve, sqrt error"+ae)}u();let q=s.isOdd(R);return(le&1)===1!==q&&(R=s.neg(R)),{x:Oe,y:R}}else if(F===D&&le===4){let Oe=s.BYTES,A=s.fromBytes(Ae.subarray(0,Oe)),R=s.fromBytes(Ae.subarray(Oe,Oe*2));if(!C(A,R))throw new Error("bad point: is not on curve");return{x:A,y:R}}else throw new Error(`bad point: got length ${F}, expected compressed=${V} or uncompressed=${D}`)}let y=e.toBytes||f,v=e.fromBytes||h;function S(Fe){let V=s.sqr(Fe),D=s.mul(V,Fe);return s.add(s.add(D,s.mul(Fe,i.a)),i.b)}function C(Fe,V){let D=s.sqr(V),F=S(Fe);return s.eql(D,F)}if(!C(i.Gx,i.Gy))throw new Error("bad curve params: generator point");let O=s.mul(s.pow(i.a,my),uF),K=s.mul(s.sqr(i.b),BigInt(27));if(s.is0(s.add(O,K)))throw new Error("bad curve params: a or b");function z(Fe,V,D=!1){if(!s.isValid(V)||D&&s.is0(V))throw new Error(`bad point coordinate ${Fe}`);return V}function Q(Fe){if(!(Fe instanceof Y))throw new Error("ProjectivePoint expected")}function oe(Fe){if(!c||!c.basises)throw new Error("no endo");return dF(Fe,c.basises,n.ORDER)}let se=uS((Fe,V)=>{let{X:D,Y:F,Z:le}=Fe;if(s.eql(le,s.ONE))return{x:D,y:F};let Ae=Fe.is0();V==null&&(V=Ae?s.ONE:s.inv(le));let Oe=s.mul(D,V),A=s.mul(F,V),R=s.mul(le,V);if(Ae)return{x:s.ZERO,y:s.ZERO};if(!s.eql(R,s.ONE))throw new Error("invZ was invalid");return{x:Oe,y:A}}),we=uS(Fe=>{if(Fe.is0()){if(e.allowInfinityPoint&&!s.is0(Fe.Y))return;throw new Error("bad point: ZERO")}let{x:V,y:D}=Fe.toAffine();if(!s.isValid(V)||!s.isValid(D))throw new Error("bad point: x or y not field elements");if(!C(V,D))throw new Error("bad point: equation left != right");if(!Fe.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function me(Fe,V,D,F,le){return D=new Y(s.mul(D.X,Fe),D.Y,D.Z),V=Gh(F,V),D=Gh(le,D),V.add(D)}class Y{constructor(V,D,F){this.X=z("x",V),this.Y=z("y",D,!0),this.Z=z("z",F),Object.freeze(this)}static CURVE(){return i}static fromAffine(V){let{x:D,y:F}=V||{};if(!V||!s.isValid(D)||!s.isValid(F))throw new Error("invalid affine point");if(V instanceof Y)throw new Error("projective point not allowed");return s.is0(D)&&s.is0(F)?Y.ZERO:new Y(D,F,s.ONE)}static fromBytes(V){let D=Y.fromAffine(v(oa(V,void 0,"point")));return D.assertValidity(),D}static fromHex(V){return Y.fromBytes(Wr("pointHex",V))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(V=8,D=!0){return Tt.createCache(this,V),D||this.multiply(my),this}assertValidity(){we(this)}hasEvenY(){let{y:V}=this.toAffine();if(!s.isOdd)throw new Error("Field doesn't support isOdd");return!s.isOdd(V)}equals(V){Q(V);let{X:D,Y:F,Z:le}=this,{X:Ae,Y:Oe,Z:A}=V,R=s.eql(s.mul(D,A),s.mul(Ae,le)),q=s.eql(s.mul(F,A),s.mul(Oe,le));return R&&q}negate(){return new Y(this.X,s.neg(this.Y),this.Z)}double(){let{a:V,b:D}=i,F=s.mul(D,my),{X:le,Y:Ae,Z:Oe}=this,A=s.ZERO,R=s.ZERO,q=s.ZERO,I=s.mul(le,le),L=s.mul(Ae,Ae),ae=s.mul(Oe,Oe),he=s.mul(le,Ae);return he=s.add(he,he),q=s.mul(le,Oe),q=s.add(q,q),A=s.mul(V,q),R=s.mul(F,ae),R=s.add(A,R),A=s.sub(L,R),R=s.add(L,R),R=s.mul(A,R),A=s.mul(he,A),q=s.mul(F,q),ae=s.mul(V,ae),he=s.sub(I,ae),he=s.mul(V,he),he=s.add(he,q),q=s.add(I,I),I=s.add(q,I),I=s.add(I,ae),I=s.mul(I,he),R=s.add(R,I),ae=s.mul(Ae,Oe),ae=s.add(ae,ae),I=s.mul(ae,he),A=s.sub(A,I),q=s.mul(ae,L),q=s.add(q,q),q=s.add(q,q),new Y(A,R,q)}add(V){Q(V);let{X:D,Y:F,Z:le}=this,{X:Ae,Y:Oe,Z:A}=V,R=s.ZERO,q=s.ZERO,I=s.ZERO,L=i.a,ae=s.mul(i.b,my),he=s.mul(D,Ae),ct=s.mul(F,Oe),xt=s.mul(le,A),Ot=s.add(D,F),St=s.add(Ae,Oe);Ot=s.mul(Ot,St),St=s.add(he,ct),Ot=s.sub(Ot,St),St=s.add(D,le);let Dt=s.add(Ae,A);return St=s.mul(St,Dt),Dt=s.add(he,xt),St=s.sub(St,Dt),Dt=s.add(F,le),R=s.add(Oe,A),Dt=s.mul(Dt,R),R=s.add(ct,xt),Dt=s.sub(Dt,R),I=s.mul(L,St),R=s.mul(ae,xt),I=s.add(R,I),R=s.sub(ct,I),I=s.add(ct,I),q=s.mul(R,I),ct=s.add(he,he),ct=s.add(ct,he),xt=s.mul(L,xt),St=s.mul(ae,St),ct=s.add(ct,xt),xt=s.sub(he,xt),xt=s.mul(L,xt),St=s.add(St,xt),he=s.mul(ct,St),q=s.add(q,he),he=s.mul(Dt,St),R=s.mul(Ot,R),R=s.sub(R,he),he=s.mul(Ot,ct),I=s.mul(Dt,I),I=s.add(I,he),new Y(R,q,I)}subtract(V){return this.add(V.negate())}is0(){return this.equals(Y.ZERO)}multiply(V){let{endo:D}=e;if(!n.isValidNot0(V))throw new Error("invalid scalar: out of range");let F,le,Ae=Oe=>Tt.cached(this,Oe,A=>py(Y,A));if(D){let{k1neg:Oe,k1:A,k2neg:R,k2:q}=oe(V),{p:I,f:L}=Ae(A),{p:ae,f:he}=Ae(q);le=L.add(he),F=me(D.beta,I,ae,Oe,R)}else{let{p:Oe,f:A}=Ae(V);F=Oe,le=A}return py(Y,[F,le])[0]}multiplyUnsafe(V){let{endo:D}=e,F=this;if(!n.isValid(V))throw new Error("invalid scalar: out of range");if(V===Xi||F.is0())return Y.ZERO;if(V===Ou)return F;if(Tt.hasCache(this))return this.multiply(V);if(D){let{k1neg:le,k1:Ae,k2neg:Oe,k2:A}=oe(V),{p1:R,p2:q}=$I(Y,F,Ae,A);return me(D.beta,R,q,le,Oe)}else return Tt.unsafe(F,V)}multiplyAndAddUnsafe(V,D,F){let le=this.multiplyUnsafe(D).add(V.multiplyUnsafe(F));return le.is0()?void 0:le}toAffine(V){return se(this,V)}isTorsionFree(){let{isTorsionFree:V}=e;return o===Ou?!0:V?V(Y,this):Tt.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:V}=e;return o===Ou?this:V?V(Y,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(V=!0){return qh(V,"isCompressed"),this.assertValidity(),y(Y,this,V)}toHex(V=!0){return Ki(this.toBytes(V))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(V=!0){return this.toBytes(V)}_setWindowSize(V){this.precompute(V)}static normalizeZ(V){return py(Y,V)}static msm(V,D){return VI(Y,n,V,D)}static fromPrivateKey(V){return Y.BASE.multiply(Nu(n,V))}}Y.BASE=new Y(i.Gx,i.Gy,s.ONE),Y.ZERO=new Y(s.ZERO,s.ONE,s.ZERO),Y.Fp=s,Y.Fn=n;let Ze=n.BITS,Tt=new hy(Y,e.endo?Math.ceil(Ze/2):Ze);return Y.BASE.precompute(8),Y}function YI(r){return Uint8Array.of(r?2:3)}function JI(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function lF(r,e={}){let{Fn:t}=r,s=e.randomBytes||sy,n=Object.assign(JI(r.Fp,t),{seed:hS(t.ORDER)});function i(y){try{return!!Nu(t,y)}catch{return!1}}function o(y,v){let{publicKey:S,publicKeyUncompressed:C}=n;try{let O=y.length;return v===!0&&O!==S||v===!1&&O!==C?!1:!!r.fromBytes(y)}catch{return!1}}function a(y=s(n.seed)){return vI(oa(y,n.seed,"seed"),t.ORDER)}function c(y,v=!0){return r.BASE.multiply(Nu(t,y)).toBytes(v)}function d(y){let v=a(y);return{secretKey:v,publicKey:c(v)}}function u(y){if(typeof y=="bigint")return!1;if(y instanceof r)return!0;let{secretKey:v,publicKey:S,publicKeyUncompressed:C}=n;if(t.allowedLengths||v===S)return;let O=Wr("key",y).length;return O===S||O===C}function f(y,v,S=!0){if(u(y)===!0)throw new Error("first arg must be private key");if(u(v)===!1)throw new Error("second arg must be public key");let C=Nu(t,y);return r.fromHex(v).multiply(C).toBytes(S)}return Object.freeze({getPublicKey:c,getSharedSecret:f,keygen:d,Point:r,utils:{isValidSecretKey:i,isValidPublicKey:o,randomSecretKey:a,isValidPrivateKey:i,randomPrivateKey:a,normPrivateKeyToScalar:y=>Nu(t,y),precompute(y=8,v=r.BASE){return v.precompute(y,!1)}},lengths:n})}function hF(r,e,t={}){ey(e),$h(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let s=t.randomBytes||sy,n=t.hmac||((D,...F)=>xS(e,D,mn(...F))),{Fp:i,Fn:o}=r,{ORDER:a,BITS:c}=o,{keygen:d,getPublicKey:u,getSharedSecret:f,utils:h,lengths:y}=lF(r,t),v={prehash:!1,lowS:typeof t.lowS=="boolean"?t.lowS:!1,format:void 0,extraEntropy:!1},S="compact";function C(D){let F=a>>Ou;return D>F}function O(D,F){if(!o.isValidNot0(F))throw new Error(`invalid signature ${D}: out of range 1..Point.Fn.ORDER`);return F}function K(D,F){_S(F);let le=y.signature,Ae=F==="compact"?le:F==="recovered"?le+1:void 0;return oa(D,Ae,`${F} signature`)}class z{constructor(F,le,Ae){this.r=O("r",F),this.s=O("s",le),Ae!=null&&(this.recovery=Ae),Object.freeze(this)}static fromBytes(F,le=S){K(F,le);let Ae;if(le==="der"){let{r:q,s:I}=Gi.toSig(oa(F));return new z(q,I)}le==="recovered"&&(Ae=F[0],le="compact",F=F.subarray(1));let Oe=o.BYTES,A=F.subarray(0,Oe),R=F.subarray(Oe,Oe*2);return new z(o.fromBytes(A),o.fromBytes(R),Ae)}static fromHex(F,le){return this.fromBytes(Hc(F),le)}addRecoveryBit(F){return new z(this.r,this.s,F)}recoverPublicKey(F){let le=i.ORDER,{r:Ae,s:Oe,recovery:A}=this;if(A==null||![0,1,2,3].includes(A))throw new Error("recovery id invalid");if(a*XI<le&&A>1)throw new Error("recovery id is ambiguous for h>1 curve");let q=A===2||A===3?Ae+a:Ae;if(!i.isValid(q))throw new Error("recovery id 2 or 3 invalid");let I=i.toBytes(q),L=r.fromBytes(mn(YI((A&1)===0),I)),ae=o.inv(q),he=oe(Wr("msgHash",F)),ct=o.create(-he*ae),xt=o.create(Oe*ae),Ot=r.BASE.multiplyUnsafe(ct).add(L.multiplyUnsafe(xt));if(Ot.is0())throw new Error("point at infinify");return Ot.assertValidity(),Ot}hasHighS(){return C(this.s)}toBytes(F=S){if(_S(F),F==="der")return Hc(Gi.hexFromSig(this));let le=o.toBytes(this.r),Ae=o.toBytes(this.s);if(F==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return mn(Uint8Array.of(this.recovery),le,Ae)}return mn(le,Ae)}toHex(F){return Ki(this.toBytes(F))}assertValidity(){}static fromCompact(F){return z.fromBytes(Wr("sig",F),"compact")}static fromDER(F){return z.fromBytes(Wr("sig",F),"der")}normalizeS(){return this.hasHighS()?new z(this.r,o.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return Ki(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return Ki(this.toBytes("compact"))}}let Q=t.bits2int||function(F){if(F.length>8192)throw new Error("input is too large");let le=Pu(F),Ae=F.length*8-c;return Ae>0?le>>BigInt(Ae):le},oe=t.bits2int_modN||function(F){return o.create(Q(F))},se=aa(c);function we(D){return cI("num < 2^"+c,D,Xi,se),o.toBytes(D)}function me(D,F){return oa(D,void 0,"message"),F?oa(e(D),void 0,"prehashed message"):D}function Y(D,F,le){if(["recovered","canonical"].some(ct=>ct in le))throw new Error("sign() legacy options not supported");let{lowS:Ae,prehash:Oe,extraEntropy:A}=SS(le,v);D=me(D,Oe);let R=oe(D),q=Nu(o,F),I=[we(q),we(R)];if(A!=null&&A!==!1){let ct=A===!0?s(y.secretKey):A;I.push(Wr("extraEntropy",ct))}let L=mn(...I),ae=R;function he(ct){let xt=Q(ct);if(!o.isValidNot0(xt))return;let Ot=o.inv(xt),St=r.BASE.multiply(xt).toAffine(),Dt=o.create(St.x);if(Dt===Xi)return;let Bs=o.create(Ot*o.create(ae+Dt*q));if(Bs===Xi)return;let Ns=(St.x===Dt?0:2)|Number(St.y&Ou),Ca=Bs;return Ae&&C(Bs)&&(Ca=o.neg(Bs),Ns^=1),new z(Dt,Ca,Ns)}return{seed:L,k2sig:he}}function Ze(D,F,le={}){D=Wr("message",D);let{seed:Ae,k2sig:Oe}=Y(D,F,le);return dI(e.outputLen,o.BYTES,n)(Ae,Oe)}function Tt(D){let F,le=typeof D=="string"||jc(D),Ae=!le&&D!==null&&typeof D=="object"&&typeof D.r=="bigint"&&typeof D.s=="bigint";if(!le&&!Ae)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(Ae)F=new z(D.r,D.s);else if(le){try{F=z.fromBytes(Wr("sig",D),"der")}catch(Oe){if(!(Oe instanceof Gi.Err))throw Oe}if(!F)try{F=z.fromBytes(Wr("sig",D),"compact")}catch{return!1}}return F||!1}function Fe(D,F,le,Ae={}){let{lowS:Oe,prehash:A,format:R}=SS(Ae,v);if(le=Wr("publicKey",le),F=me(Wr("message",F),A),"strict"in Ae)throw new Error("options.strict was renamed to lowS");let q=R===void 0?Tt(D):z.fromBytes(Wr("sig",D),R);if(q===!1)return!1;try{let I=r.fromBytes(le);if(Oe&&q.hasHighS())return!1;let{r:L,s:ae}=q,he=oe(F),ct=o.inv(ae),xt=o.create(he*ct),Ot=o.create(L*ct),St=r.BASE.multiplyUnsafe(xt).add(I.multiplyUnsafe(Ot));return St.is0()?!1:o.create(St.x)===L}catch{return!1}}function V(D,F,le={}){let{prehash:Ae}=SS(le,v);return F=me(F,Ae),z.fromBytes(D,"recovered").recoverPublicKey(F).toBytes()}return Object.freeze({keygen:d,getPublicKey:u,getSharedSecret:f,utils:h,lengths:y,Point:r,sign:Ze,verify:Fe,recoverPublicKey:V,Signature:z,hash:e})}function pF(r){let e={a:r.a,b:r.b,p:r.Fp.ORDER,n:r.n,h:r.h,Gx:r.Gx,Gy:r.Gy},t=r.Fp,s=r.allowedPrivateKeyLengths?Array.from(new Set(r.allowedPrivateKeyLengths.map(o=>Math.ceil(o/2)))):void 0,n=ei(e.n,{BITS:r.nBitLength,allowedLengths:s,modFromBytes:r.wrapPrivateKey}),i={Fp:t,Fn:n,allowInfinityPoint:r.allowInfinityPoint,endo:r.endo,isTorsionFree:r.isTorsionFree,clearCofactor:r.clearCofactor,fromBytes:r.fromBytes,toBytes:r.toBytes};return{CURVE:e,curveOpts:i}}function mF(r){let{CURVE:e,curveOpts:t}=pF(r),s={hmac:r.hmac,randomBytes:r.randomBytes,lowS:r.lowS,bits2int:r.bits2int,bits2int_modN:r.bits2int_modN};return{CURVE:e,curveOpts:t,hash:r.hash,ecdsaOpts:s}}function gF(r,e){let t=e.Point;return Object.assign({},e,{ProjectivePoint:t,CURVE:Object.assign({},r,cy(t.Fn.ORDER,t.Fn.BITS))})}function QI(r){let{CURVE:e,curveOpts:t,hash:s,ecdsaOpts:n}=mF(r),i=fF(e,t),o=hF(i,s,n);return gF(r,o)}var GI,ES,Gi,Xi,Ou,XI,my,uF,ZI=T(()=>{"use strict";UI();Fc();oy();WI();dy();GI=(r,e)=>(r+(r>=0?e:-e)/XI)/e;ES=class extends Error{constructor(e=""){super(e)}},Gi={Err:ES,_tlv:{encode:(r,e)=>{let{Err:t}=Gi;if(r<0||r>256)throw new t("tlv.encode: wrong tag");if(e.length&1)throw new t("tlv.encode: unpadded data");let s=e.length/2,n=zh(s);if(n.length/2&128)throw new t("tlv.encode: long form length too big");let i=s>127?zh(n.length/2|128):"";return zh(r)+i+n+e},decode(r,e){let{Err:t}=Gi,s=0;if(r<0||r>256)throw new t("tlv.encode: wrong tag");if(e.length<2||e[s++]!==r)throw new t("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 t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");let d=e.subarray(s,s+c);if(d.length!==c)throw new t("tlv.decode: length bytes not complete");if(d[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let u of d)o=o<<8|u;if(s+=c,o<128)throw new t("tlv.decode(long): not minimal encoding")}let a=e.subarray(s,s+o);if(a.length!==o)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(s+o)}}},_int:{encode(r){let{Err:e}=Gi;if(r<Xi)throw new e("integer: negative integers are not allowed");let t=zh(r);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return t},decode(r){let{Err:e}=Gi;if(r[0]&128)throw new e("invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return Pu(r)}},toSig(r){let{Err:e,_int:t,_tlv:s}=Gi,n=Wr("signature",r),{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:t.decode(a),s:t.decode(d)}},hexFromSig(r){let{_tlv:e,_int:t}=Gi,s=e.encode(2,t.encode(r.r)),n=e.encode(2,t.encode(r.s)),i=s+n;return e.encode(48,i)}},Xi=BigInt(0),Ou=BigInt(1),XI=BigInt(2),my=BigInt(3),uF=BigInt(4)});function gy(r,e){let t=s=>QI({...r,hash:s});return{...t(e),create:t}}var eR=T(()=>{"use strict";ZI();});var tR,rR,sR,yF,xF,bF,nR,Ule,jle,iR=T(()=>{"use strict";MI();eR();dy();tR={p:BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),h:BigInt(1),a:BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")},rR={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff"),n:BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),h:BigInt(1),a:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc"),b:BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"),Gx:BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"),Gy:BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f")},sR={p:BigInt("0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),n:BigInt("0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409"),h:BigInt(1),a:BigInt("0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc"),b:BigInt("0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00"),Gx:BigInt("0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66"),Gy:BigInt("0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650")},yF=ei(tR.p),xF=ei(rR.p),bF=ei(sR.p),nR=gy({...tR,Fp:yF,lowS:!1},OI),Ule=gy({...rR,Fp:xF,lowS:!1},DI),jle=gy({...sR,Fp:bF,lowS:!1,allowedPrivateKeyLengths:[130,131,132]},LI)});var yy,oR=T(()=>{"use strict";iR();yy=nR});var cR=re(fa=>{"use strict";Object.defineProperty(fa,"__esModule",{value:!0});fa.LEB128=fa.SignedLEB128=fa.UnsignedLEB128=void 0;var Lu;(function(r){r[r.LOWER_7=127]="LOWER_7",r[r.UPPER_1=128]="UPPER_1"})(Lu||(Lu={}));var aR=r=>Number.isSafeInteger(r),Kc=class{static decode(e,t=0){let s=this.$scanForNullBytes(e,t),n=0,i=0;for(let o=0;o<=s-t;o++){let a=e[t+o]&Lu.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 t=[],s=e;do{let n=s&Lu.LOWER_7;s>>=7,s&&(n=n|Lu.UPPER_1),t.push(n)}while(s);return Uint8Array.from(t)}static check(e){if(!aR(e))throw new Error(`${e} is not a safe integer!`)}static $scanForNullBytes(e,t=0){let s=t,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&Lu.UPPER_1);return s-1}static getLength(e,t=0){return this.$scanForNullBytes(e,t)-t}};fa.UnsignedLEB128=Kc;var Xh=class{static $ceil7mul(e){let t=e;for(;t%7;)t++;return t}static check(e){if(!aR(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 t=Math.ceil(Math.log2(-e));return Kc.encode((1<<this.$ceil7mul(t))+e)}static decode(e,t=0){let s=Kc.decode(e,t);return-((1<<Math.ceil(Math.log2(s)))-s)}};fa.SignedLEB128=Xh;var Yh=class{};fa.LEB128=Yh;Yh.encode=r=>(r>=0?Kc:Xh).encode(r);Yh.decode=(r,e=0,t=!1)=>(t?Xh:Kc).decode(r,e)});var uR=re((CS,dR)=>{"use strict";(function(r){"use strict";function e(A){return parseInt(A)===A}function t(A){if(!e(A.length))return!1;for(var R=0;R<A.length;R++)if(!e(A[R])||A[R]<0||A[R]>255)return!1;return!0}function s(A,R){if(A.buffer&&A.name==="Uint8Array")return R&&(A.slice?A=A.slice():A=Array.prototype.slice.call(A)),A;if(Array.isArray(A)){if(!t(A))throw new Error("Array contains invalid value: "+A);return new Uint8Array(A)}if(e(A.length)&&t(A))return new Uint8Array(A);throw new Error("unsupported array-like object")}function n(A){return new Uint8Array(A)}function i(A,R,q,I,L){(I!=null||L!=null)&&(A.slice?A=A.slice(I,L):A=Array.prototype.slice.call(A,I,L)),R.set(A,q)}var o=(function(){function A(q){var I=[],L=0;for(q=encodeURI(q);L<q.length;){var ae=q.charCodeAt(L++);ae===37?(I.push(parseInt(q.substr(L,2),16)),L+=2):I.push(ae)}return s(I)}function R(q){for(var I=[],L=0;L<q.length;){var ae=q[L];ae<128?(I.push(String.fromCharCode(ae)),L++):ae>191&&ae<224?(I.push(String.fromCharCode((ae&31)<<6|q[L+1]&63)),L+=2):(I.push(String.fromCharCode((ae&15)<<12|(q[L+1]&63)<<6|q[L+2]&63)),L+=3)}return I.join("")}return{toBytes:A,fromBytes:R}})(),a=(function(){function A(I){for(var L=[],ae=0;ae<I.length;ae+=2)L.push(parseInt(I.substr(ae,2),16));return L}var R="0123456789abcdef";function q(I){for(var L=[],ae=0;ae<I.length;ae++){var he=I[ae];L.push(R[(he&240)>>4]+R[he&15])}return L.join("")}return{toBytes:A,fromBytes:q}})(),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],f=[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],y=[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],v=[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],S=[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],C=[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],O=[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],K=[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],z=[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],Q=[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],oe=[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],se=[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],we=[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 me(A){for(var R=[],q=0;q<A.length;q+=4)R.push(A[q]<<24|A[q+1]<<16|A[q+2]<<8|A[q+3]);return R}var Y=function(A){if(!(this instanceof Y))throw Error("AES must be instanitated with `new`");Object.defineProperty(this,"key",{value:s(A,!0)}),this._prepare()};Y.prototype._prepare=function(){var A=c[this.key.length];if(A==null)throw new Error("invalid key size (must be 16, 24 or 32 bytes)");this._Ke=[],this._Kd=[];for(var R=0;R<=A;R++)this._Ke.push([0,0,0,0]),this._Kd.push([0,0,0,0]);for(var q=(A+1)*4,I=this.key.length/4,L=me(this.key),ae,R=0;R<I;R++)ae=R>>2,this._Ke[ae][R%4]=L[R],this._Kd[A-ae][R%4]=L[R];for(var he=0,ct=I,xt;ct<q;){if(xt=L[I-1],L[0]^=u[xt>>16&255]<<24^u[xt>>8&255]<<16^u[xt&255]<<8^u[xt>>24&255]^d[he]<<24,he+=1,I!=8)for(var R=1;R<I;R++)L[R]^=L[R-1];else{for(var R=1;R<I/2;R++)L[R]^=L[R-1];xt=L[I/2-1],L[I/2]^=u[xt&255]^u[xt>>8&255]<<8^u[xt>>16&255]<<16^u[xt>>24&255]<<24;for(var R=I/2+1;R<I;R++)L[R]^=L[R-1]}for(var R=0,Ot,St;R<I&&ct<q;)Ot=ct>>2,St=ct%4,this._Ke[Ot][St]=L[R],this._Kd[A-Ot][St]=L[R++],ct++}for(var Ot=1;Ot<A;Ot++)for(var St=0;St<4;St++)xt=this._Kd[Ot][St],this._Kd[Ot][St]=Q[xt>>24&255]^oe[xt>>16&255]^se[xt>>8&255]^we[xt&255]},Y.prototype.encrypt=function(A){if(A.length!=16)throw new Error("invalid plaintext size (must be 16 bytes)");for(var R=this._Ke.length-1,q=[0,0,0,0],I=me(A),L=0;L<4;L++)I[L]^=this._Ke[0][L];for(var ae=1;ae<R;ae++){for(var L=0;L<4;L++)q[L]=h[I[L]>>24&255]^y[I[(L+1)%4]>>16&255]^v[I[(L+2)%4]>>8&255]^S[I[(L+3)%4]&255]^this._Ke[ae][L];I=q.slice()}for(var he=n(16),ct,L=0;L<4;L++)ct=this._Ke[R][L],he[4*L]=(u[I[L]>>24&255]^ct>>24)&255,he[4*L+1]=(u[I[(L+1)%4]>>16&255]^ct>>16)&255,he[4*L+2]=(u[I[(L+2)%4]>>8&255]^ct>>8)&255,he[4*L+3]=(u[I[(L+3)%4]&255]^ct)&255;return he},Y.prototype.decrypt=function(A){if(A.length!=16)throw new Error("invalid ciphertext size (must be 16 bytes)");for(var R=this._Kd.length-1,q=[0,0,0,0],I=me(A),L=0;L<4;L++)I[L]^=this._Kd[0][L];for(var ae=1;ae<R;ae++){for(var L=0;L<4;L++)q[L]=C[I[L]>>24&255]^O[I[(L+3)%4]>>16&255]^K[I[(L+2)%4]>>8&255]^z[I[(L+1)%4]&255]^this._Kd[ae][L];I=q.slice()}for(var he=n(16),ct,L=0;L<4;L++)ct=this._Kd[R][L],he[4*L]=(f[I[L]>>24&255]^ct>>24)&255,he[4*L+1]=(f[I[(L+3)%4]>>16&255]^ct>>16)&255,he[4*L+2]=(f[I[(L+2)%4]>>8&255]^ct>>8)&255,he[4*L+3]=(f[I[(L+1)%4]&255]^ct)&255;return he};var Ze=function(A){if(!(this instanceof Ze))throw Error("AES must be instanitated with `new`");this.description="Electronic Code Block",this.name="ecb",this._aes=new Y(A)};Ze.prototype.encrypt=function(A){if(A=s(A),A.length%16!==0)throw new Error("invalid plaintext size (must be multiple of 16 bytes)");for(var R=n(A.length),q=n(16),I=0;I<A.length;I+=16)i(A,q,0,I,I+16),q=this._aes.encrypt(q),i(q,R,I);return R},Ze.prototype.decrypt=function(A){if(A=s(A),A.length%16!==0)throw new Error("invalid ciphertext size (must be multiple of 16 bytes)");for(var R=n(A.length),q=n(16),I=0;I<A.length;I+=16)i(A,q,0,I,I+16),q=this._aes.decrypt(q),i(q,R,I);return R};var Tt=function(A,R){if(!(this instanceof Tt))throw Error("AES must be instanitated with `new`");if(this.description="Cipher Block Chaining",this.name="cbc",!R)R=n(16);else if(R.length!=16)throw new Error("invalid initialation vector size (must be 16 bytes)");this._lastCipherblock=s(R,!0),this._aes=new Y(A)};Tt.prototype.encrypt=function(A){if(A=s(A),A.length%16!==0)throw new Error("invalid plaintext size (must be multiple of 16 bytes)");for(var R=n(A.length),q=n(16),I=0;I<A.length;I+=16){i(A,q,0,I,I+16);for(var L=0;L<16;L++)q[L]^=this._lastCipherblock[L];this._lastCipherblock=this._aes.encrypt(q),i(this._lastCipherblock,R,I)}return R},Tt.prototype.decrypt=function(A){if(A=s(A),A.length%16!==0)throw new Error("invalid ciphertext size (must be multiple of 16 bytes)");for(var R=n(A.length),q=n(16),I=0;I<A.length;I+=16){i(A,q,0,I,I+16),q=this._aes.decrypt(q);for(var L=0;L<16;L++)R[I+L]=q[L]^this._lastCipherblock[L];i(A,this._lastCipherblock,0,I,I+16)}return R};var Fe=function(A,R,q){if(!(this instanceof Fe))throw Error("AES must be instanitated with `new`");if(this.description="Cipher Feedback",this.name="cfb",!R)R=n(16);else if(R.length!=16)throw new Error("invalid initialation vector size (must be 16 size)");q||(q=1),this.segmentSize=q,this._shiftRegister=s(R,!0),this._aes=new Y(A)};Fe.prototype.encrypt=function(A){if(A.length%this.segmentSize!=0)throw new Error("invalid plaintext size (must be segmentSize bytes)");for(var R=s(A,!0),q,I=0;I<R.length;I+=this.segmentSize){q=this._aes.encrypt(this._shiftRegister);for(var L=0;L<this.segmentSize;L++)R[I+L]^=q[L];i(this._shiftRegister,this._shiftRegister,0,this.segmentSize),i(R,this._shiftRegister,16-this.segmentSize,I,I+this.segmentSize)}return R},Fe.prototype.decrypt=function(A){if(A.length%this.segmentSize!=0)throw new Error("invalid ciphertext size (must be segmentSize bytes)");for(var R=s(A,!0),q,I=0;I<R.length;I+=this.segmentSize){q=this._aes.encrypt(this._shiftRegister);for(var L=0;L<this.segmentSize;L++)R[I+L]^=q[L];i(this._shiftRegister,this._shiftRegister,0,this.segmentSize),i(A,this._shiftRegister,16-this.segmentSize,I,I+this.segmentSize)}return R};var V=function(A,R){if(!(this instanceof V))throw Error("AES must be instanitated with `new`");if(this.description="Output Feedback",this.name="ofb",!R)R=n(16);else if(R.length!=16)throw new Error("invalid initialation vector size (must be 16 bytes)");this._lastPrecipher=s(R,!0),this._lastPrecipherIndex=16,this._aes=new Y(A)};V.prototype.encrypt=function(A){for(var R=s(A,!0),q=0;q<R.length;q++)this._lastPrecipherIndex===16&&(this._lastPrecipher=this._aes.encrypt(this._lastPrecipher),this._lastPrecipherIndex=0),R[q]^=this._lastPrecipher[this._lastPrecipherIndex++];return R},V.prototype.decrypt=V.prototype.encrypt;var D=function(A){if(!(this instanceof D))throw Error("Counter must be instanitated with `new`");A!==0&&!A&&(A=1),typeof A=="number"?(this._counter=n(16),this.setValue(A)):this.setBytes(A)};D.prototype.setValue=function(A){if(typeof A!="number"||parseInt(A)!=A)throw new Error("invalid counter value (must be an integer)");if(A>Number.MAX_SAFE_INTEGER)throw new Error("integer value out of safe range");for(var R=15;R>=0;--R)this._counter[R]=A%256,A=parseInt(A/256)},D.prototype.setBytes=function(A){if(A=s(A,!0),A.length!=16)throw new Error("invalid counter bytes size (must be 16 bytes)");this._counter=A},D.prototype.increment=function(){for(var A=15;A>=0;A--)if(this._counter[A]===255)this._counter[A]=0;else{this._counter[A]++;break}};var F=function(A,R){if(!(this instanceof F))throw Error("AES must be instanitated with `new`");this.description="Counter",this.name="ctr",R instanceof D||(R=new D(R)),this._counter=R,this._remainingCounter=null,this._remainingCounterIndex=16,this._aes=new Y(A)};F.prototype.encrypt=function(A){for(var R=s(A,!0),q=0;q<R.length;q++)this._remainingCounterIndex===16&&(this._remainingCounter=this._aes.encrypt(this._counter._counter),this._remainingCounterIndex=0,this._counter.increment()),R[q]^=this._remainingCounter[this._remainingCounterIndex++];return R},F.prototype.decrypt=F.prototype.encrypt;function le(A){A=s(A,!0);var R=16-A.length%16,q=n(A.length+R);i(A,q);for(var I=A.length;I<q.length;I++)q[I]=R;return q}function Ae(A){if(A=s(A,!0),A.length<16)throw new Error("PKCS#7 invalid length");var R=A[A.length-1];if(R>16)throw new Error("PKCS#7 padding byte out of range");for(var q=A.length-R,I=0;I<R;I++)if(A[q+I]!==R)throw new Error("PKCS#7 invalid padding byte");var L=n(q);return i(A,L,0,0,q),L}var Oe={AES:Y,Counter:D,ModeOfOperation:{ecb:Ze,cbc:Tt,cfb:Fe,ofb:V,ctr:F},utils:{hex:a,utf8:o},padding:{pkcs7:{pad:le,strip:Ae}},_arrayTest:{coerceArray:s,createArray:n,copyArray:i}};typeof CS<"u"?dR.exports=Oe:typeof define=="function"&&define.amd?define([],function(){return Oe}):(r.aesjs&&(Oe._aesjs=r.aesjs),r.aesjs=Oe)})(CS)});function hR(r,e,t){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?EF:TF,u=e?CF:AF,f=v.prototype,h="is"+r,y="_"+h;return f.buffer=void 0,f.offset=0,f[y]=!0,f.toNumber=K,f.toString=z,f.toJSON=K,f.toArray=SF,Uu&&(f.toBuffer=_F),Mu&&(f.toArrayBuffer=pR),v[h]=S,v;function v(se,we,me,Y){return this instanceof v?C(this,se,we,me,Y):new v(se,we,me,Y)}function S(se){return!!(se&&se[y])}function C(se,we,me,Y,Ze){if(Mu&&xy&&(we instanceof xy&&(we=new Mu(we)),Y instanceof xy&&(Y=new Mu(Y))),!we&&!me&&!Y&&!ju){se.buffer=mR(fR,0);return}if(!lR(we,me)){var Tt=ju||Array;Ze=me,Y=we,me=0,we=ju===Uu?Uu.alloc(8):new Tt(8)}se.buffer=we,se.offset=me|=0,by!==typeof Y&&(typeof Y=="string"?O(we,me,Y,Ze||10):lR(Y,Ze)?TS(we,me,Y,Ze):typeof Ze=="number"?(Q(we,me+s,Y),Q(we,me+n,Ze)):Y>0?d(we,me,Y):Y<0?u(we,me,Y):TS(we,me,fR,0))}function O(se,we,me,Y){var Ze=0,Tt=me.length,Fe=0,V=0;me[0]==="-"&&Ze++;for(var D=Ze;Ze<Tt;){var F=parseInt(me[Ze++],Y);if(!(F>=0))break;V=V*Y+F,Fe=Fe*Y+Math.floor(V/Du),V%=Du}D&&(Fe=~Fe,V?V=Du-V:Fe++),Q(se,we+s,Fe),Q(se,we+n,V)}function K(){var se=this.buffer,we=this.offset,me=oe(se,we+s),Y=oe(se,we+n);return t||(me|=0),me?me*Du+Y:Y}function z(se){var we=this.buffer,me=this.offset,Y=oe(we,me+s),Ze=oe(we,me+n),Tt="",Fe=!t&&Y&2147483648;for(Fe&&(Y=~Y,Ze=Du-Ze),se=se||10;;){var V=Y%se*Du+Ze;if(Y=Math.floor(Y/se),Ze=Math.floor(V/se),Tt=(V%se).toString(se)+Tt,!Y&&!Ze)break}return Fe&&(Tt="-"+Tt),Tt}function Q(se,we,me){se[we+c]=me&255,me=me>>8,se[we+a]=me&255,me=me>>8,se[we+o]=me&255,me=me>>8,se[we+i]=me&255}function oe(se,we){return se[we+i]*wF+(se[we+o]<<16)+(se[we+a]<<8)+se[we+c]}}function SF(r){var e=this.buffer,t=this.offset;return ju=null,r!==!1&&vF(e)?e.length===8?e:e.slice(t,t+8):mR(e,t)}function _F(r){var e=this.buffer,t=this.offset;return ju=Uu,r!==!1&&Uu.isBuffer(e)?e.length===8?e:e.slice(t,t+8):Uu.from(pR.call(this,r))}function pR(r){var e=this.buffer,t=this.offset,s=e.buffer;if(ju=Mu,r!==!1&&!e.offset&&s instanceof xy)return s.byteLength===8?s:s.slice(t,t+8);var n=new Mu(8);return TS(n,0,e,t),n.buffer}function lR(r,e){var t=r&&r.length;return e|=0,t&&e+8<=t&&typeof r[e]!="string"}function TS(r,e,t,s){e|=0,s|=0;for(var n=0;n<8;n++)r[e++]=t[s++]&255}function mR(r,e){return Array.prototype.slice.call(r,e,e+8)}function EF(r,e,t){for(var s=e+8;s>e;)r[--s]=t&255,t/=256}function CF(r,e,t){var s=e+8;for(t++;s>e;)r[--s]=-t&255^255,t/=256}function TF(r,e,t){for(var s=e+8;e<s;)r[e++]=t&255,t/=256}function AF(r,e,t){var s=e+8;for(t++;e<s;)r[e++]=-t&255^255,t/=256}function IF(r){return!!r&&Object.prototype.toString.call(r)=="[object Array]"}var by,Uu,Mu,xy,fR,vF,Du,wF,ju,vy,AS,wy=T(()=>{"use strict";by="undefined",Uu=by!==typeof Buffer&&Buffer,Mu=by!==typeof Uint8Array&&Uint8Array,xy=by!==typeof ArrayBuffer&&ArrayBuffer,fR=[0,0,0,0,0,0,0,0],vF=Array.isArray||IF,Du=4294967296,wF=16777216,vy=hR("Uint64BE",!0,!0),AS=hR("Int64BE",!0,!1)});var RS=re(gR=>{"use strict";var $e=gR,{Buffer:Sy}=require("buffer"),RF=require("os");$e.toBuffer=function(r,e,t){t=~~t;let s;if(this.isV4Format(r))s=e||Sy.alloc(t+4),r.split(/\./g).map(n=>{s[t++]=parseInt(n,10)&255});else if(this.isV6Format(r)){let n=r.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||Sy.alloc(t+16),i=0;i<n.length;i++){let o=parseInt(n[i],16);s[t++]=o>>8&255,s[t++]=o&255}}if(!s)throw Error(`Invalid ip address: ${r}`);return s};$e.toString=function(r,e,t){e=~~e,t=t||r.length-e;let s=[];if(t===4){for(let n=0;n<t;n++)s.push(r[e+n]);s=s.join(".")}else if(t===16){for(let n=0;n<t;n+=2)s.push(r.readUInt16BE(e+n).toString(16));s=s.join(":"),s=s.replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3"),s=s.replace(/:{3,4}/,"::")}return s};var kF=/^(\d{1,3}\.){3,3}\d{1,3}$/,PF=/^(::)?(((\d{1,3}\.){3}(\d{1,3}){1})?([0-9a-f]){0,4}:{0,2}){1,8}(::)?$/i;$e.isV4Format=function(r){return kF.test(r)};$e.isV6Format=function(r){return PF.test(r)};function Jh(r){return r===4?"ipv4":r===6?"ipv6":r?r.toLowerCase():"ipv4"}$e.fromPrefixLen=function(r,e){r>32?e="ipv6":e=Jh(e);let t=4;e==="ipv6"&&(t=16);let s=Sy.alloc(t);for(let n=0,i=s.length;n<i;++n){let o=8;r<8&&(o=r),r-=o,s[n]=~(255>>o)&255}return $e.toString(s)};$e.mask=function(r,e){r=$e.toBuffer(r),e=$e.toBuffer(e);let t=Sy.alloc(Math.max(r.length,e.length)),s;if(r.length===e.length)for(s=0;s<r.length;s++)t[s]=r[s]&e[s];else if(e.length===4)for(s=0;s<e.length;s++)t[s]=r[r.length-4+s]&e[s];else{for(s=0;s<t.length-6;s++)t[s]=0;for(t[10]=255,t[11]=255,s=0;s<r.length;s++)t[s+12]=r[s]&e[s+12];s+=12}for(;s<t.length;s++)t[s]=0;return $e.toString(t)};$e.cidr=function(r){let e=r.split("/"),t=e[0];if(e.length!==2)throw new Error(`invalid CIDR subnet: ${t}`);let s=$e.fromPrefixLen(parseInt(e[1],10));return $e.mask(t,s)};$e.subnet=function(r,e){let t=$e.toLong($e.mask(r,e)),s=$e.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:$e.fromLong(t),firstAddress:i<=2?$e.fromLong(t):$e.fromLong(t+1),lastAddress:i<=2?$e.fromLong(t+i-1):$e.fromLong(t+i-2),broadcastAddress:$e.fromLong(t+i-1),subnetMask:e,subnetMaskLength:n,numHosts:i<=2?i:i-2,length:i,contains(o){return t===$e.toLong($e.mask(o,e))}}};$e.cidrSubnet=function(r){let e=r.split("/"),t=e[0];if(e.length!==2)throw new Error(`invalid CIDR subnet: ${t}`);let s=$e.fromPrefixLen(parseInt(e[1],10));return $e.subnet(t,s)};$e.not=function(r){let e=$e.toBuffer(r);for(let t=0;t<e.length;t++)e[t]=255^e[t];return $e.toString(e)};$e.or=function(r,e){if(r=$e.toBuffer(r),e=$e.toBuffer(e),r.length===e.length){for(let i=0;i<r.length;++i)r[i]|=e[i];return $e.toString(r)}let t=r,s=e;e.length>r.length&&(t=e,s=r);let n=t.length-s.length;for(let i=n;i<t.length;++i)t[i]|=s[i-n];return $e.toString(t)};$e.isEqual=function(r,e){if(r=$e.toBuffer(r),e=$e.toBuffer(e),r.length===e.length){for(let s=0;s<r.length;s++)if(r[s]!==e[s])return!1;return!0}if(e.length===4){let s=e;e=r,r=s}for(let s=0;s<10;s++)if(e[s]!==0)return!1;let t=e.readUInt16BE(10);if(t!==0&&t!==65535)return!1;for(let s=0;s<4;s++)if(r[s]!==e[s+12])return!1;return!0};$e.isPrivate=function(r){if($e.isLoopback(r))return!0;if(!$e.isV6Format(r)){let e=$e.normalizeToLong(r);if(e<0)throw new Error("invalid ipv4 address");r=$e.fromLong(e)}return/^(::f{4}:)?10\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(r)||/^(::f{4}:)?192\.168\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(r)||/^(::f{4}:)?172\.(1[6-9]|2\d|30|31)\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(r)||/^(::f{4}:)?169\.254\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(r)||/^f[cd][0-9a-f]{2}:/i.test(r)||/^fe80:/i.test(r)||/^::1$/.test(r)||/^::$/.test(r)};$e.isPublic=function(r){return!$e.isPrivate(r)};$e.isLoopback=function(r){return!/\./.test(r)&&!/:/.test(r)&&(r=$e.fromLong(Number(r))),/^(::f{4}:)?127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})/.test(r)||/^0177\./.test(r)||/^0x7f\./i.test(r)||/^fe80::1$/i.test(r)||/^::1$/.test(r)||/^::$/.test(r)};$e.loopback=function(r){if(r=Jh(r),r!=="ipv4"&&r!=="ipv6")throw new Error("family must be ipv4 or ipv6");return r==="ipv4"?"127.0.0.1":"fe80::1"};$e.address=function(r,e){let t=RF.networkInterfaces();if(e=Jh(e),r&&r!=="private"&&r!=="public"){let n=t[r].filter(i=>Jh(i.family)===e);return n.length===0?void 0:n[0].address}let s=Object.keys(t).map(n=>{let i=t[n].filter(o=>(o.family=Jh(o.family),o.family!==e||$e.isLoopback(o.address)?!1:r?r==="public"?$e.isPrivate(o.address):$e.isPublic(o.address):!0));return i.length?i[0].address:void 0}).filter(Boolean);return s.length?s[0]:$e.loopback(e)};$e.toLong=function(r){let e=0;return r.split(".").forEach(t=>{e<<=8,e+=parseInt(t)}),e>>>0};$e.fromLong=function(r){return`${r>>>24}.${r>>16&255}.${r>>8&255}.${r&255}`};$e.normalizeToLong=function(r){let e=r.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 t=0;switch(e.length){case 1:t=e[0];break;case 2:if(e[0]>255||e[1]>16777215)return-1;t=e[0]<<24|e[1]&16777215;break;case 3:if(e[0]>255||e[1]>255||e[2]>65535)return-1;t=e[0]<<24|e[1]<<16|e[2]&65535;break;case 4:if(e.some(n=>n>255))return-1;t=e[0]<<24|e[1]<<16|e[2]<<8|e[3];break;default:return-1}return t>>>0}});var xR=re((Kle,yR)=>{"use strict";yR.exports=function r(e,t){if(e===t)return!0;if(e&&t&&typeof e=="object"&&typeof t=="object"){if(e.constructor!==t.constructor)return!1;var s,n,i;if(Array.isArray(e)){if(s=e.length,s!=t.length)return!1;for(n=s;n--!==0;)if(!r(e[n],t[n]))return!1;return!0}if(e.constructor===RegExp)return e.source===t.source&&e.flags===t.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===t.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===t.toString();if(i=Object.keys(e),s=i.length,s!==Object.keys(t).length)return!1;for(n=s;n--!==0;)if(!Object.prototype.hasOwnProperty.call(t,i[n]))return!1;for(n=s;n--!==0;){var o=i[n];if(!r(e[o],t[o]))return!1}return!0}return e!==e&&t!==t}});var bR=re(kS=>{"use strict";kS.toString=function(r){switch(r){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_"+r};kS.toType=function(r){switch(r.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 r.toUpperCase().startsWith("UNKNOWN_")?parseInt(r.slice(8)):0}});var vR=re(PS=>{"use strict";PS.toString=function(r){switch(r){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_"+r};PS.toRcode=function(r){switch(r.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 wR=re(BS=>{"use strict";BS.toString=function(r){switch(r){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_"+r};BS.toOpcode=function(r){switch(r.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 SR=re(NS=>{"use strict";NS.toString=function(r){switch(r){case 1:return"IN";case 2:return"CS";case 3:return"CH";case 4:return"HS";case 255:return"ANY"}return"UNKNOWN_"+r};NS.toClass=function(r){switch(r.toUpperCase()){case"IN":return 1;case"CS":return 2;case"CH":return 3;case"HS":return 4;case"ANY":return 255}return 0}});var _R=re(OS=>{"use strict";OS.toString=function(r){switch(r){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 r<0?null:`OPTION_${r}`};OS.toCode=function(r){if(typeof r=="number")return r;if(!r)return-1;switch(r.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=r.match(/_(\d+)$/);return e?parseInt(e[1],10):-1}});var TR=re((CR,LS)=>{"use strict";var ER=(function(r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.decode=f,r.encode=u,r.familyOf=d,r.name=void 0,r.sizeOf=c,r.v6=r.v4=void 0;let e=/^(\d{1,3}\.){3,3}\d{1,3}$/,t=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:t,isFormat:h=>e.test(h),encode(h,y,v){v=~~v,y=y||new Uint8Array(v+t);let S=h.length,C=0;for(let O=0;O<S;){let K=h.charCodeAt(O++);K===46?(y[v++]=C,C=0):C=C*10+(K-48)}return y[v]=C,y},decode(h,y){return y=~~y,`${h[y++]}.${h[y++]}.${h[y++]}.${h[y]}`}};r.v4=i;let o={name:"v6",size:n,isFormat:h=>h.length>0&&s.test(h),encode(h,y,v){v=~~v;let S=v+n,C=-1,O=0,K=0,z=!0,Q=!1;y=y||new Uint8Array(v+n);for(let oe=0;oe<h.length;oe++){let se=h.charCodeAt(oe);se===58?(z?C!==-1?(v<S&&(y[v]=0),v<S-1&&(y[v+1]=0),v+=2):v<S&&(C=v):(Q===!0?(v<S&&(y[v]=K),v++):(v<S&&(y[v]=O>>8),v<S-1&&(y[v+1]=O&255),v+=2),O=0,K=0),z=!0,Q=!1):se===46?(v<S&&(y[v]=K),v++,K=0,O=0,z=!1,Q=!0):(z=!1,se>=97?se-=87:se>=65?se-=55:(se-=48,K=K*10+se),O=(O<<4)+se)}if(z===!1)Q===!0?(v<S&&(y[v]=K),v++):(v<S&&(y[v]=O>>8),v<S-1&&(y[v+1]=O&255),v+=2);else if(C===0)v<S&&(y[v]=0),v<S-1&&(y[v+1]=0),v+=2;else if(C!==-1){v+=2;for(let oe=Math.min(v-1,S-1);oe>=C+2;oe--)y[oe]=y[oe-2];y[C]=0,y[C+1]=0,C=v}if(C!==v&&C!==-1)for(v>S-2&&(v=S-2);S>C;)y[--S]=v<S&&v>C?y[--v]:0;else for(;v<S;)y[v++]=0;return y},decode(h,y){y=~~y;let v="";for(let S=0;S<n;S+=2)S!==0&&(v+=":"),v+=(h[y+S]<<8|h[y+S+1]).toString(16);return v.replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}};r.v6=o;let a="ip";r.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,y,v){v=~~v;let S=c(h);return typeof y=="function"&&(y=y(v+S)),S===i.size?i.encode(h,y,v):o.encode(h,y,v)}function f(h,y,v){if(y=~~y,v=v||h.length-y,v===i.size)return i.decode(h,y,v);if(v===o.size)return o.decode(h,y,v);throw Error(`Invalid buffer size needs to be ${i.size} for v4 or ${o.size} for v6.`)}return"default"in r?r.default:r})({});typeof define=="function"&&define.amd?define([],function(){return ER}):typeof LS=="object"&&typeof CR=="object"&&(LS.exports=ER)});var RR=re(Ve=>{"use strict";var Ke=require("buffer").Buffer,io=bR(),BF=vR(),NF=wR(),Ey=SR(),DS=_R(),Wc=TR(),OF=0,AR=32768,MS=32768,LF=~MS,IR=32768,DF=~IR,ve=Ve.name={};ve.encode=function(r,e,t,{mail:s=!1}={}){e||(e=Ke.alloc(ve.encodingLength(r))),t||(t=0);let n=t,i=r.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],t+1);e[t]=c,t+=c+1}}return e[t++]=0,ve.encode.bytes=t-n,e};ve.encode.bytes=0;ve.decode=function(r,e,{mail:t=!1}={}){e||(e=0);let s=[],n=e,i=0,o=0,a=!1;for(;;){if(e>=r.length)throw new Error("Cannot decode name (buffer overflow)");let c=r[e++];if(o+=a?0:1,c===0)break;if((c&192)===0){if(e+c>r.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=r.toString("utf-8",e,e+c);t&&(d=d.replace(/\./g,"\\.")),s.push(d),e+=c,o+=a?0:c}else if((c&192)===192){if(e+1>r.length)throw new Error("Cannot decode name (buffer overflow)");let d=r.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 ve.decode.bytes=o,s.length===0?".":s.join(".")};ve.decode.bytes=0;ve.encodingLength=function(r){return r==="."||r===".."?1:Ke.byteLength(r.replace(/^\.|\.$/gm,""))+2};var wt={};wt.encode=function(r,e,t){e||(e=Ke.alloc(wt.encodingLength(r))),t||(t=0);let s=e.write(r,t+1);return e[t]=s,wt.encode.bytes=s+1,e};wt.encode.bytes=0;wt.decode=function(r,e){e||(e=0);let t=r[e],s=r.toString("utf-8",e+1,e+1+t);return wt.decode.bytes=t+1,s};wt.decode.bytes=0;wt.encodingLength=function(r){return Ke.byteLength(r)+1};var bn={};bn.encode=function(r,e,t){e||(e=bn.encodingLength(r)),t||(t=0);let s=(r.flags||0)&32767,n=r.type==="response"?AR:OF;return e.writeUInt16BE(r.id||0,t),e.writeUInt16BE(s|n,t+2),e.writeUInt16BE(r.questions.length,t+4),e.writeUInt16BE(r.answers.length,t+6),e.writeUInt16BE(r.authorities.length,t+8),e.writeUInt16BE(r.additionals.length,t+10),e};bn.encode.bytes=12;bn.decode=function(r,e){if(e||(e=0),r.length<12)throw new Error("Header must be 12 bytes");let t=r.readUInt16BE(e+2);return{id:r.readUInt16BE(e),type:t&AR?"response":"query",flags:t&32767,flag_qr:(t>>15&1)===1,opcode:NF.toString(t>>11&15),flag_aa:(t>>10&1)===1,flag_tc:(t>>9&1)===1,flag_rd:(t>>8&1)===1,flag_ra:(t>>7&1)===1,flag_z:(t>>6&1)===1,flag_ad:(t>>5&1)===1,flag_cd:(t>>4&1)===1,rcode:BF.toString(t&15),questions:new Array(r.readUInt16BE(e+4)),answers:new Array(r.readUInt16BE(e+6)),authorities:new Array(r.readUInt16BE(e+8)),additionals:new Array(r.readUInt16BE(e+10))}};bn.decode.bytes=12;bn.encodingLength=function(){return 12};var Yi=Ve.unknown={};Yi.encode=function(r,e,t){return e||(e=Ke.alloc(Yi.encodingLength(r))),t||(t=0),e.writeUInt16BE(r.length,t),r.copy(e,t+2),Yi.encode.bytes=r.length+2,e};Yi.encode.bytes=0;Yi.decode=function(r,e){e||(e=0);let t=r.readUInt16BE(e),s=r.slice(e+2,e+2+t);return Yi.decode.bytes=t+2,s};Yi.decode.bytes=0;Yi.encodingLength=function(r){return r.length+2};var Ji=Ve.ns={};Ji.encode=function(r,e,t){return e||(e=Ke.alloc(Ji.encodingLength(r))),t||(t=0),ve.encode(r,e,t+2),e.writeUInt16BE(ve.encode.bytes,t),Ji.encode.bytes=ve.encode.bytes+2,e};Ji.encode.bytes=0;Ji.decode=function(r,e){e||(e=0);let t=r.readUInt16BE(e),s=ve.decode(r,e+2);return Ji.decode.bytes=t+2,s};Ji.decode.bytes=0;Ji.encodingLength=function(r){return ve.encodingLength(r)+2};var Qi=Ve.soa={};Qi.encode=function(r,e,t){e||(e=Ke.alloc(Qi.encodingLength(r))),t||(t=0);let s=t;return t+=2,ve.encode(r.mname,e,t),t+=ve.encode.bytes,ve.encode(r.rname,e,t,{mail:!0}),t+=ve.encode.bytes,e.writeUInt32BE(r.serial||0,t),t+=4,e.writeUInt32BE(r.refresh||0,t),t+=4,e.writeUInt32BE(r.retry||0,t),t+=4,e.writeUInt32BE(r.expire||0,t),t+=4,e.writeUInt32BE(r.minimum||0,t),t+=4,e.writeUInt16BE(t-s-2,s),Qi.encode.bytes=t-s,e};Qi.encode.bytes=0;Qi.decode=function(r,e){e||(e=0);let t=e,s={};return e+=2,s.mname=ve.decode(r,e),e+=ve.decode.bytes,s.rname=ve.decode(r,e,{mail:!0}),e+=ve.decode.bytes,s.serial=r.readUInt32BE(e),e+=4,s.refresh=r.readUInt32BE(e),e+=4,s.retry=r.readUInt32BE(e),e+=4,s.expire=r.readUInt32BE(e),e+=4,s.minimum=r.readUInt32BE(e),e+=4,Qi.decode.bytes=e-t,s};Qi.decode.bytes=0;Qi.encodingLength=function(r){return 22+ve.encodingLength(r.mname)+ve.encodingLength(r.rname)};var Zi=Ve.txt={};Zi.encode=function(r,e,t){Array.isArray(r)||(r=[r]);for(let n=0;n<r.length;n++)if(typeof r[n]=="string"&&(r[n]=Ke.from(r[n])),!Ke.isBuffer(r[n]))throw new Error("Must be a Buffer");e||(e=Ke.alloc(Zi.encodingLength(r))),t||(t=0);let s=t;return t+=2,r.forEach(function(n){e[t++]=n.length,n.copy(e,t,0,n.length),t+=n.length}),e.writeUInt16BE(t-s-2,s),Zi.encode.bytes=t-s,e};Zi.encode.bytes=0;Zi.decode=function(r,e){e||(e=0);let t=e,s=r.readUInt16BE(e);e+=2;let n=[];for(;s>0;){let i=r[e++];if(--s,s<i)throw new Error("Buffer overflow");n.push(r.slice(e,e+i)),e+=i,s-=i}return Zi.decode.bytes=e-t,n};Zi.decode.bytes=0;Zi.encodingLength=function(r){Array.isArray(r)||(r=[r]);let e=2;return r.forEach(function(t){typeof t=="string"?e+=Ke.byteLength(t)+1:e+=t.length+1}),e};var eo=Ve.null={};eo.encode=function(r,e,t){e||(e=Ke.alloc(eo.encodingLength(r))),t||(t=0),typeof r=="string"&&(r=Ke.from(r)),r||(r=Ke.alloc(0));let s=t;t+=2;let n=r.length;return r.copy(e,t,0,n),t+=n,e.writeUInt16BE(t-s-2,s),eo.encode.bytes=t-s,e};eo.encode.bytes=0;eo.decode=function(r,e){e||(e=0);let t=e,s=r.readUInt16BE(e);e+=2;let n=r.slice(e,e+s);return e+=s,eo.decode.bytes=e-t,n};eo.decode.bytes=0;eo.encodingLength=function(r){return r?(Ke.isBuffer(r)?r.length:Ke.byteLength(r))+2:2};var to=Ve.hinfo={};to.encode=function(r,e,t){e||(e=Ke.alloc(to.encodingLength(r))),t||(t=0);let s=t;return t+=2,wt.encode(r.cpu,e,t),t+=wt.encode.bytes,wt.encode(r.os,e,t),t+=wt.encode.bytes,e.writeUInt16BE(t-s-2,s),to.encode.bytes=t-s,e};to.encode.bytes=0;to.decode=function(r,e){e||(e=0);let t=e,s={};return e+=2,s.cpu=wt.decode(r,e),e+=wt.decode.bytes,s.os=wt.decode(r,e),e+=wt.decode.bytes,to.decode.bytes=e-t,s};to.decode.bytes=0;to.encodingLength=function(r){return wt.encodingLength(r.cpu)+wt.encodingLength(r.os)+2};var yn=Ve.ptr={},MF=Ve.cname=yn,UF=Ve.dname=yn;yn.encode=function(r,e,t){return e||(e=Ke.alloc(yn.encodingLength(r))),t||(t=0),ve.encode(r,e,t+2),e.writeUInt16BE(ve.encode.bytes,t),yn.encode.bytes=ve.encode.bytes+2,e};yn.encode.bytes=0;yn.decode=function(r,e){e||(e=0);let t=ve.decode(r,e+2);return yn.decode.bytes=ve.decode.bytes+2,t};yn.decode.bytes=0;yn.encodingLength=function(r){return ve.encodingLength(r)+2};var ro=Ve.srv={};ro.encode=function(r,e,t){e||(e=Ke.alloc(ro.encodingLength(r))),t||(t=0),e.writeUInt16BE(r.priority||0,t+2),e.writeUInt16BE(r.weight||0,t+4),e.writeUInt16BE(r.port||0,t+6),ve.encode(r.target,e,t+8);let s=ve.encode.bytes+6;return e.writeUInt16BE(s,t),ro.encode.bytes=s+2,e};ro.encode.bytes=0;ro.decode=function(r,e){e||(e=0);let t=r.readUInt16BE(e),s={};return s.priority=r.readUInt16BE(e+2),s.weight=r.readUInt16BE(e+4),s.port=r.readUInt16BE(e+6),s.target=ve.decode(r,e+8),ro.decode.bytes=t+2,s};ro.decode.bytes=0;ro.encodingLength=function(r){return 8+ve.encodingLength(r.target)};var Rs=Ve.caa={};Rs.ISSUER_CRITICAL=128;Rs.encode=function(r,e,t){let s=Rs.encodingLength(r);return e||(e=Ke.alloc(Rs.encodingLength(r))),t||(t=0),r.issuerCritical&&(r.flags=Rs.ISSUER_CRITICAL),e.writeUInt16BE(s-2,t),t+=2,e.writeUInt8(r.flags||0,t),t+=1,wt.encode(r.tag,e,t),t+=wt.encode.bytes,e.write(r.value,t),t+=Ke.byteLength(r.value),Rs.encode.bytes=s,e};Rs.encode.bytes=0;Rs.decode=function(r,e){e||(e=0);let t=r.readUInt16BE(e);e+=2;let s=e,n={};return n.flags=r.readUInt8(e),e+=1,n.tag=wt.decode(r,e),e+=wt.decode.bytes,n.value=r.toString("utf-8",e,s+t),n.issuerCritical=!!(n.flags&Rs.ISSUER_CRITICAL),Rs.decode.bytes=t+2,n};Rs.decode.bytes=0;Rs.encodingLength=function(r){return wt.encodingLength(r.tag)+wt.encodingLength(r.value)+2};var la=Ve.mx={};la.encode=function(r,e,t){e||(e=Ke.alloc(la.encodingLength(r))),t||(t=0);let s=t;return t+=2,e.writeUInt16BE(r.preference||0,t),t+=2,ve.encode(r.exchange,e,t),t+=ve.encode.bytes,e.writeUInt16BE(t-s-2,s),la.encode.bytes=t-s,e};la.encode.bytes=0;la.decode=function(r,e){e||(e=0);let t=e,s={};return e+=2,s.preference=r.readUInt16BE(e),e+=2,s.exchange=ve.decode(r,e),e+=ve.decode.bytes,la.decode.bytes=e-t,s};la.encodingLength=function(r){return 4+ve.encodingLength(r.exchange)};var so=Ve.a={};so.encode=function(r,e,t){return e||(e=Ke.alloc(so.encodingLength(r))),t||(t=0),e.writeUInt16BE(4,t),t+=2,Wc.v4.encode(r,e,t),so.encode.bytes=6,e};so.encode.bytes=0;so.decode=function(r,e){e||(e=0),e+=2;let t=Wc.v4.decode(r,e);return so.decode.bytes=6,t};so.decode.bytes=0;so.encodingLength=function(){return 6};var no=Ve.aaaa={};no.encode=function(r,e,t){return e||(e=Ke.alloc(no.encodingLength(r))),t||(t=0),e.writeUInt16BE(16,t),t+=2,Wc.v6.encode(r,e,t),no.encode.bytes=18,e};no.encode.bytes=0;no.decode=function(r,e){e||(e=0),e+=2;let t=Wc.v6.decode(r,e);return no.decode.bytes=18,t};no.decode.bytes=0;no.encodingLength=function(){return 18};var bs=Ve.option={};bs.encode=function(r,e,t){e||(e=Ke.alloc(bs.encodingLength(r))),t||(t=0);let s=t,n=DS.toCode(r.code);if(e.writeUInt16BE(n,t),t+=2,r.data)e.writeUInt16BE(r.data.length,t),t+=2,r.data.copy(e,t),t+=r.data.length;else switch(n){case 8:let i=r.sourcePrefixLength||0,o=r.family||Wc.familyOf(r.ip),a=Wc.encode(r.ip,Ke.alloc),c=Math.ceil(i/8);e.writeUInt16BE(c+4,t),t+=2,e.writeUInt16BE(o,t),t+=2,e.writeUInt8(i,t++),e.writeUInt8(r.scopePrefixLength||0,t++),a.copy(e,t,0,c),t+=c;break;case 11:r.timeout?(e.writeUInt16BE(2,t),t+=2,e.writeUInt16BE(r.timeout,t),t+=2):(e.writeUInt16BE(0,t),t+=2);break;case 12:let d=r.length||0;e.writeUInt16BE(d,t),t+=2,e.fill(0,t,t+d),t+=d;break;case 14:let u=r.tags.length*2;e.writeUInt16BE(u,t),t+=2;for(let f of r.tags)e.writeUInt16BE(f,t),t+=2;break;default:throw new Error(`Unknown roption code: ${r.code}`)}return bs.encode.bytes=t-s,e};bs.encode.bytes=0;bs.decode=function(r,e){e||(e=0);let t={};t.code=r.readUInt16BE(e),t.type=DS.toString(t.code),e+=2;let s=r.readUInt16BE(e);switch(e+=2,t.data=r.slice(e,e+s),t.code){case 8:t.family=r.readUInt16BE(e),e+=2,t.sourcePrefixLength=r.readUInt8(e++),t.scopePrefixLength=r.readUInt8(e++);let n=Ke.alloc(t.family===1?4:16);r.copy(n,0,e,e+s-4),t.ip=Wc.decode(n);break;case 11:s>0&&(t.timeout=r.readUInt16BE(e),e+=2);break;case 14:t.tags=[];for(let i=0;i<s;i+=2)t.tags.push(r.readUInt16BE(e)),e+=2}return bs.decode.bytes=s+4,t};bs.decode.bytes=0;bs.encodingLength=function(r){if(r.data)return r.data.length+4;switch(DS.toCode(r.code)){case 8:let t=r.sourcePrefixLength||0;return Math.ceil(t/8)+8;case 11:return typeof r.timeout=="number"?6:4;case 12:return r.length+4;case 14:return 4+r.tags.length*2}throw new Error(`Unknown roption code: ${r.code}`)};var Ps=Ve.opt={};Ps.encode=function(r,e,t){e||(e=Ke.alloc(Ps.encodingLength(r))),t||(t=0);let s=t,n=Hu(r,bs);return e.writeUInt16BE(n,t),t=Qh(r,bs,e,t+2),Ps.encode.bytes=t-s,e};Ps.encode.bytes=0;Ps.decode=function(r,e){e||(e=0);let t=e,s=[],n=r.readUInt16BE(e);e+=2;let i=0;for(;n>0;)s[i++]=bs.decode(r,e),e+=bs.decode.bytes,n-=bs.decode.bytes;return Ps.decode.bytes=e-t,s};Ps.decode.bytes=0;Ps.encodingLength=function(r){return 2+Hu(r||[],bs)};var ss=Ve.dnskey={};ss.PROTOCOL_DNSSEC=3;ss.ZONE_KEY=128;ss.SECURE_ENTRYPOINT=32768;ss.encode=function(r,e,t){e||(e=Ke.alloc(ss.encodingLength(r))),t||(t=0);let s=t,n=r.key;if(!Ke.isBuffer(n))throw new Error("Key must be a Buffer");return t+=2,e.writeUInt16BE(r.flags,t),t+=2,e.writeUInt8(ss.PROTOCOL_DNSSEC,t),t+=1,e.writeUInt8(r.algorithm,t),t+=1,n.copy(e,t,0,n.length),t+=n.length,ss.encode.bytes=t-s,e.writeUInt16BE(ss.encode.bytes-2,s),e};ss.encode.bytes=0;ss.decode=function(r,e){e||(e=0);let t=e;var s={},n=r.readUInt16BE(e);if(e+=2,s.flags=r.readUInt16BE(e),e+=2,r.readUInt8(e)!==ss.PROTOCOL_DNSSEC)throw new Error("Protocol must be 3");return e+=1,s.algorithm=r.readUInt8(e),e+=1,s.key=r.slice(e,t+n+2),e+=s.key.length,ss.decode.bytes=e-t,s};ss.decode.bytes=0;ss.encodingLength=function(r){return 6+Ke.byteLength(r.key)};var ri=Ve.rrsig={};ri.encode=function(r,e,t){e||(e=Ke.alloc(ri.encodingLength(r))),t||(t=0);let s=t,n=r.signature;if(!Ke.isBuffer(n))throw new Error("Signature must be a Buffer");return t+=2,e.writeUInt16BE(io.toType(r.typeCovered),t),t+=2,e.writeUInt8(r.algorithm,t),t+=1,e.writeUInt8(r.labels,t),t+=1,e.writeUInt32BE(r.originalTTL,t),t+=4,e.writeUInt32BE(r.expiration,t),t+=4,e.writeUInt32BE(r.inception,t),t+=4,e.writeUInt16BE(r.keyTag,t),t+=2,ve.encode(r.signersName,e,t),t+=ve.encode.bytes,n.copy(e,t,0,n.length),t+=n.length,ri.encode.bytes=t-s,e.writeUInt16BE(ri.encode.bytes-2,s),e};ri.encode.bytes=0;ri.decode=function(r,e){e||(e=0);let t=e;var s={},n=r.readUInt16BE(e);return e+=2,s.typeCovered=io.toString(r.readUInt16BE(e)),e+=2,s.algorithm=r.readUInt8(e),e+=1,s.labels=r.readUInt8(e),e+=1,s.originalTTL=r.readUInt32BE(e),e+=4,s.expiration=r.readUInt32BE(e),e+=4,s.inception=r.readUInt32BE(e),e+=4,s.keyTag=r.readUInt16BE(e),e+=2,s.signersName=ve.decode(r,e),e+=ve.decode.bytes,s.signature=r.slice(e,t+n+2),e+=s.signature.length,ri.decode.bytes=e-t,s};ri.decode.bytes=0;ri.encodingLength=function(r){return 20+ve.encodingLength(r.signersName)+Ke.byteLength(r.signature)};var si=Ve.rp={};si.encode=function(r,e,t){e||(e=Ke.alloc(si.encodingLength(r))),t||(t=0);let s=t;return t+=2,ve.encode(r.mbox||".",e,t,{mail:!0}),t+=ve.encode.bytes,ve.encode(r.txt||".",e,t),t+=ve.encode.bytes,si.encode.bytes=t-s,e.writeUInt16BE(si.encode.bytes-2,s),e};si.encode.bytes=0;si.decode=function(r,e){e||(e=0);let t=e,s={};return e+=2,s.mbox=ve.decode(r,e,{mail:!0})||".",e+=ve.decode.bytes,s.txt=ve.decode(r,e)||".",e+=ve.decode.bytes,si.decode.bytes=e-t,s};si.decode.bytes=0;si.encodingLength=function(r){return 2+ve.encodingLength(r.mbox||".")+ve.encodingLength(r.txt||".")};var Cr={};Cr.encode=function(r,e,t){e||(e=Ke.alloc(Cr.encodingLength(r))),t||(t=0);let s=t;for(var n=[],i=0;i<r.length;i++){var o=io.toType(r[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=Ke.from(n[i]);e.writeUInt8(i,t),t+=1,e.writeUInt8(a.length,t),t+=1,a.copy(e,t),t+=a.length}return Cr.encode.bytes=t-s,e};Cr.encode.bytes=0;Cr.decode=function(r,e,t){e||(e=0);let s=e;for(var n=[];e-s<t;){var i=r.readUInt8(e);e+=1;var o=r.readUInt8(e);e+=1;for(var a=0;a<o;a++)for(var c=r.readUInt8(e+a),d=0;d<8;d++)if(c&1<<7-d){var u=io.toString(i<<8|a<<3|d);n.push(u)}e+=o}return Cr.decode.bytes=e-s,n};Cr.decode.bytes=0;Cr.encodingLength=function(r){for(var e=[],t=0;t<r.length;t++){var s=io.toType(r[t]);e[s>>8]=Math.max(e[s>>8]||0,s&255)}var n=0;for(t=0;t<e.length;t++)e[t]!==void 0&&(n+=2+Math.ceil((e[t]+1)/8));return n};var ni=Ve.nsec={};ni.encode=function(r,e,t){e||(e=Ke.alloc(ni.encodingLength(r))),t||(t=0);let s=t;return t+=2,ve.encode(r.nextDomain,e,t),t+=ve.encode.bytes,Cr.encode(r.rrtypes,e,t),t+=Cr.encode.bytes,ni.encode.bytes=t-s,e.writeUInt16BE(ni.encode.bytes-2,s),e};ni.encode.bytes=0;ni.decode=function(r,e){e||(e=0);let t=e;var s={},n=r.readUInt16BE(e);return e+=2,s.nextDomain=ve.decode(r,e),e+=ve.decode.bytes,s.rrtypes=Cr.decode(r,e,n-(e-t)),e+=Cr.decode.bytes,ni.decode.bytes=e-t,s};ni.decode.bytes=0;ni.encodingLength=function(r){return 2+ve.encodingLength(r.nextDomain)+Cr.encodingLength(r.rrtypes)};var ii=Ve.nsec3={};ii.encode=function(r,e,t){e||(e=Ke.alloc(ii.encodingLength(r))),t||(t=0);let s=t,n=r.salt;if(!Ke.isBuffer(n))throw new Error("salt must be a Buffer");let i=r.nextDomain;if(!Ke.isBuffer(i))throw new Error("nextDomain must be a Buffer");return t+=2,e.writeUInt8(r.algorithm,t),t+=1,e.writeUInt8(r.flags,t),t+=1,e.writeUInt16BE(r.iterations,t),t+=2,e.writeUInt8(n.length,t),t+=1,n.copy(e,t,0,n.length),t+=n.length,e.writeUInt8(i.length,t),t+=1,i.copy(e,t,0,i.length),t+=i.length,Cr.encode(r.rrtypes,e,t),t+=Cr.encode.bytes,ii.encode.bytes=t-s,e.writeUInt16BE(ii.encode.bytes-2,s),e};ii.encode.bytes=0;ii.decode=function(r,e){e||(e=0);let t=e;var s={},n=r.readUInt16BE(e);e+=2,s.algorithm=r.readUInt8(e),e+=1,s.flags=r.readUInt8(e),e+=1,s.iterations=r.readUInt16BE(e),e+=2;let i=r.readUInt8(e);e+=1,s.salt=r.slice(e,e+i),e+=i;let o=r.readUInt8(e);return e+=1,s.nextDomain=r.slice(e,e+o),e+=o,s.rrtypes=Cr.decode(r,e,n-(e-t)),e+=Cr.decode.bytes,ii.decode.bytes=e-t,s};ii.decode.bytes=0;ii.encodingLength=function(r){return 8+r.salt.length+r.nextDomain.length+Cr.encodingLength(r.rrtypes)};var oi=Ve.ds={};oi.encode=function(r,e,t){e||(e=Ke.alloc(oi.encodingLength(r))),t||(t=0);let s=t,n=r.digest;if(!Ke.isBuffer(n))throw new Error("Digest must be a Buffer");return t+=2,e.writeUInt16BE(r.keyTag,t),t+=2,e.writeUInt8(r.algorithm,t),t+=1,e.writeUInt8(r.digestType,t),t+=1,n.copy(e,t,0,n.length),t+=n.length,oi.encode.bytes=t-s,e.writeUInt16BE(oi.encode.bytes-2,s),e};oi.encode.bytes=0;oi.decode=function(r,e){e||(e=0);let t=e;var s={},n=r.readUInt16BE(e);return e+=2,s.keyTag=r.readUInt16BE(e),e+=2,s.algorithm=r.readUInt8(e),e+=1,s.digestType=r.readUInt8(e),e+=1,s.digest=r.slice(e,t+n+2),e+=s.digest.length,oi.decode.bytes=e-t,s};oi.decode.bytes=0;oi.encodingLength=function(r){return 6+Ke.byteLength(r.digest)};var ks=Ve.sshfp={};ks.getFingerprintLengthForHashType=function(e){switch(e){case 1:return 20;case 2:return 32}};ks.encode=function(e,t,s){t||(t=Ke.alloc(ks.encodingLength(e))),s||(s=0);let n=s;s+=2,t[s]=e.algorithm,s+=1,t[s]=e.hash,s+=1;let i=Ke.from(e.fingerprint.toUpperCase(),"hex");if(i.length!==ks.getFingerprintLengthForHashType(e.hash))throw new Error("Invalid fingerprint length");return i.copy(t,s),s+=i.byteLength,ks.encode.bytes=s-n,t.writeUInt16BE(ks.encode.bytes-2,n),t};ks.encode.bytes=0;ks.decode=function(e,t){t||(t=0);let s=t,n={};t+=2,n.algorithm=e[t],t+=1,n.hash=e[t],t+=1;let i=ks.getFingerprintLengthForHashType(n.hash);return n.fingerprint=e.slice(t,t+i).toString("hex").toUpperCase(),t+=i,ks.decode.bytes=t-s,n};ks.decode.bytes=0;ks.encodingLength=function(r){return 4+Ke.from(r.fingerprint,"hex").byteLength};var ai=Ve.naptr={};ai.encode=function(r,e,t){e||(e=Ke.alloc(ai.encodingLength(r))),t||(t=0);let s=t;return t+=2,e.writeUInt16BE(r.order||0,t),t+=2,e.writeUInt16BE(r.preference||0,t),t+=2,wt.encode(r.flags,e,t),t+=wt.encode.bytes,wt.encode(r.services,e,t),t+=wt.encode.bytes,wt.encode(r.regexp,e,t),t+=wt.encode.bytes,ve.encode(r.replacement,e,t),t+=ve.encode.bytes,ai.encode.bytes=t-s,e.writeUInt16BE(ai.encode.bytes-2,s),e};ai.encode.bytes=0;ai.decode=function(r,e){e||(e=0);let t=e,s={};return e+=2,s.order=r.readUInt16BE(e),e+=2,s.preference=r.readUInt16BE(e),e+=2,s.flags=wt.decode(r,e),e+=wt.decode.bytes,s.services=wt.decode(r,e),e+=wt.decode.bytes,s.regexp=wt.decode(r,e),e+=wt.decode.bytes,s.replacement=ve.decode(r,e),e+=ve.decode.bytes,ai.decode.bytes=e-t,s};ai.decode.bytes=0;ai.encodingLength=function(r){return wt.encodingLength(r.flags)+wt.encodingLength(r.services)+wt.encodingLength(r.regexp)+ve.encodingLength(r.replacement)+6};var ci=Ve.tlsa={};ci.encode=function(r,e,t){e||(e=Ke.alloc(ci.encodingLength(r))),t||(t=0);let s=t,n=r.certificate;if(!Ke.isBuffer(n))throw new Error("Certificate must be a Buffer");return t+=2,e.writeUInt8(r.usage,t),t+=1,e.writeUInt8(r.selector,t),t+=1,e.writeUInt8(r.matchingType,t),t+=1,n.copy(e,t,0,n.length),t+=n.length,ci.encode.bytes=t-s,e.writeUInt16BE(ci.encode.bytes-2,s),e};ci.encode.bytes=0;ci.decode=function(r,e){e||(e=0);let t=e,s={},n=r.readUInt16BE(e);return e+=2,s.usage=r.readUInt8(e),e+=1,s.selector=r.readUInt8(e),e+=1,s.matchingType=r.readUInt8(e),e+=1,s.certificate=r.slice(e,t+n+2),e+=s.certificate.length,ci.decode.bytes=e-t,s};ci.decode.bytes=0;ci.encodingLength=function(r){return 5+Ke.byteLength(r.certificate)};var US=Ve.record=function(r){switch(r.toUpperCase()){case"A":return so;case"PTR":return yn;case"CNAME":return MF;case"DNAME":return UF;case"TXT":return Zi;case"NULL":return eo;case"AAAA":return no;case"SRV":return ro;case"HINFO":return to;case"CAA":return Rs;case"NS":return Ji;case"SOA":return Qi;case"MX":return la;case"OPT":return Ps;case"DNSKEY":return ss;case"RRSIG":return ri;case"RP":return si;case"NSEC":return ni;case"NSEC3":return ii;case"SSHFP":return ks;case"DS":return oi;case"NAPTR":return ai;case"TLSA":return ci}return Yi},Dr=Ve.answer={};Dr.encode=function(r,e,t){e||(e=Ke.alloc(Dr.encodingLength(r))),t||(t=0);let s=t;if(ve.encode(r.name,e,t),t+=ve.encode.bytes,e.writeUInt16BE(io.toType(r.type),t),r.type.toUpperCase()==="OPT"){if(r.name!==".")throw new Error("OPT name must be root.");e.writeUInt16BE(r.udpPayloadSize||4096,t+2),e.writeUInt8(r.extendedRcode||0,t+4),e.writeUInt8(r.ednsVersion||0,t+5),e.writeUInt16BE(r.flags||0,t+6),t+=8,Ps.encode(r.options||[],e,t),t+=Ps.encode.bytes}else{let n=Ey.toClass(r.class===void 0?"IN":r.class);r.flush&&(n|=MS),e.writeUInt16BE(n,t+2),e.writeUInt32BE(r.ttl||0,t+4),t+=8;let i=US(r.type);i.encode(r.data,e,t),t+=i.encode.bytes}return Dr.encode.bytes=t-s,e};Dr.encode.bytes=0;Dr.decode=function(r,e){e||(e=0);let t={},s=e;if(t.name=ve.decode(r,e),e+=ve.decode.bytes,t.type=io.toString(r.readUInt16BE(e)),t.type==="OPT")t.udpPayloadSize=r.readUInt16BE(e+2),t.extendedRcode=r.readUInt8(e+4),t.ednsVersion=r.readUInt8(e+5),t.flags=r.readUInt16BE(e+6),t.flag_do=(t.flags>>15&1)===1,t.options=Ps.decode(r,e+8),e+=8+Ps.decode.bytes;else{let n=r.readUInt16BE(e+2);t.ttl=r.readUInt32BE(e+4),t.class=Ey.toString(n&LF),t.flush=!!(n&MS);let i=US(t.type);t.data=i.decode(r,e+8),e+=8+i.decode.bytes}return Dr.decode.bytes=e-s,t};Dr.decode.bytes=0;Dr.encodingLength=function(r){let e=r.data!==null&&r.data!==void 0?r.data:r.options;return ve.encodingLength(r.name)+8+US(r.type).encodingLength(e)};var xn=Ve.question={};xn.encode=function(r,e,t){e||(e=Ke.alloc(xn.encodingLength(r))),t||(t=0);let s=t;return ve.encode(r.name,e,t),t+=ve.encode.bytes,e.writeUInt16BE(io.toType(r.type),t),t+=2,e.writeUInt16BE(Ey.toClass(r.class===void 0?"IN":r.class),t),t+=2,xn.encode.bytes=t-s,r};xn.encode.bytes=0;xn.decode=function(r,e){e||(e=0);let t=e,s={};return s.name=ve.decode(r,e),e+=ve.decode.bytes,s.type=io.toString(r.readUInt16BE(e)),e+=2,s.class=Ey.toString(r.readUInt16BE(e)),e+=2,s.class&IR&&(s.class&=DF),xn.decode.bytes=e-t,s};xn.decode.bytes=0;xn.encodingLength=function(r){return ve.encodingLength(r.name)+4};Ve.AUTHORITATIVE_ANSWER=1024;Ve.TRUNCATED_RESPONSE=512;Ve.RECURSION_DESIRED=256;Ve.RECURSION_AVAILABLE=128;Ve.AUTHENTIC_DATA=32;Ve.CHECKING_DISABLED=16;Ve.DNSSEC_OK=32768;Ve.encode=function(r,e,t){let s=!e;s&&(e=Ke.alloc(Ve.encodingLength(r))),t||(t=0);let n=t;return r.questions||(r.questions=[]),r.answers||(r.answers=[]),r.authorities||(r.authorities=[]),r.additionals||(r.additionals=[]),bn.encode(r,e,t),t+=bn.encode.bytes,t=Qh(r.questions,xn,e,t),t=Qh(r.answers,Dr,e,t),t=Qh(r.authorities,Dr,e,t),t=Qh(r.additionals,Dr,e,t),Ve.encode.bytes=t-n,s&&Ve.encode.bytes!==e.length?e.slice(0,Ve.encode.bytes):e};Ve.encode.bytes=0;Ve.decode=function(r,e){e||(e=0);let t=e,s=bn.decode(r,e);return e+=bn.decode.bytes,e=_y(s.questions,xn,r,e),e=_y(s.answers,Dr,r,e),e=_y(s.authorities,Dr,r,e),e=_y(s.additionals,Dr,r,e),Ve.decode.bytes=e-t,s};Ve.decode.bytes=0;Ve.encodingLength=function(r){return bn.encodingLength(r)+Hu(r.questions||[],xn)+Hu(r.answers||[],Dr)+Hu(r.authorities||[],Dr)+Hu(r.additionals||[],Dr)};Ve.streamEncode=function(r){let e=Ve.encode(r),t=Ke.alloc(2);t.writeUInt16BE(e.byteLength);let s=Ke.concat([t,e]);return Ve.streamEncode.bytes=s.byteLength,s};Ve.streamEncode.bytes=0;Ve.streamDecode=function(r){let e=r.readUInt16BE(0);if(r.byteLength<e+2)return null;let t=Ve.decode(r.slice(2));return Ve.streamDecode.bytes=Ve.decode.bytes,t};Ve.streamDecode.bytes=0;function Hu(r,e){let t=0;for(let s=0;s<r.length;s++)t+=e.encodingLength(r[s]);return t}function Qh(r,e,t,s){for(let n=0;n<r.length;n++)e.encode(r[n],t,s),s+=e.encode.bytes;return s}function _y(r,e,t,s){for(let n=0;n<r.length;n++)r[n]=e.decode(t,s),s+=e.decode.bytes;return s}});var BR=re((Zle,PR)=>{"use strict";var kR=$F;process.nextTick(zF,42);PR.exports=jF;function jF(r){var e=s;return t;function t(n){e(n||FF)}function s(n){var i=[n];e=o,r(a);function o(c){i.push(c)}function a(c){var d=arguments;for(e=HF(c)?s:u;i.length;)u(i.shift());function u(f){kR(qF,f,d)}}}}function HF(r){return Object.prototype.toString.call(r)==="[object Error]"}function FF(){}function qF(r,e){r.apply(null,e)}function zF(r){r===42&&(kR=process.nextTick)}function $F(r,e,t){process.nextTick(function(){r(e,t)})}});var LR=re((ehe,OR)=>{"use strict";var jS=RR(),VF=require("dgram"),KF=BR(),WF=require("events"),FS=require("os"),HS=function(){};OR.exports=function(r){r||(r={});var e=new WF.EventEmitter,t=typeof r.port=="number"?r.port:5353,s=r.type||"udp4",n=r.ip||r.host||(s==="udp4"?"224.0.0.251":null),i={address:n,port:t},o={},a=!1,c=null;if(s==="udp6"&&(!n||!r.interface))throw new Error("For IPv6 multicast you must specify `ip` and `interface`");var d=r.socket||VF.createSocket({type:s,reuseAddr:r.reuseAddr!==!1,toString:function(){return s}});d.on("error",function(f){f.code==="EACCES"||f.code==="EADDRINUSE"?e.emit("error",f):e.emit("warning",f)}),d.on("message",function(f,h){try{f=jS.decode(f)}catch(y){e.emit("warning",y);return}e.emit("packet",f,h),f.type==="query"&&e.emit("query",f,h),f.type==="response"&&e.emit("response",f,h)}),d.on("listening",function(){t||(t=i.port=d.address().port),r.multicast!==!1&&(e.update(),c=setInterval(e.update,5e3),d.setMulticastTTL(r.ttl||255),d.setMulticastLoopback(r.loopback!==!1))});var u=KF(function(f){if(!t||r.bind===!1)return f(null);d.once("error",f),d.bind(t,r.bind||r.interface,function(){d.removeListener("error",f),f(null)})});return u(function(f){if(f)return e.emit("error",f);e.emit("ready")}),e.send=function(f,h,y){if(typeof h=="function")return e.send(f,null,h);y||(y=HS),h?!h.host&&!h.address&&(h.address=i.address):h=i,u(v);function v(S){if(a)return y();if(S)return y(S);var C=jS.encode(f);d.send(C,0,C.length,h.port,h.address||h.host,y)}},e.response=e.respond=function(f,h,y){Array.isArray(f)&&(f={answers:f}),f.type="response",f.flags=(f.flags||0)|jS.AUTHORITATIVE_ANSWER,e.send(f,h,y)},e.query=function(f,h,y,v){if(typeof h=="function")return e.query(f,null,null,h);if(typeof h=="object"&&h&&h.port)return e.query(f,null,h,y);if(typeof y=="function")return e.query(f,h,null,y);v||(v=HS),typeof f=="string"&&(f=[{name:f,type:h||"ANY"}]),Array.isArray(f)&&(f={type:"query",questions:f}),f.type="query",e.send(f,y,v)},e.destroy=function(f){if(f||(f=HS),a)return process.nextTick(f);a=!0,clearInterval(c);for(var h in o)try{d.dropMembership(n,h)}catch{}o={},d.close(f)},e.update=function(){for(var f=r.interface?[].concat(r.interface):XF(),h=!1,y=0;y<f.length;y++){var v=f[y];if(!o[v])try{d.addMembership(n,v),o[v]=!0,h=!0}catch(S){e.emit("warning",S)}}if(h){if(d.setMulticastInterface)try{d.setMulticastInterface(r.interface||GF())}catch(S){e.emit("warning",S)}e.emit("networkInterface")}},e};function GF(){for(var r=FS.networkInterfaces(),e=Object.keys(r),t=0;t<e.length;t++)for(var s=r[e[t]],n=0;n<s.length;n++){var i=s[n];if(NR(i.family)&&!i.internal)return FS.platform()==="darwin"&&e[t]==="en0"?i.address:"0.0.0.0"}return"127.0.0.1"}function XF(){for(var r=FS.networkInterfaces(),e=Object.keys(r),t=[],s=0;s<e.length;s++)for(var n=r[e[s]],i=0;i<n.length;i++){var o=n[i];if(NR(o.family)){t.push(o.address);break}}return t}function NR(r){return r===4||r==="IPv4"}});var O7={};Ef(O7,{AV1Obu:()=>O9,AV1RtpPayload:()=>u_,AttributeKeys:()=>yz,BitStream:()=>ba,BitWriter:()=>Ep,BitWriter2:()=>cx,BufferChain:()=>ZF,CONSENT_FAILURES:()=>D_,CONSENT_INTERVAL:()=>cB,COOKIE:()=>bx,Candidate:()=>Sa,CandidatePair:()=>O_,CandidatePairState:()=>dB,CipherContext:()=>Ip,CipherSuite:()=>Xy,CipherSuiteList:()=>r9,Connection:()=>yB,ConnectionStates:()=>J$,CurveType:()=>y2,DEFAULT_MAX_MESSAGE_SIZE:()=>Xu,DePacketizerBase:()=>$q,Directions:()=>Uy,DtlsClient:()=>T_,DtlsServer:()=>DP,DtlsSocket:()=>A2,DtlsStates:()=>l$,Event:()=>Te,EventDisposer:()=>Xk,ExtensionProfiles:()=>ya,FINGERPRINT_LENGTH:()=>MP,FINGERPRINT_XOR:()=>UP,GenericNack:()=>Op,GroupDescription:()=>Zu,H264RtpPayload:()=>U9,HEADER_LENGTH:()=>co,HashAlgorithm:()=>Ap,ICE_COMPLETED:()=>L_,ICE_FAILED:()=>xp,INTEGRITY_LENGTH:()=>I2,IPV4_PROTOCOL:()=>R2,IPV6_PROTOCOL:()=>k2,IceCandidate:()=>rE,IceGathererStates:()=>x$,IceTransportStates:()=>y$,Inactive:()=>OB,Int:()=>Pp,MediaDescription:()=>ox,MediaStream:()=>LB,MediaStreamTrack:()=>jp,MediaStreamTrackFactory:()=>o$,Message:()=>Qs,NalUnitType:()=>ga,NamedCurveAlgorithm:()=>ho,NamedCurveAlgorithmList:()=>g2,OpusRtpPayload:()=>H9,PacketChunk:()=>Q9,PacketResult:()=>eP,PacketStatus:()=>Z9,PictureLossIndication:()=>Bp,Profiles:()=>Uq,PromiseQueue:()=>aq,ProtectionProfileAeadAes128Gcm:()=>ad,ProtectionProfileAes128CmHmacSha1_80:()=>df,RETRY_MAX:()=>jP,RETRY_RTO:()=>HP,RTCCertificate:()=>tE,RTCDataChannel:()=>j2,RTCDataChannelParameters:()=>H2,RTCDtlsFingerprint:()=>sx,RTCDtlsParameters:()=>nx,RTCDtlsTransport:()=>q_,RTCIceCandidate:()=>QB,RTCIceGatherer:()=>YB,RTCIceParameters:()=>sE,RTCIceTransport:()=>XB,RTCP_HEADER_SIZE:()=>Qy,RTCPeerConnection:()=>W$,RTCRtcpFeedback:()=>wB,RTCRtcpParameters:()=>Uz,RTCRtpCodecParameters:()=>_a,RTCRtpCodingParameters:()=>_B,RTCRtpHeaderExtensionParameters:()=>mi,RTCRtpReceiver:()=>cE,RTCRtpRtxParameters:()=>SB,RTCRtpSender:()=>R7,RTCRtpSimulcastParameters:()=>F2,RTCRtpTransceiver:()=>NB,RTCSctpCapabilities:()=>iE,RTCSctpTransport:()=>E7,RTCSessionDescription:()=>A7,RTCStatsReport:()=>BB,RTP_EXTENSION_URI:()=>Yt,ReceiverEstimatedMaxBitrate:()=>Np,RecvDelta:()=>wp,Recvonly:()=>W2,Red:()=>E2,RedEncoder:()=>vP,RedHandler:()=>wP,RedHeader:()=>S_,RtcpHeader:()=>go,RtcpPacketConverter:()=>iP,RtcpPayloadSpecificFeedback:()=>tf,RtcpReceiverInfo:()=>xx,RtcpRrPacket:()=>rf,RtcpSenderInfo:()=>_2,RtcpSourceDescriptionPacket:()=>Dp,RtcpSrPacket:()=>sd,RtcpTransportLayerFeedback:()=>rd,RtpBuilder:()=>cz,RtpHeader:()=>po,RtpPacket:()=>mo,RtpRouter:()=>I7,RunLengthChunk:()=>Qu,SDPManager:()=>P7,Sendonly:()=>K2,Sendrecv:()=>G2,SessionDescription:()=>_p,SignalingStates:()=>Y$,SignatureAlgorithm:()=>pi,SignatureScheme:()=>r_,SourceDescriptionChunk:()=>w2,SourceDescriptionItem:()=>S2,SrtcpSession:()=>PP,SrtpAuthenticationError:()=>nd,SrtpContext:()=>Rp,SrtpSession:()=>BP,SsrcDescription:()=>ax,StatusVectorChunk:()=>Y9,StunOverTurnProtocol:()=>JP,StunProtocol:()=>Zy,TcpTransport:()=>e9,TransceiverManager:()=>N7,TransportWideCC:()=>Lp,TurnProtocol:()=>ZP,UdpTransport:()=>Gy,Vp8RtpPayload:()=>q9,Vp9RtpPayload:()=>$9,WeriftError:()=>dq,addSDPHeader:()=>n2,andDirection:()=>Q2,buffer2ArrayBuffer:()=>tq,bufferArrayXor:()=>JF,bufferReader:()=>is,bufferWriter:()=>er,bufferWriterLE:()=>Uk,bufferXor:()=>YF,candidateFoundation:()=>ex,candidateFromIce:()=>of,candidateFromSdp:()=>aE,candidatePairPriority:()=>tx,candidatePriority:()=>Sp,candidateToIce:()=>JB,candidateToSdp:()=>oE,certificateTypes:()=>s9,classes:()=>P2,codecParametersFromString:()=>zp,codecParametersToString:()=>j$,compactNtp:()=>eE,crc32:()=>$k,crc32c:()=>h2,createBufferWriter:()=>vp,createSelfSignedCertificate:()=>i$,createStunOverTurnClient:()=>k_,createTurnClient:()=>tB,dePacketizeRtpPackets:()=>Vq,debug:()=>ut,deepMerge:()=>FB,defaultOptions:()=>uB,defaultPeerConfig:()=>G$,depacketizerCodecs:()=>Kq,deserializeAbsSendTime:()=>mP,deserializeAudioLevelIndication:()=>gP,deserializeString:()=>hP,deserializeUint16BE:()=>pP,deserializeVideoOrientation:()=>yP,dumpBuffer:()=>eq,enumerate:()=>Wq,findCodecByMimeType:()=>d2,findPort:()=>Wk,fingerprint:()=>Y2,generateStatsId:()=>qt,getBit:()=>ye,getDataChannelMessageSize:()=>bB,getGlobalIp:()=>Nz,getHostAddresses:()=>gB,getStatsTimestamp:()=>Ea,growBufferSize:()=>f_,int:()=>Yu,interfaceAddress:()=>ux,isDtls:()=>DB,isLinkLocalAddress:()=>mB,isMedia:()=>K9,isRtcp:()=>oP,keyLength:()=>k9,leb128decode:()=>D9,makeIntegrityKey:()=>rB,methods:()=>B2,microTime:()=>UB,milliTime:()=>Z2,nodeIpAddress:()=>j_,normalizeFamilyNodeV18:()=>Tp,normalizeFingerprintAlgorithm:()=>J2,normalizeFingerprintValue:()=>rx,ntpTime:()=>jB,ntpTime2Sec:()=>nP,paddingBits:()=>QF,paddingByte:()=>Cp,paddingLength:()=>I_,parseGroup:()=>Ky,parseIceServers:()=>HB,parseMessage:()=>vx,random16:()=>l2,random32:()=>Wy,randomPort:()=>m2,randomPorts:()=>cq,reverseDirection:()=>MB,reverseSimulcastDirection:()=>s$,rtpHeaderExtensionsParser:()=>aP,saltLength:()=>P9,serializeAbsSendTime:()=>lP,serializeAudioLevelIndication:()=>Zq,serializeRepairedRtpStreamId:()=>uP,serializeSdesMid:()=>cP,serializeSdesRTPStreamID:()=>dP,serializeTransportWideCC:()=>fP,serverReflexiveCandidate:()=>lB,signatures:()=>x2,sortCandidatePairs:()=>fB,supportedAudioCodecs:()=>Hz,supportedCodecs:()=>V2,supportedVideoCodecs:()=>jz,timer:()=>Gq,timestampSeconds:()=>Hp,uint16Add:()=>Ur,uint16Gt:()=>dx,uint16Gte:()=>oq,uint24:()=>Kk,uint32Add:()=>Yc,uint32Gt:()=>fi,uint32Gte:()=>Gu,uint8Add:()=>Vk,unwrapRtx:()=>_P,url2Address:()=>Oz,useAV1X:()=>TB,useAbsSendTime:()=>Vz,useAudioLevelIndication:()=>Wz,useDependencyDescriptor:()=>Kz,useFIR:()=>Mz,useH264:()=>EB,useNACK:()=>Jp,useOPUS:()=>z2,usePCMU:()=>$2,usePLI:()=>ff,useREMB:()=>Qp,useRepairedRtpStreamId:()=>zz,useSdesMid:()=>Fz,useSdesRTPStreamId:()=>qz,useTWCC:()=>vB,useTransportWideCC:()=>$z,useVP8:()=>q2,useVP9:()=>CB,useVideoOrientation:()=>Gz,validateAddress:()=>U_,validateRemoteCandidate:()=>M_,wrapRtx:()=>EP});function l2(){return f2.jspack.Unpack("!H",(0,u2.randomBytes)(2))[0]}function Wy(){return f2.jspack.Unpack("!L",(0,u2.randomBytes)(4))[0]}function YF(r,e){if(r.length!==e.length)throw new TypeError("[webrtc-stun] You can not XOR buffers which length are different");let t=r.length,s=Buffer.allocUnsafe(t);for(let n=0;n<t;n++)s[n]=r[n]^e[n];return s}function JF(r){let e=[...r].sort((s,n)=>s.length-n.length).reverse()[0].length,t=Buffer.allocUnsafe(e);for(let s=0;s<e;s++)t[s]=0,r.forEach(n=>{t[s]^=n[s]??0});return t}function ye(r,e,t=1){let s=r.toString(2).split("");s=[...Array(8-s.length).fill("0"),...s];let n=s.slice(e,e+t).join("");return Number.parseInt(n,2)}function Cp(r){let e=r.toString(2).split("");return[...[...Array(8-e.length)].map(()=>"0"),...e].join("")}function QF(r,e){let t=r.toString(2);return[...[...Array(e-t.length)].map(()=>"0"),...t].join("")}function er(r,e){return vp(r)(e)}function vp(r,e){let t=r.reduce((n,i)=>n+i,0),s=e?Buffer.alloc(t):void 0;return n=>{let i=s||Buffer.alloc(t),o=0;return n.forEach((a,c)=>{let d=r[c];d===8?i.writeBigUInt64BE(a,o):i.writeUIntBE(a,o,d),o+=d}),i}}function Uk(r,e){let t=r.reduce((i,o)=>i+o,0),s=Buffer.alloc(t),n=0;return e.forEach((i,o)=>{let a=r[o];a===8?s.writeBigUInt64LE(i,n):s.writeUIntLE(i,n,a),n+=a}),s}function is(r,e){let t=0;return e.map(s=>{let n;return s===8?n=r.readBigUInt64BE(t):n=r.readUIntBE(t,s),t+=s,n})}function tq(r){return r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength)}function jk(r){return typeof r!="string"}function Hk(r){let e=new Array(256),t=0;for(let s=0;s<256;++s)t=s,t=t&1?r^t>>>1:t>>>1,t=t&1?r^t>>>1:t>>>1,t=t&1?r^t>>>1:t>>>1,t=t&1?r^t>>>1:t>>>1,t=t&1?r^t>>>1:t>>>1,t=t&1?r^t>>>1:t>>>1,t=t&1?r^t>>>1:t>>>1,t=t&1?r^t>>>1:t>>>1,e[s]=t;return new Int32Array(e)}function Fk(r){let e=new Int32Array(4096),t=0,s=0,n=0;for(n=0;n<256;++n)e[n]=r[n];for(n=0;n<256;++n)for(s=r[n],t=256+n;t<4096;t+=256)s=e[t]=s>>>8^r[s&255];let i=[];for(n=1;n<16;++n)i[n-1]=e.subarray(n*256,n*256+256);return i}function qk(r,e,t){let s=e^-1,n=0,i=r.length,o=0,a=0;for(;n<i;)o=r.charCodeAt(n++),o<128?s=s>>>8^t[(s^o)&255]:o<2048?(s=s>>>8^t[(s^(192|o>>6&31))&255],s=s>>>8^t[(s^(128|o&63))&255]):o>=55296&&o<57344?(o=(o&1023)+64,a=r.charCodeAt(n++)&1023,s=s>>>8^t[(s^(240|o>>8&7))&255],s=s>>>8^t[(s^(128|o>>2&63))&255],s=s>>>8^t[(s^(128|a>>6&15|(o&3)<<4))&255],s=s>>>8^t[(s^(128|a&63))&255]):(s=s>>>8^t[(s^(224|o>>12&15))&255],s=s>>>8^t[(s^(128|o>>6&63))&255],s=s>>>8^t[(s^(128|o&63))&255]);return~s>>>0}function zk(r,e,t,s){let[n,i,o,a,c,d,u,f,h,y,v,S,C,O,K]=s,z=e^-1,Q=0,oe=r.length-15;for(;Q<oe;)z=K[r[Q++]^z&255]^O[r[Q++]^z>>>8&255]^C[r[Q++]^z>>>16&255]^S[r[Q++]^z>>>24]^v[r[Q++]]^y[r[Q++]]^h[r[Q++]]^f[r[Q++]]^u[r[Q++]]^d[r[Q++]]^c[r[Q++]]^a[r[Q++]]^o[r[Q++]]^i[r[Q++]]^n[r[Q++]]^t[r[Q++]];for(oe+=15;Q<oe;)z=z>>>8^t[(z^r[Q++])&255];return~z>>>0}function $k(r,e=0){return jk(r)?zk(r,e,e_,nq):qk(r,e,e_)}function h2(r,e=0){return jk(r)?zk(r,e,t_,iq):qk(r,e,t_)}function Vk(r,e){return r+e&255}function Ur(r,e){return r+e&65535}function Yc(r,e){return Number(BigInt(r)+BigInt(e)&0xffffffffn)}function Kk(r){return r&16777215}function dx(r,e){return r<e&&e-r>32768||r>e&&r-e<32768}function oq(r,e){return r===e||dx(r,e)}function fi(r,e){return r<e&&e-r>2147483648||r>e&&r-e<2147483648}function Gu(r,e){return r===e||fi(r,e)}async function m2(r="udp4",e){let t=(0,p2.createSocket)(r);setImmediate(()=>t.bind({port:0,address:ux(r,e)})),await new Promise(n=>{t.once("error",n),t.once("listening",n)});let s=t.address()?.port;return await new Promise(n=>t.close(()=>n())),s}async function cq(r,e="udp4",t){return Promise.all([...Array(r)].map(()=>m2(e,t)))}async function Wk(r,e,t="udp4",s){let n;for(let i=r;i<=e;i++){let o=(0,p2.createSocket)(t);if(setImmediate(()=>o.bind({port:i,address:ux(t,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())),r<=n&&n<=e)break}if(!n)throw new Error("port not found");return n}function Tp(r){return r==="IPv4"?4:r==="IPv6"?6:r}function o9(r,e,t){switch(t){case ho.secp256r1_23:return fq({publicKey:r,privateKey:e});case ho.x25519_29:return Buffer.from(i9.default.scalarMult(e,r));default:throw new Error}}function MR(r,e,t){let s=(0,lx.createHmac)(r,e);return s.update(t),s.digest()}function $p(r,e,t,s="sha256"){let n=t,i=[],o=e;do{o=MR(s,r,o);let a=MR(s,r,Buffer.concat([o,e]));i.push(a),t-=a.length}while(t>0);return Buffer.concat(i,n)}function a9(r,e,t){let s=Buffer.concat([Buffer.from("master secret"),e,t]);return $p(r,s,48)}function c9(r,e){let t=d9("sha256",e);return $p(r,Buffer.concat([Buffer.from("extended master secret"),t]),48)}function lq(r,e,t,s,n,i){let o=i?s:n,a=i?n:s,c=Buffer.concat([Buffer.from(r),o,a]);return $p(t,c,e)}function d9(r,e){return(0,lx.createHash)(r).update(e).digest()}function u9(r,e,t,s=12){let n=d9("sha256",e);return $p(r,Buffer.concat([Buffer.from(t),n]),s)}function hq(r,e){return u9(r,e,"client finished")}function pq(r,e){return u9(r,e,"server finished")}function mq(r,e,t,s,n,i,o="sha256"){let a=s*2+n*2,c=r,d=Buffer.concat([t,e]),u=$p(c,Buffer.concat([Buffer.from("key expansion"),d]),a,o),f=(0,n9.createDecode)(u),h=f.readBuffer(s),y=f.readBuffer(s),v=f.readBuffer(n),S=f.readBuffer(n),C=Buffer.alloc(i,0),O=Buffer.alloc(i,0);return v.copy(C,0),S.copy(O,0),{clientWriteKey:h,serverWriteKey:y,clientNonce:C,serverNonce:O}}function kq(){let r=new Xp;return r.id=Gp.RSA,r.name="RSA",r.keyType=Wp.RSA,r}function Pq(){let r=new Xp;return r.id=Gp.ECDHE_RSA,r.name="ECDHE_RSA",r.signType=hx.ECDHE,r.keyType=Wp.RSA,r}function Bq(){let r=new Xp;return r.id=Gp.ECDHE_ECDSA,r.name="ECDHE_ECDSA",r.signType=hx.ECDHE,r.keyType=Wp.ECDSA,r}function Nq(){let r=new Xp;return r.id=Gp.PSK,r.name="PSK",r.signType=hx.NULL,r.keyType=Wp.PSK,r}function Oq(){let r=new Xp;return r.id=Gp.ECDHE_PSK,r.name="ECDHE_PSK",r.signType=hx.ECDHE,r.keyType=Wp.PSK,r}function b9(r){switch(r){case mr.TLS_RSA_WITH_AES_128_GCM_SHA256:return di(mr.TLS_RSA_WITH_AES_128_GCM_SHA256,"TLS_RSA_WITH_AES_128_GCM_SHA256","aes-128-gcm",UR,Zh);case mr.TLS_RSA_WITH_AES_256_GCM_SHA384:return di(mr.TLS_RSA_WITH_AES_256_GCM_SHA384,"TLS_RSA_WITH_AES_256_GCM_SHA384","aes-256-gcm",UR,ep,"sha384");case mr.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:return di(mr.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,"TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256","aes-128-gcm",jR,Zh);case mr.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:return di(mr.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,"TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384","aes-256-gcm",jR,ep,"sha384");case mr.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:return di(mr.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,"TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256","aes-128-gcm",HR,Zh);case mr.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:return di(mr.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,"TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384","aes-256-gcm",HR,ep,"sha384");case mr.TLS_PSK_WITH_AES_128_GCM_SHA256:return di(mr.TLS_PSK_WITH_AES_128_GCM_SHA256,"TLS_PSK_WITH_AES_128_GCM_SHA256","aes-128-gcm",FR,Zh,"sha256");case mr.TLS_PSK_WITH_AES_256_GCM_SHA384:return di(mr.TLS_PSK_WITH_AES_256_GCM_SHA384,"TLS_PSK_WITH_AES_256_GCM_SHA384","aes-256-gcm",FR,ep,"sha384");case mr.TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256:return di(mr.TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256,"TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256","aes-128-gcm",qR,Zh,"sha256");case mr.TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384:return di(mr.TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384,"TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384","aes-256-gcm",qR,ep,"sha384");default:break}return null}function di(r,e,t,s,n,i="sha256"){let o=new Dq;return o.id=r,o.name=e,o.blockAlgorithm=t,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 w9(r){switch(r){case ho.secp256r1_23:{let{privateKey:e,publicKey:t}=uq();return{curve:r,privateKey:e,publicKey:t}}case ho.x25519_29:{let e=v9.default.box.keyPair();return{curve:r,privateKey:Buffer.from(e.secretKey.buffer),publicKey:Buffer.from(e.publicKey.buffer)}}default:throw new Error}}function Mq(r,e){return Buffer.from((0,I9.encode)(r,e).slice())}function D9(r){let e=0,t=0;for(let s=0;s<8;s++){let n=r.readUInt8(s);if(e|=(n&127)<<s*7,t++,!(n&128))break}return[e,t]}function Vq(r,e,t){let s=n=>{let i=[];for(let c of e){let d=n.deSerialize(c.payload,t);d.fragment?(t??=Buffer.alloc(0),t=d.fragment):d.payload&&(t=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:t}};switch(r.toUpperCase()){case"AV1":{let n=e.map(a=>u_.deSerialize(a.payload)),i=!!n.find(a=>a.isKeyframe),o=u_.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(U9);case"VP8":return s(q9);case"VP9":return s($9);case"OPUS":return s(H9);default:throw new Error}}function Wq(r){return r.map((e,t)=>[t,e])}function f_(r,e){let t=Buffer.alloc(e);return r.copy(t),t}function Pp(r){return Number.parseInt(r.toString(),10)}function K9(r){let e=r[0];return e>127&&e<192}function $R(r){return r%4==0?0:4-r%4}function oP(r){return r.length>=2&&r[1]>=192&&r[1]<=208}function aP(r,e){return r.map(t=>{let s=e[t.id];if(!s)return{uri:"unknown",value:t.payload};switch(s){case Yt.sdesMid:case Yt.sdesRTPStreamID:case Yt.repairedRtpStreamId:return{uri:s,value:hP(t.payload)};case Yt.transportWideCC:return{uri:s,value:pP(t.payload)};case Yt.absSendTime:return{uri:s,value:mP(t.payload)};case Yt.audioLevelIndication:return{uri:s,value:gP(t.payload)};case Yt.videoOrientation:return{uri:s,value:yP(t.payload)};default:return{uri:s,value:t.payload}}}).reduce((t,s)=>(s&&(t[s.uri]=s.value),t),{})}function cP(r){return Buffer.from(r)}function dP(r){return Buffer.from(r)}function uP(r){return Buffer.from(r)}function fP(r){return er([2],[r])}function lP(r){let e=Buffer.alloc(3),t=r>>14n&0x00ffffffn;return e.writeUIntBE(Number(t),0,3),e}function Zq(r){let e=new ba(Buffer.alloc(1));return e.writeBits(1,1),e.writeBits(7,r),e.uint8Array}function hP(r){return r.toString()}function pP(r){return r.readUInt16BE()}function mP(r){return is(r,[3])[0]}function gP(r){let e=new ba(r);return{v:e.readBits(1)===1,level:e.readBits(7)}}function yP(r){let e=new ba(r);return e.readBits(4),{c:e.readBits(1),f:e.readBits(1),r1:e.readBits(1),r0:e.readBits(1)}}function _P(r,e,t){return new mo(new po({payloadType:e,marker:r.header.marker,sequenceNumber:C2.jspack.Unpack("!H",r.payload.subarray(0,2))[0],timestamp:r.header.timestamp,ssrc:t}),r.payload.subarray(2))}function EP(r,e,t,s){return new mo(new po({payloadType:e,marker:r.header.marker,sequenceNumber:t,timestamp:r.header.timestamp,ssrc:s,csrc:r.header.csrc,extensions:r.header.extensions}),Buffer.concat([Buffer.from(C2.jspack.Pack("!H",[r.header.sequenceNumber])),r.payload]))}function T2(r,e,t="Failed to authenticate SRTP packet"){let s=r.length-e;Mp(r.length>=YR+e,t);let n=AP(()=>po.deSerialize(r.subarray(0,s)),t);return n.paddingSize=0,Mp(n.payloadOffset>=YR&&n.payloadOffset<=s,t),n}function TP(r,e,t,s="Failed to authenticate SRTCP packet"){return Mp(r.length>=rz+e+t,s),AP(()=>go.deSerialize(r.subarray(0,Qy)),s)}function Mp(r,e){if(!r)throw new nd(e)}function AP(r,e){try{return r()}catch{throw new nd(e)}}function IP(r,e,t="Failed to authenticate SRTP packet"){if(!r.padding)return r.paddingSize=0,r;Mp(e.length>r.payloadOffset,t);let s=e[e.length-1];return Mp(s>0&&s<=e.length-r.payloadOffset,t),r.paddingSize=s,r}function QR(r,e,t){if(r.length!==e.length||!(0,An.timingSafeEqual)(r,e))throw new nd(t)}function ek(r,e){try{r.final()}catch{throw new nd(`Failed to authenticate ${e} packet`)}}function rp(r){return(0,O2.randomBytes)(r).toString("hex").substring(0,r)}function FP(){return(0,O2.randomBytes)(12)}function Vu(r){let[e]=r,t=Up.default.isV4Format(e)?R2:k2,s=Buffer.alloc(4);return s.writeUInt8(0,0),s.writeUInt8(t,1),s.writeUInt16BE(r[1],2),Buffer.concat([s,Up.default.toBuffer(e)])}function xz(r){if(r.length<4)throw new Error("STUN error code is less than 4 bytes");let e=r.readUInt8(2),t=r.readUInt8(3),s=r.slice(4).toString("utf8");return[e*100+t,s]}function Ku(r){if(r.length<4)throw new Error("STUN address length is less than 4 bytes");let e=r.readUInt8(1),t=r.readUInt16BE(2),s=r.slice(4);switch(e){case R2:if(s.length!=4)throw new Error("STUN address has invalid length for IPv4");return[Up.default.toString(s),t];case k2:if(s.length!=16)throw new Error("STUN address has invalid length for IPv6");return[Up.default.toString(s),t];default:throw new Error("STUN address has unknown protocol")}}function qP(r,e){let t=[...L2,...e],s=r.slice(0,2);for(let n=2;n<r.length;n++){let i=r[n]^t[n-2],o=Buffer.alloc(1);o.writeUIntBE(i,0,1),s=Buffer.concat([s,o])}return s}function Ny(r,e){return Ku(qP(r,e))}function bz(r){let e=Buffer.alloc(4);e.writeUInt16BE(0,0),e.writeUInt8(Math.floor(r[0]/100),2),e.writeUInt8(r[0]%100,3);let t=Buffer.from(r[1],"utf8");return Buffer.concat([e,t])}function Oy(r,e){return qP(Vu(r),e)}function vx(r,e){if(r.length<co)return;let t=r.readUint16BE(2);if(r.length!==co+t)return;let s=r.readUint16BE(0),n=Buffer.from(r.slice(co-12,co)),i=new $P;for(let a=co;a<=r.length-4;){let c=r.readUInt16BE(a),d=r.readUInt16BE(a+2),u=r.slice(a+4,a+4+d),f=4*Math.floor((d+3)/4)-d;if(Object.keys(fk).includes(c.toString())){let[,y,,v]=fk[c];if(v.name===Ny.name?i.setAttribute(y,v(u,n)):i.setAttribute(y,v(u)),y==="FINGERPRINT"){let S=VP(r.slice(0,a));if(i.getAttributeValue("FINGERPRINT")!==S)return}else if(y==="MESSAGE-INTEGRITY"&&e){let S=Cz(r.slice(0,a),e),C=i.getAttributeValue("MESSAGE-INTEGRITY");if(!S.equals(C))return}}a+=4+d+f}let o=i.getAttributes();return i.clear(),new Qs(s&16111,s&272,n,o)}function VP(r){let e=D2(r,r.length-co+MP);return($k(e)^UP)>>>0}function Cz(r,e){let t=D2(r,r.length-co+I2);return Buffer.from((0,N2.createHmac)("sha1",e).update(t).digest("hex"),"hex")}function I_(r){let e=r%4;return e===0?0:4-e}async function tB({address:r,username:e,password:t},{lifetime:s,portRange:n,interfaceAddresses:i,transport:o}={}){s??=Iz,o??="udp";let a=o==="udp"?await Gy.init("udp4",{portRange:n,interfaceAddresses:i}):await e9.init(r),c=new ZP(r,e,t,s,a);return await c.connectionMade(),c}async function k_({address:r,username:e,password:t},{lifetime:s,portRange:n,interfaceAddresses:i,transport:o}={}){let a=await tB({address:r,username:e,password:t},{lifetime:s,portRange:n,interfaceAddresses:i,transport:o});return new JP(a)}function rB(r,e,t){return(0,XP.createHash)("md5").update(Buffer.from([r,e,t].join(":"))).digest()}function hk(r){return(r[0]&192)==64}function ex(r,e,t){let s=`${r}|${e}|${t}`;return(0,sB.createHash)("md5").update(s,"ascii").digest("hex").slice(7)}function Sp(r,e=65535){let s=0;return r==="host"?s=126:r==="prflx"?s=110:r==="srflx"?s=100:s=0,(1<<24)*s+256*e+255}function M_(r){if(!["host","relay","srflx"].includes(r.type))throw new Error(`Unexpected candidate type "${r.type}"`);return r}function fB(r,e){return r.sort((t,s)=>tx(t.localCandidate,t.remoteCandidate,e)-tx(s.localCandidate,s.remoteCandidate,e)).reverse()}function tx(r,e,t){let s=t&&r.priority||e.priority,n=t&&e.priority||r.priority;return 1*Math.min(s,n)+2*Math.max(s,n)+(s>n?1:0)}async function lB(r,e){let t=new Qs(1,0);try{let[s]=await r.request(t,e),n=r.localCandidate;if(!n)throw new Error("not exist");return new Sa(ex("srflx","udp",n.host),n.component,n.transport,Sp("srflx"),s.getAttributeValue("XOR-MAPPED-ADDRESS")[0],s.getAttributeValue("XOR-MAPPED-ADDRESS")[1],"srflx",n.host,n.port)}catch(s){Pz("error serverReflexiveCandidate",s)}}function U_(r){return r&&Number.isNaN(r[1])?[r[0],443]:r}async function Nz(r,e){let t=new Zy;await t.connectionMade(!0,void 0,e);let s=new Qs(1,0),[n]=await t.request(s,r??["stun.l.google.com",19302]);return await t.close(),n.getAttributeValue("XOR-MAPPED-ADDRESS")[0]}function mB(r){return Tp(r.family)===4&&r.address?.startsWith("169.254.")||Tp(r.family)===6&&r.address?.startsWith("fe80::")}function j_(r,{useLinkLocalAddress:e}={}){let t=["ipsec","tun","utun","tap"],s=["vmnet","veth"],n=hB.networkInterfaces();Bz(n);let i=Object.keys(n).map(o=>{for(let c of[...t,...s])if(o.startsWith(c))return{nic:o,addresses:[]};let a=n[o].filter(c=>Tp(c.family)===r&&!pB.default.isLoopback(c.address)&&(e?!0:!mB(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 gB(r,e,t={}){let s=[];return r&&s.push(...j_(4,t)),e&&s.push(...j_(6,t)),s}function mk(r){return r.map((e,t)=>[t,e])}function ao(r,e){let t=r.split(e);return[t[0],t.slice(1).join(e)]}function bB(r){return Buffer.isBuffer(r)?r.length:Buffer.byteLength(r)}function Fz(){return new mi({uri:Yt.sdesMid})}function qz(){return new mi({uri:Yt.sdesRTPStreamID})}function zz(){return new mi({uri:Yt.repairedRtpStreamId})}function $z(){return new mi({uri:Yt.transportWideCC})}function Vz(){return new mi({uri:Yt.absSendTime})}function Kz(){return new mi({uri:Yt.dependencyDescriptor})}function Wz(){return new mi({uri:Yt.audioLevelIndication})}function Gz(){return new mi({uri:Yt.videoOrientation})}function qt(r,...e){let t=e.filter(s=>s!==void 0);return`${r}_${t.join("_")}`}function Ea(){return performance.now()}function Y2(r,e){let t=i=>i.toUpperCase(),s=i=>i.match(/(.{2})/g).join(":"),n=(0,IB.createHash)(e).update(r).digest("hex");return s(t(n))}function J2(r){return r$[r.trim().toLowerCase()]}function rx(r){return r.replace(/[^0-9a-f]/gi,"").toLowerCase()}function DB(r){let e=r[0];return e>19&&e<64}function s$(r){return r==="recv"?"send":"recv"}function MB(r){return r==="sendonly"?"recvonly":r==="recvonly"?"sendonly":r}function HB(r){let e=a=>{if(!a)return;let[c,d]=a.split(":");return[c,Number.parseInt(d)]},t=e(r.find(({urls:a})=>a.includes("stun:"))?.urls.slice(5)),s=e(r.find(({urls:a})=>a.includes("turn:"))?.urls.slice(5)),{credential:n,username:i}=r.find(({urls:a})=>a.includes("turn:"))||{},o={stunServer:t,turnServer:s,turnUsername:i,turnPassword:n};return t$("iceOptions",o),o}function of(r){let e=new rE(r.component,r.foundation,r.host,r.port,r.priority,r.transport,r.type,r.generation,r.ufrag);return e.relatedAddress=r.relatedAddress,e.relatedPort=r.relatedPort,e.tcpType=r.tcptype,e}function JB(r){return new Sa(r.foundation,r.component,r.protocol,r.priority,r.ip,r.port,r.type,r.relatedAddress,r.relatedPort,r.tcpType,r.generation,r.ufrag)}function e0(r){let e=r%4;return e?4-e:0}function v7(r){let e=Buffer.from(""),t=Buffer.from("");return r.forEach(([s,n])=>{let i=n.length+4,o=Buffer.alloc(4);o.writeUInt16BE(s,0),o.writeUInt16BE(i,2),e=Buffer.concat([e,t,o,n]),t=Buffer.concat([...Array(e0(i))].map(()=>Buffer.from("\0")))}),e}function w7(r){let e=[],t=0;for(;t<=r.length-4;){let s=r.readUInt16BE(t),n=r.readUInt16BE(t+2);e.push([s,r.slice(t+4,t+n)]),t+=n+e0(n)}return e}function S$(r){if(r.length<12)throw new Error("SCTP packet length is less than 12 bytes");let e=r.readUInt16BE(0),t=r.readUInt16BE(2),s=r.readUInt32BE(4),n=r.readUInt32LE(8),i=h2(Buffer.concat([r.slice(0,8),Buffer.from("\0\0\0\0"),r.slice(12)]));if(n!==i)throw new Error("SCTP packet has invalid checksum");let o=[],a=12;for(;a+4<=r.length;){let c=r.readUInt8(a),d=r.readUInt8(a+1),u=r.readUInt16BE(a+2),f=r.slice(a+4,a+u),h=w$[c.toString()];if(h)o.push(new h(d,f));else throw new Error("unknown");a+=u+e0(u)}return[e,t,s,o]}function _$(r,e,t,s){let n=Buffer.alloc(8);n.writeUInt16BE(r,0),n.writeUInt16BE(e,2),n.writeUInt32BE(t,4);let i=s.bytes,o=h2(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 E$(r){return r.map((e,t)=>[t,e])}function C$(r){return r.reduce((e,t)=>(e[t]=new Te,e),{})}function Gc(r){return(r-1)%ix}function Wu(r){return(r+1)%ix}function JS(r){let e=r.match(/^IN (IP4|IP6) ([^ ]+)$/);if(!e)throw new Error("exception");return e[2]}function s2(r){return`IN IP${(0,$B.isIPv4)(r)?4:6} ${r}`}function oE(r){let e=`${r.foundation} ${r.component} ${r.protocol} ${r.priority} ${r.ip} ${r.port} typ ${r.type}`;return r.relatedAddress!=null&&(e+=` raddr ${r.relatedAddress}`),r.relatedPort!=null&&(e+=` rport ${r.relatedPort}`),r.tcpType!=null&&(e+=` tcptype ${r.tcpType}`),r.generation!=null&&(e+=` generation ${r.generation}`),r.ufrag!=null&&(e+=` ufrag ${r.ufrag}`),e}function U$(r){let e=[],t=[],s=r.split(`\r
131
+ `);return s.length===1&&(s=r.split(`
132
+ `)),s.forEach(n=>{n.startsWith("m=")?t.push([n]):t.length>0?t[t.length-1].push(n):e.push(n)}),[e,t]}function QS(r){if(r.includes(":")){let e=ao(r.slice(2),":");return[e[0],e[1]]}else return[r.slice(2),void 0]}function Ky(r,e,t=s=>s.toString()){let s=e.split(" ");s.length>0&&r.push(new Zu(s[0],s.slice(1).map(t)))}function aE(r){let e=Sa.fromSdp(r);return of(e)}function n2(r,e){let s=new vy((0,zB.randomBytes)(64)).toString().slice(0,8),n=0;e.origin=`- ${s} ${n} IN IP4 0.0.0.0`,e.msidSemantic.push(new Zu("WMS",["*"])),e.type=r}function zp(r){let e={};return r.split(";").forEach(t=>{if(t.includes("=")){let[s,n]=ao(t,"=");Zz.includes(s)?e[s]=Number(n):e[s]=n}else if(t.includes(":")){let[s,n]=t.split(":");e[s]=Number.isNaN(Number(n))?n:Number(n)}else e[t]=void 0}),e}function j$(r,e="="){let t=Object.entries(r).map(([s,n])=>n?`${s}${e}${n}`:s);if(t.length>0)return t.join(";")}function B7(){return{codecs:{audio:[z2(),$2()],video:[q2()]},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:Xu}}var u2,f2,p2,Gk,Yk,Jk,Qk,af,fx,Ju,lx,n9,i9,Mr,En,l9,p9,Jc,g9,uo,px,v9,Zc,va,ed,cf,wa,td,Cn,Tn,yx,_n,I9,B9,C2,ky,Py,An,sf,id,Xc,OP,hi,li,od,LP,N2,O2,Up,XP,R_,YP,sB,P_,iB,B_,N_,Ly,oB,aB,hB,pB,xB,AB,Dy,IB,RB,H_,kB,X2,qB,zB,$B,Fp,VB,KB,GB,ZB,jy,qp,Hy,fo,i2,o2,a2,c2,k7,Ep,cx,ZF,eq,ba,rq,sq,e_,nq,t_,iq,Yu,aq,ux,dq,ut,Te,Xk,DR,Gy,e9,pi,Ap,Xy,r9,ho,g2,y2,r_,s9,x2,uq,fq,lo,gq,s_,Ip,Rp,b2,f9,Zs,Yy,yq,h9,xq,kp,bq,vq,n_,wq,Sq,_q,Eq,v2,Qc,m9,Cq,y9,x9,Vp,o_,Tq,qS,Kp,Aq,Iq,Rq,hx,Wp,Gp,Xp,Lq,Dq,mr,Zh,ep,UR,jR,HR,FR,qR,mx,gx,ef,Jy,S9,_9,E9,c_,C9,T9,A9,R9,df,ad,Uq,k9,P9,jq,u_,O9,M9,Hq,U9,ga,Fq,qq,zq,H9,q9,$9,$q,Kq,Gq,Qy,go,zR,Bp,Np,Xq,tf,rf,xx,G9,Op,Yq,Lp,Qu,Y9,wp,Q9,Z9,eP,Jq,rd,Dp,w2,S2,sd,_2,nP,Qq,iP,Yt,ez,E2,S_,vP,tz,wP,ya,VR,KR,WR,GR,XR,po,mo,CP,nd,YR,rz,sz,JR,nz,zS,ZR,RP,tp,tk,iz,oz,kP,PP,az,BP,cz,ns,dz,uf,NP,uz,rk,fz,E_,C_,sk,nk,$S,lz,hz,ik,ok,A2,VS,T_,ui,pz,ak,mz,nf,gz,Yp,Fu,DP,bx,MP,UP,co,I2,R2,k2,jP,HP,yz,P2,B2,ck,A_,L2,sp,np,vz,wz,dk,uk,KS,WS,GS,XS,Sz,_z,zP,$P,fk,Ez,Qs,D2,KP,WP,Tz,YS,M2,lk,Zy,vs,Az,Iz,Rz,JP,ZP,Sa,kz,Pz,O_,L_,xp,cB,D_,dB,uB,Bz,Oz,Ut,yB,Lz,pk,U2,Dz,j2,H2,Mz,Jp,ff,Qp,vB,_a,mi,Uz,wB,SB,_B,F2,EB,q2,CB,TB,z2,$2,V2,jz,Hz,gk,yk,Xz,Cy,xk,bk,Yz,Jz,Qz,vk,F_,wk,Zz,PB,Sk,My,e$,BB,NB,OB,K2,W2,G2,Uy,jp,LB,t$,r$,Q2,Z2,n$,UB,Hp,jB,eE,i$,o$,FB,a$,_k,c$,d$,u$,f$,vn,q_,l$,tE,sx,nx,h$,p$,m$,g$,Ek,Ck,XB,y$,x$,YB,QB,rE,sE,gi,nE,Fy,z_,b$,qy,zy,$_,V_,Zp,K_,$y,G_,u7,X_,Y_,p7,g7,x7,v$,w$,J_,S7,Ty,Vy,Tk,Lt,T$,A$,Ak,wn,bp,_7,t2,Ik,I$,Rk,kk,Pk,R$,k$,ix,P$,B$,Bk,Nk,Ok,Lk,N$,O$,L$,D$,qu,Xu,E7,iE,M$,_p,ox,Zu,A7,ax,Ay,cE,ip,I7,H$,zu,F$,q$,ZS,Dk,Mk,R7,z$,$$,P7,op,V$,K$,Sn,W$,d2,G$,X$,N7,Y$,J$,L7=T(()=>{"use strict";u2=require("crypto"),f2=Ge(wo(),1),p2=require("dgram"),Gk=Ge(f6(),1),Yk=require("dgram"),Jk=Ge(require("net"),1),Qk=require("net"),af=require("crypto"),fx=Ge(Xb(),1);_A();Ju=Ge(Zt(),1),lx=require("crypto"),n9=Ge(Zt(),1),i9=Ge(J0(),1);oR();Mr=Ge(Zt(),1),En=Ge(Zt(),1),l9=Ge(Zt(),1),p9=require("crypto"),Jc=Ge(Zt(),1),g9=require("timers/promises"),uo=Ge(Zt(),1),px=require("crypto"),v9=Ge(J0(),1),Zc=Ge(Zt(),1),va=Ge(Zt(),1),ed=Ge(Zt(),1),cf=Ge(Zt(),1),wa=Ge(Zt(),1),td=Ge(Zt(),1),Cn=Ge(Zt(),1),Tn=Ge(Zt(),1),yx=Ge(Zt(),1),_n=Ge(Zt(),1),I9=Ge(Zt(),1),B9=Ge(cR(),1),C2=Ge(wo(),1),ky=require("crypto"),Py=Ge(uR(),1),An=require("crypto"),sf=require("crypto"),id=Ge(Zt(),1),Xc=Ge(Zt(),1),OP=require("timers/promises"),hi=Ge(Zt(),1),li=Ge(Zt(),1),od=Ge(Zt(),1),LP=require("crypto"),N2=require("crypto"),O2=require("crypto");wy();Up=Ge(RS(),1),XP=require("crypto"),R_=Ge(wo(),1),YP=require("timers/promises"),sB=require("crypto"),P_=require("net"),iB=require("crypto"),B_=require("net");wy();N_=Ge(require("timers/promises"),1),Ly=Ge(xR(),1),oB=Ge(LR(),1),aB=require("crypto"),hB=Ge(require("os"),1),pB=Ge(RS(),1),xB=require("events"),AB=require("crypto"),Dy=require("timers/promises"),IB=require("crypto"),RB=require("dgram"),H_=require("perf_hooks"),kB=require("crypto"),X2=require("crypto"),qB=require("timers/promises"),zB=require("crypto"),$B=require("net");wy();Fp=Ge(Xb(),1),VB=require("crypto"),KB=require("timers/promises"),GB=require("crypto"),ZB=require("crypto"),jy=Ge(wo(),1),qp=require("crypto"),Hy=Ge(wo(),1),fo=Ge(wo(),1),i2=require("crypto"),o2=Ge(wo(),1),a2=require("crypto"),c2=require("timers/promises"),k7=require("crypto");Ep=class{constructor(r){this.bitLength=r}value=0;set(r,e,t){return t&=(1<<r)-1,this.value|=t<<this.bitLength-r-e,this}get buffer(){let r=Math.ceil(this.bitLength/8),e=Buffer.alloc(r);return e.writeUIntBE(this.value,0,r),e}},cx=class{constructor(r){if(this.bitLength=r,r>32)throw new Error}_value=0n;offset=0n;set(r,e=1){let t=BigInt(r),s=BigInt(e);return t&=(1n<<s)-1n,this._value|=t<<BigInt(this.bitLength)-s-this.offset,this.offset+=s,this}get value(){return Number(this._value)}get buffer(){let r=Math.ceil(this.bitLength/8),e=Buffer.alloc(r);return e.writeUIntBE(this.value,0,r),e}};ZF=class{buffer;constructor(r){this.buffer=Buffer.alloc(r)}writeInt16BE(r,e){return this.buffer.writeInt16BE(r,e),this}writeUInt8(r,e){return this.buffer.writeUInt8(r,e),this}},eq=r=>"0x"+r.toString("hex").replace(/(.)(.)/g,"$1$2 ").split(" ").filter(e=>e!=null&&e.length>0).join(",0x");ba=class{constructor(r){this.uint8Array=r}position=0;bitsPending=0;writeBits(r,e){if(r==0)return this;e&=4294967295>>>32-r;let t;return this.bitsPending>0?this.bitsPending>r?(this.uint8Array[this.position-1]|=e<<this.bitsPending-r,t=r,this.bitsPending-=r):this.bitsPending==r?(this.uint8Array[this.position-1]|=e,t=r,this.bitsPending=0):(this.uint8Array[this.position-1]|=e>>r-this.bitsPending,t=this.bitsPending,this.bitsPending=0):(t=Math.min(8,r),this.bitsPending=8-t,this.uint8Array[this.position++]=e>>r-t<<this.bitsPending),r-=t,r>0&&this.writeBits(r,e),this}readBits(r){return this._readBits(r)}_readBits(r,e){if(typeof e>"u"&&(e=0),r==0)return e;let t,s;if(this.bitsPending>0){let n=this.uint8Array[this.position-1]&255>>8-this.bitsPending;s=Math.min(this.bitsPending,r),this.bitsPending-=s,t=n>>this.bitsPending}else s=Math.min(8,r),this.bitsPending=8-s,t=this.uint8Array[this.position++]>>this.bitsPending;return r-=s,e=e<<s|t,r>0?this._readBits(r,e):e}seekTo(r){this.position=r/8|0,this.bitsPending=r%8,this.bitsPending>0&&(this.bitsPending=8-this.bitsPending,this.position++)}},rq=3988292384,sq=2197175160;e_=Hk(rq),nq=Fk(e_),t_=Hk(sq),iq=Fk(t_);Yu=r=>Number.parseInt(r,10),aq=class{queue=[];running=!1;push=r=>new Promise((e,t)=>{this.queue.push({promise:r,done:e,failed:t}),this.running||this.run()});async run(){let r=this.queue.shift();if(r){this.running=!0;try{let e=await r.promise();r.done(e)}catch(e){r.failed(e)}this.run()}else this.running=!1}cancel(){this.queue=[]}},ux=(r,e)=>e?e[r]:void 0;dq=class extends Error{message;payload;path;constructor(r){super(r.message)}toJSON(){return{message:this.message,payload:JSON.parse(JSON.stringify(this.payload)),path:this.path}}},ut=Gk.default.debug,Te=class{event={stack:[],promiseStack:[],eventId:0};ended=!1;onended;onerror=r=>{};execute=(...r)=>{if(!this.ended){for(let e of this.event.stack)e.execute(...r);(async()=>{for(let e of this.event.promiseStack)await e.execute(...r)})().catch(e=>{this.onerror(e)})}};complete=()=>{if(!this.ended){for(let r of this.event.stack)r.complete&&r.complete();this.allUnsubscribe(),this.ended=!0,this.onended&&(this.onended(),this.onended=void 0)}};error=r=>{if(!this.ended){for(let e of this.event.stack)e.error&&e.error(r);this.allUnsubscribe()}};allUnsubscribe=()=>{if(this.ended)throw new Error("event completed");this.event={stack:[],promiseStack:[],eventId:0}};subscribe=(r,e,t)=>{let s=this.event.eventId;this.event.stack.push({execute:r,id:s,complete:e,error:t}),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(r){this.subscribe((...e)=>{r.execute(...e)})}queuingSubscribe=(r,e,t)=>{if(this.ended)throw new Error("event completed");let s=this.event.eventId;this.event.promiseStack.push({execute:r,id:s,complete:e,error:t}),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=(r,e,t)=>{let s=this.subscribe((...n)=>{s.unSubscribe(),r(...n)},e,t)};watch=(r,e)=>new Promise((t,s)=>{let n=e&&setTimeout(()=>{s("Event watch timeout")},e),{unSubscribe:i}=this.subscribe((...o)=>{r(...o)&&(n&&clearTimeout(n),i(),t(o))})});asPromise=r=>new Promise((e,t)=>{let s=r&&setTimeout(()=>{t("Event asPromise timeout")},r);this.once((...n)=>{s&&clearTimeout(s),e(n)},()=>{s&&clearTimeout(s),e([])},n=>{s&&clearTimeout(s),t(n)})});get returnTrigger(){let{execute:r,error:e,complete:t}=this;return{execute:r,error:e,complete:t}}get returnListener(){let{subscribe:r,once:e,asPromise:t}=this;return{subscribe:r,once:e,asPromise:t}}get length(){return this.event.stack.length}},Xk=class{_disposer=[];push(r){this._disposer.push(r)}dispose(){this._disposer.forEach(r=>r()),this._disposer=[]}},DR=ut("werift-ice:packages/ice/src/transport.ts"),Gy=class Zk{constructor(e,t={}){this.socketType=e,this.options=t,this.socket=(0,Yk.createSocket)(e),this.socket.on("message",(s,n)=>{Tp(n.family)===6&&([n.address]=n.address.split("%")),this.rinfo=n;try{this.onData(s,[n.address,n.port])}catch(i){DR("onData error",i)}})}type="udp";socket;rinfo;onData=()=>{};closed=!1;static async init(e,t={}){let s=new Zk(e,t);return await s.init(),s}async init(){let e=ux(this.socketType,this.options.interfaceAddresses);if(this.options.port)this.socket.bind({port:this.options.port,address:e});else if(this.options.portRange){let t=await Wk(this.options.portRange[0],this.options.portRange[1],this.socketType,this.options.interfaceAddresses);this.socket.bind({port:t,address:e})}else this.socket.bind({address:e});await new Promise(t=>this.socket.once("listening",t))}send=async(e,t)=>{if(t&&!Jk.isIP(t[0]))return new Promise((s,n)=>{this.socket.send(e,t[1],t[0],i=>{i?(DR("send error",t,e),n(i)):s()})});t=t??[this.rinfo?.address,this.rinfo?.port],this.socket.send(e,t[1],t[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()}})},e9=class t9{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,t)=>{try{this.client=(0,Qk.connect)({port:this.addr[1],host:this.addr[0]},e)}catch(s){t(s)}}),this.client.on("data",e=>{let t=[this.client.remoteAddress,this.client.remotePort];this.onData(e,t)}),this.client.on("end",()=>{this.connect()}),this.client.on("error",e=>{console.log("error",e)}))}async init(){await this.connecting}static async init(e){let t=new t9(e);return await t.init(),t}get address(){return{}}send=async(e,t)=>{await this.connecting,this.client.write(e,s=>{s&&console.log("err",s)})};close=async()=>{this.closed=!0,this.client.destroy()}},pi={rsa_1:1,ecdsa_3:3},Ap={sha256_4:4},Xy={TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256_49195:49195,TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256_49199:49199},r9=Object.values(Xy),ho={x25519_29:29,secp256r1_23:23},g2=Object.values(ho),y2={named_curve_3:3},r_={rsa_pkcs1_sha256:1025,ecdsa_secp256r1_sha256:1027},s9=[1,64],x2=[{hash:Ap.sha256_4,signature:pi.rsa_1},{hash:Ap.sha256_4,signature:pi.ecdsa_3}],uq=()=>{let r=yy.utils.randomPrivateKey(),e=yy.getPublicKey(r,!1),t=Buffer.from(r),s=Buffer.from(e);return{privateKey:t,publicKey:s}},fq=({publicKey:r,privateKey:e})=>{let t=yy.getSharedSecret(e,r);return Buffer.from(t).subarray(1)};lo={CLIENT:1,SERVER:2},gq=class{id=0;name;hashAlgorithm;verifyDataLength=12;blockAlgorithm;kx;init(...r){throw new Error("not implemented")}encrypt(...r){throw new Error("not implemented")}decrypt(...r){throw new Error("not implemented")}toString(){return this.name}},s_=af.webcrypto;pr.set(s_);Ip=class{constructor(r,e,t,s){this.sessionType=r,this.certPem=e,this.keyPem=t,e&&t&&s&&this.parseX509(e,t,s)}localRandom;remoteRandom;cipherSuite;remoteCertificate;remoteKeyPair;localKeyPair;masterSecret;cipher;namedCurve;signatureHashAlgorithm;localCert;localPrivateKey;static createSelfSignedCertificateWithKey=async(r,e)=>{let t=(()=>{switch(r.signature){case pi.rsa_1:return"RSASSA-PKCS1-v1_5";case pi.ecdsa_3:return"ECDSA"}})(),s=(()=>{if(r.hash===Ap.sha256_4)return"SHA-256"})(),n=(()=>{switch(e){case ho.secp256r1_23:return"P-256";case ho.x25519_29:return t==="ECDSA"?"P-256":"X25519";default:{if(t==="ECDSA")return"P-256";if(t==="RSASSA-PKCS1-v1_5")return"X25519"}}})(),i=(()=>{switch(t){case"ECDSA":return{name:t,hash:s,namedCurve:n};case"RSASSA-PKCS1-v1_5":return{name:t,hash:s,publicExponent:new Uint8Array([1,0,1]),modulusLength:2048}}})(),o=await s_.subtle.generateKey(i,!0,["sign","verify"]),c=(await zg.createSelfSigned({serialNumber:(0,af.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=Nr.encode(await s_.subtle.exportKey("pkcs8",o.privateKey),"private key");return{certPem:c,keyPem:d,signatureHash:r}};encryptPacket(r){let e=r.recordLayerHeader,t=e.protocolVersion.major<<8|e.protocolVersion.minor,s=this.cipher.encrypt(this.sessionType,r.fragment,{type:e.contentType,version:t,epoch:e.epoch,sequenceNumber:e.sequenceNumber});return r.fragment=s,r.recordLayerHeader.contentLen=s.length,r}decryptPacket(r){let e=r.recordLayerHeader,t=e.protocolVersion.major<<8|e.protocolVersion.minor;return this.cipher.decrypt(this.sessionType,r.fragment,{type:e.contentType,version:t,epoch:e.epoch,sequenceNumber:e.sequenceNumber})}verifyData(r){return this.sessionType===lo.CLIENT?hq(this.masterSecret,r):pq(this.masterSecret,r)}signatureData(r,e){let t=(0,af.createSign)(e).update(r),s=this.localPrivateKey.toPEM().toString();return t.sign(s)}generateKeySignature(r){let e=this.sessionType===lo.CLIENT?this.localRandom:this.remoteRandom,t=this.sessionType===lo.SERVER?this.localRandom:this.remoteRandom,s=this.valueKeySignature(e.serialize(),t.serialize(),this.localKeyPair.publicKey,this.namedCurve);return this.localPrivateKey.sign(s,r)}parseX509(r,e,t){let s=fx.Certificate.fromPEM(Buffer.from(r)),n=fx.PrivateKey.fromPEM(Buffer.from(e));this.localCert=s.raw,this.localPrivateKey=n,this.signatureHashAlgorithm=t}valueKeySignature(r,e,t,s){let n=Buffer.from((0,Ju.encode)({type:y2.named_curve_3,curve:s,len:t.length},{type:Ju.types.uint8,curve:Ju.types.uint16be,len:Ju.types.uint8}).slice());return Buffer.concat([r,e,n,t])}},Rp=class{srtpProfile;static findMatchingSRTPProfile(r,e){for(let t of e)if(r.includes(t))return t}},b2=r=>"0x"+r.toString("hex").replace(/(.)(.)/g,"$1$2 ").split(" ").filter(e=>e!=null&&e.length>0).join(",0x"),f9=r=>Object.entries({...r}).reduce((e,[t,s])=>((typeof s=="number"||typeof s=="string")&&(e[t]=s),Buffer.isBuffer(s)&&(e[t]=b2(s)),e),{}),Zs=class ha{constructor(e,t,s,n,i,o){this.msg_type=e,this.length=t,this.message_seq=s,this.fragment_offset=n,this.fragment_length=i,this.fragment=o}static spec={msg_type:En.types.uint8,length:En.types.uint24be,message_seq:En.types.uint16be,fragment_offset:En.types.uint24be,fragment_length:En.types.uint24be,fragment:En.types.buffer(e=>e.current.fragment_length)};get summary(){return f9(this)}static createEmpty(){return new ha(void 0,void 0,void 0,void 0,void 0,void 0)}static deSerialize(e){return new ha(...Object.values((0,En.decode)(e,ha.spec)))}serialize(){let e=(0,En.encode)(this,ha.spec).slice();return Buffer.from(e)}chunk(e){let t=0,s=this.fragment.length;if(s===0)return[new ha(this.msg_type,s,this.message_seq,t,0,this.fragment)];let n=[];for(e||(e=1240);t<s;){let i=Math.min(e,s-t),o=Buffer.from(this.fragment.slice(t,t+i));if(o.length<=0)throw new Error("Zero or less bytes processed while fragmenting handshake message.");n.push(new ha(this.msg_type,s,this.message_seq,t,o.length,o)),t+=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 t=Buffer.alloc(e[0].length);for(let s of e)s.fragment.copy(t,s.fragment_offset);return new ha(e[0].msg_type,e[0].length,e[0].message_seq,0,t.length,t)}static findAllFragments(e,t){let s=e.find(n=>n.msg_type===t);return s?e?.length?e.filter(n=>n.msg_type===s.msg_type&&n.message_seq===s.message_seq&&n.length===s.length):[]:[]}},{uint16be:Yy,uint24be:yq,buffer:h9,array:xq,uint8:kp,string:bq}=l9.types,vq={type:Yy,data:h9(Yy)},n_=xq(vq,Yy,"bytes"),wq=h9(yq),Sq=kp,_q=bq(Yy),Eq={hash:kp,signature:kp},v2={major:kp,minor:kp},Qc=class ap{constructor(e=Math.floor(Date.now()/1e3),t=(0,p9.randomBytes)(28)){this.gmt_unix_time=e,this.random_bytes=t}static spec={gmt_unix_time:Jc.types.uint32be,random_bytes:Jc.types.buffer(28)};static deSerialize(e){return new ap(...Object.values((0,Jc.decode)(e,ap.spec)))}static from(e){return new ap(...Object.values(e))}serialize(){let e=(0,Jc.encode)(this,ap.spec).slice();return Buffer.from(e)}},m9=class cp{constructor(e,t,s,n,i,o,a){this.clientVersion=e,this.random=t,this.sessionId=s,this.cookie=n,this.cipherSuites=i,this.compressionMethods=o,this.extensions=a}msgType=1;messageSeq=0;static spec={clientVersion:{major:Mr.types.uint8,minor:Mr.types.uint8},random:Qc.spec,sessionId:Mr.types.buffer(Mr.types.uint8),cookie:Mr.types.buffer(Mr.types.uint8),cipherSuites:Mr.types.array(Mr.types.uint16be,Mr.types.uint16be,"bytes"),compressionMethods:Mr.types.array(Mr.types.uint8,Mr.types.uint8,"bytes"),extensions:n_};static createEmpty(){return new cp(void 0,void 0,void 0,void 0,void 0,void 0,void 0)}static deSerialize(e){return new cp(...Object.values((0,Mr.decode)(e,cp.spec)))}serialize(){let e=(0,Mr.encode)(this,cp.spec).slice();return Buffer.from(e)}toFragment(){let e=this.serialize();return new Zs(this.msgType,e.length,this.messageSeq,0,e.length,e)}},Cq=class dp{constructor(e,t,s,n,i){this.epoch=e,this.sequenceNumber=t,this.contentType=s,this.protocolVersion=n,this.contentLen=i}static spec={epoch:uo.types.uint16be,sequenceNumber:uo.types.uint48be,contentType:uo.types.uint8,protocolVersion:v2,contentLen:uo.types.uint16be};static createEmpty(){return new dp(void 0,void 0,void 0,void 0,void 0)}static deSerialize(e){return new dp(...Object.values((0,uo.decode)(e,dp.spec)))}serialize(){let e=(0,uo.encode)(this,dp.spec).slice();return Buffer.from(e)}},y9=class i_{constructor(e,t){this.recordLayerHeader=e,this.fragment=t}get summary(){return{header:this.recordLayerHeader,fragment:b2(this.fragment)}}static createEmpty(){return new i_(void 0,void 0)}static deSerialize(e){if(e.length<13)throw new Error("Invalid DTLS record: buffer is too short");let t=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 i_({contentType:t,protocolVersion:{major:s,minor:n},epoch:i,sequenceNumber:o,contentLen:a},c)}serialize(){let e=this.fragment.length,t=13+e,s=Buffer.alloc(t);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 Cq(this.recordLayerHeader.epoch,this.recordLayerHeader.sequenceNumber,this.recordLayerHeader.contentType,this.recordLayerHeader.protocolVersion,this.recordLayerHeader.contentLen).serialize()}},x9=r=>e=>(r.lastFlight=e,e.flatMap(t=>(t.messageSeq=r.sequenceNumber++,t.toFragment().chunk()))),Vp=r=>(e,t)=>e.map(s=>new y9({contentType:s.type,protocolVersion:r.version,epoch:r.epoch,sequenceNumber:t,contentLen:s.fragment.length},s.fragment)),o_=(r=>(r[r.CloseNotify=0]="CloseNotify",r[r.UnexpectedMessage=10]="UnexpectedMessage",r[r.BadRecordMac=20]="BadRecordMac",r[r.DecryptionFailed=21]="DecryptionFailed",r[r.RecordOverflow=22]="RecordOverflow",r[r.DecompressionFailure=30]="DecompressionFailure",r[r.HandshakeFailure=40]="HandshakeFailure",r[r.NoCertificate=41]="NoCertificate",r[r.BadCertificate=42]="BadCertificate",r[r.UnsupportedCertificate=43]="UnsupportedCertificate",r[r.CertificateRevoked=44]="CertificateRevoked",r[r.CertificateExpired=45]="CertificateExpired",r[r.CertificateUnknown=46]="CertificateUnknown",r[r.IllegalParameter=47]="IllegalParameter",r[r.UnknownCa=48]="UnknownCa",r[r.AccessDenied=49]="AccessDenied",r[r.DecodeError=50]="DecodeError",r[r.DecryptError=51]="DecryptError",r[r.ExportRestriction=60]="ExportRestriction",r[r.ProtocolVersion=70]="ProtocolVersion",r[r.InsufficientSecurity=71]="InsufficientSecurity",r[r.InternalError=80]="InternalError",r[r.UserCanceled=90]="UserCanceled",r[r.NoRenegotiation=100]="NoRenegotiation",r[r.UnsupportedExtension=110]="UnsupportedExtension",r))(o_||{}),Tq=ut("werift-dtls : packages/dtls/src/flight/flight.ts : warn"),qS=ut("werift-dtls : packages/dtls/src/flight/flight.ts : err"),Kp=class a_{constructor(e,t,s,n){this.transport=e,this.dtls=t,this.flight=s,this.nextFlight=n}state="PREPARING";static RetransmitCount=10;createPacket(e){let t=x9(this.dtls)(e);return this.dtls.bufferHandshakeCache(t,!0,this.flight),Vp(this.dtls)(t.map(n=>({type:22,fragment:n.serialize()})),++this.dtls.recordSequenceNumber)}async transmit(e){let t=0;for(;t<=a_.RetransmitCount;t++){if(this.setState("SENDING"),this.send(e).catch(s=>{qS("fail to send",qS)}),this.setState("WAITING"),this.nextFlight===void 0){this.setState("FINISHED");break}if(await(0,g9.setTimeout)(1e3*((t+1)/2)),this.dtls.flight>=this.nextFlight){this.setState("FINISHED");break}else Tq(this.dtls.sessionId,"retransmit",t,this.dtls.flight)}if(t>a_.RetransmitCount)throw qS(this.dtls.sessionId,"retransmit failed",t),new Error(`over retransmitCount : ${this.flight} ${this.nextFlight}`)}send=e=>Promise.all(e.map(t=>this.transport.send(t)));setState(e){this.state=e}},Aq=class extends Kp{constructor(r,e,t){super(r,e,1,3),this.cipher=t}async exec(r){if(this.dtls.flight===1)throw new Error;this.dtls.flight=1;let e=new m9({major:254,minor:253},new Qc,Buffer.from([]),Buffer.from([]),r9,[0],r);this.dtls.version=e.clientVersion,this.cipher.localRandom=Qc.from(e.random);let t=this.createPacket([e]),s=Buffer.concat(t.map(n=>n.serialize()));await this.transmit([s])}},Iq=ut("werift-dtls : packages/dtls/src/flight/client/flight3.ts : log"),Rq=class extends Kp{constructor(r,e){super(r,e,3,5)}async exec(r){if(this.dtls.flight===3)throw new Error;this.dtls.flight=3,this.dtls.handshakeCache=[];let[e]=this.dtls.lastFlight;Iq("dtls version",e.clientVersion),e.cookie=r.cookie,this.dtls.cookie=r.cookie;let t=this.createPacket([e]),s=Buffer.concat(t.map(n=>n.serialize()));await this.transmit([s])}},hx={NULL:0,ECDHE:1},Wp={NULL:0,RSA:1,ECDSA:2,PSK:3},Gp={NULL:0,RSA:1,ECDHE_RSA:2,ECDHE_ECDSA:3,PSK:4,ECDHE_PSK:5},Xp=class{id=0;name;signType;keyType;toString(){return this.name}};Lq=ut("werift-dtls : packages/dtls/src/cipher/suites/aead.ts : err"),Dq=class extends gq{keyLength=0;nonceLength=0;ivLength=0;authTagLength=0;nonceImplicitLength=0;nonceExplicitLength=0;clientWriteKey;serverWriteKey;clientNonce;serverNonce;constructor(){super()}get summary(){return f9(this)}init(r,e,t){let s=mq(r,t,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(r,e,t){let s=r===lo.CLIENT,n=s?this.clientNonce:this.serverNonce,i=s?this.clientWriteKey:this.serverWriteKey;if(!n||!i)throw new Error;n.writeUInt16BE(t.epoch,this.nonceImplicitLength),n.writeUIntBE(t.sequenceNumber,this.nonceImplicitLength+2,6);let o=n.slice(this.nonceImplicitLength),a=this.encodeAdditionalBuffer(t,e.length),c=(0,px.createCipheriv)(this.blockAlgorithm,i,n,{authTagLength:this.authTagLength});c.setAAD(a,{plaintextLength:e.length});let d=c.update(e),u=c.final(),f=c.getAuthTag();return Buffer.concat([o,d,u,f])}encodeAdditionalBuffer(r,e){let t=Buffer.alloc(13);return t.writeUInt16BE(r.epoch,0),t.writeUintBE(r.sequenceNumber,2,6),t.writeUInt8(r.type,8),t.writeUInt16BE(r.version,9),t.writeUInt16BE(e,11),t}decrypt(r,e,t){let s=r===lo.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(t,a.length),u=(0,px.createDecipheriv)(this.blockAlgorithm,i,n,{authTagLength:this.authTagLength});u.setAuthTag(c),u.setAAD(d,{plaintextLength:a.length});let f=u.update(a);try{let h=u.final();return h.length>0?Buffer.concat([f,h]):f}catch(h){throw Lq("decrypt failed",h,r,b2(e),t,this.summary),h}}},mr={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},Zh={K_LEN:16,N_MIN:12,N_MAX:12,P_MAX:2**36-31,A_MAX:2**53-1,C_MAX:2**36-15},ep={K_LEN:32,N_MIN:12,N_MAX:12,P_MAX:2**36-31,A_MAX:2**53-1,C_MAX:2**36-15},UR=kq(),jR=Pq(),HR=Bq(),FR=Nq(),qR=Oq();mx=class{static type=23},gx=class $u{static type=65281;static spec={type:Zc.types.uint16be,data:Zc.types.uint8};type=$u.type;data=0;constructor(e={}){Object.assign(this,e)}static createEmpty(){return new $u}static deSerialize(e){return new $u((0,Zc.decode)(e,$u.spec))}serialize(){let e=(0,Zc.encode)(this,$u.spec).slice();return Buffer.from(e)}get extension(){return{type:this.type,data:this.serialize().slice(2)}}},ef=class pa{static type=14;static spec={type:va.types.uint16be,data:va.types.buffer(va.types.uint16be)};type=pa.type;data=Buffer.from([]);profiles=[];mki=Buffer.from([0]);constructor(e={}){Object.assign(this,e)}static create(e,t){return new pa({profiles:e,mki:t})}static deSerialize(e){let t=new pa((0,va.decode)(e,pa.spec)),s=t.data.readUInt16BE(),n=new Array(s/2);for(let i=0;i<n.length;i++)n[i]=t.data.readUInt16BE(i*2+2);return t.profiles=n,t.mki=t.data.slice(s+2),t}serialize(){let e=Buffer.alloc(2);e.writeUInt16BE(this.profiles.length*2);let t=Buffer.concat([e,...this.profiles.map(n=>{let i=Buffer.alloc(2);return i.writeUInt16BE(n),i}),this.mki]);this.data=t;let s=(0,va.encode)(this,pa.spec).slice();return Buffer.from(s)}static fromData(e){let t=Buffer.alloc(4);return t.writeUInt16BE(pa.type),t.writeUInt16BE(e.length,2),pa.deSerialize(Buffer.concat([t,e]))}get extension(){return{type:this.type,data:this.serialize().slice(4)}}},Jy=class up{constructor(e){this.certificateList=e}msgType=11;messageSeq;static spec={certificateList:ed.types.array(wq,ed.types.uint24be,"bytes")};static createEmpty(){return new up(void 0)}static deSerialize(e){return new up(...Object.values((0,ed.decode)(e,up.spec)))}serialize(){let e=(0,ed.encode)(this,up.spec).slice();return Buffer.from(e)}toFragment(){let e=this.serialize();return new Zs(this.msgType,e.length,this.messageSeq,0,e.length,e)}},S9=class fp{constructor(e=1){this.type=e}static spec={type:cf.types.uint8};static createEmpty(){return new fp}static deSerialize(e){return new fp(...Object.values((0,cf.decode)(e,fp.spec)))}serialize(){let e=(0,cf.encode)(this,fp.spec).slice();return Buffer.from(e)}},_9=class lp{constructor(e,t){this.algorithm=e,this.signature=t}msgType=15;messageSeq;static spec={algorithm:wa.types.uint16be,signature:wa.types.buffer(wa.types.uint16be)};static createEmpty(){return new lp(void 0,void 0)}static deSerialize(e){let t=(0,wa.decode)(e,lp.spec);return new lp(...Object.values(t))}serialize(){let e=(0,wa.encode)(this,lp.spec).slice();return Buffer.from(e)}toFragment(){let e=this.serialize();return new Zs(this.msgType,e.length,this.messageSeq,0,e.length,e)}},E9=class hp{constructor(e){this.publicKey=e}msgType=16;messageSeq;static spec={publicKey:td.types.buffer(td.types.uint8)};static createEmpty(){return new hp(void 0)}static deSerialize(e){let t=(0,td.decode)(e,hp.spec);return new hp(...Object.values(t))}serialize(){let e=(0,td.encode)(this,hp.spec).slice();return Buffer.from(e)}toFragment(){let e=this.serialize();return new Zs(this.msgType,e.length,this.messageSeq,0,e.length,e)}},c_=class d_{constructor(e){this.verifyData=e}msgType=20;messageSeq;static createEmpty(){return new d_(void 0)}static deSerialize(e){return new d_(e)}serialize(){return this.verifyData}toFragment(){let e=this.serialize();return new Zs(this.msgType,e.length,this.messageSeq,0,e.length,e)}},C9=class pp{constructor(e,t,s){this.certificateTypes=e,this.signatures=t,this.authorities=s}msgType=13;messageSeq;static spec={certificateTypes:Cn.types.array(Sq,Cn.types.uint8,"bytes"),signatures:Cn.types.array(Eq,Cn.types.uint16be,"bytes"),authorities:Cn.types.array(_q,Cn.types.uint16be,"bytes")};static createEmpty(){return new pp(void 0,void 0,void 0)}static deSerialize(e){return new pp(...Object.values((0,Cn.decode)(e,pp.spec)))}serialize(){let e=(0,Cn.encode)(this,pp.spec).slice();return Buffer.from(e)}toFragment(){let e=this.serialize();return new Zs(this.msgType,e.length,this.messageSeq,0,e.length,e)}},T9=class ma{constructor(e,t,s,n,i,o){this.serverVersion=e,this.random=t,this.sessionId=s,this.cipherSuite=n,this.compressionMethod=i,this.extensions=o}msgType=2;messageSeq;static spec={serverVersion:v2,random:Qc.spec,sessionId:Tn.types.buffer(Tn.types.uint8),cipherSuite:Tn.types.uint16be,compressionMethod:Tn.types.uint8};static createEmpty(){return new ma(void 0,void 0,void 0,void 0,void 0,void 0)}static deSerialize(e){let t=(0,Tn.decode)(e,ma.spec),s=new ma(...Object.values(t));return s.serialize().length<e.length?new ma(...Object.values((0,Tn.decode)(e,{...ma.spec,extensions:n_}))):s}serialize(){let e=this.extensions===void 0?(0,Tn.encode)(this,ma.spec).slice():(0,Tn.encode)(this,{...ma.spec,extensions:n_}).slice();return Buffer.from(e)}toFragment(){let e=this.serialize();return new Zs(this.msgType,e.length,this.messageSeq,0,e.length,e)}},A9=class mp{msgType=14;messageSeq;static spec={};static createEmpty(){return new mp}static deSerialize(e){return new mp(...Object.values((0,yx.decode)(e,mp.spec)))}serialize(){let e=(0,yx.encode)(this,mp.spec).slice();return Buffer.from(e)}toFragment(){let e=this.serialize();return new Zs(this.msgType,e.length,this.messageSeq,0,e.length,e)}};R9=class gp{constructor(e,t,s,n,i,o,a,c){this.ellipticCurveType=e,this.namedCurve=t,this.publicKeyLength=s,this.publicKey=n,this.hashAlgorithm=i,this.signatureAlgorithm=o,this.signatureLength=a,this.signature=c}msgType=12;messageSeq;static spec={ellipticCurveType:_n.types.uint8,namedCurve:_n.types.uint16be,publicKeyLength:_n.types.uint8,publicKey:_n.types.buffer(e=>e.current.publicKeyLength),hashAlgorithm:_n.types.uint8,signatureAlgorithm:_n.types.uint8,signatureLength:_n.types.uint16be,signature:_n.types.buffer(e=>e.current.signatureLength)};static createEmpty(){return new gp(void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0)}static deSerialize(e){let t=(0,_n.decode)(e,gp.spec);return new gp(...Object.values(t))}serialize(){return Mq(this,gp.spec)}toFragment(){let e=this.serialize();return new Zs(this.msgType,e.length,this.messageSeq,0,e.length,e)}},df=1,ad=7,Uq=[df,ad],k9=r=>{switch(r){case df:case ad:return 16}},P9=r=>{switch(r){case df:return 14;case ad:return 12}},jq=ut("werift-rtp : packages/rtp/src/codec/av1.ts"),u_=class N9{zBit_RtpStartsWithFragment;yBit_RtpEndsWithFragment;w_RtpNumObus;nBit_RtpStartsNewCodedVideoSequence;obu_or_fragment=[];static deSerialize=e=>{let t=new N9,s=0;if(t.zBit_RtpStartsWithFragment=ye(e[s],0),t.yBit_RtpEndsWithFragment=ye(e[s],1),t.w_RtpNumObus=ye(e[s],2,2),t.nBit_RtpStartsNewCodedVideoSequence=ye(e[s],4),s++,t.nBit_RtpStartsNewCodedVideoSequence&&t.zBit_RtpStartsWithFragment)throw new Error;[...Array(t.w_RtpNumObus-1).keys()].forEach(i=>{let[o,a]=D9(e.subarray(s)),c=s+a,d=c+o,u=!1;t.zBit_RtpStartsWithFragment&&i===0&&(u=!0),t.obu_or_fragment.push({data:e.subarray(c,d),isFragment:u}),s+=a+o});let n=!1;return(t.yBit_RtpEndsWithFragment||t.w_RtpNumObus===1&&t.zBit_RtpStartsWithFragment)&&(n=!0),t.obu_or_fragment.push({data:e.subarray(s),isFragment:n}),t};static isDetectedFinalPacketInSequence(e){return e.marker}get isKeyframe(){return this.nBit_RtpStartsNewCodedVideoSequence===1}static getFrame(e){let t=[],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 f=[];for(let h=a;h<n;h++){let y=s[h];if(y.isFragment)f.push(y.data),delete s[h];else break}f.length<=1&&(jq("fragment lost, maybe packet lost"),f=[]),t.push(Buffer.concat(f))}else t.push(d)}let i=t.map(a=>O9.deSerialize(a)),o=i.pop();return Buffer.concat([...i.map(a=>(a.obu_has_size_field=1,a.serialize())),o.serialize()])}},O9=class L9{obu_forbidden_bit;obu_type;obu_extension_flag;obu_has_size_field;obu_reserved_1bit;payload;static deSerialize(e){let t=new L9,s=0;return t.obu_forbidden_bit=ye(e[s],0),t.obu_type=M9[ye(e[s],1,4)],t.obu_extension_flag=ye(e[s],5),t.obu_has_size_field=ye(e[s],6),t.obu_reserved_1bit=ye(e[s],7),s++,t.payload=e.subarray(s),t}serialize(){let e=new cx(8).set(this.obu_forbidden_bit).set(Hq[this.obu_type],4).set(this.obu_extension_flag).set(this.obu_has_size_field).set(this.obu_reserved_1bit).buffer,t=Buffer.alloc(0);return this.obu_has_size_field&&(t=B9.LEB128.encode(this.payload.length)),Buffer.concat([e,t,this.payload])}};M9={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"},Hq=Object.entries(M9).reduce((r,[e,t])=>(r[t]=Number(e),r),{}),U9=class j9{f;nri;nalUnitType;s;e;r;nalUnitPayloadType;payload;fragment;static deSerialize(e,t){let s=new j9,n=0,i=e[n];if(s.f=ye(i,0),s.nri=ye(i,1,2),s.nalUnitType=ye(i,3,5),n++,s.s=ye(e[n],0),s.e=ye(e[n],1),s.r=ye(e[n],2),s.nalUnitPayloadType=ye(e[n],3,5),n++,0<s.nalUnitType&&s.nalUnitType<ga.stap_a)s.payload=this.packaging(e);else if(s.nalUnitType===ga.stap_a){let o=qq,a=Buffer.alloc(0);for(;o<e.length;){let c=e.readUInt16BE(o);o+=zq,a=Buffer.concat([a,this.packaging(e.subarray(o,o+c))]),o+=c}s.payload=a}else if(s.nalUnitType===ga.fu_a){t||(t=Buffer.alloc(0));let o=e.subarray(n);if(s.fragment=Buffer.concat([t,o]),s.e){let a=new ba(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([Fq,e])}static isDetectedFinalPacketInSequence(e){return e.marker}get isKeyframe(){return this.nalUnitType===ga.idrSlice||this.nalUnitPayloadType===ga.idrSlice}get isPartitionHead(){return this.nalUnitType===ga.fu_a||this.nalUnitType===ga.fu_b?this.s!==0:!0}},ga={idrSlice:5,stap_a:24,stap_b:25,mtap16:26,mtap24:27,fu_a:28,fu_b:29},Fq=Buffer.from([0,0,0,1]),qq=1,zq=2,H9=class F9{payload;static deSerialize(e){let t=new F9;return t.payload=e,t}static isDetectedFinalPacketInSequence(e){return!0}get isKeyframe(){return!0}static createCodecPrivate(e=48e3){return Buffer.concat([Buffer.from("OpusHead"),er([1,1],[1,2]),Uk([2,4,2,1],[312,e,0,0])])}},q9=class z9{xBit;nBit;sBit;pid;iBit;lBit;tBit;kBit;mBit;pictureId;payload;size0=0;hBit;ver;pBit;size1=0;size2=0;static deSerialize(e){let t=new z9,s=0;if(t.xBit=ye(e[s],0),t.nBit=ye(e[s],2),t.sBit=ye(e[s],3),t.pid=ye(e[s],5,3),s++,t.xBit&&(t.iBit=ye(e[s],0),t.lBit=ye(e[s],1),t.tBit=ye(e[s],2),t.kBit=ye(e[s],3),s++),t.iBit)if(t.mBit=ye(e[s],0),t.mBit){let n=Cp(ye(e[s],1,7)),i=Cp(e[s+1]);t.pictureId=Number.parseInt(n+i,2),s+=2}else t.pictureId=ye(e[s],1,7),s++;return t.lBit&&s++,(t.lBit||t.kBit)&&(t.tBit,t.kBit,s++),t.payload=e.subarray(s),t.payloadHeaderExist&&(t.size0=ye(e[s],0,3),t.hBit=ye(e[s],3),t.ver=ye(e[s],4,3),t.pBit=ye(e[s],7),s++,t.size1=e[s],s++,t.size2=e[s]),t}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}},$9=class V9{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:t,offset:s}=this.parseRtpPayload(e);return t.payload=e.subarray(s),t}static parseRtpPayload(e){let t=new V9,s=0;if(t.iBit=ye(e[s],0),t.pBit=ye(e[s],1),t.lBit=ye(e[s],2),t.fBit=ye(e[s],3),t.bBit=ye(e[s],4),t.eBit=ye(e[s],5),t.vBit=ye(e[s],6),t.zBit=ye(e[s],7),s++,t.iBit)if(t.m=ye(e[s],0),t.m){let n=Cp(ye(e[s],1,7)),i=Cp(e[s+1]);t.pictureId=Number.parseInt(n+i,2),s+=2}else t.pictureId=ye(e[s],1,7),s++;if(t.lBit&&(t.tid=ye(e[s],0,3),t.u=ye(e[s],3),t.sid=ye(e[s],4,3),t.d=ye(e[s],7),s++,t.fBit===0&&(t.tl0PicIdx=e[s],s++)),t.fBit&&t.pBit)for(;;){t.pDiff=[...t.pDiff,ye(e[s],0,7)];let n=ye(e[s],7);if(s++,n===0)break}return t.vBit&&(t.n_s=ye(e[s],0,3),t.y=ye(e[s],3),t.g=ye(e[s],4),s++,t.y&&[...Array(t.n_s+1)].forEach(()=>{t.width.push(e.readUInt16BE(s)),s+=2,t.height.push(e.readUInt16BE(s)),s+=2}),t.g&&(t.n_g=e[s],s++),t.n_g>0&&[...Array(t.n_g).keys()].forEach(n=>{t.pgT.push(ye(e[s],0,3)),t.pgU.push(ye(e[s],3));let i=ye(e[s],4,2);s++,t.pgP_Diff[n]=[],i>0&&[...Array(i)].forEach(()=>{t.pgP_Diff[n].push(e[s]),s++})})),{offset:s,p:t}}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)}},$q=class{payload;fragment;static deSerialize(r,e){return{}}static isDetectedFinalPacketInSequence(r){return!0}get isKeyframe(){return!0}};Kq=["MPEG4/ISO/AVC","VP8","VP9","OPUS","AV1"];Gq={setTimeout:(...r)=>{let e=setTimeout(...r);return()=>clearTimeout(e)},setInterval:(...r)=>{let e=setInterval(()=>{r[0]()},...r.slice(1));return()=>clearInterval(e)}};Qy=4,go=class l_{version=2;padding=!1;count=0;type=0;length=0;constructor(e={}){Object.assign(this,e)}static serialize(e,t,s,n){let o=new l_({type:e,count:t,version:2,length:n}).serialize();return Buffer.concat([o,s])}serialize(){let e=new Ep(8);return e.set(2,0,this.version),this.padding&&e.set(1,2,1),e.set(5,3,this.count),er([1,1,2],[e.value,this.type,this.length])}static deSerialize(e){let[t,s,n]=is(e,[1,1,2]),i=ye(t,0,2),o=ye(t,2,1)>0,a=ye(t,3,5);return new l_({version:i,padding:o,count:a,type:s,length:n})}},zR=class h_{static count=4;count=h_.count;senderSsrc;mediaSsrc;fir=[];constructor(e={}){Object.assign(this,e)}get length(){return Math.floor(this.serialize().length/4-1)}static deSerialize(e){let[t,s]=is(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 h_({senderSsrc:t,mediaSsrc:s,fir:n})}serialize(){let e=er([4,4],[this.senderSsrc,this.mediaSsrc]),t=Buffer.alloc(this.fir.length*8);return this.fir.forEach(({ssrc:s,sequenceNumber:n},i)=>{t.writeUInt32BE(s,i*8),t[i*8+4]=n}),Buffer.concat([e,t])}},Bp=class p_{static count=1;count=p_.count;length=2;senderSsrc;mediaSsrc;constructor(e={}){Object.assign(this,e)}static deSerialize(e){let[t,s]=is(e,[4,4]);return new p_({senderSsrc:t,mediaSsrc:s})}serialize(){return er([4,4],[this.senderSsrc,this.mediaSsrc])}},Np=class m_{static count=15;length;count=m_.count;senderSsrc;mediaSsrc;uniqueID="REMB";ssrcNum=0;brExp;brMantissa;bitrate;ssrcFeedbacks=[];constructor(e={}){Object.assign(this,e)}static deSerialize(e){let[t,s,n,i,o]=is(e,[4,4,4,1,1]),a=ye(o,0,6),c=(ye(o,6,2)<<16)+(e[14]<<8)+e[15],d=a>46?18446744073709551615n:BigInt(c)<<BigInt(a),u=[];for(let f=16;f<e.length;f+=4){let h=e.slice(f).readUIntBE(0,4);u.push(h)}return new m_({senderSsrc:t,mediaSsrc:s,uniqueID:er([4],[n]).toString(),ssrcNum:i,brExp:a,brMantissa:c,ssrcFeedbacks:u,bitrate:d})}serialize(){let e=Buffer.concat([er([4,4],[this.senderSsrc,this.mediaSsrc]),Buffer.from(this.uniqueID),er([1],[this.ssrcNum])]),t=new Ep(24);t.set(6,0,this.brExp).set(18,6,this.brMantissa);let s=Buffer.concat(this.ssrcFeedbacks.map(i=>er([4],[i]))),n=Buffer.concat([e,er([3],[t.value]),s]);return this.length=n.length/4,n}},Xq=ut("werift-rtp: /rtcp/psfb/index"),tf=class g_{static type=206;type=g_.type;feedback;constructor(e={}){Object.assign(this,e)}serialize(){let e=this.feedback.serialize();return go.serialize(this.type,this.feedback.count,e,this.feedback.length)}static deSerialize(e,t){let s;switch(t.count){case zR.count:s=zR.deSerialize(e);break;case Bp.count:s=Bp.deSerialize(e);break;case Np.count:s=Np.deSerialize(e);break;default:Xq("unknown psfb packet",t.count);break}return new g_({feedback:s})}},rf=class Iy{ssrc=0;reports=[];static type=201;type=Iy.type;constructor(e={}){Object.assign(this,e)}serialize(){let e=er([4],[this.ssrc]);return e=Buffer.concat([e,...this.reports.map(t=>t.serialize())]),go.serialize(Iy.type,this.reports.length,e,Math.floor(e.length/4))}static deSerialize(e,t){let[s]=is(e,[4]),n=4,i=[];for(let o=0;o<t;o++)i.push(xx.deSerialize(e.slice(n,n+24))),n+=24;return new Iy({ssrc:s,reports:i})}},xx=class W9{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 er([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[t,s,n,i,o,a,c]=is(e,[4,1,3,4,4,4,4]);return new W9({ssrc:t,fractionLost:s,packetsLost:n,highestSequence:i,jitter:o,lsr:a,dlsr:c})}},G9=205,Op=class y_{static count=1;count=y_.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 go({type:G9,count:this.count,version:2}))}static deSerialize(e,t){let[s,n]=is(e,[4,4]),i=[];for(let o=8;o<e.length;o+=4){let[a,c]=is(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 y_({header:t,senderSsrc:s,mediaSourceSsrc:n,lost:i})}serialize(){let e=er([4,4],[this.senderSsrc,this.mediaSourceSsrc]),t=[];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:(t.push(er([2,2],[n,i])),n=o,i=0)}),t.push(er([2,2],[n,i]))}let s=Buffer.concat([e,Buffer.concat(t)]);return this.header.length=s.length/4,Buffer.concat([this.header.serialize(),s])}},Yq=ut("werift/rtp/rtcp/rtpfb/twcc"),Lp=class x_{static count=15;count=x_.count;length=2;senderSsrc;mediaSourceSsrc;baseSequenceNumber;packetStatusCount;referenceTime;fbPktCount;packetChunks=[];recvDeltas=[];header;constructor(e={}){Object.assign(this,e),this.header||(this.header=new go({type:205,count:this.count,version:2}))}static deSerialize(e,t){let[s,n,i,o,a,c]=is(e,[4,4,2,2,3,1]),d=[],u=[],f=16;for(let y=0;y<o;){let v=ye(e.slice(f,f+1)[0],0,1),S;switch(v){case 0:{let C=Qu.deSerialize(e.slice(f,f+2));S=C;let O=Math.min(o-y,C.runLength);if(C.packetStatus===1||C.packetStatus===2)for(let K=0;K<O;K++)u.push(new wp({type:C.packetStatus}));y+=O}break;case 1:{let C=Y9.deSerialize(e.slice(f,f+2));S=C,C.symbolSize===0&&C.symbolList.forEach(O=>{O===1&&u.push(new wp({type:1}))}),C.symbolSize===1&&C.symbolList.forEach(O=>{(O===1||O===2)&&u.push(new wp({type:O}))}),y+=C.symbolList.length}break}if(!S)throw new Error;f+=2,d.push(S)}let h=f;return u.forEach(y=>{y.type===1&&(y.deSerialize(e.slice(h,h+1)),h++),y.type===2&&(y.deSerialize(e.slice(h,h+2)),h+=2)}),new x_({senderSsrc:s,mediaSourceSsrc:n,baseSequenceNumber:i,packetStatusCount:o,referenceTime:a,fbPktCount:c,recvDeltas:u,packetChunks:d,header:t})}serialize(){let e=er([4,4,2,2,3,1],[this.senderSsrc,this.mediaSourceSsrc,this.baseSequenceNumber,this.packetStatusCount,this.referenceTime,this.fbPktCount]),t=Buffer.concat(this.packetChunks.map(i=>i.serialize())),s=Buffer.concat(this.recvDeltas.map(i=>{try{return i.serialize()}catch(o){Yq(o?.message);return}}).filter(i=>i)),n=Buffer.concat([e,t,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,t=this.packetChunks.filter(o=>o instanceof Qu).flatMap(o=>o.results(e)),s=0,i=BigInt(this.referenceTime)*64n;for(let o of t){let a=this.recvDeltas[s];!o.received||!a||(i+=BigInt(a.delta)/1000n,o.delta=a.delta,o.receivedAtMs=Number(i),s++)}return t}},Qu=class X9{type;packetStatus;runLength;constructor(e={}){Object.assign(this,e),this.type=0}static deSerialize(e){let t=ye(e[0],1,2),s=(ye(e[0],3,5)<<8)+e[1];return new X9({type:0,packetStatus:t,runLength:s})}serialize(){return new cx(16).set(0).set(this.packetStatus,2).set(this.runLength,13).buffer}results(e){let t=this.packetStatus===1||this.packetStatus===2,s=[];for(let n=0;n<=this.runLength;++n)s.push(new eP({sequenceNumber:++e,received:t}));return s}},Y9=class J9{type;symbolSize;symbolList=[];constructor(e={}){Object.assign(this,e)}static deSerialize(e){let s=ye(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(ye(e[0],2+o,1))),i(8,o=>n.push(ye(e[1],o,1)));break;case 1:i(3,o=>n.push(ye(e[0],2+o*2,2))),i(4,o=>n.push(ye(e[1],o*2,2)));break;default:s=(ye(e[0],2,6)<<8)+e[1]}return new J9({type:1,symbolSize:s,symbolList:n})}serialize(){let e=Buffer.alloc(2),t=new cx(16).set(1).set(this.symbolSize),s=this.symbolSize===0?1:2;return this.symbolList.forEach(n=>{t.set(n,s)}),e.writeUInt16BE(t.value),e}},wp=class b_{type;delta;constructor(e={}){Object.assign(this,e)}static deSerialize(e){let t,s;if(e.length===1?(t=1,s=250*e[0]):e.length===2&&(t=2,s=250*e.readInt16BE()),t===void 0||s===void 0)throw new Error;return new b_({type:t,delta:s})}deSerialize(e){let t=b_.deSerialize(e);this.delta=t.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)}},Q9=(r=>(r[r.TypeTCCRunLengthChunk=0]="TypeTCCRunLengthChunk",r[r.TypeTCCStatusVectorChunk=1]="TypeTCCStatusVectorChunk",r[r.packetStatusChunkLength=2]="packetStatusChunkLength",r))(Q9||{}),Z9=(r=>(r[r.TypeTCCPacketNotReceived=0]="TypeTCCPacketNotReceived",r[r.TypeTCCPacketReceivedSmallDelta=1]="TypeTCCPacketReceivedSmallDelta",r[r.TypeTCCPacketReceivedLargeDelta=2]="TypeTCCPacketReceivedLargeDelta",r[r.TypeTCCPacketReceivedWithoutDelta=3]="TypeTCCPacketReceivedWithoutDelta",r))(Z9||{}),eP=class{sequenceNumber=0;delta=0;received=!1;receivedAtMs=0;constructor(r){Object.assign(this,r)}},Jq=ut("werift-rtp:packages/rtp/rtcp/rtpfb/index"),rd=class v_{static type=G9;type=v_.type;feedback;header;constructor(e={}){Object.assign(this,e)}serialize(){return this.feedback.serialize()}static deSerialize(e,t){let s;switch(t.count){case Op.count:s=Op.deSerialize(e,t);break;case Lp.count:s=Lp.deSerialize(e,t);break;default:Jq("unknown rtpfb packet",t.count);break}return new v_({feedback:s,header:t})}},Dp=class w_{static type=202;type=w_.type;chunks=[];constructor(e){Object.assign(this,e)}get length(){let e=0;return this.chunks.forEach(t=>e+=t.length),e}serialize(){let e=Buffer.concat(this.chunks.map(t=>t.serialize()));for(;e.length%4;)e=Buffer.concat([e,Buffer.from([0])]);return go.serialize(this.type,this.chunks.length,e,e.length/4)}static deSerialize(e,t){let s=[];for(let n=0;n<e.length;){let i=w2.deSerialize(e.slice(n));s.push(i),n+=i.length}return new w_({chunks:s})}},w2=class tP{source;items=[];constructor(e={}){Object.assign(this,e)}get length(){let e=4;return this.items.forEach(t=>e+=t.length),e+=1,e+=$R(e),e}serialize(){let e=Buffer.concat([er([4],[this.source]),Buffer.concat(this.items.map(s=>s.serialize()))]);return Buffer.concat([e,Buffer.alloc($R(e.length))])}static deSerialize(e){let t=e.readUInt32BE(),s=[];for(let n=4;n<e.length&&e[n]!==0;){let o=S2.deSerialize(e.slice(n));s.push(o),n+=o.length}return new tP({source:t,items:s})}},S2=class rP{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([er([1,1],[this.type,e.length]),e])}static deSerialize(e){let t=e[0],s=e[1],n=e.slice(2,2+s).toString();return new rP({type:t,text:n})}};sd=class Ry{ssrc=0;senderInfo;reports=[];static type=200;type=Ry.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(t=>t.serialize())]),go.serialize(Ry.type,this.reports.length,e,Math.floor(e.length/4))}static deSerialize(e,t){let s=e.readUInt32BE(),n=_2.deSerialize(e.subarray(4,24)),i=24,o=[];for(let c=0;c<t;c++)o.push(xx.deSerialize(e.subarray(i,i+24))),i+=24;return new Ry({ssrc:s,senderInfo:n,reports:o})}},_2=class sP{ntpTimestamp;rtpTimestamp;packetCount;octetCount;constructor(e={}){Object.assign(this,e)}toJSON(){return{ntpTimestamp:nP(this.ntpTimestamp),rtpTimestamp:this.rtpTimestamp}}serialize(){return er([8,4,4,4],[this.ntpTimestamp,this.rtpTimestamp,this.packetCount,this.octetCount])}static deSerialize(e){let[t,s,n,i]=is(e,[8,4,4,4]);return new sP({ntpTimestamp:t,rtpTimestamp:s,packetCount:n,octetCount:i})}},nP=r=>{let[e,t]=is(er([8],[r]),[4,4]);return+`${e}.${t}`},Qq=ut("werift-rtp:packages/rtp/src/rtcp/rtcp.ts"),iP=class{static deSerialize(r){let e=0,t=[];for(;e<r.length;){let s=go.deSerialize(r.subarray(e,e+Qy));e+=Qy;let n=r.subarray(e);e+=s.length*4,s.padding&&(n=n.subarray(0,n.length-n.subarray(-1)[0]));try{switch(s.type){case sd.type:t.push(sd.deSerialize(n,s.count));break;case rf.type:t.push(rf.deSerialize(n,s.count));break;case Dp.type:t.push(Dp.deSerialize(n,s));break;case rd.type:t.push(rd.deSerialize(n,s));break;case tf.type:t.push(tf.deSerialize(n,s));break;default:break}}catch(i){Qq("deSerialize RTCP",i)}}return t}};Yt={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"};ez=ut("packages/rtp/src/rtp/red/packet.ts"),E2=class xP{header;blocks=[];static deSerialize(e){let t=e instanceof ArrayBuffer?Buffer.from(e):e,s=new xP,n=0;return[s.header,n]=S_.deSerialize(t),s.header.fields.forEach(({blockLength:i,timestampOffset:o,blockPT:a})=>{if(i&&o){let c=t.subarray(n,n+i);s.blocks.push({block:c,blockPT:a,timestampOffset:o}),n+=i}else{let c=t.subarray(n);s.blocks.push({block:c,blockPT:a})}}),s}serialize(){this.header=new S_;for(let{timestampOffset:t,blockPT:s,block:n}of this.blocks)t?this.header.fields.push({fBit:1,blockPT:s,blockLength:n.length,timestampOffset:t}):this.header.fields.push({fBit:0,blockPT:s});let e=this.header.serialize();for(let{block:t}of this.blocks)e=Buffer.concat([e,t]);return e}},S_=class bP{fields=[];static deSerialize(e){let t=0,s=new bP;for(;;){let n={};s.fields.push(n);let i=new ba(e.subarray(t));if(n.fBit=i.readBits(1),n.blockPT=i.readBits(7),t++,n.fBit===0)break;n.timestampOffset=i.readBits(14),n.blockLength=i.readBits(10),t+=3}return[s,t]}serialize(){let e=Buffer.alloc(0);for(let t of this.fields)try{if(t.timestampOffset&&t.blockLength){let s=new ba(Buffer.alloc(4)).writeBits(1,t.fBit).writeBits(7,t.blockPT).writeBits(14,t.timestampOffset).writeBits(10,t.blockLength);e=Buffer.concat([e,s.uint8Array])}else{let s=new ba(Buffer.alloc(1)).writeBits(1,0).writeBits(7,t.blockPT);e=Buffer.concat([e,s.uint8Array])}}catch(s){ez(s?.message)}return e}},vP=class{constructor(r=1){this.distance=r}cache=[];cacheSize=10;push(r){this.cache.push(r),this.cache.length>this.cacheSize&&this.cache.shift()}build(){let r=new E2,e=this.cache.slice(-(this.distance+1)),t=e.pop();return t&&(e.forEach(s=>{let n=Yc(t.timestamp,-s.timestamp);n>tz||r.blocks.push({block:s.block,blockPT:s.blockPT,timestampOffset:n})}),r.blocks.push({block:t.block,blockPT:t.blockPT})),r}},tz=16383,wP=class{size=150;sequenceNumbers=[];push(r,e){let t=[];return r.blocks.forEach(({blockPT:n,timestampOffset:i,block:o},a)=>{let c=Ur(e.header.sequenceNumber,-(r.blocks.length-(a+1)));i?t.push(new mo(new po({timestamp:Yc(e.header.timestamp,-i),payloadType:n,ssrc:e.header.ssrc,sequenceNumber:c,marker:!0}),o)):t.push(new mo(new po({timestamp:e.header.timestamp,payloadType:n,ssrc:e.header.ssrc,sequenceNumber:c,marker:!0}),o))}),t.filter(n=>this.sequenceNumbers.includes(n.header.sequenceNumber)?!1:(this.sequenceNumbers.length>this.size&&this.sequenceNumbers.shift(),this.sequenceNumbers.push(n.header.sequenceNumber),!0))}},ya={OneByte:48862,TwoByte:4096},VR=2,KR=4,WR=8,GR=12,XR=4,po=class SP{version=2;padding=!1;paddingSize=0;extension=!1;marker=!1;payloadOffset=0;payloadType=0;sequenceNumber=0;timestamp=0;ssrc=0;csrcLength=0;csrc=[];extensionProfile=ya.OneByte;extensionLength;extensions=[];constructor(e={}){Object.assign(this,e)}static deSerialize(e){let t=new SP,s=0,n=e[s++];t.version=ye(n,0,2),t.padding=ye(n,2)>0,t.extension=ye(n,3)>0,t.csrcLength=ye(n,4,4),t.csrc=[...Array(t.csrcLength)].map(()=>{let o=e.readUInt32BE(s);return s+=4,o}),s+=GR-1;let i=e[1];t.marker=ye(i,0)>0,t.payloadType=ye(i,1,7),t.sequenceNumber=e.readUInt16BE(VR),t.timestamp=e.readUInt32BE(KR),t.ssrc=e.readUInt32BE(WR);for(let o=0;o<t.csrc.length;o++){let a=GR+o*XR;t.csrc[o]=e.subarray(a).readUInt32BE()}if(t.extension){t.extensionProfile=e.subarray(s).readUInt16BE(),s+=2;let o=e.subarray(s).readUInt16BE()*4;switch(t.extensionLength=o,s+=2,t.extensionProfile){case ya.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)};t.extensions=[...t.extensions,u],s+=d}}break;case ya.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)};t.extensions=[...t.extensions,u],s+=d}}break;default:{let a={id:0,payload:e.subarray(s,s+o)};t.extensions=[...t.extensions,a],s+=t.extensions[0].payload.length}break}}return t.payloadOffset=s,t.padding&&(t.paddingSize=e[e.length-1]),t}get serializeSize(){let{csrc:e,extensionProfile:t,extensions:s}=this,n=12+e.length*XR;if(s.length>0||this.extension===!0){let i=4;switch(t){case ya.OneByte:for(let o of s)i+=1+o.payload.length;break;case ya.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 t=Buffer.alloc(e),s=0,n=new Ep(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),t.writeUInt8(n.value,s++);let i=new Ep(8);this.marker&&i.set(1,0,1),i.set(7,1,this.payloadType),t.writeUInt8(i.value,s++),t.writeUInt16BE(this.sequenceNumber,VR),s+=2,t.writeUInt32BE(this.timestamp,KR),s+=4,t.writeUInt32BE(this.ssrc,WR),s+=4;for(let o of this.csrc)t.writeUInt32BE(o,s),s+=4;if(this.extension){let o=s;t.writeUInt16BE(this.extensionProfile,s),s+=4;let a=s;switch(this.extensionProfile){case ya.OneByte:for(let u of this.extensions)t.writeUInt8(u.id<<4|u.payload.length-1,s++),u.payload.copy(t,s),s+=u.payload.length;break;case ya.TwoByte:for(let u of this.extensions)t.writeUInt8(u.id,s++),t.writeUInt8(u.payload.length,s++),u.payload.copy(t,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(t,s),s+=u}}let c=s-a,d=Math.trunc((c+3)/4)*4;t.writeUInt16BE(Math.trunc(d/4),o+2);for(let u=0;u<d-c;u++)t.writeUInt8(0,s),s++}return this.payloadOffset=s,t}},mo=class __{constructor(e,t){this.header=e,this.payload=t}get serializeSize(){return this.header.serializeSize+this.payload.length}clone(){return new __(new po({...this.header}),this.payload)}serialize(){let e=this.header.serialize(this.header.serializeSize+this.payload.length),{payloadOffset:t}=this.header;if(this.payload.copy(e,t),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 t=po.deSerialize(e);return new __(t,e.subarray(t.payloadOffset,e.length-t.paddingSize))}clear(){this.payload=null}};CP=class{constructor(r,e,t,s){this.srtpSessionKey=r,this.srtpSessionSalt=e,this.srtcpSessionKey=t,this.srtcpSessionSalt=s}encryptRtp(r,e,t){return Buffer.from([])}decryptRtp(r,e,t){return[]}encryptRTCP(r,e){return Buffer.from([])}decryptRTCP(r){return[]}},nd=class extends Error{constructor(r){super(r),this.name="SrtpAuthenticationError"}},YR=12,rz=8;sz=class extends CP{constructor(r,e,t,s,n,i){super(r,e,t,s),this.srtpSessionAuthTag=n,this.srtcpSessionAuthTag=i}authTagLength=10;encryptRtp(r,e,t){let s=r.serialize(r.serializeSize),n=this.generateCounter(r.sequenceNumber,t,r.ssrc,this.srtpSessionSalt),o=(0,An.createCipheriv)("aes-128-ctr",this.srtpSessionKey,n).update(e),a=this.generateSrtpAuthTag(t,s,o);return Buffer.concat([s,o,a])}decryptRtp(r,e,t=T2(r,this.authTagLength)){let s=r.length-this.authTagLength,n=r.subarray(0,s),i=r.subarray(s),o=this.generateSrtpAuthTag(e,n.subarray(0,t.payloadOffset),n.subarray(t.payloadOffset));QR(i,o,"Failed to authenticate SRTP packet");let a=this.generateCounter(t.sequenceNumber,e,t.ssrc,this.srtpSessionSalt),c=(0,An.createDecipheriv)("aes-128-ctr",this.srtpSessionKey,a),d=n.subarray(t.payloadOffset),u=c.update(d),f=Buffer.concat([n.subarray(0,t.payloadOffset),u]);return[f,IP(t,f,"Failed to authenticate SRTP packet")]}encryptRTCP(r,e){let t=Buffer.from(r),s=t.readUInt32BE(4),n=this.generateCounter(e&65535,e>>16,s,this.srtcpSessionSalt);(0,An.createCipheriv)("aes-128-ctr",this.srtcpSessionKey,n).update(t.slice(8)).copy(t,8),t=Buffer.concat([t,Buffer.alloc(4)]),t.writeUInt32BE(e,t.length-4),t[t.length-4]|=128;let a=this.generateSrtcpAuthTag(t);return t=Buffer.concat([t,a]),t}decryptRTCP(r){let e=TP(r,this.authTagLength,JR),t=r.length-(this.authTagLength+JR),s=r.subarray(0,r.length-this.authTagLength),n=r.subarray(r.length-this.authTagLength),i=this.generateSrtcpAuthTag(s);QR(n,i,"Failed to authenticate SRTCP packet");let o=Buffer.from(r).slice(0,t);if(r[t]>>>7===0)return[o,e];let c=r.readUInt32BE(t);c&=~(1<<31);let d=r.readUInt32BE(4),u=this.generateCounter(c&65535,c>>16,d,this.srtcpSessionSalt);return(0,An.createDecipheriv)("aes-128-ctr",this.srtcpSessionKey,u).update(o.subarray(8)).copy(o,8),[o,e]}generateSrtcpAuthTag(r){return(0,An.createHmac)("sha1",this.srtcpSessionAuthTag).update(r).digest().slice(0,10)}generateCounter(r,e,t,s){let n=Buffer.alloc(16);n.writeUInt32BE(t,4),n.writeUInt32BE(e,8),n.writeUInt32BE(Number(BigInt(r)<<16n),12);for(let i=0;i<s.length;i++)n[i]^=s[i];return n}generateSrtpAuthTag(r,...e){let t=(0,An.createHmac)("sha1",this.srtpSessionAuthTag),s=Buffer.alloc(4);s.writeUInt32BE(r);for(let n of e)t.update(n);return t.update(s).digest().subarray(0,10)}},JR=4;nz=class extends CP{aeadAuthTagLen=16;rtpIvWriter=vp([2,4,4,2],!0);rtcpIvWriter=vp([2,4,2,4],!0);aadWriter=vp([4],!0);constructor(r,e,t,s){super(r,e,t,s)}encryptRtp(r,e,t){let s=r.serialize(r.serializeSize),n=this.rtpInitializationVector(r,t),i=(0,sf.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(r,e,t=T2(r,this.aeadAuthTagLen)){let s=r.subarray(0,t.payloadOffset),n=r.length-this.aeadAuthTagLen,i=r.subarray(n),o=Buffer.from([]);o=f_(o,r.length-this.aeadAuthTagLen),s.copy(o);let a=this.rtpInitializationVector(t,e),c=r.slice(t.payloadOffset,n),d=(0,sf.createDecipheriv)("aes-128-gcm",this.srtpSessionKey,a);d.setAAD(s),d.setAuthTag(i);let u=d.update(c);return ek(d,"SRTP"),u.copy(o,t.payloadOffset),[o,IP(t,o,"Failed to authenticate SRTP packet")]}encryptRTCP(r,e){let t=r.readUInt32BE(4),s=r.length+this.aeadAuthTagLen,n=Buffer.from([]);n=f_(n,s+zS),r.slice(0,8).copy(n);let i=this.rtcpInitializationVector(t,e),o=this.rtcpAdditionalAuthenticatedData(r,e),a=(0,sf.createCipheriv)("aes-128-gcm",this.srtcpSessionKey,i);a.setAAD(o);let c=a.update(r.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(r){let e=TP(r,this.aeadAuthTagLen,zS),t=r.length-zS,s=t-this.aeadAuthTagLen,n=r.readUInt32BE(4),i=r.readUInt32BE(t),o=i>>>31===1,a=i&~(ZR<<24),c=this.rtcpInitializationVector(n,a),d=o?Buffer.concat([r.subarray(0,8),r.subarray(t)]):Buffer.concat([r.subarray(0,s),r.subarray(t)]),u=o?r.slice(8,s):Buffer.alloc(0),f=o?Buffer.alloc(s):Buffer.from(r.subarray(0,s));o&&r.slice(0,8).copy(f);let h=(0,sf.createDecipheriv)("aes-128-gcm",this.srtcpSessionKey,c);h.setAAD(d),h.setAuthTag(r.subarray(s,t));let y=h.update(u);return ek(h,"SRTCP"),o&&y.copy(f,8),[f,e]}rtpInitializationVector(r,e){let t=this.rtpIvWriter([0,r.ssrc,e,r.sequenceNumber]);for(let s=0;s<t.length;s++)t[s]^=this.srtpSessionSalt[s];return t}rtcpInitializationVector(r,e){let t=this.rtcpIvWriter([0,r,0,e]);for(let s=0;s<t.length;s++)t[s]^=this.srtcpSessionSalt[s];return t}rtcpAdditionalAuthenticatedData(r,e){let t=Buffer.concat([r.subarray(0,8),this.aadWriter([e])]);return t[8]|=ZR,t}},zS=4,ZR=128;RP=class{constructor(r,e,t){this.masterKey=r,this.masterSalt=e,this.profile=t;{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,ky.createHmac)("sha1",this.srtpSessionAuthTag),this.srtcpSessionKey=this.generateSessionKey(3),this.srtcpSessionSalt=this.generateSessionSalt(5),this.srtcpSessionAuthTag=this.generateSessionAuthTag(4),this.srtcpSessionAuth=(0,ky.createHmac)("sha1",this.srtcpSessionAuthTag),t){case df:this.cipher=new sz(this.srtpSessionKey,this.srtpSessionSalt,this.srtcpSessionKey,this.srtcpSessionSalt,this.srtpSessionAuthTag,this.srtcpSessionAuthTag);break;case ad:this.cipher=new nz(this.srtpSessionKey,this.srtpSessionSalt,this.srtcpSessionKey,this.srtcpSessionSalt);break}}srtpSSRCStates={};srtpSessionKey;srtpSessionSalt;srtpSessionAuthTag;srtpSessionAuth;srtcpSSRCStates={};srtcpSessionKey;srtcpSessionSalt;srtcpSessionAuthTag;srtcpSessionAuth;cipher;generateSessionKey(r){let e=Buffer.from(this.masterSalt),t=Buffer.from([r,0,0,0,0,0,0]);for(let n=t.length-1,i=e.length-1;n>=0;n--,i--)e[i]=e[i]^t[n];e=Buffer.concat([e,Buffer.from([0,0])]);let s=new Py.default.AES(this.masterKey);return Buffer.from(s.encrypt(e))}generateSessionSalt(r){let e=Buffer.from(this.masterSalt),t=Buffer.from([r,0,0,0,0,0,0]);for(let n=t.length-1,i=e.length-1;n>=0;n--,i--)e[i]=e[i]^t[n];e=Buffer.concat([e,Buffer.from([0,0])]);let s=new Py.default.AES(this.masterKey);return e=Buffer.from(s.encrypt(e)),e.subarray(0,14)}generateSessionAuthTag(r){let e=Buffer.from(this.masterSalt),t=Buffer.from([r,0,0,0,0,0,0]);for(let o=t.length-1,a=e.length-1;o>=0;o--,a--)e[a]=e[a]^t[o];let s=Buffer.concat([e,Buffer.from([0,0])]),n=Buffer.concat([e,Buffer.from([0,1])]),i=new Py.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(r){let e=this.srtpSSRCStates[r];return e||(e={ssrc:r,rolloverCounter:0,lastSequenceNumber:0},this.srtpSSRCStates[r]=e,e)}getSrtcpSsrcState(r){let e=this.srtcpSSRCStates[r];return e||(e={srtcpIndex:0,ssrc:r},this.srtcpSSRCStates[r]=e,e)}updateRolloverCount(r,e){e.rolloverHasProcessed?r===0?e.lastSequenceNumber>tp&&e.rolloverCounter++:e.lastSequenceNumber<tp&&r>tk-tp?e.rolloverCounter>0&&e.rolloverCounter--:r<tp&&e.lastSequenceNumber>tk-tp&&e.rolloverCounter++:e.rolloverHasProcessed=!0,e.lastSequenceNumber=r}generateSrtpAuthTag(r,e){this.srtpSessionAuth=(0,ky.createHmac)("sha1",this.srtpSessionAuthTag);let t=Buffer.alloc(4);return t.writeUInt32BE(e),this.srtpSessionAuth.update(r).update(t).digest().slice(0,10)}index(r){let e=this.srtcpSSRCStates[r];return e?e.srtcpIndex:0}setIndex(r,e){let t=this.getSrtcpSsrcState(r);t.srtcpIndex=e%2147483647}},tp=100,tk=65535,iz=class extends RP{constructor(r,e,t){super(r,e,t)}encryptRTCP(r){let e=r.readUInt32BE(4),t=this.getSrtcpSsrcState(e);return t.srtcpIndex++,t.srtcpIndex>>oz&&(t.srtcpIndex=0),this.cipher.encryptRTCP(r,t.srtcpIndex)}decryptRTCP(r){return this.cipher.decryptRTCP(r)}},oz=2147483647,kP=class{constructor(r){this.ContextCls=r}localContext;remoteContext;onData;start(r,e,t,s,n){this.localContext=new this.ContextCls(r,e,n),this.remoteContext=new this.ContextCls(t,s,n)}},PP=class extends kP{constructor(r){super(iz),this.config=r,this.start(r.keys.localMasterKey,r.keys.localMasterSalt,r.keys.remoteMasterKey,r.keys.remoteMasterSalt,r.profile)}decrypt=r=>{let[e]=this.remoteContext.decryptRTCP(r);return e};encrypt(r){return this.localContext.encryptRTCP(r)}},az=class extends RP{constructor(r,e,t){super(r,e,t)}encryptRtp(r,e){let t=this.getSrtpSsrcState(e.ssrc);return this.updateRolloverCount(e.sequenceNumber,t),this.cipher.encryptRtp(e,r,t.rolloverCounter)}decryptRtp(r){let e=T2(r,this.rtpAuthTagLength),t=this.srtpSSRCStates[e.ssrc],s=t?{...t}:{ssrc:e.ssrc,rolloverCounter:0,lastSequenceNumber:0};this.updateRolloverCount(e.sequenceNumber,s);let n=this.cipher.decryptRtp(r,s.rolloverCounter,e);return t?Object.assign(t,s):this.srtpSSRCStates[e.ssrc]=s,n}get rtpAuthTagLength(){return this.profile===ad?16:10}},BP=class extends kP{constructor(r){super(az),this.config=r,this.start(r.keys.localMasterKey,r.keys.localMasterSalt,r.keys.remoteMasterKey,r.keys.remoteMasterSalt,r.profile)}decrypt=r=>{let[e]=this.remoteContext.decryptRtp(r);return e};encrypt(r,e){return this.localContext.encryptRtp(r,e)}},cz=class{constructor(r){this.props=r}sequenceNumber=l2();timestamp=Wy();create(r){this.sequenceNumber=Ur(this.sequenceNumber,1);let e=this.props.between*this.props.clockRate/1e3;this.timestamp=Yc(this.timestamp,e);let t=new po({sequenceNumber:this.sequenceNumber,timestamp:Number(this.timestamp),payloadType:96,extension:!0,marker:!1,padding:!1});return new mo(t,r)}},ns=ut("werift-dtls : packages/dtls/src/flight/client/flight5.ts : log"),dz=class extends Kp{constructor(r,e,t,s){super(r,e,5,7),this.cipher=t,this.srtp=s}handleHandshake(r){this.dtls.bufferHandshakeCache([r],!1,4);let e=(()=>{switch(r.msg_type){case 2:return T9.deSerialize(r.fragment);case 11:return Jy.deSerialize(r.fragment);case 12:return R9.deSerialize(r.fragment);case 13:return C9.deSerialize(r.fragment);case 14:return A9.deSerialize(r.fragment)}})();e&&uf[e.msgType]({dtls:this.dtls,cipher:this.cipher,srtp:this.srtp})(e)}async exec(){if(this.dtls.flight===5){ns(this.dtls.sessionId,"flight5 twice"),this.send(this.dtls.lastMessage);return}this.dtls.flight=5;let r=this.dtls.requestedCertificateTypes.length>0;ns(this.dtls.sessionId,"send flight5",r);let e=[r&&this.sendCertificate(),this.sendClientKeyExchange(),r&&this.sendCertificateVerify(),this.sendChangeCipherSpec(),this.sendFinished()].filter(t=>t);this.dtls.lastMessage=e,await this.transmit(e)}sendCertificate(){let r=new Jy([Buffer.from(this.cipher.localCert)]),e=this.createPacket([r]);return Buffer.concat(e.map(s=>s.serialize()))}sendClientKeyExchange(){if(!this.cipher.localKeyPair)throw new Error;let r=new E9(this.cipher.localKeyPair.publicKey),e=this.createPacket([r]),t=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=o9(n.publicKey,s.privateKey,s.curve);ns(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?c9(i,o):a9(i,this.cipher.localRandom.serialize(),this.cipher.remoteRandom.serialize()),this.cipher.cipher=b9(this.cipher.cipherSuite),this.cipher.cipher.init(this.cipher.masterSecret,this.cipher.remoteRandom.serialize(),this.cipher.localRandom.serialize()),ns(this.dtls.sessionId,"cipher",this.cipher.cipher.summary),t}sendCertificateVerify(){let r=Buffer.concat(this.dtls.sortedHandshakeCache.map(o=>o.serialize())),e=this.cipher.signatureData(r,"sha256"),t=(()=>{switch(this.cipher.signatureHashAlgorithm?.signature){case pi.ecdsa_3:return r_.ecdsa_secp256r1_sha256;case pi.rsa_1:return r_.rsa_pkcs1_sha256}})();if(!t)throw new Error;ns(this.dtls.sessionId,"signatureScheme",this.cipher.signatureHashAlgorithm?.signature,t);let s=new _9(t,e),n=this.createPacket([s]);return Buffer.concat(n.map(o=>o.serialize()))}sendChangeCipherSpec(){let r=S9.createEmpty().serialize(),e=Vp(this.dtls)([{type:20,fragment:r}],++this.dtls.recordSequenceNumber);return Buffer.concat(e.map(s=>s.serialize()))}sendFinished(){let r=Buffer.concat(this.dtls.sortedHandshakeCache.map(i=>i.serialize())),e=this.cipher.verifyData(r),t=new c_(e);this.dtls.epoch=1;let[s]=this.createPacket([t]);this.dtls.recordSequenceNumber=0;let n=this.cipher.encryptPacket(s).serialize();return ns(this.dtls.sessionId,"finished",this.cipher.cipher.summary),n}},uf={};uf[2]=({cipher:r,srtp:e,dtls:t})=>s=>{ns(t.sessionId,"serverHello",s.cipherSuite),r.remoteRandom=Qc.from(s.random),r.cipherSuite=s.cipherSuite,ns(t.sessionId,"selected cipherSuite",r.cipherSuite),s.extensions&&s.extensions.forEach(n=>{switch(n.type){case ef.type:{let i=ef.fromData(n.data),o=Rp.findMatchingSRTPProfile(i.profiles,t.options.srtpProfiles||[]);if(ns(t.sessionId,"selected srtp profile",o),o==null)return;e.srtpProfile=o}break;case mx.type:t.remoteExtendedMasterSecret=!0;break;case gx.type:ns(t.sessionId,"RenegotiationIndication");break}})};uf[11]=({cipher:r,dtls:e})=>t=>{ns(e.sessionId,"handshake certificate",t),r.remoteCertificate=t.certificateList[0]};uf[12]=({cipher:r,dtls:e})=>t=>{if(!r.localRandom||!r.remoteRandom)throw new Error;ns(e.sessionId,"ServerKeyExchange",t),ns(e.sessionId,"selected curve",t.namedCurve),r.remoteKeyPair={curve:t.namedCurve,publicKey:t.publicKey},r.localKeyPair=w9(t.namedCurve)};uf[13]=({dtls:r})=>e=>{ns(r.sessionId,"certificate_request",e),r.requestedCertificateTypes=e.certificateTypes,r.requestedSignatureAlgorithms=e.signatures};uf[14]=({dtls:r})=>e=>{ns(r.sessionId,"server_hello_done",e)};NP=class yp{constructor(e,t){this.serverVersion=e,this.cookie=t}msgType=3;messageSeq;static spec={serverVersion:v2,cookie:id.types.buffer(id.types.uint8)};static createEmpty(){return new yp(void 0,void 0)}static deSerialize(e){return new yp(...Object.values((0,id.decode)(e,yp.spec)))}serialize(){let e=(0,id.encode)(this,yp.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 Zs(this.msgType,e.length,this.messageSeq,0,e.length,e)}},uz=ut("werift-dtls : packages/dtls/src/context/dtls.ts : log"),rk=class{constructor(r,e){this.options=r,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(([r],[e])=>Number(r)-Number(e)).flatMap(([,{data:r}])=>r.sort((e,t)=>e.message_seq-t.message_seq))}checkHandshakesExist=r=>!r.find(e=>this.sortedHandshakeCache.find(t=>t.msg_type===e)==null);bufferHandshakeCache(r,e,t){this.handshakeCache[t]||(this.handshakeCache[t]={data:[],isLocal:e,flight:t});let s=r.filter(n=>{let i=this.handshakeCache[t].data.find(o=>o.msg_type===n.msg_type);return i?(uz(this.sessionId,"exist",i.summary,e,t),!1):!0});this.handshakeCache[t].data=[...this.handshakeCache[t].data,...s]}},fz=class{constructor(r){this.socket=r}send=r=>this.socket.send(r)},E_=class oo{static type=10;static spec={type:hi.types.uint16be,data:hi.types.array(hi.types.uint16be,hi.types.uint16be,"bytes")};type=oo.type;data=[];constructor(e={}){Object.assign(this,e)}static createEmpty(){return new oo}static fromData(e){return new oo({type:oo.type,data:(0,hi.decode)(e,oo.spec.data)})}static deSerialize(e){return new oo((0,hi.decode)(e,oo.spec))}serialize(){return Buffer.from((0,hi.encode)(this,oo.spec).slice())}get extension(){return{type:this.type,data:this.serialize().slice(2)}}},C_=class xa{static type=13;static spec={type:li.types.uint16be,data:li.types.array({hash:li.types.uint8,signature:li.types.uint8},li.types.uint16be,"bytes")};type=xa.type;data=[];constructor(e={}){Object.assign(this,e)}static createEmpty(){return new xa}static deSerialize(e){return new xa((0,li.decode)(e,xa.spec))}serialize(){let e=(0,li.encode)(this,xa.spec).slice();return Buffer.from(e)}static fromData(e){let t=Buffer.alloc(2);return t.writeUInt16BE(xa.type),xa.deSerialize(Buffer.concat([t,e]))}get extension(){return{type:this.type,data:this.serialize().slice(2)}}},sk=class By{constructor(e,t){this.level=e,this.description=t}static spec={level:od.types.uint8,description:od.types.uint8};static deSerialize(e){return new By(...Object.values((0,od.decode)(e,By.spec)))}serialize(){let e=(0,od.encode)(this,By.spec).slice();return Buffer.from(e)}},nk=ut("werift-dtls : packages/dtls/record/receive.ts : log"),$S=ut("werift-dtls : packages/dtls/record/receive.ts : err"),lz=r=>{let e=0,t=[];for(;r.length>e;){let s=r.readUInt16BE(e+11);if(r.length<e+(12+s))break;let n=y9.deSerialize(r.subarray(e));t.push(n),e+=13+s}return t},hz=(r,e)=>t=>{switch(t.recordLayerHeader.contentType){case 20:return nk(r.sessionId,"change cipher spec"),[{type:20,data:void 0}];case 22:{let n=t.fragment;try{t.recordLayerHeader.epoch>0&&(nk(r.sessionId,"decrypt handshake"),n=e.decryptPacket(t))}catch(i){throw $S(r.sessionId,"decrypt failed",i),i}try{let i=0,o=[];for(;n.length>i;){let a=Zs.deSerialize(n.subarray(i));o.push({type:22,data:a}),i+=a.fragment_length+12}return o}catch(i){throw $S(r.sessionId,"decSerialize failed",i,n),i}}case 23:return[{type:23,data:e.decryptPacket(t)}];case 21:{let n=sk.deSerialize(t.fragment);if(o_[n.description]==null){let i=e.decryptPacket(t);n=sk.deSerialize(i)}if($S(r.sessionId,"ContentType.alert",n,o_[n.description],"flight",r.flight,"lastFlight",r.lastFlight),n.level>1)throw new Error("alert fatal error");return[{type:21,data:void 0}]}default:return[{type:21,data:void 0}]}},ik=ut("werift-dtls : packages/dtls/src/socket.ts : log"),ok=ut("werift-dtls : packages/dtls/src/socket.ts : err"),A2=class{constructor(r,e){this.options=r,this.sessionType=e,this.dtls=new rk(this.options,this.sessionType),this.cipher=new Ip(this.sessionType,this.options.cert,this.options.key,this.options.signatureHash),this.transport=new fz(this.options.transport),this.setupExtensions(),this.transport.socket.onData=this.udpOnMessage}onConnect=new Te;onData=new Te;onError=new Te;onClose=new Te;transport;cipher;dtls;srtp=new Rp;connected=!1;extensions=[];onHandleHandshakes;bufferFragmentedHandshakes=[];renegotiation(){ik("renegotiation",this.sessionType),this.connected=!1,this.cipher=new Ip(this.sessionType,this.options.cert,this.options.key,this.options.signatureHash),this.dtls=new rk(this.options,this.sessionType),this.srtp=new Rp,this.extensions=[],this.bufferFragmentedHandshakes=[]}udpOnMessage=r=>{let e=lz(r);for(let t of e)try{let s=hz(this.dtls,this.cipher)(t);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=>Zs.assemble(c)).sort((c,d)=>c.msg_type-d.msg_type);this.onHandleHandshakes(a).catch(c=>{ok(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){ok(this.dtls.sessionId,"catch udpOnMessage error",s)}};setupExtensions(){if(ik(this.dtls.sessionId,"support srtpProfiles",this.options.srtpProfiles),this.options.srtpProfiles&&this.options.srtpProfiles.length>0){let r=ef.create(this.options.srtpProfiles,Buffer.from([0]));this.extensions.push(r.extension)}{let r=E_.createEmpty();r.data=g2,this.extensions.push(r.extension)}{let r=C_.createEmpty();r.data=x2,this.extensions.push(r.extension)}this.options.extendedMasterSecret&&this.extensions.push({type:mx.type,data:Buffer.alloc(0)});{let r=gx.createEmpty();this.extensions.push(r.extension)}}waitForReady=r=>new Promise(async(e,t)=>{for(let s=0;s<10;s++)if(r()){e();break}else await(0,OP.setTimeout)(100*s);t("waitForReady timeout")});handleFragmentHandshake(r){let e=r.filter(t=>t.fragment_length!==t.length?(this.bufferFragmentedHandshakes.push(t),!1):!0);if(this.bufferFragmentedHandshakes.length>1){let[t]=this.bufferFragmentedHandshakes.slice(-1);t.fragment_offset+t.fragment_length===t.length&&(e=[...this.bufferFragmentedHandshakes,...e],this.bufferFragmentedHandshakes=[])}return e}send=async r=>{let e=Vp(this.dtls)([{type:23,fragment:r}],++this.dtls.recordSequenceNumber)[0];await this.transport.send(this.cipher.encryptPacket(e).serialize())};close(){this.transport.socket.close()}extractSessionKeys(r,e){let t=this.exportKeyingMaterial("EXTRACTOR-dtls_srtp",r*2+e*2),{clientKey:s,serverKey:n,clientSalt:i,serverSalt:o}=(0,Xc.decode)(t,{clientKey:Xc.types.buffer(r),serverKey:Xc.types.buffer(r),clientSalt:Xc.types.buffer(e),serverSalt:Xc.types.buffer(e)});return this.sessionType===lo.CLIENT?{localKey:s,localSalt:i,remoteKey:n,remoteSalt:o}:{localKey:n,localSalt:o,remoteKey:s,remoteSalt:i}}exportKeyingMaterial(r,e){return lq(r,e,this.cipher.masterSecret,this.cipher.localRandom.serialize(),this.cipher.remoteRandom.serialize(),this.sessionType===lo.CLIENT)}get remoteCertificate(){return this.cipher.remoteCertificate}},VS=ut("werift-dtls : packages/dtls/src/client.ts : log"),T_=class extends A2{constructor(r){super(r,lo.CLIENT),this.onHandleHandshakes=this.handleHandshakes,VS(this.dtls.sessionId,"start client")}async connect(){await new Aq(this.transport,this.dtls,this.cipher).exec(this.extensions)}flight5;handleHandshakes=async r=>{VS(this.dtls.sessionId,"handleHandshakes",r.map(e=>e.msg_type));for(let e of r)switch(e.msg_type){case 3:{let t=NP.deSerialize(e.fragment);await new Rq(this.transport,this.dtls).exec(t)}break;case 2:{if(this.connected)return;this.flight5=new dz(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 t=[11,12,this.options.certificateRequest&&13].filter(s=>typeof s=="number");await this.waitForReady(()=>this.dtls.checkHandshakesExist(t)),await this.flight5?.exec()}break;case 20:this.dtls.flight=7,this.connected=!0,this.onConnect.execute(),VS(this.dtls.sessionId,"dtls connected");break}}},ui=ut("werift-dtls : packages/dtls/flight/server/flight2.ts : log"),pz=(r,e,t,s)=>n=>{ui("dtls version",n.clientVersion),e.flight=2,e.recordSequenceNumber=0,e.sequenceNumber=0,n.extensions.forEach(f=>{switch(f.type){case E_.type:{let h=E_.fromData(f.data).data;ui(e.sessionId,"curves",h);let y=h.filter(v=>g2.includes(v))[0];t.namedCurve=y,ui(e.sessionId,"curve selected",t.namedCurve)}break;case C_.type:{if(!t.signatureHashAlgorithm)throw new Error("need to set certificate");let h=C_.fromData(f.data).data;ui(e.sessionId,"hash,signature",h);let y=h.find(S=>S.signature===t.signatureHashAlgorithm?.signature)?.signature,v=h.find(S=>S.hash===t.signatureHashAlgorithm?.hash)?.hash;if(y==null||v==null)throw new Error("invalid signatureHash")}break;case ef.type:{if(!e.options?.srtpProfiles||e.options.srtpProfiles.length===0)return;let h=ef.fromData(f.data);ui(e.sessionId,"srtp profiles",h.profiles);let y=Rp.findMatchingSRTPProfile(h.profiles,e.options?.srtpProfiles);if(!y)throw new Error;s.srtpProfile=y,ui(e.sessionId,"srtp profile selected",s.srtpProfile)}break;case mx.type:e.remoteExtendedMasterSecret=!0;break;case gx.type:ui(e.sessionId,"RenegotiationIndication",f.data);break;case 43:{let y=[...f.data.subarray(1)].map(v=>v.toString(10));ui("dtls supported version",y)}break}}),t.localRandom=new Qc,t.remoteRandom=Qc.from(n.random);let i=n.cipherSuites;ui(e.sessionId,"cipher suites",i);let o=(()=>{switch(t.signatureHashAlgorithm?.signature){case pi.ecdsa_3:return Xy.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256_49195;case pi.rsa_1:return Xy.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256_49199}})();if(o===void 0||!i.includes(o))throw new Error("dtls cipher suite negotiation failed");t.cipherSuite=o,ui(e.sessionId,"selected cipherSuite",t.cipherSuite),t.localKeyPair=w9(t.namedCurve),e.cookie||=(0,LP.randomBytes)(20);let a=new NP({major:254,minor:253},e.cookie),c=x9(e)([a]),u=Vp(e)(c.map(f=>({type:22,fragment:f.serialize()})),++e.recordSequenceNumber).map(f=>f.serialize());for(let f of u)r.send(f)},ak=ut("werift-dtls : packages/dtls/flight/server/flight4.ts : log"),mz=class extends Kp{constructor(r,e,t,s){super(r,e,4,6),this.cipher=t,this.srtp=s}async exec(r,e=!1){if(this.dtls.flight===4){ak(this.dtls.sessionId,"flight4 twice"),this.send(this.dtls.lastMessage);return}this.dtls.flight=4,this.dtls.sequenceNumber=1,this.dtls.bufferHandshakeCache([r],!1,4);let t=[this.sendServerHello(),this.sendCertificate(),this.sendServerKeyExchange(),e&&this.sendCertificateRequest(),this.sendServerHelloDone()].filter(s=>s);this.dtls.lastMessage=t,await this.transmit(t)}sendServerHello(){let r=[];this.srtp.srtpProfile&&r.push(ef.create([this.srtp.srtpProfile],Buffer.from([0])).extension),this.dtls.options.extendedMasterSecret&&r.push({type:mx.type,data:Buffer.alloc(0)});let e=gx.createEmpty();r.push(e.extension);let t=new T9(this.dtls.version,this.cipher.localRandom,Buffer.from([0]),this.cipher.cipherSuite,0,r),s=this.createPacket([t]);return Buffer.concat(s.map(n=>n.serialize()))}sendCertificate(){let r=new Jy([Buffer.from(this.cipher.localCert)]),e=this.createPacket([r]);return Buffer.concat(e.map(t=>t.serialize()))}sendServerKeyExchange(){let r=this.cipher.generateKeySignature("sha256");if(!this.cipher.signatureHashAlgorithm)throw new Error("not exist");let e=new R9(y2.named_curve_3,this.cipher.namedCurve,this.cipher.localKeyPair.publicKey.length,this.cipher.localKeyPair.publicKey,this.cipher.signatureHashAlgorithm.hash,this.cipher.signatureHashAlgorithm.signature,r.length,r),t=this.createPacket([e]);return Buffer.concat(t.map(s=>s.serialize()))}sendCertificateRequest(){let r=new C9(s9,x2,[]);ak(this.dtls.sessionId,"sendCertificateRequest",r);let e=this.createPacket([r]);return Buffer.concat(e.map(t=>t.serialize()))}sendServerHelloDone(){let r=new A9,e=this.createPacket([r]);return Buffer.concat(e.map(t=>t.serialize()))}},nf=ut("werift-dtls : packages/dtls/flight/server/flight6.ts"),gz=class extends Kp{constructor(r,e,t){super(r,e,6),this.cipher=t}handleHandshake(r){this.dtls.bufferHandshakeCache([r],!1,5);let e=(()=>{switch(r.msg_type){case 11:return Jy.deSerialize(r.fragment);case 15:return _9.deSerialize(r.fragment);case 16:return E9.deSerialize(r.fragment);case 20:return c_.deSerialize(r.fragment)}})();if(e){let t=Yp[e.msgType];if(!t)return;t({dtls:this.dtls,cipher:this.cipher})(e)}}async exec(){if(this.dtls.flight===6){nf(this.dtls.sessionId,"flight6 twice"),this.send(this.dtls.lastMessage);return}this.dtls.flight=6;let r=[this.sendChangeCipherSpec(),this.sendFinished()];this.dtls.lastMessage=r,await this.transmit(r)}sendChangeCipherSpec(){let r=S9.createEmpty().serialize(),e=Vp(this.dtls)([{type:20,fragment:r}],++this.dtls.recordSequenceNumber);return Buffer.concat(e.map(s=>s.serialize()))}sendFinished(){let r=Buffer.concat(this.dtls.sortedHandshakeCache.map(i=>i.serialize())),e=this.cipher.verifyData(r),t=new c_(e);this.dtls.epoch=1;let[s]=this.createPacket([t]);return this.dtls.recordSequenceNumber=0,this.cipher.encryptPacket(s).serialize()}},Yp={};Yp[16]=({cipher:r,dtls:e})=>t=>{if(r.remoteKeyPair={curve:r.namedCurve,publicKey:t.publicKey},!r.remoteKeyPair.publicKey||!r.localKeyPair||!r.remoteRandom||!r.localRandom)throw new Error("not exist");let s=o9(r.remoteKeyPair.publicKey,r.localKeyPair.privateKey,r.localKeyPair.curve);nf(e.sessionId,"extendedMasterSecret",e.options.extendedMasterSecret,e.remoteExtendedMasterSecret);let n=Buffer.concat(e.sortedHandshakeCache.map(i=>i.serialize()));r.masterSecret=e.options.extendedMasterSecret&&e.remoteExtendedMasterSecret?c9(s,n):a9(s,r.remoteRandom.serialize(),r.localRandom.serialize()),r.cipher=b9(r.cipherSuite),r.cipher.init(r.masterSecret,r.localRandom.serialize(),r.remoteRandom.serialize()),nf(e.sessionId,"setup cipher",r.cipher.summary)};Yp[11]=({cipher:r,dtls:e})=>t=>{nf(e.sessionId,"handshake certificate",t),r.remoteCertificate=t.certificateList[0]};Yp[15]=({cipher:r,dtls:e})=>t=>{if(!r.remoteCertificate)throw new Error("client certificate missing before certificate verify");nf(e.sessionId,"certificate_verify",t.algorithm)};Yp[20]=({dtls:r})=>e=>{nf(r.sessionId,"finished",e)};Fu=ut("werift-dtls : packages/dtls/src/server.ts : log"),DP=class extends A2{constructor(r){super(r,lo.SERVER),this.onHandleHandshakes=this.handleHandshakes,Fu(this.dtls.sessionId,"start server")}flight6;handleHandshakes=async r=>{Fu(this.dtls.sessionId,"handleHandshakes",r.map(e=>e.msg_type));for(let e of r)switch(e.msg_type){case 1:{this.connected&&this.renegotiation();let t=m9.deSerialize(e.fragment);t.cookie.length===0?(Fu(this.dtls.sessionId,"send flight2"),pz(this.transport,this.dtls,this.cipher,this.srtp)(t)):this.dtls.cookie&&t.cookie.equals(this.dtls.cookie)?(Fu(this.dtls.sessionId,"send flight4"),await new mz(this.transport,this.dtls,this.cipher,this.srtp).exec(e,this.options.certificateRequest)):Fu("wrong state",{dtlsCookie:this.dtls.cookie?.toString("hex").slice(10),helloCookie:t.cookie.toString("hex").slice(10)})}break;case 11:case 15:case 16:{if(this.connected)return;this.flight6=new gz(this.transport,this.dtls,this.cipher),this.flight6.handleHandshake(e)}break;case 20:{await this.waitForReady(()=>!!this.flight6),this.flight6?.handleHandshake(e);let t=[16,this.options.certificateRequest&&11,this.options.certificateRequest&&15].filter(s=>typeof s=="number");await this.waitForReady(()=>this.dtls.checkHandshakesExist(t)),await this.flight6?.exec(),this.connected=!0,this.onConnect.execute(),Fu(this.dtls.sessionId,"dtls connected")}break}}},bx=554869826,MP=8,UP=1398035790,co=20,I2=24,R2=1,k2=2,jP=6,HP=50,yz=["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"],P2=(r=>(r[r.REQUEST=0]="REQUEST",r[r.INDICATION=16]="INDICATION",r[r.RESPONSE=256]="RESPONSE",r[r.ERROR=272]="ERROR",r))(P2||{}),B2=(r=>(r[r.BINDING=1]="BINDING",r[r.SHARED_SECRET=2]="SHARED_SECRET",r[r.ALLOCATE=3]="ALLOCATE",r[r.REFRESH=4]="REFRESH",r[r.SEND=6]="SEND",r[r.DATA=7]="DATA",r[r.CREATE_PERMISSION=8]="CREATE_PERMISSION",r[r.CHANNEL_BIND=9]="CHANNEL_BIND",r))(B2||{});ck=class{queue=[];wait=new Te;put(r){this.queue.push(r),this.queue.length===1&&this.wait.execute(r)}get(){let r=this.queue.shift();return r||new Promise(e=>{this.wait.subscribe(t=>{this.queue.shift(),e(t)})})}},A_=r=>{let e,t,s=new Promise((i,o)=>{e=i,t=o});s.then(()=>{n.execute(void 0),n.complete()}).catch(i=>{n.execute(i??new Error),n.complete()});let n=new Te;return r(e,t,n).catch(()=>{}),{awaitable:s,resolve:e,reject:t}};L2=Buffer.alloc(6);L2.writeUInt16BE(bx>>16,0);L2.writeUInt32BE(bx,2);sp=r=>{let e=Buffer.alloc(4);return e.writeUInt32BE(r,0),e},np=r=>r.readUInt32BE(0),vz=r=>{let e=Buffer.alloc(4);return e.writeUInt16BE(r,0),e},wz=r=>r.readUInt16BE(0),dk=r=>new AS(r.toString()).toBuffer(),uk=r=>{let e=new AS(r);return BigInt(e.toString())},KS=r=>Buffer.from(r,"utf8"),WS=r=>r.toString("utf8"),GS=r=>r,XS=r=>r,Sz=r=>Buffer.from([]),_z=r=>null,zP=[[1,"MAPPED-ADDRESS",Vu,Ku],[3,"CHANGE-REQUEST",sp,np],[4,"SOURCE-ADDRESS",Vu,Ku],[5,"CHANGED-ADDRESS",Vu,Ku],[6,"USERNAME",KS,WS],[8,"MESSAGE-INTEGRITY",GS,XS],[9,"ERROR-CODE",bz,xz],[12,"CHANNEL-NUMBER",vz,wz],[13,"LIFETIME",sp,np],[18,"XOR-PEER-ADDRESS",Oy,Ny],[19,"DATA",GS,XS],[20,"REALM",KS,WS],[21,"NONCE",GS,XS],[22,"XOR-RELAYED-ADDRESS",Oy,Ny],[25,"REQUESTED-TRANSPORT",sp,np],[32,"XOR-MAPPED-ADDRESS",Oy,Ny],[36,"PRIORITY",sp,np],[37,"USE-CANDIDATE",Sz,_z],[32802,"SOFTWARE",KS,WS],[32808,"FINGERPRINT",sp,np],[32809,"ICE-CONTROLLED",dk,uk],[32810,"ICE-CONTROLLING",dk,uk],[32811,"RESPONSE-ORIGIN",Vu,Ku],[32812,"OTHER-ADDRESS",Vu,Ku]],$P=class{constructor(r=[]){this.attributes=r}getAttributes(){return this.attributes}setAttribute(r,e){let t=this.attributes.find(s=>s[0]===r);return t?t[1]=e:this.attributes.push([r,e]),this}getAttributeValue(r){let e=this.attributes.find(t=>t[0]===r);if(e)return e[1]}get attributesKeys(){return this.attributes.map(r=>r[0])}clear(){this.attributes=[]}},fk=zP.reduce((r,e)=>(r[e[0]]=e,r),{}),Ez=zP.reduce((r,e)=>(r[e[1]]=e,r),{});Qs=class extends $P{constructor(r,e,t=FP(),s=[]){super(s),this.messageMethod=r,this.messageClass=e,this.transactionId=t}toJSON(){return this.json}get json(){return{messageMethod:B2[this.messageMethod],messageClass:P2[this.messageClass],attributes:this.attributes}}get transactionIdHex(){return this.transactionId.toString("hex")}get bytes(){let r=Buffer.from([]);for(let t of this.attributesKeys){let s=this.getAttributeValue(t),[n,,i]=Ez[t],o=i.name===Oy.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),r=Buffer.concat([r,d,o,Buffer.alloc(c,0)])}let e=Buffer.alloc(8);return e.writeUInt16BE(this.messageMethod|this.messageClass,0),e.writeUInt16BE(r.length,2),e.writeUInt32BE(bx,4),Buffer.concat([e,this.transactionId,r])}addMessageIntegrity(r){return this.setAttribute("MESSAGE-INTEGRITY",this.messageIntegrity(r)),this}messageIntegrity(r){let e=D2(this.bytes,this.bytes.length-co+I2);return Buffer.from((0,N2.createHmac)("sha1",r).update(e).digest("hex"),"hex")}addFingerprint(){this.setAttribute("FINGERPRINT",VP(this.bytes))}},D2=(r,e)=>{let t=Buffer.alloc(r.length);return r.copy(t,0,0,2),t.writeUInt16BE(e,2),r.copy(t,4,4),t};KP=class extends Error{response;addr},WP=class extends KP{constructor(r,e){super(),this.response=r,this.addr=e}get str(){let r="STUN transaction failed",e=this.response.getAttributeValue("ERROR-CODE");if(e){let[t,s]=e;r+=` (${t} - ${s})`}return r}},Tz=class extends KP{get str(){return"STUN transaction timed out"}},YS=ut("werift-ice:packages/ice/src/stun/transaction.ts"),M2=class{constructor(r,e,t,s){this.request=r,this.addr=e,this.protocol=t,this.retransmissions=s,this.triesMax=1+(this.retransmissions?this.retransmissions:jP)}timeoutDelay=HP;ended=!1;tries=0;triesMax;onResponse=new Te;responseReceived=(r,e)=>{this.onResponse.length>0&&(r.messageClass===256?(this.onResponse.execute(r,e),this.onResponse.complete()):this.onResponse.error(new WP(r,e)))};run=async()=>{try{return this.retry().catch(e=>{YS("retry failed",e)}),await this.onResponse.asPromise()}catch(r){throw r}finally{this.cancel()}};retry=async()=>{for(;this.tries<this.triesMax&&!this.ended&&(this.protocol.sendStun(this.request,this.addr).catch(r=>{YS("send stun failed",r)}),await new Promise(r=>setTimeout(r,this.timeoutDelay)),!this.ended);)this.timeoutDelay*=2,this.tries++;this.tries>=this.triesMax&&(YS(`retry failed times:${this.tries} maxLimit:${this.triesMax}`),this.onResponse.error(new Tz))};cancel(){this.ended=!0}},lk=ut("werift-ice : packages/ice/src/stun/protocol.ts"),Zy=class GP{static type="stun";type=GP.type;transport;transactions={};get transactionsKeys(){return Object.keys(this.transactions)}localCandidate;sentMessage;localIp;onRequestReceived=new Te;onDataReceived=new Te;constructor(){}connectionMade=async(e,t,s)=>{e?this.transport=await Gy.init("udp4",{portRange:t,interfaceAddresses:s}):this.transport=await Gy.init("udp6",{portRange:t,interfaceAddresses:s}),this.transport.onData=(n,i)=>{this.datagramReceived(n,i)}};datagramReceived(e,t){try{let s=vx(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,t):s.messageClass===0&&this.onRequestReceived.execute(s,t,e)}catch(s){lk("datagramReceived error",s)}}getExtraInfo(){let{address:e,port:t}=this.transport.address;return[e,t]}async sendStun(e,t){if(this.transport.closed)return;let s=e.bytes;await this.transport.send(s,t).catch(()=>{lk("sendStun failed",t,e)})}async sendData(e,t){this.transport.closed||await this.transport.send(e,t)}async request(e,t,s,n){if(this.transactionsKeys.includes(e.transactionIdHex))throw new Error("already request ed");s&&(e.addMessageIntegrity(s),e.addFingerprint());let i=new M2(e,t,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()}},vs=ut("werift-ice:packages/ice/src/turn/protocol.ts"),Az=500,Iz=600,Rz=285212672,JP=class QP{constructor(e){this.turn=e,e.onData.subscribe((t,s)=>{this.handleStunMessage(t,s)}).disposer(this.disposer)}static type="turn";type=QP.type;localCandidate;disposer=new Xk;onRequestReceived=new Te;onDataReceived=new Te;handleStunMessage=(e,t)=>{try{let s=vx(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,t)}else s.messageClass===0&&this.onRequestReceived.execute(s,t,e)}catch(s){vs("datagramReceived error",s)}};async request(e,t,s){if(this.turn.transactions[e.transactionIdHex])throw new Error("exist");s&&(e.addMessageIntegrity(s),e.addFingerprint());let n=new M2(e,t,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,t){await this.turn.sendData(e,t)}async sendStun(e,t){await this.turn.sendData(e.bytes,t)}async close(){return this.disposer.dispose(),this.turn.close()}},ZP=class eB{constructor(e,t,s,n,i,o={}){this.server=e,this.username=t,this.password=s,this.lifetime=n,this.transport=i,this.options=o,this.channelRefreshTime=this.options.channelRefreshTime??Az}static type="turn";type=eB.type;onData=new Te;onRequestReceived=new Te;onDataReceived=new Te;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 Qs(3,0);e.setAttribute("LIFETIME",this.lifetime).setAttribute("REQUESTED-TRANSPORT",Rz);let[t]=await this.requestWithRetry(e,this.server).catch(n=>{throw vs("connect error",n),n});this.relayedAddress=t.getAttributeValue("XOR-RELAYED-ADDRESS"),this.mappedAddress=t.getAttributeValue("XOR-MAPPED-ADDRESS");let s=t.getAttributeValue("LIFETIME");vs("connect",this.relayedAddress,this.mappedAddress,{exp:s}),this.refresh(s)}handleChannelData(e){let[t,s]=R_.jspack.Unpack("!HH",e.slice(0,4)),n=this.addrByChannel[t];if(n){let i=e.subarray(4,4+s);this.onData.execute(i,n)}}handleSTUNMessage(e,t){try{let s=vx(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,t)}else s.messageClass===0&&this.onData.execute(e,t);if(s.getAttributeValue("DATA")){let n=s.getAttributeValue("DATA");this.onData.execute(n,t)}}catch{vs("parse error",e.toString())}}dataReceived(e,t){let s=(n,i)=>{n.length>=4&&hk(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]=is(this.tcpBuffer.subarray(0,4),[2,2]);n+=I_(n);let i=hk(this.tcpBuffer)?4+n:20+n;if(this.tcpBuffer.length<i)break;s(this.tcpBuffer.subarray(0,i),t),this.tcpBuffer=this.tcpBuffer.subarray(i)}else s(e,t)}async send(e,t){if(!this.transport.closed)if(this.transport.type==="tcp"){let s=I_(e.length);await this.transport.send(s>0?Buffer.concat([e,Buffer.alloc(s)]):e,t)}else await this.transport.send(e,t)}async createPermission(e){let t=new Qs(8,0);t.setAttribute("XOR-PEER-ADDRESS",e).setAttribute("USERNAME",this.username).setAttribute("REALM",this.realm).setAttribute("NONCE",this.nonce),await this.request(t,this.server).catch(s=>{throw s})}refresh=e=>{this.refreshHandle=A_(async(t,s,n)=>{let i=!0;for(n.once(()=>{i=!1});i;){let o=.8333333333333334*e*1e3;vs("refresh delay",o,{exp:e}),await(0,YP.setTimeout)(o);let a=new Qs(4,0);a.setAttribute("LIFETIME",e);try{let[c]=await this.requestWithRetry(a,this.server);e=c.getAttributeValue("LIFETIME"),vs("refresh",{exp:e})}catch(c){vs("refresh error",c)}}})};async request(e,t){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 M2(e,t,this);this.transactions[e.transactionIdHex]=s;try{return await s.run()}catch(n){throw n}finally{delete this.transactions[e.transactionIdHex]}}async requestWithRetry(e,t){let s,n;try{[s,n]=await this.request(e,t)}catch(i){if(!(i instanceof WP))throw vs("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)vs("retry with nonce",o),this.nonce=a,o===401&&(this.realm=c),this.integrityKey=rB(this.username,this.realm,this.password),e.transactionId=FP(),[s,n]=await this.request(e,this.server);else throw i}return[s,n]}async sendData(e,t){let s=await this.getChannel(t).catch(i=>new Error("channelBind error"));if(s instanceof Error){await this.getPermission(t);let i=new Qs(6,16).setAttribute("DATA",e).setAttribute("XOR-PEER-ADDRESS",t);await this.sendStun(i,this.server);return}let n=R_.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 vs("createPermission error",s),s}))}async getChannel(e){this.channelBinding&&await this.channelBinding;let t=this.channelByAddr[e.join(":")];return t?this.channelRefreshAt<Yu(Date.now()/1e3)&&(this.channelBinding=this.channelBind(t.number,e),this.channelRefreshAt=Yu(Date.now()/1e3)+this.channelRefreshTime,await this.channelBinding.catch(s=>{throw vs("channelBind error",s),s}),this.channelBinding=void 0,vs("channelBind refresh",t)):(this.channelByAddr[e.join(":")]={number:this.channelNumber++,address:e},t=this.channelByAddr[e.join(":")],this.addrByChannel[t.number]=e,this.channelBinding=this.channelBind(t.number,e),await this.channelBinding.catch(s=>{throw vs("channelBind error",s),s}),this.channelRefreshAt=Yu(Date.now()/1e3)+this.channelRefreshTime,this.channelBinding=void 0,vs("channelBind",t)),t}async channelBind(e,t){let s=new Qs(9,0);s.setAttribute("CHANNEL-NUMBER",e).setAttribute("XOR-PEER-ADDRESS",t);let[n]=await this.requestWithRetry(s,this.server);if(n.messageMethod!==9)throw new Error("should be CHANNEL_BIND")}async sendStun(e,t){await this.send(e.bytes,t)}async close(){this.refreshHandle?.resolve?.(),await this.transport.close()}};Sa=class nB{constructor(e,t,s,n,i,o,a,c,d,u,f,h){this.foundation=e,this.component=t,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=f,this.ufrag=h}static fromSdp(e){let t=e.split(" ");if(t.length<8)throw new Error("SDP does not have enough properties");let s={foundation:t[0],component:Number(t[1]),transport:t[2],priority:Number(t[3]),host:t[4],port:Number(t[5]),type:t[7]};for(let f=8,h=t.length-1;f<h;f+=2)t[f]==="raddr"?s.related_address=t[f+1]:t[f]==="rport"?s.related_port=Number(t[f+1]):t[f]==="tcptype"?s.tcptype=t[f+1]:t[f]==="generation"?s.generation=Number(t[f+1]):t[f]==="ufrag"&&(s.ufrag=t[f+1]);let{foundation:n,component:i,transport:o,priority:a,host:c,port:d,type:u}=s;return new nB(n,i,o,a,c,d,u,s.related_address,s.related_port,s.tcptype,s.generation,s.ufrag)}canPairWith(e){let t=(0,P_.isIPv4)(this.host),s=(0,P_.isIPv4)(e.host);return this.component===e.component&&this.transport.toLowerCase()===e.transport.toLowerCase()&&t===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}};kz=class{cache=new Map;mdnsInstance=(0,oB.default)();constructor(){this.mdnsInstance.setMaxListeners(50)}lookup(r){return new Promise((e,t)=>{let s=()=>{this.mdnsInstance.removeListener("response",i),clearTimeout(n)},n=setTimeout(()=>{s(),t(new Error("No mDNS response"))},1e4),i=o=>{let a=o.answers?.[0];a?.type==="A"&&a.name===r&&(s(),e(a.data))};this.mdnsInstance.on("response",i),this.mdnsInstance.query(r,"A")})}close(){this.mdnsInstance.destroy()}},Pz=ut("werift-ice : packages/ice/src/ice.ts : log"),O_=class{constructor(r,e,t){this.protocol=r,this.remoteCandidate=e,this.iceControlling=t}id=(0,aB.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(r){this._state=r}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 tx(this.localCandidate,this.remoteCandidate,this.iceControlling)}get foundation(){return this.localCandidate.foundation}},L_=1,xp=2,cB=5,D_=6,dB=(r=>(r[r.FROZEN=0]="FROZEN",r[r.WAITING=1]="WAITING",r[r.IN_PROGRESS=2]="IN_PROGRESS",r[r.SUCCEEDED=3]="SUCCEEDED",r[r.FAILED=4]="FAILED",r))(dB||{}),uB={useIpv4:!0,useIpv6:!0};Bz=ut("werift-ice : packages/ice/src/utils.ts");Oz=r=>{if(!r)return;let[e,t]=r.split(":");return[e,Number.parseInt(t)]},Ut=ut("werift-ice : packages/ice/src/ice.ts : log"),yB=class{constructor(r,e){this._iceControlling=r,this.options={...uB,...e};let{stunServer:t,turnServer:s}=this.options;this.stunServer=U_(t)??["stun.l.google.com",19302],this.turnServer=U_(s),this.restart(),Ut("new Connection",this.options)}localUsername=rp(4);localPassword=rp(22);remoteIsLite=!1;remotePassword="";remoteUsername="";checkList=[];localCandidates=[];stunServer;turnServer;options;remoteCandidatesEnd=!1;localCandidatesEnd=!1;generation=-1;userHistory={};tieBreaker=BigInt(new vy((0,iB.randomBytes)(64)).toString());state="new";lookup;_remoteCandidates=[];nominated;nominating=!1;checkListDone=!1;checkListState=new ck;earlyChecks=[];earlyChecksDone=!1;localCandidatesStart=!1;protocols=[];queryConsentHandle;onData=new Te;stateChanged=new Te;onIceCandidate=new Te;get iceControlling(){return this._iceControlling}set iceControlling(r){if(!(this.generation>0||this.nominated)){this._iceControlling=r;for(let e of this.checkList)e.iceControlling=r}}async restart(){this.generation++,this.localUsername=rp(4),this.localPassword=rp(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 ck,this.earlyChecks=[],this.earlyChecksDone=!1,this.localCandidatesStart=!1;for(let r of this.protocols)r.localCandidate&&(r.localCandidate.generation=this.generation,r.localCandidate.ufrag=this.localUsername);this.queryConsentHandle?.resolve?.(),this.queryConsentHandle=void 0}resetNominatedPair(){Ut("resetNominatedPair"),this.nominated=void 0,this.nominating=!1}setRemoteParams({iceLite:r,usernameFragment:e,password:t}){Ut("setRemoteParams",{iceLite:r,usernameFragment:e,password:t}),this.remoteIsLite=r,this.remoteUsername=e,this.remotePassword=t}async gatherCandidates(){if(!this.localCandidatesStart){this.localCandidatesStart=!0;let r=gB(this.options.useIpv4,this.options.useIpv6,{useLinkLocalAddress:this.options.useLinkLocalAddress}),{interfaceAddresses:e}=this.options;if(e){let s=r.filter(n=>Object.values(e).includes(n));s.length&&(r=s)}this.options.additionalHostAddresses&&(r=Array.from(new Set([...this.options.additionalHostAddresses,...r])));let t=this.getCandidatePromises(r,5);await Promise.allSettled(t),this.localCandidatesEnd=!0}this.setState("completed")}appendLocalCandidate(r){this.localCandidates.push(r),this.onIceCandidate.execute(r)}ensureProtocol(r){r.onRequestReceived.subscribe((e,t,s)=>{if(e.messageMethod!==1){this.respondError(e,t,r,[400,"Bad Request"]);return}let n=e.getAttributeValue("USERNAME"),{remoteUsername:i}=pk(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,t,r,[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,t,r,[487,"Role Conflict"]);else{this.switchRole(!0);return}if(this.options.filterStunResponse&&!this.options.filterStunResponse(e,t,r))return;let c=new Qs(1,256,e.transactionId);c.setAttribute("XOR-MAPPED-ADDRESS",t).addMessageIntegrity(Buffer.from(o,"utf8")).addFingerprint(),r.sendStun(c,t).catch(d=>{Ut("sendStun error",d)}),this.checkList.length===0&&!this.earlyChecksDone?this.earlyChecks.push([e,t,r]):this.checkIncoming(e,t,r)}),r.onDataReceived.subscribe(e=>{try{let t=this.nominated;t&&t.protocol===r&&(t.packetsReceived++,t.bytesReceived+=e.length),this.onData.execute(e)}catch(t){Ut("dataReceived",t)}})}getCandidatePromises(r,e=5){let t=[];r=r.filter(c=>!this.protocols.find(d=>d.localIp===c));let s=r.map(async c=>{let d=new Zy;this.ensureProtocol(d);try{await d.connectionMade((0,B_.isIPv4)(c),this.options.portRange,this.options.interfaceAddresses),d.localIp=c,this.protocols.push(d),Ut("protocol",d.localIp);let u=[c,d.getExtraInfo()[1]];return d.localCandidate=new Sa(ex("host","udp",u[0]),1,"udp",Sp("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){Ut("error protocol STUN",u)}});t.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,y)=>{let v=setTimeout(y,e*1e3);if(u.localCandidate?.host&&(0,B_.isIPv4)(u.localCandidate?.host)){let S=await lB(u,n).catch(C=>{Ut("error",C)});S&&this.appendLocalCandidate(S),clearTimeout(v),h(S)}else clearTimeout(v),h()}).catch(h=>{Ut("query STUN server",h)}):void 0});t.push(...c)}let{turnUsername:o,turnPassword:a}=this.options;if(i&&o&&a){let c=(async()=>{let d=await k_({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 k_({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,f=d.turn.mappedAddress;return Ut("turn candidateAddress",u),d.localCandidate=new Sa(ex("relay","udp",u[0]),1,"udp",Sp("relay"),u[0],u[1],"relay",f[0],f[1],void 0,this.generation,this.localUsername),this.appendLocalCandidate(d.localCandidate),d.localCandidate})().catch(d=>{Ut("query TURN server",d)});this.options.forceTurn&&(t=[]),t.push(c)}return t}async connect(){if(Ut("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(),Ut("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 N_.setTimeout(20);let r=xp;for(;this.checkList.length>0&&r===xp;)r=await this.checkListState.get(),Ut("checkListState",r);for(let e of this.checkList)e.handle?.resolve?.();if(r!==L_)throw new Error("ICE negotiation failed");this.queryConsent(),this.setState("connected")}unfreezeInitial(){let[r]=this.checkList;if(!r)return;r.state===0&&r.updateState(1);let e=new Set(r.localCandidate.foundation);for(let t of this.checkList)t.component===r.component&&!e.has(t.localCandidate.foundation)&&t.state===0&&(t.updateState(1),e.add(t.localCandidate.foundation))}schedulingChecks(){{let r=this.checkList.filter(e=>!(this.options.forceTurn&&e.protocol.type===Zy.type)).find(e=>e.state===1);if(r)return r.handle=this.checkStart(r),!0}{let r=this.checkList.find(e=>e.state===0);if(r)return r.handle=this.checkStart(r),!0}return this.remoteCandidatesEnd?!1:!this.checkListDone}queryConsent=()=>{this.queryConsentHandle&&this.queryConsentHandle.resolve(),this.queryConsentHandle=A_(async(r,e,t)=>{let s=0,n=!1,i=new AbortController;t.once(()=>{n=!0,s+=D_,i.abort(),this.queryConsentHandle=void 0});let{localUsername:o,remoteUsername:a,iceControlling:c}=this;try{for(;this.state!=="closed"&&!n;){await N_.setTimeout(cB*(.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){Ut("no stun response"),s++,this.setState("disconnected");break}}if(s>=D_){Ut("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(r=>{r(xp)})),this.nominated=void 0;for(let r of this.protocols)r.close&&await r.close();this.protocols=[],this.localCandidates=[],this.lookup?.close?.(),this.lookup=void 0}setState(r){this.state=r,this.stateChanged.execute(r)}async addRemoteCandidate(r){if(!r){this.remoteCandidatesEnd=!0;return}if(r.host.includes(".local"))try{this.lookup||(this.lookup=new kz);let e=await this.lookup.lookup(r.host);r.host=e}catch{return}try{M_(r)}catch{return}Ut("addRemoteCandidate",r),this._remoteCandidates.push(r),this.pairRemoteCandidate(r),this.sortCheckList()}send=async r=>{let e=this.nominated;if(e)await e.protocol.sendData(r,e.remoteAddr),e.packetsSent++,e.bytesSent+=r.length;else return};getDefaultCandidate(){let r=this.localCandidates.sort((t,s)=>t.priority-s.priority),[e]=r;return e}set remoteCandidates(r){if(this.remoteCandidatesEnd)throw new Error("Cannot set remote candidates after end-of-candidates.");this._remoteCandidates=[];for(let e of r){try{M_(e)}catch{continue}this._remoteCandidates.push(e)}this.remoteCandidatesEnd=!0}get remoteCandidates(){return this._remoteCandidates}get candidatePairs(){return this.checkList}sortCheckList(){fB(this.checkList,this.iceControlling)}findPair(r,e){return this.checkList.find(s=>(0,Ly.default)(s.protocol,r)&&(0,Ly.default)(s.remoteCandidate,e))}switchRole(r){Ut("switch role",r),this.iceControlling=r,this.sortCheckList()}checkComplete(r){if(r.handle=void 0,r.state===3){if(r.nominated&&(r.remoteCandidate.generation==null||r.remoteCandidate.generation===this.generation)&&this.nominated==null){Ut("nominated",r.toJSON()),this.nominated=r,this.nominating=!1;for(let e of this.checkList)e.component===r.component&&[1,0].includes(e.state)&&e.updateState(4)}if(this.nominated){this.checkListDone||(Ut("ICE completed"),this.checkListState.put(new Promise(e=>e(L_))),this.checkListDone=!0);return}Ut("not completed",r.toJSON());for(let e of this.checkList)e.localCandidate.foundation===r.localCandidate.foundation&&e.state===0&&e.updateState(1)}{let e=[3,4];if(this.checkList.find(({state:t})=>!e.includes(t)))return}!this.iceControlling&&this.checkList.find(({state:t})=>t===3)||this.checkListDone||(Ut("ICE failed"),this.checkListState.put(new Promise(e=>{e(xp)})))}checkStart=r=>A_(async e=>{Ut("check start",r.toJSON()),r.updateState(2);let t={},{remotePassword:s,remoteUsername:n,generation:i}=this,o=r.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,f]=await r.protocol.request(c,r.remoteAddr,Buffer.from(s,"utf8"),4),y=(performance.now()-d)/1e3;r.rtt=y,r.totalRoundTripTime+=y,r.roundTripTimeMeasurements++,Ut("response received",c.toJSON(),u.toJSON(),f,{localUsername:o,remoteUsername:n,remotePassword:s,generation:i,rtt:y}),t.response=u,t.addr=f}catch(u){let f=u;if(Ut("failure case",c.toJSON(),f.response?JSON.stringify(f.response.toJSON(),null,2):u,{localUsername:o,remoteUsername:n,remotePassword:s,generation:i},r.remoteAddr),f.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(r).awaitable,e();return}if(f.response?.getAttributeValue("ERROR-CODE")[0]===401){Ut("retry 401",r.toJSON()),await this.checkStart(r).awaitable,e();return}else{Ut("checkStart CandidatePairState.FAILED",r.toJSON()),r.updateState(4),this.checkComplete(r),e();return}}if(!(0,Ly.default)(t.addr,r.remoteAddr)){r.updateState(4),this.checkComplete(r),e();return}if(a||r.remoteNominated)r.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 r.protocol.request(u,r.remoteAddr,Buffer.from(this.remotePassword,"utf8"))}catch{r.updateState(4),this.checkComplete(r);return}r.nominated=!0}r.updateState(3),this.checkComplete(r),e()});addPair(r){this.checkList.push(r),this.sortCheckList()}checkIncoming(r,e,t){let s=r.getAttributeValue("USERNAME"),{remoteUsername:n}=pk(s),i,[o,a]=e;for(let d of this.remoteCandidates)if(d.host===o&&d.port===a){i=d;break}i||(i=new Sa(rp(10),1,"udp",r.getAttributeValue("PRIORITY"),o,a,"prflx",void 0,void 0,void 0,void 0,void 0),this._remoteCandidates.push(i));let c=this.findPair(t,i);c||(c=new O_(t,i,this.iceControlling),c.updateState(1),this.addPair(c)),c.localCandidate.ufrag=n,Ut("Triggered Checks",r.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)),r.attributesKeys.includes("USE-CANDIDATE")&&!this.iceControlling&&(c.remoteNominated=!0,c.state===3&&(c.nominated=!0,this.checkComplete(c)))}tryPair(r,e){if(r.localCandidate?.canPairWith(e)&&!this.findPair(r,e)){let t=new O_(r,e,this.iceControlling);if(this.options.filterCandidatePair&&!this.options.filterCandidatePair(t))return;t.updateState(1),this.addPair(t)}}pairLocalProtocol(r){for(let e of this.remoteCandidates)this.tryPair(r,e)}pairRemoteCandidate=r=>{for(let e of this.protocols)this.tryPair(e,r)};buildRequest({nominate:r,remoteUsername:e,localUsername:t,iceControlling:s}){let n=Lz({remoteUsername:e,localUsername:t}),i=new Qs(1,0);return i.setAttribute("USERNAME",n).setAttribute("PRIORITY",Sp("prflx")),s?(i.setAttribute("ICE-CONTROLLING",this.tieBreaker),r&&i.setAttribute("USE-CANDIDATE",null)):i.setAttribute("ICE-CONTROLLED",this.tieBreaker),i}respondError(r,e,t,s){let n=new Qs(r.messageMethod,272,r.transactionId);n.setAttribute("ERROR-CODE",s).addMessageIntegrity(Buffer.from(this.localPassword,"utf8")).addFingerprint(),t.sendStun(n,e).catch(i=>{Ut("sendStun error",i)})}},Lz=({remoteUsername:r,localUsername:e})=>`${r}:${e}`,pk=r=>{let[e,t]=r.split(":");return{remoteUsername:e,localUsername:t}};U2=class extends xB.EventEmitter{addEventListener=(r,e)=>{this.addListener(r,e)};removeEventListener=(r,e)=>{this.removeListener(r,e)}},Dz=ut("werift:packages/webrtc/src/dataChannel.ts");j2=class extends U2{constructor(r,e,t=!0){if(super(),this.sctp=r,this.parameters=e,this.sendOpen=t,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 t&&(this.sendOpen=!1,this.sctp.dataChannelOpen(this))}stateChange=new Te;stateChanged=new Te;onMessage=new Te;error=new Te;bufferedAmountLow=new Te;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(r){if(r<0||r>4294967295)throw new Error("bufferedAmountLowThreshold must be in range 0 - 4294967295");this._bufferedAmountLowThreshold=r}setId(r){this.id=r}setReadyState(r){if(r!==this.readyState){switch(this.readyState=r,this.stateChange.execute(r),this.stateChanged.execute(r),r){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}Dz("change state",r)}}addBufferedAmount(r){let e=this.bufferedAmount>this.bufferedAmountLowThreshold&&this.bufferedAmount+r<=this.bufferedAmountLowThreshold;this.bufferedAmount+=r,e&&(this.bufferedAmountLow.execute(),this.emit("bufferedamountlow"))}send(r){let e=this.sctp.datachannelSend(this,r);this.messagesSent++,this.bytesSent+=e}close(){this.sctp.dataChannelClose(this)}},H2=class{label="";maxPacketLifeTime;maxRetransmits;ordered=!0;protocol="";negotiated=!1;id;constructor(r={}){Object.assign(this,r)}},Mz=()=>({type:"ccm",parameter:"fir"}),Jp=()=>({type:"nack"}),ff=()=>({type:"nack",parameter:"pli"}),Qp=()=>({type:"goog-remb"}),vB=()=>({type:"transport-cc"}),_a=class{payloadType;mimeType;clockRate;channels;rtcpFeedback=[];parameters;direction="all";constructor(r){Object.assign(this,r)}get name(){return this.mimeType.split("/")[1]}get contentType(){return this.mimeType.split("/")[0]}get str(){let r=`${this.name}/${this.clockRate}`;return this.channels===2&&(r+="/2"),r}},mi=class{id;uri;constructor(r){Object.assign(this,r)}},Uz=class{cname;mux=!1;ssrc;constructor(r={}){Object.assign(this,r)}},wB=class{type;parameter;constructor(r={}){Object.assign(this,r)}},SB=class{ssrc;constructor(r={}){Object.assign(this,r)}},_B=class{ssrc;payloadType;rtx;constructor(r){Object.assign(this,r)}},F2=class{rid;direction;constructor(r){Object.assign(this,r)}},EB=(r={})=>new _a({mimeType:"video/h264",clockRate:9e4,rtcpFeedback:[Jp(),ff(),Qp()],parameters:"profile-level-id=42e01f;packetization-mode=1;level-asymmetry-allowed=1",...r}),q2=(r={})=>new _a({mimeType:"video/VP8",clockRate:9e4,rtcpFeedback:[Jp(),ff(),Qp()],...r}),CB=(r={})=>new _a({mimeType:"video/VP9",clockRate:9e4,rtcpFeedback:[Jp(),ff(),Qp()],...r}),TB=(r={})=>new _a({mimeType:"video/AV1X",clockRate:9e4,rtcpFeedback:[Jp(),ff(),Qp()],...r}),z2=(r={})=>new _a({mimeType:"audio/OPUS",clockRate:48e3,channels:2,...r}),$2=(r={})=>new _a({mimeType:"audio/PCMU",clockRate:8e3,channels:1,payloadType:0,...r}),V2=[TB(),CB(),q2(),EB(),z2(),$2()].map(r=>r.mimeType),jz=V2.filter(r=>r.toLowerCase().startsWith("video/")),Hz=V2.filter(r=>r.toLowerCase().startsWith("audio/"));gk=2,yk=3,Xz=0,Cy=50,xk=51,bk=53,Yz=56,Jz=57,Qz="0.0.0.0",vk=9,F_={auto:"actpass",client:"active",server:"passive"},wk=Object.keys(F_).reduce((r,e)=>{let t=F_[e];return r[t]=e,r},{}),Zz=["apt","max-fr","max-fs","maxplaybackrate","minptime","stereo","useinbandfec"],PB=["cname","msid","mslabel","label"],Sk={SRTP_AES128_CM_HMAC_SHA1_80:df,SRTP_AEAD_AES_128_GCM:ad},My=["sendonly","sendrecv"],e$=["sendrecv","recvonly"],BB=class extends Map{constructor(r){if(super(),r)for(let e of r)this.set(e.id,e)}};NB=class{constructor(r,e,t,s,n){this.kind=r,this.receiver=t,this.sender=s,this._direction=n,e&&this.setDtlsTransport(e)}id=(0,kB.randomUUID)().toString();onTrack=new Te;mid;mLineIndex;usedForSender=!1;_currentDirection;offerDirection;_codecs=[];set codecs(r){this._codecs=r}get codecs(){return this._codecs}headerExtensions=[];options={};stopping=!1;stopped=!1;get dtlsTransport(){return this.receiver.dtlsTransport}get direction(){return this._direction}setDirection(r){this._direction=r,My.includes(this._currentDirection??"")&&(this.usedForSender=!0)}get currentDirection(){return this._currentDirection}setCurrentDirection(r){this._currentDirection=r}setDtlsTransport(r){this.receiver.setDtlsTransport(r),this.sender.setDtlsTransport(r)}get msid(){return`${this.sender.streamId} ${this.sender.trackId}`}addTrack(r){this.receiver.addTrack(r)&&this.onTrack.execute(r,this)}stop(){this.stopping||(this.stopping=!0)}getPayloadType(r){return this.codecs.find(e=>e.mimeType.toLowerCase().includes(r.toLowerCase()))?.payloadType}getCodecStats(){let r=Ea(),e=[];if(!this.dtlsTransport)return e;let t=qt("transport",this.dtlsTransport.id);for(let s of this.codecs){let n={type:"codec",id:qt("codec",s.payloadType,t),timestamp:r,payloadType:s.payloadType,transportId:t,mimeType:s.mimeType,clockRate:s.clockRate,channels:s.channels,sdpFmtpLine:s.parameters};e.push(n)}return e}},OB="inactive",K2="sendonly",W2="recvonly",G2="sendrecv",Uy=[OB,K2,W2,G2],jp=class extends U2{uuid=(0,X2.randomUUID)().toString();streamId;remote=!1;label;kind;id;ssrc;rid;header;codec;enabled=!0;onReceiveRtp=new Te;onReceiveRtcp=new Te;onSourceChanged=new Te;stopped=!1;muted=!0;constructor(r){super(),Object.assign(this,r),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=r=>{if(this.remote)throw new Error("this is remoteTrack");if(this.stopped)return;let e=Buffer.isBuffer(r)?mo.deSerialize(r):r;e.header.payloadType=this.codec?.payloadType??e.header.payloadType,this.onReceiveRtp.execute(e)}},LB=class{id;tracks=[];constructor(r){Array.isArray(r)?this.tracks=r:Object.assign(this,r),this.id??=(0,X2.randomUUID)().toString()}addTrack(r){r.streamId=this.id,this.tracks.push(r)}getTracks(){return this.tracks}getAudioTracks(){return this.tracks.filter(r=>r.kind==="audio")}getVideoTracks(){return this.tracks.filter(r=>r.kind==="video")}},t$=ut("werift:packages/webrtc/src/utils.ts");r$={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"};Q2=(r,e)=>Uy[Uy.indexOf(r)&Uy.indexOf(e)];Z2=Date.now,n$=BigInt(Date.now())*1000n-process.hrtime.bigint()/1000n,UB=()=>n$+process.hrtime.bigint()/1000n,Hp=()=>Date.now()/1e3,jB=()=>{let e=(H_.performance.timeOrigin+H_.performance.now()-Date.UTC(1900,0,1))/1e3,[t,s]=e.toString().split(".").map(Number);return er([4,4],[t,s]).readBigUInt64BE()},eE=r=>{let e=er([8],[r]),[,t,s]=is(e,[2,2,2,2]);return er([2,2],[t,s]).readUInt32BE()};i$=Ip.createSelfSignedCertificateWithKey,o$=class{static async rtpSource({port:r,kind:e,cb:t}){r??=await m2();let s=new jp({kind:e}),n=(0,RB.createSocket)("udp4");n.bind(r);let i=a=>{t&&(a=t(a)),s.writeRtp(a)};return n.addListener("message",i),[s,r,()=>{n.removeListener("message",i);try{n.close()}catch{}}]}},FB=(r,e)=>{if(!r||typeof r!="object")return e!==null&&typeof e=="object"?e:r;if(!e||typeof e!="object")return e??r;for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)){let s=e[t];s!=null&&(r[t]=s)}return r},a$=ut("werift:packages/webrtc/src/media/receiver/nack.ts"),_k=150,c$=class{constructor(r){this.receiver=r}newEstSeqNum=0;_lost={};nackLoop;onPacketLost=new Te;mediaSourceSsrc;retryCount=10;closed=!1;get lostSeqNumbers(){return Object.keys(this._lost).map(Number).sort()}getLost(r){return this._lost[r]}setLost(r,e){this._lost[r]=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(t){a$("failed to send nack",t)}},5))}removeLost(r){delete this._lost[r]}addPacket(r){let{sequenceNumber:e,ssrc:t}=r.header;if(this.mediaSourceSsrc=t,this.newEstSeqNum===0){this.newEstSeqNum=e;return}if(this.getLost(e)){this.removeLost(e);return}if(e===Ur(this.newEstSeqNum,1))this.newEstSeqNum=e;else if(e>Ur(this.newEstSeqNum,1)){for(let s=Ur(this.newEstSeqNum,1);s<e;s=Ur(s,1))this.setLost(s,1);this.newEstSeqNum=e,this.pruneLost()}}pruneLost(){this.lostSeqNumbers.length>_k&&(this._lost=Object.entries(this._lost).slice(-_k).reduce((r,[e,t])=>(r[e]=t,r),{}))}close(){this.closed=!0,clearInterval(this.nackLoop),this._lost={}}updateRetryCount(){this.lostSeqNumbers.forEach(r=>{if(this._lost[r]++>this.retryCount)return this.removeLost(r),r})}sendNack=()=>new Promise((r,e)=>{if(this.lostSeqNumbers.length>0&&this.mediaSourceSsrc){let t=new Op({senderSsrc:this.receiver.rtcpSsrc,mediaSourceSsrc:this.mediaSourceSsrc,lost:this.lostSeqNumbers}),s=new rd({feedback:t});this.receiver.dtlsTransport.sendRtcp([s]).then(r).catch(e),this.updateRetryCount(),this.onPacketLost.execute(t)}})},d$=ut("werift:packages/webrtc/media/receiver/receiverTwcc"),u$=class{constructor(r,e,t){this.dtlsTransport=r,this.rtcpSsrc=e,this.mediaSourceSsrc=t,this.runTWCC()}extensionInfo={};twccRunning=!1;fbPktCount=0;lastTimestamp;handleTWCC(r){this.extensionInfo[r]={tsn:r,timestamp:UB()},Object.keys(this.extensionInfo).length>10&&this.sendTWCC()}async runTWCC(){for(;this.twccRunning;)this.sendTWCC(),await(0,qB.setTimeout)(100)}sendTWCC(){if(Object.keys(this.extensionInfo).length===0)return;let r=Object.values(this.extensionInfo).sort((u,f)=>u.tsn-f.tsn),e=r[0].tsn,t=r.slice(-1)[0].tsn,s=[],n=r[0].tsn,i=Ur(t-e,1),o,a,c=[];for(let u=e;u<=t;u++){let f=this.extensionInfo[u]?.timestamp;if(f){this.lastTimestamp||(this.lastTimestamp=f),o||(o=this.lastTimestamp);let h=f-this.lastTimestamp;this.lastTimestamp=f;let y=new wp({delta:Number(h)});y.parseDelta(),c.push(y),a!=null&&a.status!==y.type&&(s.push(new Qu({packetStatus:a.status,runLength:u-a.minTSN})),a={minTSN:u,status:y.type}),u===t&&(a!=null?s.push(new Qu({packetStatus:a.status,runLength:u-a.minTSN+1})):s.push(new Qu({packetStatus:y.type,runLength:1}))),a==null&&(a={minTSN:u,status:y.type})}}if(!o)return;let d=new rd({feedback:new Lp({senderSsrc:this.rtcpSsrc,mediaSourceSsrc:this.mediaSourceSsrc,baseSequenceNumber:n,packetStatusCount:i,referenceTime:Kk(Math.floor(Number(o/1000n/64n))),fbPktCount:this.fbPktCount,recvDeltas:c,packetChunks:s})});this.dtlsTransport.sendRtcp([d]).catch(u=>{d$(u)}),this.extensionInfo={},this.fbPktCount=Vk(this.fbPktCount,1)}},f$=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(r){this.clockRate=r}add(r,e=Date.now()/1e3){let t=this.max_seq==null||dx(r.header.sequenceNumber,this.max_seq);if(this.packets_received++,this.base_seq==null&&(this.base_seq=r.header.sequenceNumber),t){let s=Yu(e*this.clockRate);if(this.max_seq!=null&&r.header.sequenceNumber<this.max_seq&&(this.cycles+=65536),this.max_seq=r.header.sequenceNumber,r.header.timestamp!==this.last_timestamp&&this.packets_received>1){let n=Math.abs(s-(this.last_arrival??0)-(r.header.timestamp-(this.last_timestamp??0)));this.jitter_q4+=n-(this.jitter_q4+8>>4)}this.last_arrival=s,this.last_timestamp=r.header.timestamp}}get fraction_lost(){let r=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 t=r-e;return r==0||t<=0?0:Math.floor((t<<8)/r)}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 r=this.packets_expected-this.packets_received;return r<0?0:r}},vn=ut("werift:packages/webrtc/src/transport/dtls.ts"),q_=class WB{constructor(e,t,s,n=[]){this.config=e,this.iceTransport=t,this.localCertificate=s,this.srtpProfiles=n,this.localCertificate??=WB.localCertificate}id=(0,VB.randomUUID)().toString();state="new";role="auto";srtpStarted=!1;transportSequenceNumber=0;bytesSent=0;bytesReceived=0;packetsSent=0;packetsReceived=0;dataReceiver=()=>{};dtls;srtp;srtcp;onStateChange=new Te;onRtcp=new Te;onRtp=new Te;static localCertificate;static localCertificatePromise;remoteParameters;get localParameters(){return new nx(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:t,signatureHash:s}=await Ip.createSelfSignedCertificateWithKey({signature:pi.ecdsa_3,hash:Ap.sha256_4},ho.secp256r1_23);return this.localCertificate=new tE(t,e,s),this.localCertificate})(),this.localCertificatePromise)}setRemoteParams(e){let t=h$([...this.remoteParameters?.fingerprints??[],...e.fingerprints]),s=e.role==="auto"&&this.remoteParameters?.role?this.remoteParameters.role:e.role;this.remoteParameters=new nx(t,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,t)=>{this.role==="server"?this.dtls=new DP({cert:this.localCertificate?.certPem,key:this.localCertificate?.privateKey,signatureHash:this.localCertificate?.signatureHash,transport:Ek(this.iceTransport.connection),srtpProfiles:this.srtpProfiles,extendedMasterSecret:!0,certificateRequest:!0}):this.dtls=new T_({cert:this.localCertificate?.certPem,key:this.localCertificate?.privateKey,signatureHash:this.localCertificate?.signatureHash,transport:Ek(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"),vn("dtls failed",s),t(s)}),this.dtls instanceof T_&&(await(0,KB.setTimeout)(100),this.dtls.connect().catch(s=>{this.setState("failed"),vn("dtls connect failed",s),t(s)}))});try{this.verifyRemoteCertificateFingerprint()}catch(e){throw this.setState("failed"),this.dtls?.close(),e}this.srtpProfiles.length>0&&this.startSrtp(),this.setState("connected"),vn("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 t=this.remoteParameters.fingerprints.flatMap(({algorithm:a,value:c})=>{let d=J2(a);if(!d)return[];let u=rx(c);if(!u)throw new Error("remote fingerprint value is empty");return[{normalizedAlgorithm:d,normalizedValue:u}]});if(t.length===0)throw new Error("no supported remote fingerprint algorithms");let s=m$(t),n=t.filter(({normalizedAlgorithm:a})=>a===s),i=n.reduce((a,{normalizedAlgorithm:c})=>(a.has(c)||a.set(c,rx(Y2(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");vn("selected SRTP Profile",e);let{localKey:t,localSalt:s,remoteKey:n,remoteSalt:i}=this.dtls.extractSessionKeys(k9(e),P9(e)),o={keys:{localMasterKey:t,localMasterSalt:s,remoteMasterKey:n,remoteMasterSalt:i},profile:e};this.srtp=new BP(o),this.srtcp=new PP(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())&&K9(e))if(this.bytesReceived+=e.length,this.packetsReceived++,oP(e)){let t;try{t=this.srtcp.decrypt(e)}catch(n){if(n instanceof nd){vn("dropping invalid SRTCP packet",n);return}throw n}let s;try{s=iP.deSerialize(t)}catch(n){vn("dropping malformed SRTCP packet",n);return}for(let n of s)try{this.onRtcp.execute(n)}catch(i){vn("RTCP error",i)}}else{let t;try{t=this.srtp.decrypt(e)}catch(n){if(n instanceof nd){vn("dropping invalid SRTP packet",n);return}throw n}let s;try{s=mo.deSerialize(t)}catch(n){vn("dropping malformed SRTP packet",n);return}try{this.onRtp.execute(s)}catch(n){vn("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,t){try{let s=this.srtp.encrypt(e,t);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 vn("failed to send",s),0}}async sendRtcp(e){let t=Buffer.concat(e.map(n=>n.serialize())),s=this.srtcp.encrypt(t);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=Ea(),t=[],n={type:"transport",id:qt("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?qt("candidate-pair",this.iceTransport.connection.nominated.localCandidate.foundation,this.iceTransport.connection.nominated.remoteCandidate.foundation):void 0,localCertificateId:this.localCertificate?qt("certificate","local"):void 0,remoteCertificateId:this.remoteParameters?qt("certificate","remote"):void 0,dtlsRole:this.role==="auto"?void 0:this.role};if(t.push(n),this.localCertificate){let o=this.localCertificate.getFingerprints();if(o.length>0){let a={type:"certificate",id:qt("certificate","local"),timestamp:e,fingerprint:o[0].value,fingerprintAlgorithm:o[0].algorithm,base64Certificate:Buffer.from(this.localCertificate.certPem).toString("base64")};t.push(a)}}if(this.remoteParameters&&this.remoteParameters.fingerprints.length>0){let o={type:"certificate",id:qt("certificate","remote"),timestamp:e,fingerprint:this.remoteParameters.fingerprints[0].value,fingerprintAlgorithm:this.remoteParameters.fingerprints[0].algorithm,base64Certificate:""};t.push(o)}let i=await this.iceTransport.getStats();return t.push(...i),t}},l$=["new","connecting","connected","closed","failed"],tE=class{constructor(r,e,t){this.certPem=e,this.signatureHash=t;let s=Fp.Certificate.fromPEM(Buffer.from(e));this.publicKey=s.publicKey.toPEM(),this.privateKey=Fp.PrivateKey.fromPEM(Buffer.from(r)).toPEM()}publicKey;privateKey;getFingerprints(){return[new sx("sha-256",Y2(Fp.Certificate.fromPEM(Buffer.from(this.certPem)).raw,"sha256"))]}},sx=class{constructor(r,e){this.algorithm=r,this.value=e}},nx=class{constructor(r=[],e){this.fingerprints=r,this.role=e}},h$=r=>{let e=new Set;return r.filter(({algorithm:t,value:s})=>{let n=`${J2(t)??t.trim().toLowerCase()}:${rx(s)}`;return e.has(n)?!1:(e.add(n),!0)})},p$=["sha512","sha384","sha256","sha224","sha1"],m$=r=>p$.find(e=>r.some(({normalizedAlgorithm:t})=>t===e))??r[0].normalizedAlgorithm,g$=class{constructor(r){this.ice=r,r.onData.subscribe(e=>{DB(e)&&this.onData&&this.onData(e)})}closed=!1;onData=()=>{};get address(){return{}}type="ice";send=r=>this.ice.send(r);async close(){this.closed=!0,this.ice.close()}},Ek=r=>new g$(r),Ck=ut("werift:packages/webrtc/src/transport/ice.ts"),XB=class{constructor(r){this.iceGather=r,this.connection=this.iceGather.connection,this.connection.stateChanged.subscribe(e=>{this.setState(e)}),this.iceGather.onIceCandidate=e=>{this.onIceCandidate.execute(e)}}id=(0,GB.randomUUID)().toString();connection;state="new";waitStart;renominating=!1;onStateChange=new Te;onIceCandidate=new Te;onNegotiationNeeded=new Te;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(r){r!==this.state&&(this.state=r,this.onStateChange.execute(r))}gather(){return this.iceGather.gather()}addRemoteCandidate=r=>{if(!this.connection.remoteCandidatesEnd)return r?this.connection.addRemoteCandidate(JB(r)):this.connection.addRemoteCandidate(void 0)};setRemoteParams(r,e=!1){e&&(this.renominating=!0),this.connection.remoteUsername&&this.connection.remotePassword&&(this.connection.remoteUsername!==r.usernameFragment||this.connection.remotePassword!==r.password)&&(this.renominating?(Ck("renomination",r),this.connection.resetNominatedPair(),this.renominating=!1):(Ck("restart",r),this.restart())),this.connection.setRemoteParams(r)}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 Te,this.setState("checking");try{await this.connection.connect()}catch(r){throw this.setState("failed"),r}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 r=Ea(),e=[];for(let s of this.localCandidates){let n={type:"local-candidate",id:qt("local-candidate",s.foundation),timestamp:r,transportId:qt("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=of(s),i={type:"remote-candidate",id:qt("remote-candidate",n.foundation),timestamp:r,transportId:qt("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 t=this.connection?.candidatePairs?[...this.connection.candidatePairs.filter(s=>s.nominated),...this.connection.candidatePairs.filter(s=>!s.nominated)]:[];for(let s of t){let n={type:"candidate-pair",id:qt("candidate-pair",s.foundation),timestamp:r,transportId:qt("transport",this.id),localCandidateId:qt("local-candidate",s.localCandidate.foundation),remoteCandidateId:qt("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}},y$=["new","checking","connected","completed","disconnected","failed","closed"],x$=["new","gathering","complete"],YB=class{constructor(r={}){this.options=r,this.connection=new yB(!1,this.options),this.connection.onIceCandidate.subscribe(e=>{this.onIceCandidate(of(e))})}onIceCandidate=()=>{};gatheringState="new";connection;onGatheringStateChange=new Te;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(of)}get localParameters(){return new sE({usernameFragment:this.connection.localUsername,password:this.connection.localPassword})}setState(r){r!==this.gatheringState&&(this.gatheringState=r,this.onGatheringStateChange.execute(r))}};QB=class{candidate;sdpMid;sdpMLineIndex;usernameFragment;constructor(r){Object.assign(this,r)}static fromSdp(r){let e=Sa.fromSdp(r);return of(e).toJSON()}static isThis(r){if(typeof r?.candidate=="string")return!0}toJSON(){return{candidate:this.candidate,sdpMid:this.sdpMid,sdpMLineIndex:this.sdpMLineIndex,usernameFragment:this.usernameFragment}}},rE=class{constructor(r,e,t,s,n,i,o,a,c){this.component=r,this.foundation=e,this.ip=t,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 QB({candidate:oE(this),sdpMLineIndex:this.sdpMLineIndex,sdpMid:this.sdpMid,usernameFragment:this.ufrag})}static fromJSON(r){try{if(!r.candidate)throw new Error("candidate is required");let e=aE(r.candidate);return e.sdpMLineIndex=r.sdpMLineIndex??void 0,e.sdpMid=r.sdpMid??void 0,e}catch{}}},sE=class{iceLite=!1;usernameFragment;password;constructor(r={}){Object.assign(this,r)}},gi=class e7{constructor(e=0,t=Buffer.from("")){this.flags=e,this._body=t}get body(){return this._body}set body(e){this._body=e}static type=-1;get type(){return e7.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(e0(this.body.length))].map(()=>Buffer.from("\0"))])}},nE=class extends gi{constructor(r=0,e){super(r,e),this.flags=r,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=w7(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 r=Buffer.alloc(16);return r.writeUInt32BE(this.initiateTag,0),r.writeUInt32BE(this.advertisedRwnd,4),r.writeUInt16BE(this.outboundStreams,8),r.writeUInt16BE(this.inboundStreams,10),r.writeUInt32BE(this.initialTsn,12),Buffer.concat([r,v7(this.params)])}},Fy=class t7 extends nE{static type=1;get type(){return t7.type}},z_=class r7 extends nE{static type=2;get type(){return r7.type}},b$=class s7 extends nE{static type=130;get type(){return s7.type}},qy=class n7 extends gi{constructor(e=0,t){if(super(e,t),this.flags=e,t){this.cumulativeTsn=t.readUInt32BE(0);let s=4;for(;s<t.length;)this.streams.push([t.readUInt16BE(s),t.readUInt16BE(s+2)]),s+=4}else this.cumulativeTsn=0}static type=192;streams=[];cumulativeTsn;get type(){return n7.type}set body(e){}get body(){let e=Buffer.alloc(4);return e.writeUInt32BE(this.cumulativeTsn,0),Buffer.concat([e,...this.streams.map(([t,s])=>{let n=Buffer.alloc(4);return n.writeUInt16BE(t,0),n.writeUInt16BE(s,2),n})])}},zy=class i7 extends gi{constructor(e=0,t){super(e,t),this.flags=e,t&&(this.tsn=t.readUInt32BE(0),this.streamId=t.readUInt16BE(4),this.streamSeqNum=t.readUInt16BE(6),this.protocol=t.readUInt32BE(8),this.userData=t.slice(12))}static type=0;get type(){return i7.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,t=Buffer.alloc(16);t.writeUInt8(this.type,0),t.writeUInt8(this.flags,1),t.writeUInt16BE(e,2),t.writeUInt32BE(this.tsn,4),t.writeUInt16BE(this.streamId,8),t.writeUInt16BE(this.streamSeqNum,10),t.writeUInt32BE(this.protocol,12);let s=Buffer.concat([t,this.userData]);return e%4&&(s=Buffer.concat([s,...[...Array(e0(e))].map(()=>Buffer.from("\0"))])),s}},$_=class o7 extends gi{static type=10;get type(){return o7.type}},V_=class a7 extends gi{static type=11;get type(){return a7.type}},Zp=class extends gi{constructor(r=0,e=void 0){super(r,e),this.flags=r,e&&(this.params=w7(e))}params=[];get body(){return v7(this.params)}},K_=class c7 extends Zp{static type=6;get type(){return c7.type}},$y=class W_ extends Zp{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 W_.type}get descriptions(){return this.params.map(([e,t])=>({name:(Object.entries(W_.CODE).find(([,n])=>n===e)||[])[0],body:t}))}},G_=class d7 extends Zp{static type=4;get type(){return d7.type}},u7=class f7 extends Zp{static type=5;get type(){return f7.type}},X_=class l7 extends Zp{static type=130;get type(){return l7.type}},Y_=class h7 extends gi{constructor(e=0,t){if(super(e,t),this.flags=e,t){this.cumulativeTsn=t.readUInt32BE(0),this.advertisedRwnd=t.readUInt32BE(4);let s=t.readUInt16BE(8),n=t.readUInt16BE(10),i=12;[...Array(s)].forEach(()=>{this.gaps.push([t.readUInt16BE(i),t.readUInt16BE(i+2)]),i+=4}),[...Array(n)].forEach(()=>{this.duplicates.push(t.readUInt32BE(i)),i+=4})}}static type=3;get type(){return h7.type}gaps=[];duplicates=[];cumulativeTsn=0;advertisedRwnd=0;get bytes(){let e=16+4*(this.gaps.length+this.duplicates.length),t=Buffer.alloc(16);t.writeUInt8(this.type,0),t.writeUInt8(this.flags,1),t.writeUInt16BE(e,2),t.writeUInt32BE(this.cumulativeTsn,4),t.writeUInt32BE(this.advertisedRwnd,8),t.writeUInt16BE(this.gaps.length,12),t.writeUInt16BE(this.duplicates.length,14);let s=Buffer.concat([t,...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}},p7=class m7 extends gi{constructor(e=0,t){super(e,t),this.flags=e,t&&(this.cumulativeTsn=t.readUInt32BE(0))}static type=7;get type(){return m7.type}cumulativeTsn=0;get body(){let e=Buffer.alloc(4);return e.writeUInt32BE(this.cumulativeTsn,0),e}},g7=class y7 extends gi{static type=8;get type(){return y7.type}},x7=class b7 extends gi{static type=14;get type(){return b7.type}},v$=[zy,Fy,z_,Y_,G_,u7,K_,p7,g7,$y,$_,V_,x7,X_,qy],w$=v$.reduce((r,e)=>(r[e.type]=e,r),{});J_=class Q_{constructor(e,t,s,n){this.requestSequence=e,this.responseSequence=t,this.lastTsn=s,this.streams=n}static type=13;get type(){return Q_.type}get bytes(){let e=Buffer.from(fo.jspack.Pack("!LLL",[this.requestSequence,this.responseSequence,this.lastTsn]));return Buffer.concat([e,...this.streams.map(t=>Buffer.from(fo.jspack.Pack("!H",[t])))])}static parse(e){let[t,s,n]=fo.jspack.Unpack("!LLL",e),i=[];for(let o=12;o<e.length;o+=2)i.push(fo.jspack.Unpack("!H",e.slice(o))[0]);return new Q_(t,s,n,i)}},S7=class Z_{constructor(e,t){this.requestSequence=e,this.newStreams=t}static type=17;get type(){return Z_.type}get bytes(){return Buffer.from(fo.jspack.Pack("!LHH",[this.requestSequence,this.newStreams,0]))}static parse(e){let[t,s]=fo.jspack.Unpack("!LHH",e);return new Z_(t,s)}},Ty={ReconfigResultSuccessPerformed:1,BadSequenceNumber:5},Vy=class e2{constructor(e,t){this.responseSequence=e,this.result=t}static type=16;get type(){return e2.type}get bytes(){return Buffer.from(fo.jspack.Pack("!LL",[this.responseSequence,this.result]))}static parse(e){let[t,s]=fo.jspack.Unpack("!LL",e);return new e2(t,s)}},Tk={13:J_,16:Vy,17:S7},Lt=ut("werift/sctp/sctp"),T$=24,A$=60,Ak=65535,wn=1200,bp=1,_7=2,t2=4,Ik=10,I$=8,Rk=1/8,kk=1/4,Pk=3,R$=1,k$=60,ix=2**32,P$=200,B$=30,Bk=135,Nk=7,Ok=32776,Lk=49152,N$=["new","closed","connected","connecting"],O$=class r2{constructor(e,t=5e3){this.transport=e,this.port=t,this.localPort=this.port,this.transport.onData=s=>{this.handleData(s)}}flush=new Te;stateChanged=C$(N$);onReconfigStreams=new Te;onReceive=new Te;onSackReceived=async()=>{};associationState=1;started=!1;state="new";isServer=!0;isStopping=!1;isClosed=!1;hmacKey=(0,qp.randomBytes)(16);localPartialReliability=!0;localPort;localVerificationTag=Wy();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=Ak;lastReceivedTsn;sackDuplicates=[];sackMisOrdered=new Set;sackNeeded=!1;sackPacketCount=0;sackHasNewDataInPacket=!1;sackImmediate=!1;sackTimeout;cwnd=3*wn;fastRecoveryExit;fastRecoveryTransmit=!1;forwardTsnChunk;flightSize=0;outboundQueue=[];outboundStreamSeq={};_outboundStreamsCount=Ak;localTsn=Number(Wy());lastSackedTsn=Gc(this.localTsn);advancedPeerAckTsn=Gc(this.localTsn);partialBytesAcked=0;sentQueue=[];transmitting=!1;transmitRequested=!1;reconfigRequestSeq=this.localTsn;reconfigResponseSeq=0;reconfigRequest;reconfigQueue=[];srtt;rttvar;rto=Pk;timer1Handle;timer1Chunk;timer1Failures=0;timer2Handle;timer2Chunk;timer2Failures=0;timer3Handle;timerReconfigHandle;timerReconfigFailures=0;timerHeartbeatHandle;heartbeatInterval=B$;ssthresh;get isStopped(){return this.isStopping||this.isClosed}get maxChannels(){if(this._inboundStreamsCount>0)return Math.min(this._inboundStreamsCount,this._outboundStreamsCount)}static client(e,t=5e3){let s=new r2(e,t);return s.isServer=!1,s}static server(e,t=5e3){let s=new r2(e,t);return s.isServer=!0,s}async handleData(e){if(this.isStopped)return;let t,[,,s,n]=S$(e);if(n.filter(o=>o.type===Fy.type).length>0){if(n.length!=1)throw new Error;t=0}else t=this.localVerificationTag;if(s===t){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=>{Lt("send delayed sack failed",e.message)})},P$))}}async sendSack(){if(this.isStopped||!this.sackNeeded)return;let e=[],t;[...this.sackMisOrdered].sort().forEach(n=>{let i=(n-this.lastReceivedTsn)%ix;n===t?e[e.length-1][1]=i:e.push([i,i]),t=Wu(n)});let s=new Y_(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=>{Lt("send sack failed",n.message)}),this.sackDuplicates=[],this.sackNeeded=!1,this.sackPacketCount=0,this.sackImmediate=!1}async receiveChunk(e){switch(e.type){case zy.type:this.receiveDataChunk(e);break;case Fy.type:{if(!this.isServer)return;let t=e;Lt("receive init",t),this.lastReceivedTsn=Gc(t.initialTsn),this.reconfigResponseSeq=Gc(t.initialTsn),this.remoteVerificationTag=t.initiateTag,this.ssthresh=t.advertisedRwnd,this.peerAdvertisedRwnd=t.advertisedRwnd,this.getExtensions(t.params),this._inboundStreamsCount=Math.min(t.outboundStreams,this._inboundStreamsMax),this._outboundStreamsCount=Math.min(this._outboundStreamsCount,t.inboundStreams);let s=new z_;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(Hy.jspack.Pack("!L",[n]));i=Buffer.concat([i,(0,qp.createHmac)("sha1",this.hmacKey).update(i).digest()]),s.params.push([Nk,i]),Lt("send initAck",s),await this.sendChunk(s).catch(o=>{Lt("send initAck failed",o.message)})}break;case z_.type:{if(this.associationState!=2)return;let t=e;this.timer1Cancel(),this.lastReceivedTsn=Gc(t.initialTsn),this.reconfigResponseSeq=Gc(t.initialTsn),this.remoteVerificationTag=t.initiateTag,this.ssthresh=t.advertisedRwnd,this.peerAdvertisedRwnd=t.advertisedRwnd,this.getExtensions(t.params),this._inboundStreamsCount=Math.min(t.outboundStreams,this._inboundStreamsMax),this._outboundStreamsCount=Math.min(this._outboundStreamsCount,t.inboundStreams);let s=new $_;for(let[n,i]of t.params)if(n===Nk){s.body=i;break}await this.sendChunk(s).catch(n=>{Lt("send echo failed",n.message)}),this.timer1Start(s),this.setState(3)}break;case Y_.type:await this.receiveSackChunk(e);break;case G_.type:{let t=new u7;t.params=e.params,await this.sendChunk(t).catch(s=>{Lt("send heartbeat ack failed",s.message)})}break;case K_.type:this.setState(1);break;case p7.type:{this.timer2Cancel(),this.setState(7);let t=new g7;await this.sendChunk(t).catch(s=>{Lt("send shutdown ack failed",s.message)}),this.t2Start(t),this.setState(6)}break;case $y.type:Lt("ErrorChunk",e.descriptions);break;case $_.type:{if(!this.isServer)return;let s=e.body,n=(0,qp.createHmac)("sha1",this.hmacKey).update(s.slice(0,4)).digest();if(s?.length!=T$||!s.slice(4).equals(n)){Lt("x State cookie is invalid");return}let i=Date.now()/1e3,o=Hy.jspack.Unpack("!L",s)[0];if(o<i-A$||o>i){let c=new $y(0,void 0);c.params.push([$y.CODE.StaleCookieError,Buffer.concat([...Array(8)].map(()=>Buffer.from("\0")))]),await this.sendChunk(c).catch(d=>{Lt("send errorChunk failed",d.message)});return}let a=new V_;await this.sendChunk(a).catch(c=>{Lt("send cookieAck failed",c.message)}),this.setState(4)}break;case V_.type:{if(this.associationState!=3)return;this.timer1Cancel(),this.setState(4)}break;case x7.type:{if(this.associationState!=8)return;this.timer2Cancel(),this.setState(1)}break;case X_.type:{if(this.associationState!=4)return;let t=e;for(let[s,n]of t.params){let i=Tk[s];i&&await this.receiveReconfigParam(i.parse(n))}}break;case qy.type:this.receiveForwardTsnChunk(e);break}}getExtensions(e){for(let[t,s]of e)t===Lk?this.remotePartialReliability=!0:t===Ok&&(this.remoteExtensions=[...s])}async receiveReconfigParam(e){switch(Lt("receiveReconfigParam",Tk[e.type]),e.type){case J_.type:{let t=e,s=new Vy(t.requestSequence,Ty.ReconfigResultSuccessPerformed);this.reconfigResponseSeq=t.requestSequence,await this.sendReconfigParam(s),await Promise.all(t.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(t.streams)}break;case Vy.type:{let t=e;if(t.result!==Ty.ReconfigResultSuccessPerformed)Lt("OutgoingSSNResetRequestParam failed",Object.keys(Ty).find(s=>Ty[s]===t.result));else if(t.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=Pk,this.timerReconfigFailures=0,this.reconfigQueue.length>0&&await this.transmitReconfigRequest()}}break;case S7.type:{let t=e;this._inboundStreamsCount+=t.newStreams;let s=new Vy(t.requestSequence,1);this.reconfigResponseSeq=t.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&bp)===0&&(this.sackImmediate=!0),this.sackMisOrdered.size>0&&(this.sackImmediate=!0);let t=this.getInboundStream(e.streamId);t.addChunk(e),this.advertisedRwnd-=e.userData.length;for(let s of t.popMessages())this.advertisedRwnd+=s[2].length,this.receive(...s)}async receiveSackChunk(e){if(fi(this.lastSackedTsn,e.cumulativeTsn))return;let t=Date.now()/1e3;this.lastSackedTsn=e.cumulativeTsn;let s=this.flightSize>=this.cwnd,n=0,i=0;for(;this.sentQueue.length>0&&Gu(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(t-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 f=u[0];f<u[1]+1;f++)c=(e.cumulativeTsn+f)%ix,a.add(c)});let d=e.cumulativeTsn;for(let u of this.sentQueue){if(fi(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(fi(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,wn):(this.partialBytesAcked+=i,this.partialBytesAcked>=this.cwnd&&(this.partialBytesAcked-=this.cwnd,this.cwnd+=wn))),o&&(this.ssthresh=Math.max(Math.floor(this.cwnd/2),4*wn),this.cwnd=this.ssthresh,this.partialBytesAcked=0,this.fastRecoveryExit=this.sentQueue[this.sentQueue.length-1].tsn,this.fastRecoveryTransmit=!0)):Gu(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,Gu(this.lastReceivedTsn,e.cumulativeTsn))return;let t=s=>fi(s,this.lastReceivedTsn);this.lastReceivedTsn=e.cumulativeTsn,this.sackMisOrdered=new Set([...this.sackMisOrdered].filter(t));for(let s of[...this.sackMisOrdered].sort())if(s===Wu(this.lastReceivedTsn))this.lastReceivedTsn=s;else break;this.sackDuplicates=this.sackDuplicates.filter(t),this.sackMisOrdered=new Set([...this.sackMisOrdered].filter(t));for(let[s,n]of e.streams){let i=this.getInboundStream(s);i.streamSequenceNumber=Ur(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-kk)*this.rttvar+kk*Math.abs(this.srtt-e),this.srtt=(1-Rk)*this.srtt+Rk*e):(this.rttvar=e/2,this.srtt=e),this.rto=Math.max(R$,Math.min(this.srtt+4*this.rttvar,k$))}receive(e,t,s){this.onReceive.execute(e,t,s)}getInboundStream(e){return this.inboundStreams[e]||(this.inboundStreams[e]=new L$),this.inboundStreams[e]}markReceived(e){if(Gu(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===Wu(this.lastReceivedTsn))this.lastReceivedTsn=s;else break;let t=s=>fi(s,this.lastReceivedTsn);return this.sackDuplicates=this.sackDuplicates.filter(t),this.sackMisOrdered=new Set([...this.sackMisOrdered].filter(t)),!1}send=async(e,t,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/wn),d=0,u=[];for(let f=0;f<c;f++){let h=new zy(0,void 0);h.flags=0,o||(h.flags=t2),f===0&&(h.flags|=_7),f===c-1&&(h.flags|=bp),h.tsn=this.localTsn,h.streamId=e,h.streamSeqNum=a,h.protocol=t,h.userData=s.slice(d,d+wn),h.bookSize=h.userData.length,h.expiry=n,h.maxRetransmits=i,d+=wn,this.localTsn=Wu(this.localTsn),u.push(h)}for(u.forEach(f=>{this.outboundQueue.push(f)}),o&&(this.outboundStreamSeq[e]=Ur(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=>{Lt("send forwardTsn failed",n.message)}),this.forwardTsnChunk=void 0,this.timer3Handle||this.timer3Start());let e=this.fastRecoveryExit!=null?2*wn:4*wn,t=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>=t)break;this.flightSizeIncrease(n),n.misses=0,n.retransmit=!1,n.sentCount++,await this.sendChunk(n).catch(i=>{Lt("send data failed",i.message)}),s&&this.timer3Restart()}s=!1}for(;this.outboundQueue.length>0&&this.flightSize<t&&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=>{Lt("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)],t=e.slice(0,Bk);this.reconfigQueue=e.slice(Bk);let s=new J_(this.reconfigRequestSeq,this.reconfigResponseSeq,Gc(this.localTsn),t);this.reconfigRequestSeq=Wu(this.reconfigRequestSeq),this.reconfigRequest=s,await this.sendReconfigParam(s),this.timerReconfigHandleStart()}}async sendReconfigParam(e){Lt("sendReconfigParam",e);let t=new X_;t.params.push([e.type,e.bytes]),await this.sendChunk(t).catch(s=>{Lt("send reconfig failed",s.message)})}async sendResetRequest(e){Lt("sendResetRequest",e);let t=new zy(0,void 0);t.streamId=e,this.outboundQueue.push(t),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>I$)this.setState(1);else{if(setImmediate(()=>{this.isStopped||this.sendChunk(this.timer1Chunk).catch(e=>{Lt("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>Ik)this.setState(1);else{if(setImmediate(()=>{this.isStopped||this.sendChunk(this.timer2Chunk).catch(e=>{Lt("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*wn),this.cwnd=wn,this.transmit())};timer3Cancel(){this.timer3Handle&&(clearTimeout(this.timer3Handle),this.timer3Handle=void 0)}timerReconfigHandleStart(){this.isStopped||this.timerReconfigHandle||(Lt("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>Ik)Lt("timerReconfigFailures",this.timerReconfigFailures),this.setState(1),this.timerReconfigHandle=void 0;else if(this.reconfigRequest){if(Lt("timerReconfigHandleExpired",this.timerReconfigFailures,this.rto),await this.sendReconfigParam(this.reconfigRequest),this.isStopped)return;this.timerReconfigHandle=setTimeout(this.timerReconfigHandleExpired,this.rto*1e3)}}};timerReconfigCancel(){this.timerReconfigHandle&&(Lt("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 G_;e.params.push([1,Buffer.from(Hy.jspack.Pack("!L",[Math.floor(Date.now()/1e3)]))]),await this.sendChunk(e).catch(t=>{Lt("send heartbeat failed",t.message)})}this.heartbeatStart()}};setHeartbeatInterval(e){if(e<=0)throw new Error("heartbeat interval must be > 0");this.heartbeatInterval=e,this.heartbeatRestart()}updateAdvancedPeerAckPoint(){fi(this.lastSackedTsn,this.advancedPeerAckTsn)&&(this.advancedPeerAckTsn=this.lastSackedTsn);let e=0,t={};for(;this.sentQueue.length>0&&this.sentQueue[0].abandoned;){let s=this.sentQueue.shift();this.advancedPeerAckTsn=s.tsn,e++,s.flags&t2||(t[s.streamId]=s.streamSeqNum)}this.sentQueue.length||(this.sentQueue=[]),e&&(this.forwardTsnChunk=new qy(0,void 0),this.forwardTsnChunk.cumulativeTsn=this.advancedPeerAckTsn,this.forwardTsnChunk.streams=Object.entries(t).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&bp)break}for(let n=s;n<this.sentQueue.length;n++){let i=this.sentQueue[n];if(i.abandoned=!0,i.retransmit=!1,i.flags&bp)break}return!0}static getCapabilities(){return new D$(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 Fy;e.initiateTag=this.localVerificationTag,e.advertisedRwnd=this.advertisedRwnd,e.outboundStreams=this._outboundStreamsCount,e.inboundStreams=this._inboundStreamsMax,e.initialTsn=this.localTsn,this.setExtensions(e.params),Lt("send init",e);try{await this.sendChunk(e),this.timer1Start(e),this.setState(2)}catch(t){Lt("send init failed",t.message)}}setExtensions(e){let t=[];this.localPartialReliability&&(e.push([Lk,Buffer.from("")]),t.push(qy.type)),t.push(b$.type),e.push([Ok,Buffer.from(t)])}async sendChunk(e){if(this.state==="closed")return;if(this.remotePort===void 0)throw new Error("invalid remote port");let t=_$(this.localPort,this.remotePort,this.remoteVerificationTag,e);await this.transport.send(t)}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,Lt("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 K_;await this.sendChunk(e).catch(t=>{Lt("send abort failed",t.message)})}removeAllListeners(){Object.values(this.stateChanged).forEach(e=>e.allUnsubscribe())}},L$=class{reassembly=[];streamSequenceNumber=0;constructor(){}addChunk(r){if(this.reassembly.length===0||fi(r.tsn,this.reassembly[this.reassembly.length-1].tsn)){this.reassembly.push(r);return}for(let[e,t]of E$(this.reassembly)){if(t.tsn===r.tsn)throw new Error("duplicate chunk in reassembly");if(fi(t.tsn,r.tsn)){this.reassembly.splice(e,0,r);break}}}*popMessages(){let r=0,e,t,s;for(;r<this.reassembly.length;){let n=this.reassembly[r];if(e===void 0){if(s=!(n.flags&t2),!(n.flags&_7)){if(s)break;r++;continue}if(s&&dx(n.streamSeqNum,this.streamSequenceNumber))break;t=n.tsn,e=r}else if(n.tsn!==t){if(s)break;e=void 0,r++;continue}if(n.flags&bp){let i=this.reassembly.slice(e,r+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(r+1)],s&&n.streamSeqNum===this.streamSequenceNumber&&(this.streamSequenceNumber=Ur(this.streamSequenceNumber,1)),r=e,yield[n.streamId,n.protocol,o]}else r++;t=Wu(t)}}pruneChunks(r){let e=-1,t=0;for(let[s,n]of this.reassembly.entries())if(Gu(r,n.tsn))e=s,t+=n.userData.length;else break;return this.reassembly=this.reassembly.slice(e+1),t}},D$=class{constructor(r){this.maxMessageSize=r}};qu=ut("werift:packages/webrtc/src/transport/sctp.ts"),Xu=65536,E7=class C7{constructor(e=5e3,t=Xu){this.port=e,this.maxMessageSize=t}dtlsTransport;sctp;onDataChannel=new Te;id=(0,ZB.randomUUID)().toString();mid;mLineIndex;bundled=!1;dataChannels={};remoteMaxMessageSize=Xu;dataChannelQueue=[];dataChannelId;eventDisposer=[];setDtlsTransport(e){this.dtlsTransport&&this.dtlsTransport.id===e.id||(this.eventDisposer.forEach(t=>t()),this.dtlsTransport=e,this.sctp=new O$(new M$(this.dtlsTransport),this.port),this.eventDisposer=[...[this.sctp.onReceive.subscribe(this.datachannelReceive),this.sctp.onReconfigStreams.subscribe(t=>{t.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(t=>{t.negotiated&&t.readyState!=="open"&&t.setReadyState("open")}),this.dataChannelFlush()}),this.sctp.stateChanged.closed.subscribe(()=>{Object.values(this.dataChannels).forEach(t=>{t.setReadyState("closed")}),this.dataChannels={}}),this.dtlsTransport.onStateChange.subscribe(t=>{t==="closed"&&this.sctp.setState(1)})].map(t=>t.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(t=>t.label===e)}datachannelReceive=async(e,t,s)=>{if(t===Cy&&s.length>0)switch(qu("DCEP",e,t,s),s[0]){case yk:{if(s.length<12){qu("DATA_CHANNEL_OPEN data.length not enough");return}if(Object.keys(this.dataChannels).includes(e.toString()))qu("datachannel already opened","retransmit ack");else{let[,i,,o,a,c]=jy.jspack.Unpack("!BBHLHH",s),d=12,u=s.slice(d,d+a).toString("utf8");d+=a;let f=s.slice(d,d+c).toString("utf8");qu("DATA_CHANNEL_OPEN",{channelType:i,reliability:o,streamId:e,label:u,protocol:f});let h=(i&3)===1?o:void 0,y=(i&3)===2?o:void 0,v=new H2({label:u,ordered:(i&128)===0,maxPacketLifeTime:y,maxRetransmits:h,protocol:f,id:e}),S=new j2(this,v,!1);S.isCreatedByRemote=!0,this.dataChannels[e]=S,this.onDataChannel.execute(S),S.setReadyState("open")}let n=this.dataChannels[e];this.dataChannelQueue.push([n,Cy,Buffer.from(jy.jspack.Pack("!B",[gk]))]),await this.dataChannelFlush()}break;case gk:{qu("DATA_CHANNEL_ACK",e,t);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(t){case xk:return s.toString("utf8");case Yz:return"";case bk:return s;case Jz: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 t=Xz,s=0,n=0;e.ordered||(t=128),e.maxRetransmits?(t=1,n=e.maxRetransmits):e.maxPacketLifeTime&&(t=2,n=e.maxPacketLifeTime);let i=jy.jspack.Pack("!BBHLHH",[yk,t,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,Cy,o]),this.dataChannelFlush()}async dataChannelFlush(){if(this.sctp.associationState==4){for(;this.dataChannelQueue.length>0;){let[e,t,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(t===Cy)await this.sctp.send(n,t,s,{ordered:!0});else{let i=e.maxPacketLifeTime?Date.now()+e.maxPacketLifeTime/1e3:void 0;await this.sctp.send(n,t,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,t)=>{let s=Buffer.isBuffer(t)?t:Buffer.from(t),n=bB(t);return this.assertSendableMessageSize(n),e.addBufferedAmount(n),this.dataChannelQueue.push(typeof t=="string"?[e,xk,s]:[e,bk,s]),this.sctp.associationState!==4&&qu("sctp not established",this.sctp.associationState),this.dataChannelFlush(),n};getCapabilities(){return C7.getCapabilities(this.maxMessageSize)}static getCapabilities(e=Xu){return new iE(e)}setRemoteMaxMessageSize(e){this.remoteMaxMessageSize=e??Xu}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(t=>t[0].id!==e.id),this.sctp.reconfigQueue=this.sctp.reconfigQueue.filter(t=>t!==e.id),e.id&&delete this.dataChannels[e.id],e.setReadyState("closed")))}},iE=class{constructor(r){this.maxMessageSize=r}},M$=class{constructor(r){this.dtls=r}set onData(r){this.dtls.dataReceiver=r}send=r=>this.dtls.sendData(r);close(){}},_p=class T7{version=0;origin;name="-";time="0 0";host;group=[];extMapAllowMixed=!0;msidSemantic=[];media=[];type;dtlsRole;iceOptions;iceLite;icePassword;iceUsernameFragment;dtlsFingerprints=[];static parse(e){let[t,s]=U$(e),n=new T7;t.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=JS(o.slice(2));else if(o.startsWith("t="))n.time=o.slice(2);else if(o.startsWith("a=")){let[a,c]=QS(o);switch(a){case"fingerprint":{let[d,u]=c?.split(" ")||[];n.dtlsFingerprints.push(new sx(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":Ky(n.group,c);break;case"msid-semantic":Ky(n.msidSemantic,c);break;case"setup":n.dtlsRole=wk[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(" "),f=["audio","video"].includes(d)?u.map(v=>Number(v)):void 0,h=new ox(d,Number.parseInt(c[2]),c[3],f||u);if(h.dtlsParams=new nx([...n.dtlsFingerprints],n.dtlsRole),h.iceParams=new sE({iceLite:n.iceLite,usernameFragment:n.iceUsernameFragment,password:n.icePassword}),h.iceOptions=n.iceOptions,n.media.push(h),o.slice(1).forEach(v=>{if(v.startsWith("c="))h.host=JS(v.slice(2));else if(v.startsWith("a=")){let[S,C]=QS(v);switch(S){case"candidate":if(!C)throw new Error;h.iceCandidates.push(aE(C));break;case"end-of-candidates":h.iceCandidatesComplete=!0;break;case"extmap":{let[O,K]=C.split(" ");O.includes("/")&&([O]=O.split("/")),h.rtp.headerExtensions.push(new mi({id:Number.parseInt(O),uri:K}))}break;case"fingerprint":{if(!C)throw new Error;let[O,K]=C.split(" ");h.dtlsParams?.fingerprints.push(new sx(O,K))}break;case"ice-options":h.iceOptions=C;break;case"ice-pwd":h.iceParams.password=C;break;case"ice-ufrag":h.iceParams.usernameFragment=C;break;case"ice-lite":h.iceParams.iceLite=!0;break;case"max-message-size":h.sctpCapabilities=new iE(Number.parseInt(C,10));break;case"mid":h.rtp.muxId=C;break;case"msid":h.msid=C;break;case"rtcp":{let[O,K]=ao(C," ");h.rtcpPort=Number.parseInt(O),h.rtcpHost=JS(K)}break;case"rtcp-mux":h.rtcpMux=!0;break;case"setup":h.dtlsParams.role=wk[C];break;case"recvonly":case"sendonly":case"sendrecv":case"inactive":h.direction=S;break;case"rtpmap":{let[O,K]=ao(C," "),[z,Q,oe]=K.split("/"),se;h.kind==="audio"&&(se=oe?Number.parseInt(oe):1);let we=new _a({mimeType:h.kind+"/"+z,channels:se,clockRate:Number.parseInt(Q),payloadType:Number.parseInt(O)});h.rtp.codecs.push(we)}break;case"sctpmap":{if(!C)throw new Error;let[O,K]=ao(C," ");h.sctpMap[Number.parseInt(O)]=K,h.sctpPort=Number.parseInt(O)}break;case"sctp-port":if(!C)throw new Error;h.sctpPort=Number.parseInt(C);break;case"ssrc":{let[O,K]=ao(C," "),z=Number.parseInt(O),[Q,oe]=ao(K,":"),se=h.ssrc.find(we=>we.ssrc===z);se||(se=new ax({ssrc:z}),h.ssrc.push(se)),PB.includes(Q)&&(se[Q]=oe)}break;case"ssrc-group":Ky(h.ssrcGroup,C);break;case"rid":{let[O,K]=ao(C," ");h.simulcastParameters.push(new F2({rid:O,direction:K}))}break}}}),(!h.iceParams.usernameFragment||!h.iceParams.password)&&h.rtp.muxId&&i&&i.items.includes(h.rtp.muxId))for(let v=0;v<i.items.length;v++){if(!i.items.includes(v.toString()))continue;let S=n.media[v];if(S.iceParams?.usernameFragment&&S.iceParams.password){h.iceParams={...S.iceParams};break}}h.dtlsParams.role||(h.dtlsParams=void 0);let y=v=>h.rtp.codecs.find(S=>S.payloadType===v);o.slice(1).forEach(v=>{if(v.startsWith("a=")){let[S,C]=QS(v);if(S==="fmtp"){let[O,K]=ao(C," "),z=y(Number(O));z.parameters=K}else if(S==="rtcp-fb"){let[O,K,z]=C.split(" ");h.rtp.codecs.forEach(Q=>{["*",Q.payloadType.toString()].includes(O)&&Q.rtcpFeedback.push(new wB({type:K,parameter:z}))})}}})}),n}webrtcTrackId(e){if(e.msid?.includes(" ")){let t=e.msid.split(" ");for(let s of this.msidSemantic)if(s.semantic==="WMS"&&(s.items.includes(t[0])||s.items.includes("*")))return t[1]}}get string(){let e=[`v=${this.version}`,`o=${this.origin}`,`s=${this.name}`];this.host&&e.push(`c=${s2(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 t=this.media.map(n=>n.toString()).join("");return e.join(`\r
133
+ `)+`\r
134
+ `+t}toJSON(){return new A7(this.string,this.type)}toSdp(){return{type:this.type,sdp:this.string}}},ox=class{constructor(r,e,t,s){this.kind=r,this.port=e,this.profile=t,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 r=[];if(r.push(`m=${this.kind} ${this.port} ${this.profile} ${this.fmt.map(e=>e.toString()).join(" ")}`),this.host&&r.push(`c=${s2(this.host)}`),this.iceCandidates.forEach(e=>{r.push(`a=candidate:${oE(e)}`)}),this.iceCandidatesComplete&&r.push("a=end-of-candidates"),this.iceParams?.usernameFragment&&r.push(`a=ice-ufrag:${this.iceParams.usernameFragment}`),this.iceParams?.password&&r.push(`a=ice-pwd:${this.iceParams.password}`),this.iceParams?.iceLite&&r.push("a=ice-lite"),this.iceOptions&&r.push(`a=ice-options:${this.iceOptions}`),this.dtlsParams&&(this.dtlsParams.fingerprints.forEach(e=>{r.push(`a=fingerprint:${e.algorithm} ${e.value}`)}),r.push(`a=setup:${F_[this.dtlsParams.role]}`)),this.direction&&r.push(`a=${this.direction}`),this.rtp.muxId&&r.push(`a=mid:${this.rtp.muxId}`),this.msid&&r.push(`a=msid:${this.msid}`),this.rtcpPort&&this.rtcpHost&&(r.push(`a=rtcp:${this.rtcpPort} ${s2(this.rtcpHost)}`),this.rtcpMux&&r.push("a=rtcp-mux")),this.ssrcGroup.forEach(e=>{r.push(`a=ssrc-group:${e.str}`)}),this.ssrc.forEach(e=>{PB.forEach(t=>{let s=e[t];s!==void 0&&r.push(`a=ssrc:${e.ssrc} ${t}:${s}`)})}),this.rtp.codecs.forEach(e=>{r.push(`a=rtpmap:${e.payloadType} ${e.str}`),e.rtcpFeedback.forEach(t=>{let s=t.type;t.parameter&&(s+=` ${t.parameter}`),r.push(`a=rtcp-fb:${e.payloadType} ${s}`)}),e.parameters&&r.push(`a=fmtp:${e.payloadType} ${e.parameters}`)}),Object.keys(this.sctpMap).forEach(e=>{let t=this.sctpMap[Number(e)];r.push(`a=sctpmap:${e} ${t}`)}),this.sctpPort&&r.push(`a=sctp-port:${this.sctpPort}`),this.sctpCapabilities&&r.push(`a=max-message-size:${this.sctpCapabilities.maxMessageSize}`),this.rtp.headerExtensions.forEach(e=>r.push(`a=extmap:${e.id} ${e.uri}`)),this.simulcastParameters.length){this.simulcastParameters.forEach(n=>{r.push(`a=rid:${n.rid} ${n.direction}`)});let e="a=simulcast:",t=this.simulcastParameters.filter(n=>n.direction==="recv");t.length&&(e+=`recv ${t.map(n=>n.rid).join(";")} `);let s=this.simulcastParameters.filter(n=>n.direction==="send");s.length&&(e+=`send ${s.map(n=>n.rid).join(";")}`),r.push(e)}return r.join(`\r
135
+ `)+`\r
136
+ `}},Zu=class{constructor(r,e){this.semantic=r,this.items=e}get str(){return`${this.semantic} ${this.items.join(" ")}`}};A7=class{constructor(r,e){this.sdp=r,this.type=e}static isThis(r){if(typeof r?.sdp=="string")return!0}toSdp(){return{sdp:this.sdp,type:this.type}}};ax=class{ssrc;cname;msid;msLabel;label;constructor(r){Object.assign(this,r)}},Ay=ut("werift:packages/webrtc/src/media/rtpReceiver.ts"),cE=class{constructor(r,e,t){this.config=r,this.kind=e,this.rtcpSsrc=t}codecs={};get codecArray(){return Object.values(this.codecs).sort((r,e)=>r.payloadType-e.payloadType)}ssrcByRtx={};nack=new c$(this);audioRedHandler=new wP;type="receiver";uuid=(0,AB.randomUUID)().toString();tracks=[];trackBySSRC={};trackByRID={};lastSRtimestamp={};receiveLastSRTimestamp={};onPacketLost=this.nack.onPacketLost;onRtcp=new Te;dtlsTransport;sdesMid;latestRid;latestRepairedRid;receiverTWCC;stopped=!1;remoteStreamId;remoteTrackId;rtcpRunning=!1;rtcpCancel=new AbortController;remoteStreams={};setDtlsTransport(r){this.dtlsTransport=r}get track(){return this.tracks[0]??new jp({kind:this.kind})}get nackEnabled(){return this.codecArray[0]?.rtcpFeedback.find(r=>r.type==="nack")}get twccEnabled(){return this.codecArray[0]?.rtcpFeedback.find(r=>r.type===vB().type)}get pliEnabled(){return this.codecArray[0]?.rtcpFeedback.find(r=>r.type===ff().type)}prepareReceive(r){r.codecs.forEach(e=>{this.codecs[e.payloadType]=e}),r.encodings.forEach(e=>{e.rtx&&(this.ssrcByRtx[e.rtx.ssrc]=e.ssrc)})}setupTWCC(r){this.twccEnabled&&!this.receiverTWCC&&(this.receiverTWCC=new u$(this.dtlsTransport,this.rtcpSsrc,r))}addTrack(r){return this.tracks.find(t=>{if(t.rid)return t.rid===r.rid;if(t.ssrc)return t.ssrc===r.ssrc})?!1:(this.tracks.push(r),r.ssrc&&(this.trackBySSRC[r.ssrc]=r),r.rid&&(this.trackByRID[r.rid]=r),!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,Dy.setTimeout)(500+Math.random()*1e3,void 0,{signal:this.rtcpCancel.signal});let r=Object.entries(this.remoteStreams).map(([t,s])=>{let n=0,i=0;if(this.lastSRtimestamp[t]){n=this.lastSRtimestamp[t];let o=Hp()-this.receiveLastSRTimestamp[t];o>0&&o<65536&&(i=Yu(o*65536))}return new xx({ssrc:Number(t),fractionLost:s.fraction_lost,packetsLost:s.packets_lost,highestSequence:s.max_seq,jitter:s.jitter,lsr:n,dlsr:i})}),e=new rf({ssrc:this.rtcpSsrc,reports:r});try{this.config.debug.receiverReportDelay&&await(0,Dy.setTimeout)(this.config.debug.receiverReportDelay),await this.dtlsTransport.sendRtcp([e])}catch(t){Ay("sendRtcp failed",t),await(0,Dy.setTimeout)(500+Math.random()*1e3)}}}catch{}}}async getStats(){let r=Ea(),e=[];if(!this.dtlsTransport)return e;let t=qt("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:qt("inbound-rtp",s.ssrc),timestamp:r,ssrc:s.ssrc,kind:this.kind,transportId:t,codecId:this.codecs[0]?qt("codec",this.codecs[0].payloadType,t):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:qt("remote-outbound-rtp",s.ssrc),timestamp:r,ssrc:s.ssrc,kind:this.kind,transportId:t,codecId:i.codecId,localId:i.id,remoteTimestamp:this.receiveLastSRTimestamp[s.ssrc]*1e3};e.push(o)}}return e}async sendRtcpPLI(r){if(!this.pliEnabled){Ay("pli not supported",{mediaSsrc:r});return}if(this.stopped)return;Ay("sendRtcpPLI",{mediaSsrc:r});let e=new tf({feedback:new Bp({senderSsrc:this.rtcpSsrc,mediaSsrc:r})});try{await this.dtlsTransport.sendRtcp([e])}catch(t){Ay(t)}}handleRtcpPacket(r){switch(r.type){case sd.type:{let e=r;this.lastSRtimestamp[e.ssrc]=eE(e.senderInfo.ntpTimestamp),this.receiveLastSRTimestamp[e.ssrc]=Hp();let t=this.trackBySSRC[r.ssrc];t&&t.onReceiveRtcp.execute(r)}break}this.onRtcp.execute(r)}handleRtpBySsrc=(r,e)=>{let t=this.trackBySSRC[r.header.ssrc];this.handleRTP(r,e,t)};handleRtpByRid=(r,e,t)=>{let s=this.trackByRID[e];this.trackBySSRC[r.header.ssrc]||(this.trackBySSRC[r.header.ssrc]=s),this.handleRTP(r,t,s)};handleRTP(r,e,t){if(this.stopped)return;let s=this.codecs[r.header.payloadType];if(!s)return;if(this.remoteStreams[r.header.ssrc]=this.remoteStreams[r.header.ssrc]??new f$(s.clockRate),this.remoteStreams[r.header.ssrc].add(r),this.receiverTWCC){let i=e[Yt.transportWideCC];if(!i==null)throw new Error("undefined");this.receiverTWCC.handleTWCC(i)}else this.twccEnabled&&this.setupTWCC(r.header.ssrc);if(s.name.toLowerCase()==="rtx"){let i=this.ssrcByRtx[r.header.ssrc],o=zp(s.parameters??""),a=this.codecs[o.apt];if(r.payload.length<2)return;r=_P(r,a.payloadType,i),t=this.trackBySSRC[i]}let n;if(!(s.name.toLowerCase()==="red"&&(n=E2.deSerialize(r.payload),!Object.keys(this.codecs).includes(n.header.fields[0].blockPT.toString())))){if(t?.kind==="video"&&this.nackEnabled&&this.nack.addPacket(r),t)if(n){if(t.kind==="audio"){let i=this.audioRedHandler.push(n,r);for(let o of i)t.onReceiveRtp.execute(o.clone(),e)}}else t.onReceiveRtp.execute(r.clone(),e);this.runRtcp()}}},ip=ut("werift:packages/webrtc/src/media/router.ts"),I7=class{ssrcTable={};ridTable={};extIdUriMap={};constructor(){}registerRtpSender(r){this.ssrcTable[r.ssrc]=r}registerRtpReceiver(r,e){ip("registerRtpReceiver",e),this.ssrcTable[e]=r}registerRtpReceiverBySsrc(r,e){ip("registerRtpReceiverBySsrc",e),e.encodings.filter(t=>t.ssrc!=null).forEach((t,s)=>{this.registerRtpReceiver(r.receiver,t.ssrc),r.addTrack(new jp({ssrc:t.ssrc,kind:r.kind,id:r.sender.trackId,remote:!0,codec:e.codecs[s]})),t.rtx&&this.registerRtpReceiver(r.receiver,t.rtx.ssrc)}),e.headerExtensions.forEach(t=>{this.extIdUriMap[t.id]=t.uri})}registerRtpReceiverByRid(r,e,t){let[s]=t.codecs;ip("registerRtpReceiverByRid",e),r.addTrack(new jp({rid:e.rid,kind:r.kind,id:r.sender.trackId,remote:!0,codec:s})),this.ridTable[e.rid]=r.receiver}routeRtp=r=>{let e=aP(r.header.extensions,this.extIdUriMap),t=this.ssrcTable[r.header.ssrc],s=e[Yt.sdesRTPStreamID];if(typeof s=="string"?(t=this.ridTable[s],t.latestRid=s,t.handleRtpByRid(r,s,e)):t?t.handleRtpBySsrc(r,e):(t=Object.values(this.ridTable).filter(o=>o instanceof cE).find(o=>o.trackBySSRC[r.header.ssrc]),t&&(ip("simulcast register receiver by ssrc",r.header.ssrc),this.registerRtpReceiver(t,r.header.ssrc),t.handleRtpBySsrc(r,e))),!t){ip("ssrcReceiver not found");return}let n=e[Yt.sdesMid];typeof n=="string"&&(t.sdesMid=n);let i=e[Yt.repairedRtpStreamId];typeof i=="string"&&(t.latestRepairedRid=i)};routeRtcp=r=>{let e=[];switch(r.type){case sd.type:r=r,e.push(this.ssrcTable[r.ssrc]);break;case rf.type:r=r,r.reports.forEach(t=>{e.push(this.ssrcTable[t.ssrc])});break;case Dp.type:{let t=r}break;case rd.type:{let t=r;t.feedback&&e.push(this.ssrcTable[t.feedback.mediaSourceSsrc])}break;case tf.type:{let t=r;switch(t.feedback.count){case Np.count:{let s=t.feedback;e.push(this.ssrcTable[s.ssrcFeedbacks[0]])}break;default:e.push(this.ssrcTable[t.feedback.senderSsrc]||this.ssrcTable[t.feedback.mediaSsrc])}}break}e.filter(t=>t).forEach(t=>t.handleRtcpPacket(r))}},H$=class{numPackets=0;totalSize=0;firstPacketSentAtMs=0;lastPacketSentAtMs=0;firstPacketReceivedAtMs=0;lastPacketReceivedAtMs=0;addPacket(r,e,t){this.numPackets===0?(this.firstPacketSentAtMs=e,this.firstPacketReceivedAtMs=t,this.lastPacketSentAtMs=e,this.lastPacketReceivedAtMs=t):(e<this.firstPacketSentAtMs&&(this.firstPacketSentAtMs=e),t<this.firstPacketReceivedAtMs&&(this.firstPacketReceivedAtMs=t),e>this.lastPacketSentAtMs&&(this.lastPacketSentAtMs=e),t>this.lastPacketReceivedAtMs&&(this.lastPacketReceivedAtMs=t)),this.numPackets++,this.totalSize+=r}reset(){this.numPackets=0,this.totalSize=0,this.firstPacketSentAtMs=0,this.lastPacketSentAtMs=0,this.firstPacketReceivedAtMs=0,this.lastPacketReceivedAtMs=0}get receiveBitrate(){let r=this.lastPacketReceivedAtMs-this.firstPacketReceivedAtMs,e=this.totalSize/r*8*1e3;return Pp(e)}get sendBitrate(){let r=this.lastPacketSentAtMs-this.firstPacketSentAtMs,e=this.totalSize/r*8*1e3;return Pp(e)}},zu=20,F$=10,q$=class{congestion=!1;onAvailableBitrate=new Te;onCongestion=new Te;onCongestionScore=new Te;congestionCounter=0;cumulativeResult=new H$;sentInfos={};_congestionScore=1;get congestionScore(){return this._congestionScore}set congestionScore(r){this._congestionScore=r,this.onCongestionScore.execute(r)}_availableBitrate=0;get availableBitrate(){return this._availableBitrate}set availableBitrate(r){this._availableBitrate=r,this.onAvailableBitrate.execute(r)}constructor(){}receiveTWCC(r){let t=Z2()-this.cumulativeResult.firstPacketSentAtMs;t>1e3&&(this.cumulativeResult.reset(),this.congestionCounter<zu?this.congestionCounter++:this.congestionScore<F$&&this.congestionScore++,this.congestionCounter>=zu&&!this.congestion&&(this.congestion=!0,this.onCongestion.execute(this.congestion)));for(let s of r.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(t>=100&&this.cumulativeResult.numPackets>=20){if(this.availableBitrate=Math.min(this.cumulativeResult.sendBitrate,this.cumulativeResult.receiveBitrate),this.cumulativeResult.reset(),this.congestionCounter>-zu){let s=Pp(zu/2)+1,n=Pp(zu/4)+1,i=s-(s-n)/10*this.congestionScore;this.congestionCounter=this.congestionCounter-i}this.congestionCounter<=-zu&&(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(r){Object.keys(r).map(e=>Number(e)).sort().filter(e=>e<r.wideSeq).forEach(e=>{delete this.sentInfos[e]}),this.sentInfos[r.wideSeq]=r}},ZS=ut("werift:packages/webrtc/src/media/rtpSender.ts"),Dk=128,Mk=.85,R7=class{constructor(r){this.trackOrKind=r,this.kind=typeof this.trackOrKind=="string"?this.trackOrKind:this.trackOrKind.kind,typeof r!="string"&&(r.streamId&&(this.streamId=r.streamId),this.registerTrack(r))}type="sender";kind;ssrc=o2.jspack.Unpack("!L",(0,i2.randomBytes)(4))[0];rtxSsrc=o2.jspack.Unpack("!L",(0,i2.randomBytes)(4))[0];streamId=(0,a2.randomUUID)().toString();trackId=(0,a2.randomUUID)().toString();onReady=new Te;onRtcp=new Te;onPictureLossIndication=new Te;onGenericNack=new Te;senderBWE=new q$;cname;mid;rtpStreamId;repairedRtpStreamId;rtxPayloadType;rtxSequenceNumber=l2();redRedundantPayloadType;_redDistance=2;redEncoder=new vP(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(r){this.dtlsTransport&&this.dtlsDisposer.forEach(e=>e()),this.dtlsTransport=r,this.dtlsDisposer=[this.dtlsTransport.onStateChange.subscribe(e=>{e==="connected"&&this.onReady.execute()}).unSubscribe]}get redDistance(){return this._redDistance}set redDistance(r){this._redDistance=r,this.redEncoder.distance=r}prepareSend(r){this.cname=r.rtcp?.cname,this.mid=r.muxId,this.headerExtensions=r.headerExtensions,this.rtpStreamId=r.rtpStreamId,this.repairedRtpStreamId=r.repairedRtpStreamId,this.codec=r.codecs[0],this.track&&(this.track.codec=this.codec),r.codecs.forEach(e=>{let t=zp(e.parameters??"");e.name.toLowerCase()==="rtx"&&t.apt===this.codec?.payloadType&&(this.rtxPayloadType=e.payloadType),e.name.toLowerCase()==="red"&&(this.redRedundantPayloadType=Number((e.parameters??"").split("/")[0]))})}registerTrack(r){if(r.stopped)throw new Error("track is ended");this.disposeTrack&&this.disposeTrack(),r.id=this.trackId;let{unSubscribe:e}=r.onReceiveRtp.subscribe(async t=>{await this.sendRtp(t)});this.track=r,this.disposeTrack=e,this.codec&&(r.codec=this.codec),r.onSourceChanged.subscribe(t=>{this.replaceRTP(t)})}async replaceTrack(r){if(r!==null){if(r.stopped)throw new Error("track is ended");if(this.sequenceNumber!=null){let e=r.header||(await r.onReceiveRtp.asPromise())[0].header;this.replaceRTP(e)}this.registerTrack(r),ZS("replaceTrack","ssrc",r.ssrc,"rid",r.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,c2.setTimeout)(500+Math.random()*1e3,void 0,{signal:this.rtcpCancel.signal});let r=[new sd({ssrc:this.ssrc,senderInfo:new _2({ntpTimestamp:this.ntpTimestamp,rtpTimestamp:this.rtpTimestamp,packetCount:this.packetCount,octetCount:this.octetCount})})];this.lastSRtimestamp=eE(this.ntpTimestamp),this.lastSentSRTimestamp=Hp(),this.cname&&r.push(new Dp({chunks:[new w2({source:this.ssrc,items:[new S2({type:1,text:this.cname})]})]}));try{await this.dtlsTransport.sendRtcp(r)}catch(e){ZS("sendRtcp failed",e),await(0,c2.setTimeout)(500+Math.random()*1e3)}}}catch{}}}replaceRTP({sequenceNumber:r,timestamp:e},t=!1){this.sequenceNumber!=null&&(this.seqOffset=Ur(this.sequenceNumber,-r),t&&(this.seqOffset=Ur(this.seqOffset,2))),this.timestamp!=null&&(this.timestampOffset=Yc(this.timestamp,-e),t&&(this.timestampOffset=Ur(this.timestampOffset,1))),this.rtpCache=[],ZS("replaceRTP",this.sequenceNumber,r,this.seqOffset)}async sendRtp(r){if(this.dtlsTransport.state!=="connected"||!this.codec)return;r=Buffer.isBuffer(r)?mo.deSerialize(r):r;let{header:e,payload:t}=r;e.ssrc=this.ssrc,e.payloadType=this.codec.payloadType,e.timestamp=Yc(e.timestamp,this.timestampOffset),e.sequenceNumber=Ur(e.sequenceNumber,this.seqOffset),this.timestamp=e.timestamp,this.sequenceNumber=e.sequenceNumber;let s=jB(),n=[...e.extensions];e.extensions=this.headerExtensions.map(d=>{let u=(()=>{switch(d.uri){case Yt.sdesMid:return this.mid?cP(this.mid):void 0;case Yt.sdesRTPStreamID:return this.rtpStreamId?dP(this.rtpStreamId):void 0;case Yt.repairedRtpStreamId:return this.repairedRtpStreamId?uP(this.repairedRtpStreamId):void 0;case Yt.transportWideCC:return this.dtlsTransport.transportSequenceNumber=Ur(this.dtlsTransport.transportSequenceNumber,1),fP(this.dtlsTransport.transportSequenceNumber);case Yt.absSendTime:return lP(s)}})();if(u)return{id:d.id,payload:u}}).filter(d=>d);for(let d of n){let u=e.extensions.find(f=>f.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+=t.length,this.packetCount=Yc(this.packetCount,1),this.rtpCache[e.sequenceNumber%Dk]=r;let i=t;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=Z2(),c={wideSeq:this.dtlsTransport.transportSequenceNumber,size:o,sendingAtMs:a,sentAtMs:a};this.senderBWE.rtpPacketSent(c)}handleRtcpPacket(r){switch(r.type){case sd.type:case rf.type:r.reports.filter(t=>t.ssrc===this.ssrc).forEach(t=>{if(this.lastSRtimestamp===t.lsr&&t.dlsr&&this.lastSentSRTimestamp){let s=Hp()-this.lastSentSRTimestamp-t.dlsr/65536;this.rtt===void 0?this.rtt=s:this.rtt=Mk*this.rtt+(1-Mk)*s}});break;case rd.type:{let e=r;switch(e.feedback.count){case Lp.count:{let t=e.feedback;this.senderBWE.receiveTWCC(t)}break;case Op.count:{let t=e.feedback;t.lost.forEach(async s=>{let n=this.rtpCache[s%Dk];n&&n.header.sequenceNumber!==s&&(n=void 0),n&&(this.rtxPayloadType!=null&&(n=EP(n,this.rtxPayloadType,this.rtxSequenceNumber,this.rtxSsrc),this.rtxSequenceNumber=Ur(this.rtxSequenceNumber,1)),await this.dtlsTransport.sendRtp(n.payload,n.header))}),this.onGenericNack.execute(t)}break}}break;case tf.type:{let e=r;switch(e.feedback.count){case Np.count:{let t=e.feedback;this.receiverEstimatedMaxBitrate=t.bitrate}break;case Bp.count:this.onPictureLossIndication.execute();break}}break}this.onRtcp.execute(r)}getParameters(){return{encodings:[]}}setParameters(r){}async getStats(){let r=Ea(),e=[];if(!this.dtlsTransport)return e;let t=qt("transport",this.dtlsTransport.id),s={type:"outbound-rtp",id:qt("outbound-rtp",this.ssrc),timestamp:r,ssrc:this.ssrc,kind:this.kind,transportId:t,codecId:this.codec?qt("codec",this.codec.payloadType,t):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:qt("media-source",this.trackId),timestamp:r,trackIdentifier:this.trackId,kind:this.kind};e.push(n)}if(this.rtt!==void 0){let n={type:"remote-inbound-rtp",id:qt("remote-inbound-rtp",this.ssrc),timestamp:r,ssrc:this.ssrc,kind:this.kind,transportId:t,codecId:s.codecId,localId:s.id,roundTripTime:this.rtt};e.push(n)}return e}},z$=ut("werift:packages/webrtc/src/transport/sctpManager.ts"),$$=class{sctpTransport;sctpRemotePort;dataChannelsOpened=0;dataChannelsClosed=0;dataChannels=[];onDataChannel=new Te;constructor(){}createSctpTransport(r){let e=new E7(5e3,r);return e.mid=void 0,e.onDataChannel.subscribe(t=>{this.dataChannelsOpened++,this.dataChannels.push(t),this.onDataChannel.execute(t)}),this.sctpTransport=e,e}createDataChannel(r,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 H2({id:s.id,label:r,maxPacketLifeTime:s.maxPacketLifeTime,maxRetransmits:s.maxRetransmits,negotiated:s.negotiated,ordered:s.ordered,protocol:s.protocol}),i=new j2(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(),z$("sctp connected"))}setRemoteSCTP(r,e){if(this.sctpTransport){if(this.sctpTransport.setRemoteMaxMessageSize(r.sctpCapabilities?.maxMessageSize),this.sctpRemotePort=r.sctpPort,!this.sctpRemotePort)throw new Error("sctpRemotePort not exist");this.sctpTransport.setRemotePort(this.sctpRemotePort),this.sctpTransport.mLineIndex=e,this.sctpTransport.mid||(this.sctpTransport.mid=r.rtp.muxId)}}async close(){this.sctpTransport&&await this.sctpTransport.stop(),this.onDataChannel.allUnsubscribe()}async getStats(){let r=Ea(),e=[];for(let t of this.dataChannels){let s={type:"data-channel",id:qt("data-channel",t.id),timestamp:r,label:t.label,protocol:t.protocol,dataChannelIdentifier:t.id,state:t.readyState,messagesSent:t.messagesSent||0,bytesSent:t.bytesSent||0,messagesReceived:t.messagesReceived||0,bytesReceived:t.bytesReceived||0};e.push(s)}return e}},P7=class{currentLocalDescription;currentRemoteDescription;pendingLocalDescription;pendingRemoteDescription;cname;midSuffix;bundlePolicy;seenMid=new Set;constructor({cname:r,midSuffix:e,bundlePolicy:t}){this.cname=r,this.midSuffix=e??!1,this.bundlePolicy=t}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?.(r=>r.direction==="inactive")}createMediaDescriptionForTransceiver(r,e){let t=new ox(r.kind,9,"UDP/TLS/RTP/SAVPF",r.codecs.map(s=>s.payloadType));return t.direction=e,t.msid=r.msid,t.rtp={codecs:r.codecs,headerExtensions:r.headerExtensions,muxId:r.mid},t.rtcpHost="0.0.0.0",t.rtcpPort=9,t.rtcpMux=!0,t.ssrc=[new ax({ssrc:r.sender.ssrc,cname:this.cname})],r.options.simulcast&&(t.simulcastParameters=r.options.simulcast.map(s=>new F2(s))),t.rtp.codecs.find(s=>s.name.toLowerCase()==="rtx")&&(t.ssrc.push(new ax({ssrc:r.sender.rtxSsrc,cname:this.cname})),t.ssrcGroup=[new Zu("FID",[r.sender.ssrc.toString(),r.sender.rtxSsrc.toString()])]),this.addTransportDescription(t,r.dtlsTransport),t}createMediaDescriptionForSctp(r){let e=new ox("application",vk,"UDP/DTLS/SCTP",["webrtc-datachannel"]);return e.sctpPort=r.port,e.rtp.muxId=r.mid,e.sctpCapabilities=r.getCapabilities(),this.addTransportDescription(e,r.dtlsTransport),e}addTransportDescription(r,e){let t=e.iceTransport;r.iceCandidates=t.localCandidates,r.iceCandidatesComplete=t.gatheringState==="complete",r.iceParams=t.localParameters,r.iceOptions="trickle",r.host=Qz,r.port=vk,r.direction==="inactive"&&(r.port=0,r.msid=void 0),r.dtlsParams||(r.dtlsParams=e.localParameters,r.dtlsParams.fingerprints||(r.dtlsParams.fingerprints=e.localParameters.fingerprints))}allocateMid(r=""){let e="";for(let t=0;e=(t++).toString()+r,!!this.seenMid.has(e););return this.seenMid.add(e),e}parseSdp({sdp:r,isLocal:e,signalingState:t,type:s}){let n=_p.parse(r);return this.validateDescription({description:n,isLocal:e,signalingState:t}),n.type=s,n}validateDescription({description:r,isLocal:e,signalingState:t}){if(e){if(r.type==="offer"){if(!["stable","have-local-offer"].includes(t))throw new Error("Cannot handle offer in signaling state")}else if(r.type==="answer"&&!["have-remote-offer","have-local-pranswer"].includes(t))throw new Error("Cannot handle answer in signaling state")}else if(r.type==="offer"){if(!["stable","have-remote-offer"].includes(t))throw new Error("Cannot handle offer in signaling state")}else if(r.type==="answer"&&!["have-local-offer","have-remote-pranswer"].includes(t))throw new Error("Cannot handle answer in signaling state")}buildOfferSdp(r,e){let t=new _p;n2("offer",t),(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,t.media.push(this.createMediaDescriptionForSctp(e))}else{let a=r.find(c=>c.mid===o);if(!a){if(n.direction==="inactive"){t.media.push(n);return}throw new Error("transceiver not found")}a.mLineIndex=i,t.media.push(this.createMediaDescriptionForTransceiver(a,a.direction))}});for(let n of r.filter(i=>!t.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=t.media.length,t.media.push(i)):t.media[n.mLineIndex]=i}if(e&&!t.media.find(n=>n.kind==="application")&&(e.mLineIndex=t.media.length,e.mid==null&&(e.mid=this.allocateMid(this.midSuffix?"dc":"")),t.media.push(this.createMediaDescriptionForSctp(e))),this.bundlePolicy!=="disable"){let n=t.media.map(i=>i.rtp.muxId).filter(i=>i);if(n.length){let i=new Zu("BUNDLE",n);t.group.push(i)}}return t}buildAnswerSdp({transceivers:r,sctpTransport:e,signalingState:t}){if(!["have-remote-offer","have-local-pranswer"].includes(t))throw new Error("createAnswer failed");if(!this._remoteDescription)throw new Error("wrong state");let s=new _p;n2("answer",s);for(let n of this._remoteDescription.media){let i,o;if(["audio","video"].includes(n.kind)){let a=r.find(c=>c.mid===n.rtp.muxId);if(!a)throw new Error(`Transceiver with mid=${n.rtp.muxId} not found`);o=this.createMediaDescriptionForTransceiver(a,Q2(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 Zu("BUNDLE",[]);for(let i of s.media)i.rtp.muxId&&n.items.push(i.rtp.muxId);s.group.push(n)}return s}setLocalDescription(r){this.currentLocalDescription=r,r.type==="answer"?this.pendingLocalDescription=void 0:this.pendingLocalDescription=r}setRemoteDescription(r,e){if(!r.sdp||!r.type||r.type==="rollback"||r.type==="pranswer")throw new Error("invalid sessionDescription");let t=this.parseSdp({sdp:r.sdp,isLocal:!1,signalingState:e,type:r.type});return t.type==="answer"?(this.currentRemoteDescription=t,this.pendingRemoteDescription=void 0):this.pendingRemoteDescription=t,t}registerMid(r){this.seenMid.add(r)}get remoteIsBundled(){let r=this._remoteDescription;return r?r.group.find(t=>t.semantic==="BUNDLE"&&this.bundlePolicy!=="disable"):void 0}setLocal(r,e,t){let s=new Map(e.map(o=>[o?.mLineIndex,o])),n=e.find(o=>o?.dtlsTransport)?.dtlsTransport??t?.dtlsTransport;r.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=r.media.find(o=>o.kind==="application");t&&i&&this.addTransportDescription(i,t.dtlsTransport),this.setLocalDescription(r)}},op=ut("werift:packages/webrtc/src/transport/secureTransportManager.ts"),V$=class{connectionState="new";iceConnectionState="new";iceGatheringState="new";certificate;iceGatheringStateChange=new Te;iceConnectionStateChange=new Te;onIceCandidate=new Te;connectionStateChange=new Te;config;transceiverManager;sctpManager;constructor({config:r,transceiverManager:e,sctpManager:t}){if(this.config=r,this.transceiverManager=e,this.sctpManager=t,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,t)=>(e.map(s=>s.id).includes(t.id)||e.push(t),e),[])}get iceTransports(){return this.dtlsTransports.map(r=>r.iceTransport)}setupCertificate(r){this.certificate=new tE(r.keyPem,r.certPem,r.signatureHash)}createTransport(){let r=this.iceTransports.find(n=>n.state!=="closed"),e=new YB({...HB(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});r&&(e.connection.localUsername=r.connection.localUsername,e.connection.localPassword=r.connection.localPassword),e.onGatheringStateChange.subscribe(()=>{this.updateIceGatheringState()}),this.updateIceGatheringState();let t=new XB(e);return t.onStateChange.subscribe(()=>{this.updateIceConnectionState()}),new q_(this.config,t,this.certificate,K$)}handleNewIceCandidate({candidate:r,media:e,remoteIsBundled:t,transceiver:s,sctpTransport:n,bundlePolicy:i}){return i==="max-bundle"||t?(r.sdpMLineIndex=0,e&&(r.sdpMid=e.rtp.muxId)):(s&&(r.sdpMLineIndex=s.mLineIndex,r.sdpMid=s.mid),n&&(r.sdpMLineIndex=n.mLineIndex,r.sdpMid=n.mid)),r.foundation&&!r.foundation.startsWith("candidate:")&&(r.foundation="candidate:"+r.foundation),this.onIceCandidate.execute(r),r}async addIceCandidate(r,e){let t=rE.fromJSON(e);if(!t)return;let s;typeof t.sdpMid=="number"&&(s=this.getTransportByMid(t.sdpMid)),!s&&typeof t.sdpMLineIndex=="number"&&(s=this.getTransportByMLineIndex(r,t.sdpMLineIndex)),s||(s=this.iceTransports[0]),s?await s.addRemoteCandidate(t):op("iceTransport not found for candidate",t)}getTransportByMid(r){let e,t=this.transceiverManager.getTransceivers().find(s=>s.mid===r);return t?e=t.dtlsTransport.iceTransport:!e&&this.sctpManager.sctpTransport?.mid===r&&(e=this.sctpManager.sctpTransport.dtlsTransport.iceTransport),e}getTransportByMLineIndex(r,e){let t=r.media[e];return t?this.getTransportByMid(t.rtp.muxId):void 0}restartIce(){for(let r of this.iceTransports)r.restart()}setLocalRole({type:r,role:e}){for(let t of this.dtlsTransports){let s=t.iceTransport;r==="offer"?s.connection.iceControlling=!0:s.connection.iceControlling=!1,s.connection.remoteIsLite&&(s.connection.iceControlling=!0),r==="answer"&&e&&(t.role=e)}}updateIceGatheringState(){let r=this.iceTransports;function e(...s){return r.filter(n=>s.includes(n.gatheringState)).length===r.length}let t;r.length&&e("complete")?t="complete":!r.length||e("new","complete")?t="new":r.map(s=>s.gatheringState).includes("gathering")?t="gathering":t="new",this.iceGatheringState!==t&&(this.iceGatheringState=t,this.iceGatheringStateChange.execute(t))}updateIceConnectionState(){let r=this.iceTransports,e;function t(...n){return r.filter(i=>n.includes(i.state)).length===r.length}function s(...n){return r.some(i=>n.includes(i.state))}this.connectionState==="closed"?e="closed":s("failed")?e="failed":s("disconnected")?e="disconnected":t("new","closed")?e="new":s("new","checking")?e="checking":t("completed","closed")?e="completed":t("connected","completed","closed")?e="connected":e="new",this.iceConnectionState!==e&&(op("iceConnectionStateChange",e),this.iceConnectionState=e,this.iceConnectionStateChange.execute(e))}async gatherCandidates(r){let e=this.iceTransports.find(t=>t.state==="connected"||t.state==="completed");r&&e?op("skipping ICE gathering for bundled connection"):await Promise.allSettled(this.iceTransports.map(t=>t.gather())).catch(t=>{op("gatherCandidates failed",t)})}setConnectionState(r){op("connectionStateChange",r),this.connectionState=r,this.connectionStateChange.execute(r)}async getStats(){let r=[];for(let e of this.dtlsTransports){let t=await e.getStats();t&&r.push(...t)}return r}async ensureCerts(){this.certificate||(this.certificate=await q_.SetupCertificate());for(let r of this.dtlsTransports)r.localCertificate=this.certificate}async close(){this.setConnectionState("closed"),await Promise.allSettled([...this.dtlsTransports.map(r=>r.stop())]),this.iceGatheringStateChange.allUnsubscribe(),this.iceConnectionStateChange.allUnsubscribe(),this.onIceCandidate.allUnsubscribe(),this.connectionStateChange.allUnsubscribe()}},K$=[Sk.SRTP_AEAD_AES_128_GCM,Sk.SRTP_AES128_CM_HMAC_SHA1_80],Sn=ut("werift:packages/webrtc/src/peerConnection.ts"),W$=class extends U2{cname=(0,k7.randomUUID)().toString();config=B7();signalingState="stable";negotiationneeded=!1;needRestart=!1;router=new I7;sdpManager;transceiverManager;sctpManager;secureManager;isClosed=!1;shouldNegotiationneeded=!1;remoteBundleNegotiated=!1;iceGatheringStateChange=new Te;iceConnectionStateChange=new Te;signalingStateChange=new Te;connectionStateChange=new Te;onDataChannel=new Te;onRemoteTransceiverAdded=new Te;onTransceiverAdded=new Te;onIceCandidate=new Te;onNegotiationneeded=new Te;onTrack=new Te;ondatachannel;onicecandidate;onicecandidateerror;onicegatheringstatechange;onnegotiationneeded;onsignalingstatechange;ontrack;onconnectionstatechange;oniceconnectionstatechange;constructor(r={}){super(),this.setConfiguration(r),this.sdpManager=new P7({cname:this.cname,bundlePolicy:this.config.bundlePolicy}),this.transceiverManager=new N7(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:t,transceiver:s})=>{let n={track:e,streams:[t],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 $$,this.sctpManager.onDataChannel.subscribe(e=>{this.onDataChannel.execute(e);let t={channel:e};this.ondatachannel?.(t),this.emit("datachannel",t)}),this.secureManager=new V$({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 t=e?e.toJSON():void 0;this.onIceCandidate.execute(t),this.onicecandidate?.({candidate:t}),this.emit("icecandidate",{candidate:t})})}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(r){if(FB(this.config,r),this.config.icePortRange){let[e,t]=this.config.icePortRange;if(e===t)throw new Error("should not be same value");if(e>=t)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,t]of mk([...this.config.codecs.audio||[],...this.config.codecs.video||[]]))if(t.payloadType==null)switch(t.payloadType=96+e,t.name.toLowerCase()){case"rtx":t.parameters=`apt=${t.payloadType-1}`;break;case"red":if(t.contentType==="audio"){let s=t.payloadType+1;t.parameters=`${s}/${s}`,t.payloadType=63}break}[...this.config.headerExtensions.audio||[],...this.config.headerExtensions.video||[]].forEach((e,t)=>{e.id=1+t})}getConfiguration(){return this.config}async createOffer({iceRestart:r}={}){(r||this.needRestart)&&(this.needRestart=!1,this.secureManager.restartIce()),await this.secureManager.ensureCerts();for(let t of this.transceiverManager.getTransceivers())t.codecs.length===0&&this.transceiverManager.assignTransceiverCodecs(t),t.headerExtensions.length===0&&(t.headerExtensions=this.config.headerExtensions[t.kind]??[]);return this.sdpManager.buildOfferSdp(this.transceiverManager.getTransceivers(),this.sctpTransport).toJSON()}createSctpTransport(){let r=this.sctpManager.createSctpTransport(this.config.maxMessageSize),e=this.findOrCreateTransport();return r.setDtlsTransport(e),r}createDataChannel(r,e={}){this.sctpTransport||(this.createSctpTransport(),this.needNegotiation());let t=this.sctpManager.createDataChannel(r,e);if(!t.sctp.dtlsTransport){let s=this.findOrCreateTransport();t.sctp.setDtlsTransport(s)}return t}removeTrack(r){if(this.isClosed)throw new Error("peer closed");this.transceiverManager.removeTrack(r),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 r=this.dtlsTransports.find(n=>n.state!=="closed"),e=r?.iceTransport;if((this.sdpManager.bundlePolicy==="max-bundle"||this.sdpManager.bundlePolicy!=="disable"&&(this.remoteIsBundled||this.remoteBundleNegotiated))&&r)return r;let t=this.secureManager.createTransport();t.onRtp.subscribe(n=>{this.router.routeRtp(n)}),t.onRtcp.subscribe(n=>{this.router.routeRtcp(n)});let s=t.iceTransport;return s.onNegotiationNeeded.subscribe(()=>{this.needNegotiation()}),s.onIceCandidate.subscribe(n=>{if(!this.localDescription){Sn("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){Sn("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})}),t}async setLocalDescription(r){r=r??(["stable","have-local-offer","have-remote-pranswer"].includes(this.signalingState)?await this.createOffer():await this.createAnswer());let t=this.sdpManager.parseSdp({sdp:r.sdp,isLocal:!0,signalingState:this.signalingState,type:r.type});t.type==="offer"?this.setSignalingState("have-local-offer"):t.type==="answer"&&this.setSignalingState("stable");for(let[n,i]of mk(t.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=t.media.find(n=>n.dtlsParams)?.dtlsParams?.role;if(this.secureManager.setLocalRole({type:t.type,role:s}),["answer","pranswer"].includes(t.type))for(let n of this.transceiverManager.getTransceivers()){let i=Q2(n.direction,n.offerDirection);n.setCurrentDirection(i)}return this.sdpManager.setLocal(t,this.transceiverManager.getTransceivers(),this.sctpTransport),await this.gatherCandidates().catch(n=>{Sn("gatherCandidates failed",n)}),t.type==="answer"&&this.connect().catch(n=>{Sn("connect failed",n),this.secureManager.setConnectionState("failed")}),this.sdpManager.setLocal(t,this.transceiverManager.getTransceivers(),this.sctpTransport),this.shouldNegotiationneeded&&this.needNegotiation(),t}async gatherCandidates(){await this.secureManager.gatherCandidates(!!this.sdpManager.remoteIsBundled)}async addIceCandidate(r){let e=this.sdpManager.buildOfferSdp(this.transceiverManager.getTransceivers(),this.sctpTransport);await this.secureManager.addIceCandidate(e,r)}async connect(){Sn("start connect"),(await Promise.allSettled(this.dtlsTransports.map(async e=>{let{iceTransport:t}=e;if(t.state==="connected")return;let s=()=>e.state==="connected";s()||(this.secureManager.setConnectionState("connecting"),await t.start().catch(n=>{throw Sn("iceTransport.start failed",n),n}),!s()&&(await e.start().catch(n=>{throw Sn("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(r){r instanceof _p&&(r=r.toSdp());let e=this.sdpManager.setRemoteDescription(r,this.signalingState);e.group.some(o=>o.semantic==="BUNDLE"&&o.items.length>0)&&(this.remoteBundleNegotiated=!0);let t,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(f=>s(f,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,r.type==="answer"&&u.setCurrentDirection("inactive");return}this.sdpManager.remoteIsBundled&&(t?u.setDtlsTransport(t):t=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&&(t?u.setDtlsTransport(t):t=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(r.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"&&(Sn("caller start connect"),this.connect().catch(o=>{Sn("connect failed",o),this.secureManager.setConnectionState("failed")})),this.negotiationneeded=!1,this.shouldNegotiationneeded&&this.needNegotiation()}addTransceiver(r,e={}){let t=this.findOrCreateTransport(),s=this.transceiverManager.addTransceiver(r,t,e);return this.secureManager.updateIceConnectionState(),this.needNegotiation(),s}addTrack(r,e){if(this.isClosed)throw new Error("is closed");let t=this.transceiverManager.addTrack(r,e);if(!t.dtlsTransport){let s=this.findOrCreateTransport();t.setDtlsTransport(s)}return this.needNegotiation(),t.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(r){Sn("signalingStateChange",r),this.signalingState=r,this.signalingStateChange.execute(r),this.onsignalingstatechange&&this.onsignalingstatechange({})}createPeerConnectionStats(){let r=Ea();return{type:"peer-connection",id:qt("peer-connection"),timestamp:r,dataChannelsOpened:this.sctpManager.dataChannelsOpened,dataChannelsClosed:this.sctpManager.dataChannelsClosed}}async getStats(r){let e=[];e.push(this.createPeerConnectionStats());let t=await this.transceiverManager.getStats(r);e.push(...t);let s=await this.secureManager.getStats();if(e.push(...s),this.sctpTransport){let n=await this.sctpManager.getStats();n&&e.push(...n)}return new BB(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(),Sn("peerConnection closed"))}},d2=(r,e)=>r.find(t=>t.mimeType.toLowerCase()===e.mimeType.toLowerCase())?e:void 0;G$=B7(),X$=ut("werift:packages/webrtc/src/media/rtpTransceiverManager.ts"),N7=class{constructor(r,e,t){this.cname=r,this.config=e,this.router=t}transceivers=[];onTransceiverAdded=new Te;onRemoteTransceiverAdded=new Te;onTrack=new Te;onNegotiationNeeded=new Te;getTransceivers(){return this.transceivers}getSenders(){return this.getTransceivers().map(r=>r.sender)}getReceivers(){return this.getTransceivers().map(r=>r.receiver)}getTransceiverByMLineIndex(r){return this.transceivers.find(e=>e.mLineIndex===r)}pushTransceiver(r){this.transceivers.push(r)}replaceTransceiver(r,e){this.transceivers[e]=r}addTransceiver(r,e,t={}){let s=typeof r=="string"?r:r.kind,n=t.direction||"sendrecv",i=new R7(r),o=new cE(this.config,s,i.ssrc),a=new NB(s,e,o,i,n);a.options=t,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(r,e){if(this.getSenders().find(n=>n.track?.uuid===r.uuid))throw new Error("Track already added");let t=this.transceivers.find(n=>n.sender.track==null&&n.kind===r.kind&&My.includes(n.direction)===!0);if(t)return t.sender.registerTrack(r),t;let s=this.transceivers.find(n=>n.sender.track==null&&n.kind===r.kind&&My.includes(n.direction)===!1&&!n.usedForSender);if(s){switch(s.sender.registerTrack(r),s.direction){case"recvonly":s.setDirection("sendrecv");break;case"inactive":s.setDirection("sendonly");break}return s}else return this.addTransceiver(r,void 0,{direction:"sendrecv"})}removeTrack(r){if(!this.getSenders().find(({ssrc:t})=>r.ssrc===t))throw new Error("Sender does not exist");let e=this.transceivers.find(({sender:{ssrc:t}})=>r.ssrc===t);if(!e)throw new Error("No matching transceiver found");if(r.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(r){let e=this.config.codecs[r.kind].filter(t=>{switch(t.direction){case"recvonly":return!!e$.includes(r.direction);case"sendonly":return!!My.includes(r.direction);case"sendrecv":return!![G2,W2,K2].includes(r.direction);case"all":return!0;default:return!1}});r.codecs=e}getLocalRtpParams(r){if(r.mid==null)throw new Error("mid not assigned");return{codecs:r.codecs,muxId:r.mid,headerExtensions:r.headerExtensions,rtcp:{cname:this.cname,ssrc:r.sender.ssrc,mux:!0}}}getRemoteRtpParams(r,e){return{muxId:r.rtp.muxId,rtcp:r.rtp.rtcp,codecs:e.codecs,headerExtensions:e.headerExtensions,encodings:Object.values(e.codecs.reduce((s,n)=>{if(n.name.toLowerCase()==="rtx"){let i=zp(n.parameters??""),o=s[i.apt];return o&&r.ssrc.length===2&&(o.rtx=new SB({ssrc:r.ssrc[1].ssrc})),s}return s[n.payloadType]=new _B({ssrc:r.ssrc[0]?.ssrc,payloadType:n.payloadType}),s},{}))}}setRemoteRTP(r,e,t,s){if(r.mid||(r.mid=e.rtp.muxId),r.mLineIndex=s,r.codecs=e.rtp.codecs.filter(a=>{let c=this.config.codecs[e.kind]||[],d=d2(c,a);if(!d)return!1;if(d?.name.toLowerCase()==="rtx"){let f=zp(d.parameters??"").apt,h=e.rtp.codecs.find(y=>y.payloadType===f);return h?!!d2(c,h):!1}return!0}),X$("negotiated codecs",r.codecs),r.codecs.length===0)throw new Error("negotiate codecs failed.");r.headerExtensions=e.rtp.headerExtensions.filter(a=>(this.config.headerExtensions[e.kind]||[]).find(c=>c.uri===a.uri));let n=e.direction??"inactive",i=MB(n);["answer","pranswer"].includes(t)?r.setCurrentDirection(i):r.offerDirection=i;let o=this.getLocalRtpParams(r);if(r.sender.prepareSend(o),["recvonly","sendrecv"].includes(r.direction)){let a=this.getRemoteRtpParams(e,r);for(let c of e.simulcastParameters)this.router.registerRtpReceiverByRid(r,c,a);r.receiver.prepareReceive(a),this.router.registerRtpReceiverBySsrc(r,a)}if(["sendonly","sendrecv"].includes(n)){if(e.msid){let[a,c]=e.msid.split(" ");r.receiver.remoteStreamId=a,r.receiver.remoteTrackId=c}this.onTrack.execute({track:r.receiver.track,transceiver:r,stream:new LB({id:r.receiver.remoteStreamId,tracks:[r.receiver.track]})})}e.ssrc[0]?.ssrc&&r.receiver.setupTWCC(e.ssrc[0].ssrc)}async getStats(r){let e=[];for(let t of this.transceivers){let s=!r||t.sender.track===r||t.receiver.track===r;if(t.sender){let n=await t.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(t.receiver){let n=await t.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=t.getCodecStats();n&&e.push(...n)}}return e}close(){for(let r of this.transceivers)r.receiver.stop(),r.sender.stop();this.onTransceiverAdded.allUnsubscribe(),this.onRemoteTransceiverAdded.allUnsubscribe(),this.onTrack.allUnsubscribe(),this.onNegotiationNeeded.allUnsubscribe()}},Y$=["stable","have-local-offer","have-remote-offer","have-local-pranswer","have-remote-pranswer","closed"],J$=["closed","failed","disconnected","new","connecting","connected"]});var $V={};Ef($V,{App:()=>rN,RequestAbortError:()=>yo,RequestCancelledError:()=>mf,RequestError:()=>yi,RequestTimeoutError:()=>pf,Session:()=>gf,createStore:()=>iN,videoStream:()=>oN});module.exports=kx($V);var hd=class{_handlers=new Map;_ws;_onMessage;_onOpen;_listeningForOpen=!1;_pendingSends=[];_disposed=!1;constructor(e){this._ws=e,this._onMessage=t=>{if(typeof t.data!="string")return;let s;try{s=JSON.parse(t.data)}catch{console.warn("[ChannelMultiplexer] Failed to parse WebSocket message as JSON");return}if(!s.channel)return;let n=this._handlers.get(s.channel);if(n)for(let i of n)i(s)},this._ws.addEventListener("message",this._onMessage),this._onOpen=()=>{this.flushPendingSends()}}on(e,t){let s=this._handlers.get(e);return s||(s=new Set,this._handlers.set(e,s)),s.add(t),()=>{s.delete(t),s.size===0&&this._handlers.delete(e)}}emit(e,t){if(this._disposed)return;let s=JSON.stringify({channel:e,...t});if(this._ws.readyState===WebSocket.OPEN){this._ws.send(s);return}this._ws.readyState===WebSocket.CONNECTING&&(this._pendingSends.push(s),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 e=this._pendingSends;this._pendingSends=[];for(let t of e)this._ws.send(t)}listenForOpen(){this._listeningForOpen||(this._listeningForOpen=!0,this._ws.addEventListener("open",this._onOpen))}},pd=class{_handlers=new Map;_pendingSends=[];_target=null;_targetUnsubscribes=[];_disposed=!1;setTarget(e){if(this._disposed)return;this.detachTarget(),this._target=e;for(let[s,n]of this._handlers)for(let i of n)this._targetUnsubscribes.push(e.on(s,i));let t=this._pendingSends;this._pendingSends=[];for(let s of t)e.emit(s.channel,s.data)}rewriteSessionChannels(e,t){if(e===t)return;let s=`session:${e}:`,n=`session:${t}:`,i=new Map;for(let[o,a]of this._handlers)i.set(o.startsWith(s)?n+o.slice(s.length):o,a);this._handlers=i,this._pendingSends=this._pendingSends.map(o=>({...o,channel:o.channel.startsWith(s)?n+o.channel.slice(s.length):o.channel}))}on(e,t){if(this._disposed)return()=>{};let s=this._handlers.get(e);s||(s=new Set,this._handlers.set(e,s)),s.add(t);let n=this._target?.on(e,t);return n&&this._targetUnsubscribes.push(n),()=>{s?.delete(t),s?.size===0&&this._handlers.delete(e),n?.(),n&&(this._targetUnsubscribes=this._targetUnsubscribes.filter(i=>i!==n))}}emit(e,t){if(!this._disposed){if(this._target){this._target.emit(e,t);return}this._pendingSends.push({channel:e,data:t})}}dispose(){this._disposed=!0,this._pendingSends=[],this._handlers.clear(),this.detachTarget()}detachTarget(){for(let e of this._targetUnsubscribes)e();this._targetUnsubscribes=[],this._target=null}};var V7=Ge(ub());var Bb=Ge(i6(),1);function Sx(){return typeof window>"u"&&typeof process<"u"&&process.versions!=null&&process.versions.node!=null}function M7(){return Sx()?"Chrome111":void 0}var Q$=["RTCSessionDescription","RTCIceCandidate","RTCRtpReceiver","RTCRtpSender","RTCRtpTransceiver","RTCDataChannel","MediaStream","MediaStreamTrack"],wx=null;function U7(){return Sx()?wx||(wx=Z$(),wx):Promise.resolve()}async function Z$(){let r=globalThis;if(typeof r.WebSocket>"u")try{let e=await import("ws"),t=e.default??e;r.WebSocket=t}catch(e){D7("WebSocket",e)}if(typeof r.RTCPeerConnection>"u")try{let e=await Promise.resolve().then(()=>(L7(),O7));eV(r,e)}catch(e){D7("werift",e)}}function eV(r,e){let{RTCPeerConnection:t,useH264:s,useVP8:n,useOPUS:i,useSdesMid:o,useSdesRTPStreamId:a,useAbsSendTime:c,useTransportWideCC:d,useVideoOrientation:u}=e,f=()=>({video:[s(),n()],audio:[i()]}),h=()=>({video:[o(),a(),c(),d(),u()],audio:[o(),c(),d()]});class y extends t{constructor(S){super({...S,codecs:S?.codecs??f(),headerExtensions:S?.headerExtensions??h()})}}r.RTCPeerConnection=y;for(let v of Q$)e[v]!=null&&typeof r[v]>"u"&&(r[v]=e[v])}function D7(r,e){let t=e instanceof Error?e.message:String(e);console.warn(`[urun-sh/core] Node WebRTC support: optional dependency "${r}" unavailable (${t}). Realtime media will not work in this Node process; install "${r}" to enable it. Doc/KV transport over WebSocket is unaffected.`)}var j7="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function tV(r){let e=globalThis.crypto,t=new Uint8Array(r);if(e?.getRandomValues)return e.getRandomValues(t),t;for(let s=0;s<r;s++)t[s]=Math.floor(Math.random()*256);return t}function _x(r=16){let e=tV(r),t="";for(let s=0;s<r;s++)t+=j7[e[s]%j7.length];return t}var H7=[1e3,2e3,4e3,8e3,3e4],F7=5,rV=15e3,sV=2e3,nV=6e3,iV=2,oV=750,aV=3,q7=[1e3,2e3,4e3],cV=15e3,dE="control",K7=0,W7=1,uE=64;function dV(r,e){if(r===dE){let n=new Uint8Array(1+e.length);return n[0]=K7,n.set(e,1),n}let t=new TextEncoder().encode(r);if(t.length<1||t.length>uE)throw new Error(`[urun] doc key length out of range (1..${uE}): ${t.length}`);let s=new Uint8Array(3+t.length+e.length);return s[0]=W7,s[1]=t.length>>>8&255,s[2]=t.length&255,s.set(t,3),s.set(e,3+t.length),s}function uV(r){if(r.length===0)return{docKey:dE,payload:r.slice()};let e=r[0];if(e===K7)return{docKey:dE,payload:r.slice(1)};if(e===W7){if(r.length<3)return null;let t=r[1]<<8|r[2];if(t<1||t>uE||r.length<3+t)return null;let s=new TextDecoder().decode(r.subarray(3,3+t)),n=r.slice(3+t);return{docKey:s,payload:n}}return null}var fV={queued:"queued",pending:"provisioning",allocating:"provisioning",provisioning:"provisioning",allocated:"connecting",connecting:"connecting",live:"live",running:"live",failed:"error",rejected:"error",expired:"error",cancelled:"ended",canceled:"ended",closed:"ended"},lV=8e3,z7=[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun1.l.google.com:19302"}],lf=class{_state="disconnected";_sessionId=null;_tracks=new Map;_tracksByName=new Map;_options;_emitter=new Bb.default;_ws=null;_device=null;_recvTransport=null;_sendTransport=null;_consumers=new Map;_audioProducer=null;_videoProducer=null;_pendingProduce=null;_multiplexer=null;_reconnectAttempts=0;_intentionalDisconnect=!1;_reconnectTimer=null;_stableResetTimer=null;_generation=0;_lastStartOptions;_resolveConnection=null;_recvTransportMsg=null;_lastConsumeMsg=null;_recvConnectWatchdog=null;_recvTcpFailoverDone=!1;_phase={name:"idle"};_requestId;_liveReached=!1;_mediaMonitorTimer=null;_lastInboundTotal=0;_mediaEverFlowed=!1;_lastInboundAdvanceAt=0;_mediaDeathHandled=!1;_currentEpoch=0;_consumerId=null;_pendingStreamSubscribes=new Set;get consumerId(){return this._consumerId===null&&(this._consumerId=hV()),this._consumerId}get state(){return this._state}get currentIncarnation(){return this._currentEpoch}get phase(){return this._phase}get sessionId(){return this._sessionId}get tracks(){return this._tracks}get multiplexer(){return this._multiplexer}get isOpen(){return this._ws?.readyState===WebSocket.OPEN}getTrackByName(e){let t=this._tracksByName.get(e);if(t&&t.readyState!=="ended")return t;for(let s of this._tracks.values())if(s.kind===e&&s.readyState!=="ended")return s;return t}setAuth(e){this._options={...this._options,...e},this.isOpen&&this._send({type:"auth",orgId:this._options.orgId,jwt:this._options.jwt,authProvider:this._options.authProvider})}constructor(e){this._options=e??{url:""},e?.sessionId&&(this._sessionId=e.sessionId)}setConnection(e){if(this.isOpen)throw new Error("TransportSession: cannot change connection while connected");this._options={...this._options,...e},e.sessionId&&(this._sessionId=e.sessionId)}setConnectionResolver(e){this._resolveConnection=e}applyControlDocState(e){let t=e&&typeof e=="object"?e.session:void 0,s=mV(t);s!==void 0&&this.setIncarnation(s)}setIncarnation(e){if(!Number.isFinite(e)||e<=this._currentEpoch)return;let t=this._currentEpoch>0,s=this._state==="connected";this._currentEpoch=e,t&&s&&!this._intentionalDisconnect&&this._renegotiate()}isStaleIncarnation(e){return Number.isFinite(e)?e<this._currentEpoch:!1}isStaleClosedMarker(e){if(!e)return!1;let t=typeof e.status=="string"?e.status:void 0;if(t!=="closed"&&t!=="ended")return!1;let s=e.status_epoch??e.statusEpoch,n=typeof s=="number"?s:Number(s);return Number.isFinite(n)?n<this._currentEpoch:!1}async connect(e){this._lastStartOptions=e,this._intentionalDisconnect=!1;let t=++this._generation;this._state!=="reconnecting"&&this._state!=="renegotiating"&&this._setState("connecting");let s=null,n=()=>t!==this._generation||this._intentionalDisconnect,i=()=>{if(n())throw new Error("TransportSession: connect cancelled")},o=async()=>{for(let c of this._connectUrls()){i();try{return await this._connectOnce(c,t,e),!0}catch(d){s=d instanceof Error?d:new Error(String(d)),this._cleanupSocket()}}return!1},a=this._resolveConnection?iV:1;for(let c=0;c<a;c++)if(c>0&&(await $7(oV),i()),await o())return;if(this._resolveConnection)for(let c=0;c<aV;c++){this._setState("reconnecting"),await $7(q7[Math.min(c,q7.length-1)]),i();try{let d=await this._resolveConnection();i(),this.setAuth({jwt:d.jwt??this._options.jwt,authProvider:this._options.authProvider,orgId:this._options.orgId}),this.setConnection({url:d.url,sessionId:d.sessionId,iceServers:d.iceServers??this._options.iceServers})}catch(d){if(n())throw new Error("TransportSession: connect cancelled");s=d instanceof Error?d:new Error(String(d));continue}if(await o())return}throw this._setState("failed"),s??new Error("TransportSession: connect failed")}disconnect(){if(this._generation+=1,this._intentionalDisconnect=!0,this._stopMediaMonitor(),this._reconnectTimer&&(clearTimeout(this._reconnectTimer),this._reconnectTimer=null),this._clearReconnectBudgetReset(),this._reconnectAttempts=0,this._audioProducer){this._send({type:"stopAudio"});try{this._audioProducer.close()}catch{}this._audioProducer=null}if(this._videoProducer){this._send({type:"stopVideo"});try{this._videoProducer.close()}catch{}this._videoProducer=null}for(let e of this._consumers.values())try{e.close()}catch{}if(this._consumers.clear(),this._sendTransport){try{this._sendTransport.close()}catch{}this._sendTransport=null}if(this._recvTransport){this._clearRecvWatchdog();try{this._recvTransport.close()}catch{}this._recvTransport=null}if(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._ws){let e=this._ws;this._ws=null;try{e.close(1e3,"intentional disconnect")}catch{}}this._tracks.clear(),this._tracksByName.clear(),this._setState("disconnected"),this._liveReached=!1,this._setPhase("ended"),this._emitter.emit("disconnected")}on(e,t){return this._emitter.on(e,t),()=>{this._emitter.off(e,t)}}sendInput(e,t){this._send({type:"input",data:e,sequence:t})}sendDocSync(e,t){!this._ws||this._ws.readyState!==WebSocket.OPEN||this._ws.send(dV(e,t))}onDocSync(e,t){let s=(n,i)=>{n===e&&t(i)};return this.on("docSync",s)}onDocSyncReady(e){return this.on("docSyncReady",e)}_emitDocSyncFrame(e){let t=uV(e);if(!t){console.warn("[urun] doc-sync: unknown/malformed typed-v1 frame; dropped");return}this._emitter.emit("docSync",t.docKey,t.payload)}async addTrack(e){if(!this._sendTransport)throw new Error("TransportSession: send transport not ready");this._audioProducer=await this._sendTransport.produce({track:e,codecOptions:{opusStereo:!1,opusDtx:!1,opusFec:!1}})}removeTrack(){this._audioProducer&&(this._send({type:"stopAudio"}),this._audioProducer.close(),this._audioProducer=null)}async addVideoTrack(e){if(!this._sendTransport)throw new Error("TransportSession: send transport not ready");this._videoProducer=await this._sendTransport.produce({track:e})}stopVideo(){this._videoProducer&&(this._send({type:"stopVideo"}),this._videoProducer.close(),this._videoProducer=null)}requestDiagnostics(){this._send({type:"diagnostics"})}seekStream(e,t){this._send({type:"stream.seek",stream:e,target:t})}subscribeStream(e){this._pendingStreamSubscribes.add(e),this._sendStreamSubscribe(e)}unsubscribeStream(e){this._pendingStreamSubscribes.delete(e),this._send({t:"stream.unsubscribe",name:e,consumerId:this.consumerId})}_sendStreamSubscribe(e){this._send({t:"stream.subscribe",name:e,consumerId:this.consumerId})}_flushStreamSubscribes(){for(let e of this._pendingStreamSubscribes)this._sendStreamSubscribe(e)}async _handleMessage(e){switch(e.type){case"routerRtpCapabilities":await this._onRouterCapabilities(e.rtpCapabilities);break;case"createWebRtcTransport":await this._onCreateRecvTransport(e);break;case"createSendTransport":await this._onCreateSendTransport(e);break;case"consume":await this._onConsume(e);break;case"produced":if(this._pendingProduce){let t=this._pendingProduce;this._pendingProduce=null,clearTimeout(t.timeoutId),t.resolve(e.id)}break;case"started":this._emitter.emit("started");break;case"status":this._onStatus(e);break}}_onStatus(e){let t=e.request_id??e.requestId;if(t&&(this._requestId=t),this._liveReached)return;let s=typeof e.status=="string"?e.status:void 0,n=(s&&fV[s])??"provisioning",i=e.queue_position??e.queuePosition,o=e.queue_depth??e.queueDepth,a=typeof i=="number"&&typeof o=="number";if(n==="error"){this._setPhase("error",{error:{reason:s??"admission failed",code:s}});return}if(n==="ended"){this._setPhase("ended");return}if(n==="queued"){this._setPhase("queued",a?{queue:{position:i,depth:o}}:void 0);return}if(n==="connecting"){this._setPhase("connecting");return}this._setPhase("provisioning")}async _onRouterCapabilities(e){Sx()&&await U7();let t=M7(),s=new V7.Device(t?{handlerName:t}:void 0);await s.load({routerRtpCapabilities:e}),this._device=s,this._send({type:"rtpCapabilities",rtpCapabilities:s.rtpCapabilities})}async _onCreateRecvTransport(e){this._device&&(this._recvTransportMsg=e,this._recvTcpFailoverDone=!1,this._buildRecvTransport(e,!1))}_buildRecvTransport(e,t){if(!this._device)return;let s=e.iceCandidates,n=t?s.filter(a=>a.protocol==="tcp"):s,i=this._device.createRecvTransport({id:e.id,iceParameters:e.iceParameters,iceCandidates:n,dtlsParameters:e.dtlsParameters,iceServers:this._options.iceServers??z7}),o=this._generation;i.on("connect",({dtlsParameters:a},c,d)=>{try{this._send({type:"connectTransport",transportId:i.id,dtlsParameters:a}),c()}catch(u){d(u)}}),i.on("connectionstatechange",a=>{if(o===this._generation){if(a==="connected"){this._clearRecvWatchdog();return}if(!(this._intentionalDisconnect&&a==="closed")&&(a==="failed"||a==="disconnected")){if(!t&&!this._recvTcpFailoverDone){this._failoverRecvToTcp(`state:${a}`);return}a==="failed"&&this._emitError(new Error(`media transport ${a}`),a)}}}),this._recvTransport=i,this._clearRecvWatchdog(),t||(this._recvConnectWatchdog=setTimeout(()=>{o===this._generation&&this._recvTransport?.connectionState!=="connected"&&this._failoverRecvToTcp("timeout")},lV))}_clearRecvWatchdog(){this._recvConnectWatchdog&&(clearTimeout(this._recvConnectWatchdog),this._recvConnectWatchdog=null)}_failoverRecvToTcp(e){if(this._recvTcpFailoverDone||this._intentionalDisconnect)return;let t=this._recvTransportMsg;if(!this._device||!t)return;if(!t.iceCandidates.some(n=>n.protocol==="tcp")){this._emitter.emit("error",new Error(`media transport failed (${e}); no TCP candidate`));return}if(this._recvTcpFailoverDone=!0,this._clearRecvWatchdog(),this._recvTransport)try{this._recvTransport.close()}catch{}this._buildRecvTransport(t,!0),this._lastConsumeMsg&&this._onConsume(this._lastConsumeMsg)}async _onCreateSendTransport(e){if(!this._device)return;let t=this._device.createSendTransport({id:e.id,iceParameters:e.iceParameters,iceCandidates:e.iceCandidates,dtlsParameters:e.dtlsParameters,iceServers:this._options.iceServers??z7}),s=this._generation;t.on("connect",({dtlsParameters:n},i,o)=>{try{this._send({type:"connectSendTransport",transportId:t.id,dtlsParameters:n}),i()}catch(a){o(a)}}),t.on("produce",({kind:n,rtpParameters:i},o,a)=>{if(this._pendingProduce){a(new Error("produce already pending"));return}let c=setTimeout(()=>{let d=this._pendingProduce;!d||d.timeoutId!==c||(this._pendingProduce=null,d.reject(new Error("Produce timed out")))},15e3);this._pendingProduce={timeoutId:c,resolve:d=>{o({id:d})},reject:a};try{this._send({type:"produce",kind:n,rtpParameters:i})}catch(d){this._pendingProduce?.timeoutId===c&&(this._pendingProduce=null,clearTimeout(c)),a(d)}}),t.on("connectionstatechange",n=>{s===this._generation&&(this._intentionalDisconnect&&n==="closed"||(n==="failed"||n==="closed")&&this._emitError(new Error(`media send transport ${n}`),n))}),this._sendTransport=t,this._emitter.emit("audioTransportReady")}async _onConsume(e){if(!this._recvTransport)return;this._lastConsumeMsg=e;let t=this._generation,s=await this._recvTransport.consume({id:e.id,producerId:e.producerId,kind:e.kind,rtpParameters:e.rtpParameters});this._consumers.set(s.id,s),this._tracks.set(s.track.id,s.track);let n=e.streamName??e.label;n&&this._tracksByName.set(n,s.track),this._liveReached||this._setPhase("live"),this._emitter.emit("track",s.track),s.track.addEventListener("ended",()=>{t!==this._generation||this._intentionalDisconnect||this._renegotiate()},{once:!0}),this._send({type:"resumeConsumer",consumerId:s.id}),this._startMediaMonitor()}_mediaPollMs(){let e=this._options.mediaLiveness?.pollMs;return e===void 0?sV:e}_mediaStallTimeoutMs(){let e=this._options.mediaLiveness?.stallTimeoutMs;return e===void 0?nV:e}_startMediaMonitor(){let e=this._mediaPollMs();if(e<=0||this._mediaMonitorTimer)return;this._lastInboundTotal=0,this._mediaEverFlowed=!1,this._lastInboundAdvanceAt=Date.now(),this._mediaDeathHandled=!1;let t=this._generation;this._mediaMonitorTimer=setInterval(()=>{t!==this._generation||this._intentionalDisconnect||this._sampleMediaLiveness(t)},e)}_stopMediaMonitor(){this._mediaMonitorTimer&&(clearInterval(this._mediaMonitorTimer),this._mediaMonitorTimer=null)}async _sampleMediaLiveness(e){if(this._consumers.size===0)return;let t=0;for(let n of this._consumers.values())t+=await pV(n);if(e!==this._generation||this._intentionalDisconnect)return;let s=Date.now();if(t>this._lastInboundTotal){this._lastInboundTotal=t,this._lastInboundAdvanceAt=s,t>0&&(this._mediaEverFlowed=!0);return}this._mediaEverFlowed&&(this._mediaDeathHandled||s-this._lastInboundAdvanceAt>=this._mediaStallTimeoutMs()&&(this._mediaDeathHandled=!0,this._renegotiate()))}_renegotiate(){this._intentionalDisconnect||this._reconnectTimer||(this._stopMediaMonitor(),this._setState("renegotiating"),this._attemptReconnect())}_attemptReconnect(e){if(this._intentionalDisconnect||this._reconnectTimer)return;if(this._reconnectAttempts>=F7){this._setState("failed"),this._emitError(new Error(`Failed after ${F7} attempts`));return}let t=H7[Math.min(this._reconnectAttempts,H7.length-1)];this._reconnectAttempts++,this._state!=="renegotiating"&&this._setState("reconnecting"),this._reconnectTimer=setTimeout(async()=>{this._reconnectTimer=null,this._cleanupMedia();try{await this.connect(e??this._lastStartOptions)}catch(s){if(s instanceof Error&&s.message==="TransportSession: connect cancelled")return;this._attemptReconnect(e)}},t)}_connectUrls(){let e=[],t=s=>{if(!s)return;let n=/\/ws\/rtc\/[^/?#]+/.test(s),i=this._sessionId&&!n?`${s}${s.includes("?")?"&":"?"}sessionId=${encodeURIComponent(this._sessionId)}`:s;e.includes(i)||e.push(i)};t(this._options.url);for(let s of this._options.fallbackUrls??[])t(s);return e}_connectOnce(e,t,s){return new Promise((n,i)=>{let o=!1,a=!1,c=null,d=new WebSocket(e);d.binaryType="arraybuffer",this._ws=d;let u=f=>{a||this._ws!==d||t!==this._generation||(a=!0,c&&clearTimeout(c),i(f))};c=setTimeout(()=>{try{d.close()}catch{}u(new Error("TransportSession: connect timed out"))},rV),d.onopen=()=>{a||t!==this._generation||(o=!0,c&&clearTimeout(c),this._multiplexer=new hd(d),d.send(JSON.stringify(this._startMessage(s))),this._emitter.emit("docSyncReady"),this._flushStreamSubscribes(),this._scheduleReconnectBudgetReset(),this._setState("connected"),this._liveReached||this._setPhase("connecting"),this._emitter.emit("connected"),a=!0,n())},d.onerror=()=>{o||u(new Error("WebSocket connection error"))},d.onclose=()=>{if(!(this._ws!==d||t!==this._generation)){if(this._clearReconnectBudgetReset(),!o){u(new Error("WebSocket closed before connecting"));return}c&&clearTimeout(c),this._setState("disconnected"),this._intentionalDisconnect||(this._emitter.emit("disconnected"),this._attemptReconnect(s))}},d.onmessage=f=>{if(!(this._ws!==d||t!==this._generation)){if(typeof f.data=="string")try{this._handleMessage(JSON.parse(f.data))}catch(h){this._emitter.emit("error",h instanceof Error?h:new Error(String(h)))}else if(f.data instanceof ArrayBuffer)this._emitDocSyncFrame(new Uint8Array(f.data));else if(ArrayBuffer.isView(f.data)){let h=f.data;this._emitDocSyncFrame(new Uint8Array(h.buffer,h.byteOffset,h.byteLength))}}}})}_startMessage(e){let t={type:"start",docFraming:"typed-v1",video:e?.video??{width:854,height:480,frameRate:16}};return e?.prompt&&(t.prompt=e.prompt),e?.cameraControl&&(t.camera_control=e.cameraControl),e?.args&&(t.args=e.args),e?.app&&(t.app=e.app),e?.functionName&&(t.function=e.functionName),e?.role&&(t.role=e.role),this._options.orgId&&(t.orgId=this._options.orgId),this._options.jwt&&(t.jwt=this._options.jwt),this._options.authProvider&&(t.authProvider=this._options.authProvider),t}_cleanupSocket(){if(this._clearReconnectBudgetReset(),!this._ws)return;let e=this._ws;this._ws=null;try{e.close()}catch{}}_scheduleReconnectBudgetReset(){this._clearReconnectBudgetReset(),this._reconnectAttempts!==0&&(this._stableResetTimer=setTimeout(()=>{this._stableResetTimer=null,this._reconnectAttempts=0},cV))}_clearReconnectBudgetReset(){this._stableResetTimer&&(clearTimeout(this._stableResetTimer),this._stableResetTimer=null)}_cleanupMedia(){this._stopMediaMonitor();for(let e of this._consumers.values())try{e.close()}catch{}if(this._consumers.clear(),this._audioProducer){try{this._audioProducer.close()}catch{}this._audioProducer=null}if(this._clearRecvWatchdog(),this._recvTransport){try{this._recvTransport.close()}catch{}this._recvTransport=null}if(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(e){!this._ws||this._ws.readyState!==WebSocket.OPEN||this._ws.send(JSON.stringify(e))}_setState(e){this._state!==e&&(this._state=e,this._emitter.emit("stateChange",e))}_setPhase(e,t){e==="live"&&(this._liveReached=!0);let s={name:e};t?.queue&&(s.queue=t.queue),this._requestId&&(s.requestId=this._requestId),this._sessionId&&(s.sessionId=this._sessionId),t?.error&&(s.error=t.error),this._phase=s,this._emitter.emit("phase",s)}_emitError(e,t){this._setPhase("error",{error:{reason:e.message,code:t}}),this._emitter.emit("error",e)}};function $7(r){return new Promise(e=>setTimeout(e,r))}function hV(){return _x()}async function pV(r){if(typeof r.getStats!="function")return 0;let e;try{e=await r.getStats()}catch{return 0}let t=0,s=n=>{if(!n||typeof n!="object")return;let i=n;if(i.type==="inbound-rtp"){let o=typeof i.bytesReceived=="number"?i.bytesReceived:0,a=typeof i.packetsReceived=="number"?i.packetsReceived:0;t+=o+a}};if(e instanceof Map)for(let n of e.values())s(n);else if(Array.isArray(e))for(let n of e)s(n);else e&&typeof e.forEach=="function"&&e.forEach(s);return t}function mV(r){if(!r||typeof r!="object")return;let e=r.epoch,t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?t:void 0}var gV="session-api.prod.cloud.urun.sh",yV=["https://session-api.use2.prod.cloud.urun.sh","https://session-api.usw2.prod.cloud.urun.sh"];function Ex(r){return r.trim().replace(/\/+$/,"")}function G7(r,e){let t=[],s=n=>{if(!n)return;let i=Ex(n);i&&!t.includes(i)&&t.push(i)};s(r);for(let n of e??[])s(n);for(let n of TV(r))s(n);return t}var xV=120,bV=1e3,vV=3;function wV(r){if(!r)return null;try{let e=new URL(r),t=e.pathname.replace(/\/api\/sessions\/create\/?$/,"");return Ex(`${e.origin}${t}`)}catch{return null}}async function X7(r){let e=G7(r.baseUrl,r.fallbackUrls),t=null,s=e.length>1;for(let n of e)try{return await SV(n,r,{pollAttempts:xV,retryAfterLimitMs:s?bV:void 0})}catch(i){if(t=i instanceof Error?i:new Error(String(i)),t instanceof cd)throw t}throw t??new Error("[urun] session allocation failed")}async function SV(r,e,t){let s,n,i,o=r,a=0,c=new Set;for(let d=0;d<t.pollAttempts;d++){n=i??await lE(e),i=void 0;let u=s?await fetch(`${o}/api/session-requests/${encodeURIComponent(s)}`,{headers:fE(e,n)}):await fetch(`${o}/api/sessions/create`,{method:"POST",redirect:"manual",headers:{...fE(e,n),"Content-Type":"application/json","Idempotency-Key":e.idempotencyKey},body:JSON.stringify(_V(e))});if(!s&&(u.status===307||u.status===308)){let v=wV(u.headers.get("location"));if(v&&v!==o&&a<vV){a+=1,o=v;continue}throw new Error(`[urun] session create redirected from ${o} without a usable target`)}let f=await J7(u);if(u.ok&&(f.status==="allocated"||!f.status&&!!f.session_id)&&!!f.session_id){let v=f.session_id;if(!f.ws_url)throw new cd(`[urun] gateway allocated session ${v} without ws_url`);if(!Q7(f.ws_url))throw new cd(`[urun] gateway allocated session ${v} with non-absolute ws_url`);return{baseUrl:o,sessionId:v,wsUrl:f.ws_url,response:f}}if(u.status===202||f.status==="pending"||f.status==="queued"||f.queued){if(s=f.request_id||s,!s)throw new Error("[urun] gateway queued session without request_id");await CV(EV(u,f,t.retryAfterLimitMs));continue}if((u.status===401||u.status===403)&&e.getAccessToken){let v=n??"";c.add(v);let S=await lE(e,{forceRefresh:!0,reason:"unauthorized"});if(S&&!c.has(S)){i=S,s=void 0;continue}}let y=f.error_message||f.error_code||`HTTP ${u.status}`;throw new Error(`[urun] session allocation failed at ${o}: ${y}`)}throw new Error(`[urun] timed out waiting for session allocation at ${o}`)}function fE(r,e){let t={"X-Tenant-Id":r.orgId,"X-Auth-Provider":r.authProvider||"default","X-User-Id":"anonymous"};return e&&(t.Authorization=`Bearer ${e}`),t}async function lE(r,e){return r.getAccessToken?await r.getAccessToken(e)??void 0:r.jwt}function _V(r){return{app:r.app,function:r.functionName,gpus:1,idempotency_key:r.idempotencyKey}}async function Y7(r){let e=G7(r.baseUrl,r.fallbackUrls),t=null;for(let s of e)try{let n={baseUrl:s,app:"",functionName:"",orgId:r.orgId,jwt:r.jwt,getAccessToken:r.getAccessToken,authProvider:r.authProvider,idempotencyKey:""},i=await lE(n),o=await fetch(`${Ex(s)}/api/sessions/${encodeURIComponent(r.sessionId)}/viewer-connect`,{headers:fE(n,i)});if(!o.ok)throw new Error(`[urun] viewer-connect for ${r.sessionId} failed: HTTP ${o.status}`);let a=await J7(o);if(!a.ws_url||!Q7(a.ws_url))throw new cd(`[urun] viewer-connect returned no usable ws_url for ${r.sessionId}`);return{baseUrl:Ex(s),sessionId:r.sessionId,wsUrl:a.ws_url,response:a}}catch(n){if(t=n instanceof Error?n:new Error(String(n)),t instanceof cd)throw t}throw t??new Error("[urun] viewer-connect failed")}async function J7(r){try{let e=await r.json();return e&&typeof e=="object"?e:{}}catch{return{}}}function EV(r,e,t){let s=Number(r.headers.get("Retry-After")||""),n=Number(e.retry_after_seconds??s),i=t??1e4;return Number.isFinite(n)&&n>0?Math.min(n*1e3,i):1e3}function CV(r){return new Promise(e=>setTimeout(e,r))}var cd=class extends Error{};function Q7(r){try{let e=new URL(r);return e.protocol==="ws:"||e.protocol==="wss:"}catch{return!1}}function TV(r){try{return new URL(r).hostname!==gV?[]:yV}catch{return[]}}var hf=Ge(require("yjs")),Z7=Symbol("urun:doc:remote"),AV=Symbol("urun:doc:local");function dd(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}var Cx="$bytes";function IV(r){return r instanceof Uint8Array||r instanceof ArrayBuffer}function RV(r){if(!dd(r))return!1;let e=Object.keys(r);return e.length===1&&e[0]===Cx&&typeof r[Cx]=="string"}function kV(r){return r instanceof ArrayBuffer?new Uint8Array(r):r}function PV(r){if(typeof Buffer<"u")return Buffer.from(r).toString("base64");let e="";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return btoa(e)}function BV(r){if(typeof Buffer<"u")return new Uint8Array(Buffer.from(r,"base64"));let e=atob(r),t=new Uint8Array(e.length);for(let s=0;s<e.length;s++)t[s]=e.charCodeAt(s);return t}function hE(r){if(IV(r))return{[Cx]:PV(kV(r))};if(Array.isArray(r))return r.map(hE);if(dd(r)){let e={};for(let[t,s]of Object.entries(r))e[t]=hE(s);return e}return r}function t0(r){if(RV(r))return BV(r[Cx]);if(Array.isArray(r))return r.map(t0);if(dd(r)){let e={};for(let[t,s]of Object.entries(r))e[t]=t0(s);return e}return r}function pE(r,e){let t={...r};for(let s of Object.keys(e)){let n=e[s],i=t[s];dd(n)&&dd(i)?t[s]=pE(i,n):t[s]=n}return t}var tN=Symbol("urun:doc:path-absent");function NV(r,e){let t=e.split("."),s=r;for(let n of t){if(s===null||typeof s!="object"||!(n in s))return tN;s=s[n]}return s}function eN(r){return r===void 0?r:JSON.parse(JSON.stringify(r))}var Tx=class{_doc=new hf.Doc;_root=this._doc.getMap("session");_listeners=new Set;_key;_sessionId;_transport;_transportUnsubs=[];_synced;_pendingPatches=[];_texts=new Map;_observer=()=>this.notify();_updateHandler=(e,t)=>{t!==Z7&&this._transport?.sendDocSync(this._key,e)};constructor(e,t,s){this._key=e,this._sessionId=t,this._transport=s??null,this._synced=this._transport===null,this._root.observeDeep(this._observer),this._doc.on("update",this._updateHandler),this._transport&&(this._transportUnsubs.push(this._transport.onDocSync(this._key,n=>this.applyRemote(n)),this._transport.onDocSyncReady(()=>this.sendHello())),this._transport.isOpen&&this.sendHello())}setSessionId(e){this._sessionId=e}set(e){if(e=hE(e),!this._synced){this._pendingPatches.push(eN(e)),this.notify();return}this.applyPatch(e)}get(e,t){let s=this.snapshot();if(!e)return t0(s);let n=NV(s,e);return n===tN?t:t0(n)}on(e,t){return this._listeners.add(t),()=>this._listeners.delete(t)}text(e){let t=this._texts.get(e);return t||(t=new mE(this._doc.getText(`text:${e}`)),this._texts.set(e,t)),t}dispose(){this._root.unobserveDeep(this._observer),this._doc.off("update",this._updateHandler);for(let e of this._transportUnsubs)e();this._transportUnsubs=[],this._transport=null,this._listeners.clear();for(let e of this._texts.values())e.dispose();this._texts.clear(),this._doc.destroy()}sendHello(){this._transport&&this._transport.sendDocSync(this._key,hf.encodeStateAsUpdate(this._doc))}applyRemote(e){if(hf.applyUpdate(this._doc,e,Z7),!this._synced){this._synced=!0;let t=this._pendingPatches.splice(0);for(let s of t)this.applyPatch(s)}}applyPatch(e){this._doc.transact(()=>{let t=this._root.toJSON();for(let[s,n]of Object.entries(e)){let i=t[s],o=dd(n)&&dd(i)?pE(i,n):eN(n);JSON.stringify(o)!==JSON.stringify(i)&&this._root.set(s,o)}},AV)}snapshot(){let e=this._root.toJSON();for(let t of this._pendingPatches)e=pE(e,t);return e}notify(){let e=t0(this.snapshot());for(let t of this._listeners)t(e)}},mE=class{constructor(e){this._ytext=e;this._observer=t=>{for(let s of t.delta)if(typeof s.insert=="string"&&s.insert.length>0){let n=s.insert;for(let i of this._delta)i(n)}},this._ytext.observe(this._observer)}_ytext;_delta=new Set;_observer;append(e){e.length!==0&&this._ytext.insert(this._ytext.length,e)}toString(){return this._ytext.toString()}get length(){return this._ytext.length}on(e,t){return this._delta.add(t),()=>this._delta.delete(t)}dispose(){this._ytext.unobserve(this._observer),this._delta.clear()}};var yi=class extends Error{requestId;code;constructor(e,t){super(e),this.name="RequestError",this.requestId=t?.requestId,this.code=t?.code,t?.cause!==void 0&&(this.cause=t.cause),Object.setPrototypeOf(this,new.target.prototype)}},pf=class extends yi{timeoutMs;constructor(e,t){super(`[urun] request timed out after ${e}ms`,{requestId:t}),this.name="RequestTimeoutError",this.timeoutMs=e,Object.setPrototypeOf(this,new.target.prototype)}},yo=class extends yi{constructor(e){super("[urun] request aborted",{requestId:e}),this.name="RequestAbortError",Object.setPrototypeOf(this,new.target.prototype)}},mf=class extends yi{constructor(e){super("[urun] request cancelled: session disconnected",{requestId:e}),this.name="RequestCancelledError",Object.setPrototypeOf(this,new.target.prototype)}};var OV=new Set,LV="rpc",DV="llm",MV="llm-resp";function UV(r){return`${MV}:${r}`}function gE(){return _x()}function jV(r){if(r&&typeof r=="object"){let e=r.error;if(e&&typeof e=="object"){let{message:t,code:s}=e;return{message:typeof t=="string"?t:JSON.stringify(e),code:typeof s=="string"?s:void 0}}if(typeof e=="string")return{message:e}}return{message:typeof r=="string"?r:JSON.stringify(r)}}function HV(r,e,t,s,n,i,o,a){let c=[],d=null,u=!1,f=null,h=!1,y,v,S=new Promise((D,F)=>{y=D,v=F});S.catch(()=>{});let C=i(),O=null,K=null,z=!0,Q=()=>{z=!1,O?.(),O=null,K?.(),K=null,o?.removeEventListener("abort",Y),C.dispose(),h&&r.set({requests:{[e]:null}})},oe=()=>{if(d){if(c.length>0){let D=d;d=null,D.resolve({value:c.shift(),done:!1})}else if(f!==null){let D=d;d=null,D.reject(f)}else if(u){let D=d;d=null,D.resolve({value:void 0,done:!0})}}},se=D=>{u||(c.push(D),oe())},we=D=>{u||(f=D,u=!0,v(D),Q(),oe())},me=D=>{u||(u=!0,y(D),Q(),oe())},Y=()=>we(new yo(e)),Ze=D=>{if(!(u||!D||typeof D!="object"))switch(D.t){case"delta":typeof D.delta=="string"&&se(D.delta);break;case"response":me(D.body);break;case"error":{let{message:F,code:le}=jV(D.body);we(new yi(F,{requestId:e,code:D.code??le}));break}}},Tt=()=>{let D=C.messages()[Symbol.asyncIterator]();O=()=>{D.return?.(void 0)};let F=()=>{z&&D.next().then(le=>{if(z){if(le.done){u||me(void 0);return}Ze(le.value),F()}},le=>{z&&we(le)})};F()},Fe=()=>{if(!h){if(h=!0,o){if(o.aborted){we(new yo(e));return}o.addEventListener("abort",Y,{once:!0})}K=a?.(D=>we(D))??null,Tt(),r.set({requests:{[e]:{payload:t,consumer_id:s,stream:n}}})}};return{deltas:{[Symbol.asyncIterator](){return{next(){if(Fe(),c.length>0)return Promise.resolve({value:c.shift(),done:!1});if(f!==null){let D=f;return f=null,Promise.reject(D)}return u?Promise.resolve({value:void 0,done:!0}):new Promise((D,F)=>{d={resolve:D,reject:F}})},return(){return u||(u=!0,y(void 0),Q()),Promise.resolve({value:void 0,done:!0})},throw(D){return u||(u=!0,v(D),Q()),Promise.reject(D)}}}},body:S,start:Fe}}function FV(r,e){return[`streams/${r}/${e}`,`streams/${r}/*`]}var yE=class{constructor(e,t,s){this._name=e;this._transport=t;this._laneDoc=s;this._track=this._transport.getTrackByName(this._name)??null,this._unsubscribeTransport=this._transport.on("track",()=>{let n=this._transport.getTrackByName(this._name)??null;n!==this._track&&this._setTrack(n)})}_name;_transport;_laneDoc;_track=null;_handlers=new Map;_unsubscribeTransport=null;_subscribed=!1;_messageConsumers=new Set;_laneUnsubs=[];_laneSeen=new Map;_disposed=!1;messages(){this._ensureSubscribed();let e=this;return{[Symbol.asyncIterator](){let t=[],s=null,n=!1,i={push(a){if(!n)if(s){let c=s;s=null,c({value:a,done:!1})}else t.push(a)},end(){if(n=!0,s){let a=s;s=null,a({value:void 0,done:!0})}}};e._messageConsumers.add(i);let o=()=>{n=!0,e._messageConsumers.delete(i)};return{next(){return t.length>0?Promise.resolve({value:t.shift(),done:!1}):n?Promise.resolve({value:void 0,done:!0}):new Promise(a=>{s=a})},return(){return o(),Promise.resolve({value:void 0,done:!0})}}}}}_ensureSubscribed(){if(!(this._subscribed||this._disposed)&&(this._subscribed=!0,this._transport.subscribeStream(this._name),!!this._laneDoc))for(let e of FV(this._name,this._transport.consumerId)){let t=this._laneDoc(e);this._laneSeen.set(e,0);let s=n=>this._drainLane(e,n);s(t.get()),this._laneUnsubs.push(t.on("change",s))}}_drainLane(e,t){let s=t.messages;if(!Array.isArray(s))return;let n=this._laneSeen.get(e)??0;for(;n<s.length;n++){let i=s[n];for(let o of this._messageConsumers)o.push(i)}this._laneSeen.set(e,n)}get track(){let e=this._transport.getTrackByName(this._name)??this._track;return e!==this._track&&this._setTrack(e),this._track}async attach(e){await this._transport.addTrack(e)}async attachVideo(e){await this._transport.addVideoTrack(e)}async detach(){this._transport.removeTrack()}async detachVideo(){this._transport.stopVideo()}async seek(e){if(e!=="live"&&(!Number.isFinite(e)||e<0))throw new Error('[urun] stream.seek target must be "live" or a non-negative number of seconds');this._transport.seekStream(this._name,e)}on(e,t){let s=this._handlers.get(e);return s||(s=new Set,this._handlers.set(e,s)),s.add(t),()=>{s?.delete(t),s?.size===0&&this._handlers.delete(e)}}dispose(){this._disposed=!0,this._unsubscribeTransport?.(),this._unsubscribeTransport=null,this._handlers.clear(),this._subscribed&&this._transport.unsubscribeStream(this._name);for(let e of this._laneUnsubs)e();this._laneUnsubs=[];for(let e of this._messageConsumers)e.end();this._messageConsumers.clear()}_setTrack(e){this._track=e,e&&e.addEventListener("ended",()=>{this._track===e&&this._setTrack(null)},{once:!0});let t=this._handlers.get("track");if(t)for(let s of t)s(e)}},gf=class r{_sessionId;_multiplexer;_transport;_docs=new Map;_streams=new Map;_activeRequests=new Set;constructor(e,t,s){this._sessionId=e,this._multiplexer=t,this._transport=s,this._wireControlDocIncarnation()}_wireControlDocIncarnation(){let e=this.doc("control");this._transport.applyControlDocState(e.get()),e.on("change",t=>{this._transport.applyControlDocState(t)})}static async attach(e,t){let s=await Y7({baseUrl:t.baseUrl,fallbackUrls:t.fallbackUrls,sessionId:e,orgId:t.orgId,jwt:t.jwt,getAccessToken:t.getAccessToken,authProvider:t.authProvider}),n=t.getAccessToken?await t.getAccessToken()??void 0:t.jwt,i=new pd,o=new lf({url:s.wsUrl,orgId:t.orgId,jwt:n,authProvider:t.authProvider,sessionId:e,iceServers:s.response.ice_servers}),a=new r(e,i,o);return o.on("connected",()=>{o.multiplexer&&i.setTarget(o.multiplexer)}),o.setConnection({url:s.wsUrl,sessionId:e,iceServers:s.response.ice_servers}),await o.connect({role:"viewer"}),a}get id(){return this._sessionId}get phase(){return this._transport.phase}onPhase(e){return e(this._transport.phase),this._transport.on("phase",e)}setSessionId(e){if(e===this._sessionId)return;this._multiplexer.rewriteSessionChannels?.call(this._multiplexer,this._sessionId,e),this._sessionId=e;for(let s of this._docs.values())s.setSessionId(e)}stream(e){let t=this._streams.get(e);return t||(t=new yE(e,this._transport,s=>this.doc(s)),this._streams.set(e,t)),t}doc(e){let t=this._docs.get(e);return t||(t=new Tx(e,this._sessionId,OV.has(e)?null:this._transport),this._docs.set(e,t)),t}sendImage(e){this.doc("control").set({desired:{reference_image:{value:e}}})}request(e,t={}){let s=this.doc(LV),n=gE();return new Promise((i,o)=>{let a=!1,c=null,d=null,u=null,f=()=>{d&&(clearTimeout(d),d=null),c&&(c(),c=null),u&&(this._activeRequests.delete(u),u=null),t.signal?.removeEventListener("abort",y),s.set({requests:{[n]:null}})},h=S=>{a||(a=!0,f(),S())},y=()=>h(()=>o(new yo(n)));if(t.signal){if(t.signal.aborted){a=!0,o(new yo(n));return}t.signal.addEventListener("abort",y,{once:!0})}let v=S=>{let O=S.responses?.[n];if(O==null)return;let K=O;if(K.error!==void 0&&K.error!==null){let z=typeof K.error=="string"?K.error:JSON.stringify(K.error);h(()=>o(new yi(z,{requestId:n,code:K.code})))}else h(()=>i(K.result))};c=s.on("change",v),u=S=>h(()=>o(S)),this._activeRequests.add(u),typeof t.timeout=="number"&&t.timeout>=0&&(d=setTimeout(()=>h(()=>o(new pf(t.timeout,n))),t.timeout)),s.set({requests:{[n]:{payload:e}}}),v(s.get())})}_consumeResponse(e,t,s,n){let i=this.doc(DV);return HV(i,e,t,this._transport.consumerId,s,()=>this.stream(UV(e)),n,o=>(this._activeRequests.add(o),()=>this._activeRequests.delete(o)))}requestStream(e,t={}){let s=gE();return this._consumeResponse(s,e,!0,t.signal).deltas}complete(e,t={}){let s=gE(),n=this._consumeResponse(s,e,!1,t.signal);return n.start(),n.body}disconnect(){let e=Array.from(this._activeRequests);this._activeRequests.clear();for(let t of e)try{t(new mf)}catch{}for(let t of this._docs.values())t.dispose();this._docs.clear();for(let t of this._streams.values())t.dispose();this._streams.clear(),this._transport.disconnect()}};var qV=new Set(["then","catch","finally","toJSON",Symbol.toPrimitive]);function rN(r,e){return new Proxy({},{get(t,s){if(!(qV.has(s)||typeof s!="string"))return n=>{let i=n??{},o=()=>`s_${Date.now()}_${Math.random().toString(36).slice(2)}`,a=o(),c=new pd,d=new lf({url:"",orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionId:a}),u=new gf(a,c,d),f=async h=>{let y=await X7({baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,app:r,functionName:s,orgId:e.orgId,jwt:e.jwt,getAccessToken:e.getAccessToken,authProvider:e.authProvider,idempotencyKey:h}),v=e.getAccessToken?await e.getAccessToken()??void 0:e.jwt;return u.setSessionId(y.sessionId),{url:y.wsUrl,sessionId:y.sessionId,jwt:v,iceServers:y.response.ice_servers}};return d.setConnectionResolver(()=>f(o())),d.on("connected",()=>{d.multiplexer&&c.setTarget(d.multiplexer)}),(async()=>{let h=await f(a);d.setAuth({jwt:h.jwt,authProvider:e.authProvider,orgId:e.orgId}),d.setConnection({url:h.url,sessionId:h.sessionId,iceServers:h.iceServers}),await d.connect({app:r,functionName:s,args:i})})().catch(h=>{console.error(`[urun] Failed to connect session for ${s}:`,h)}),u}}})}var sN=3e4,nN="stream:",xE=class{_ws;_multiplexer;_pendingRpc=new Map;_rpcId=0;constructor(e,t){this._ws=e,this._multiplexer=t,this._ws.addEventListener("message",s=>{let n;try{n=JSON.parse(typeof s.data=="string"?s.data:"")}catch{return}if(n.rpcId&&this._pendingRpc.has(n.rpcId)){let i=this._pendingRpc.get(n.rpcId);this._pendingRpc.delete(n.rpcId),clearTimeout(i.timer),n.error?i.reject(new Error(n.error)):i.resolve(n.result)}})}async get(e){return this._sendRpc("store.get",{key:e})}async has(e){return await this._sendRpc("store.has",{key:e})}on(e,t){let s=`${nN}${e}`;return this._multiplexer.on(s,n=>{t(n)})}emit(e,t){let s=`${nN}${e}`,n=typeof t=="object"&&t!==null&&!Array.isArray(t)?t:{data:t};this._multiplexer.emit(s,n)}_getInternals(){return{multiplexer:this._multiplexer,ws:this._ws}}_sendRpc(e,t){return new Promise((s,n)=>{if(!this._ws||this._ws.readyState!==WebSocket.OPEN){n(new Error("WebSocket not open"));return}let i=String(++this._rpcId),o=setTimeout(()=>{this._pendingRpc.has(i)&&(this._pendingRpc.delete(i),n(new Error(`RPC request "${e}" timed out after ${sN}ms`)))},sN);this._pendingRpc.set(i,{resolve:s,reject:n,timer:o}),this._ws.send(JSON.stringify({rpcId:i,type:e,...t}))})}};function iN(r){let s=`${r.baseUrl.replace(/\/$/,"").replace(/^http/,"ws")}/store/${encodeURIComponent(r.orgId)}`,n=new WebSocket(s);(r.jwt||r.apiKey)&&n.addEventListener("open",()=>{n.send(JSON.stringify({type:"auth",orgId:r.orgId,jwt:r.jwt,authProvider:r.authProvider,apiKey:r.apiKey}))});let i=new hd(n);return new xE(n,i)}var zV='video/mp4; codecs="avc1.42E01E"';function oN(r,e){let t=e?.codec??zV,s=document.createElement("video");s.muted=!0,s.playsInline=!0;let n=new MediaSource,i=URL.createObjectURL(n);s.src=i,n.addEventListener("sourceopen",()=>{let h;try{h=n.addSourceBuffer(t)}catch(C){throw C instanceof DOMException&&C.name==="NotSupportedError"?new Error(`Codec not supported: "${t}". Ensure the codec string matches the fMP4 container format. Common values: video/mp4; codecs="avc1.42E01E" (H.264 Baseline), video/mp4; codecs="avc1.4D401F" (H.264 Main).`):C}let y=r.getReader();function v(){return h.updating?new Promise(C=>{h.addEventListener("updateend",()=>C(),{once:!0})}):Promise.resolve()}async function S(){try{for(;;){let{done:C,value:O}=await y.read();if(C){await v(),n.readyState==="open"&&n.endOfStream();return}await v();try{h.appendBuffer(O)}catch(K){if(K instanceof DOMException&&K.name==="QuotaExceededError"){let z=h.buffered;if(z.length>0){let Q=z.start(z.length-1);h.remove(0,Q),await v(),h.appendBuffer(O)}else throw K}else throw K}}}catch{if(n.readyState==="open")try{n.endOfStream("decode")}catch{}}}S()}),s.play().catch(()=>{});let o=s,a=o.captureStream??o.mozCaptureStream;if(!a)throw new Error("captureStream() is not supported in this browser. videoStream() requires HTMLMediaElement.captureStream() support.");let c=a.call(s),d=c.getTracks(),u=0,f=d.length;if(f===0)s.addEventListener("emptied",()=>{URL.revokeObjectURL(i)},{once:!0});else for(let h of d)h.addEventListener("ended",()=>{u++,u>=f&&URL.revokeObjectURL(i)});return c}0&&(module.exports={App,RequestAbortError,RequestCancelledError,RequestError,RequestTimeoutError,Session,createStore,videoStream});