@urun-sh/core 0.1.41 → 0.1.43
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-PWBUBR5C.mjs +7 -0
- package/dist/index.d.mts +24 -4
- package/dist/index.d.ts +24 -4
- package/dist/index.js +5 -134
- package/dist/index.mjs +1 -1
- package/dist/internal.d.mts +1 -1
- package/dist/internal.d.ts +1 -1
- package/dist/internal.js +5 -134
- package/dist/internal.mjs +1 -1
- package/dist/{transport-CI8aVD2U.d.ts → transport-BWNRIdMX.d.mts} +4 -0
- package/dist/{transport-CI8aVD2U.d.mts → transport-BWNRIdMX.d.ts} +4 -0
- package/package.json +1 -1
- package/dist/chunk-4O3YOYT6.mjs +0 -7
- package/dist/chunk-FNR7JDXN.mjs +0 -1
- package/dist/lib-RR67JYGM.mjs +0 -130
package/dist/index.js
CHANGED
|
@@ -1,136 +1,7 @@
|
|
|
1
|
-
"use strict";var dN=Object.create;var i0=Object.defineProperty;var uN=Object.getOwnPropertyDescriptor;var fN=Object.getOwnPropertyNames;var lN=Object.getPrototypeOf,hN=Object.prototype.hasOwnProperty;var A=(r,e,t)=>()=>{if(t)throw t[0];try{return r&&(e=r(r=0)),e}catch(s){throw t=[s],s}};var se=(r,e)=>()=>{try{return e||r((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}},Cf=(r,e)=>{for(var t in e)i0(r,t,{get:e[t],enumerable:!0})},SE=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of fN(e))!hN.call(r,n)&&n!==t&&i0(r,n,{get:()=>e[n],enumerable:!(s=uN(e,n))||s.enumerable});return r};var Ge=(r,e,t)=>(t=r!=null?dN(lN(r)):{},SE(e||!r||!r.__esModule?i0(t,"default",{value:r,enumerable:!0}):t,r)),Px=r=>SE(i0({},"__esModule",{value:!0}),r);var Bx=se((XV,_E)=>{"use strict";var md=1e3,gd=md*60,yd=gd*60,Ra=yd*24,pN=Ra*7,mN=Ra*365.25;_E.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return gN(r);if(t==="number"&&isFinite(r))return e.long?xN(r):yN(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function gN(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*mN;case"weeks":case"week":case"w":return t*pN;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 yN(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 xN(r){var e=Math.abs(r);return e>=Ra?o0(r,e,Ra,"day"):e>=yd?o0(r,e,yd,"hour"):e>=gd?o0(r,e,gd,"minute"):e>=md?o0(r,e,md,"second"):r+" ms"}function o0(r,e,t,s){var n=e>=t*1.5;return Math.round(r/t)+" "+s+(n?"s":"")}});var Nx=se((YV,EE)=>{"use strict";function bN(r){t.debug=t,t.default=t,t.coerce=c,t.disable=o,t.enable=n,t.enabled=a,t.humanize=Bx(),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,(te,Ee)=>{if(te==="%%")return"%";Q++;let ge=t.formatters[Ee];if(typeof ge=="function"){let Y=C[Q];te=ge.call(O,Y),C.splice(Q,1),Q--}return te}),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}EE.exports=bN});var CE=se((os,a0)=>{"use strict";os.formatArgs=wN;os.save=SN;os.load=_N;os.useColors=vN;os.storage=EN();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 vN(){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 wN(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+a0.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 SN(r){try{r?os.storage.setItem("debug",r):os.storage.removeItem("debug")}catch{}}function _N(){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 EN(){try{return localStorage}catch{}}a0.exports=Nx()(os);var{formatters:CN}=a0.exports;CN.j=function(r){try{return JSON.stringify(r)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var Dx={};Cf(Dx,{createSupportsColor:()=>Lx,default:()=>kN});function Os(r,e=globalThis.Deno?globalThis.Deno.args:d0.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 TN(){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 AN(r){return r===0?!1:{level:r,hasBasic:!0,has256:r>=2,has16m:r>=3}}function IN(r,{streamIsTTY:e,sniffFlags:t=!0}={}){let s=TN();s!==void 0&&(c0=s);let n=t?c0: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(d0.default.platform==="win32"){let o=TE.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 Lx(r,e={}){let t=IN(r,{streamIsTTY:r&&r.isTTY,...e});return AN(t)}var d0,TE,Ox,Jt,c0,RN,kN,Mx=A(()=>{"use strict";d0=Ge(require("process"),1),TE=Ge(require("os"),1),Ox=Ge(require("tty"),1);({env:Jt}=d0.default);Os("no-color")||Os("no-colors")||Os("color=false")||Os("color=never")?c0=0:(Os("color")||Os("colors")||Os("color=true")||Os("color=always"))&&(c0=1);RN={stdout:Lx({isTTY:Ox.default.isatty(1)}),stderr:Lx({isTTY:Ox.default.isatty(2)})},kN=RN});var IE=se((Sr,f0)=>{"use strict";var PN=require("tty"),u0=require("util");Sr.init=UN;Sr.log=LN;Sr.formatArgs=NN;Sr.save=DN;Sr.load=MN;Sr.useColors=BN;Sr.destroy=u0.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=(Mx(),Px(Dx));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 BN(){return"colors"in Sr.inspectOpts?!!Sr.inspectOpts.colors:PN.isatty(process.stderr.fd)}function NN(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(`
|
|
1
|
+
"use strict";var oo=Object.create;var Ot=Object.defineProperty;var ao=Object.getOwnPropertyDescriptor;var co=Object.getOwnPropertyNames;var po=Object.getPrototypeOf,lo=Object.prototype.hasOwnProperty;var uo=(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}},Us=(s,e)=>{for(var t in e)Ot(s,t,{get:e[t],enumerable:!0})},zs=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of co(e))!lo.call(s,n)&&n!==t&&Ot(s,n,{get:()=>e[n],enumerable:!(r=ao(e,n))||r.enumerable});return s};var Se=(s,e,t)=>(t=s!=null?oo(po(s)):{},zs(e||!s||!s.__esModule?Ot(t,"default",{value:s,enumerable:!0}):t,s)),Bs=s=>zs(Ot({},"__esModule",{value:!0}),s);var Ws=C((vp,Vs)=>{"use strict";var $e=1e3,Ue=$e*60,ze=Ue*60,Ee=ze*24,ho=Ee*7,fo=Ee*365.25;Vs.exports=function(s,e){e=e||{};var t=typeof s;if(t==="string"&&s.length>0)return mo(s);if(t==="number"&&isFinite(s))return e.long?_o(s):go(s);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(s))};function mo(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*fo;case"weeks":case"week":case"w":return t*ho;case"days":case"day":case"d":return t*Ee;case"hours":case"hour":case"hrs":case"hr":case"h":return t*ze;case"minutes":case"minute":case"mins":case"min":case"m":return t*Ue;case"seconds":case"second":case"secs":case"sec":case"s":return t*$e;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function go(s){var e=Math.abs(s);return e>=Ee?Math.round(s/Ee)+"d":e>=ze?Math.round(s/ze)+"h":e>=Ue?Math.round(s/Ue)+"m":e>=$e?Math.round(s/$e)+"s":s+"ms"}function _o(s){var e=Math.abs(s);return e>=Ee?At(s,e,Ee,"day"):e>=ze?At(s,e,ze,"hour"):e>=Ue?At(s,e,Ue,"minute"):e>=$e?At(s,e,$e,"second"):s+" ms"}function At(s,e,t,r){var n=e>=t*1.5;return Math.round(s/t)+" "+r+(n?"s":"")}});var xr=C((wp,Hs)=>{"use strict";function vo(s){t.debug=t,t.default=t,t.coerce=c,t.disable=o,t.enable=n,t.enabled=a,t.humanize=Ws(),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,m,f;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,he)=>{if(I==="%%")return"%";P++;let ae=t.formatters[he];if(typeof ae=="function"){let Y=g[P];I=ae.call(_,Y),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:(m!==t.namespaces&&(m=t.namespaces,f=t.enabled(p)),f),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,m=0,f=-1,h=0;for(;u<p.length;)if(m<l.length&&(l[m]===p[u]||l[m]==="*"))l[m]==="*"?(f=m,h=u,m++):(u++,m++);else if(f!==-1)m=f+1,h++,u=h;else return!1;for(;m<l.length&&l[m]==="*";)m++;return m===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}Hs.exports=vo});var Gs=C((H,Nt)=>{"use strict";H.formatArgs=yo;H.save=bo;H.load=So;H.useColors=wo;H.storage=Ro();H.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`."))}})();H.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 wo(){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 yo(s){if(s[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+s[0]+(this.useColors?"%c ":" ")+"+"+Nt.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)}H.log=console.debug||console.log||(()=>{});function bo(s){try{s?H.storage.setItem("debug",s):H.storage.removeItem("debug")}catch{}}function So(){let s;try{s=H.storage.getItem("debug")||H.storage.getItem("DEBUG")}catch{}return!s&&typeof process<"u"&&"env"in process&&(s=process.env.DEBUG),s}function Ro(){try{return localStorage}catch{}}Nt.exports=xr()(H);var{formatters:Co}=Nt.exports;Co.j=function(s){try{return JSON.stringify(s)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var Qs={};Us(Qs,{createSupportsColor:()=>Dr,default:()=>Po});function J(s,e=globalThis.Deno?globalThis.Deno.args:Ft.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 To(){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 Eo(s){return s===0?!1:{level:s,hasBasic:!0,has256:s>=2,has16m:s>=3}}function ko(s,{streamIsTTY:e,sniffFlags:t=!0}={}){let r=To();r!==void 0&&(jt=r);let n=t?jt: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(Ft.default.platform==="win32"){let o=Ks.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 Dr(s,e={}){let t=ko(s,{streamIsTTY:s&&s.isTTY,...e});return Eo(t)}var Ft,Ks,Pr,O,jt,xo,Po,Ys=uo(()=>{"use strict";Ft=Se(require("process"),1),Ks=Se(require("os"),1),Pr=Se(require("tty"),1);({env:O}=Ft.default);J("no-color")||J("no-colors")||J("color=false")||J("color=never")?jt=0:(J("color")||J("colors")||J("color=true")||J("color=always"))&&(jt=1);xo={stdout:Dr({isTTY:Pr.default.isatty(1)}),stderr:Dr({isTTY:Pr.default.isatty(2)})},Po=xo});var Xs=C((F,$t)=>{"use strict";var Do=require("tty"),qt=require("util");F.init=jo;F.log=Oo;F.formatArgs=Lo;F.save=Ao;F.load=No;F.useColors=Io;F.destroy=qt.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=(Ys(),Bs(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 Io(){return"colors"in F.inspectOpts?!!F.inspectOpts.colors:Do.isatty(process.stderr.fd)}function Lo(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(`
|
|
2
2
|
`).join(`
|
|
3
|
-
`+i),
|
|
4
|
-
`)}function
|
|
5
|
-
`).map(e=>e.trim()).join(" ")};AE.O=function(r){return this.inspectOpts.colors=this.useColors,u0.inspect(r,this.inspectOpts)}});var Tf=se((JV,Ux)=>{"use strict";typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?Ux.exports=CE():Ux.exports=IE()});var kE=se(RE=>{"use strict";Object.defineProperty(RE,"__esModule",{value:!0})});var Yr=se(l0=>{"use strict";Object.defineProperty(l0,"__esModule",{value:!0});l0.Logger=void 0;var xd=Tf(),bd="media-client",jx=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}};l0.Logger=jx});var FE=se((eK,Hx)=>{"use strict";var vd=typeof Reflect=="object"?Reflect:null,PE=vd&&typeof vd.apply=="function"?vd.apply:function(e,t,s){return Function.prototype.apply.call(e,t,s)},h0;vd&&typeof vd.ownKeys=="function"?h0=vd.ownKeys:Object.getOwnPropertySymbols?h0=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:h0=function(e){return Object.getOwnPropertyNames(e)};function jN(r){console&&console.warn&&console.warn(r)}var NE=Number.isNaN||function(e){return e!==e};function Ht(){Ht.init.call(this)}Hx.exports=Ht;Hx.exports.once=zN;Ht.EventEmitter=Ht;Ht.prototype._events=void 0;Ht.prototype._eventsCount=0;Ht.prototype._maxListeners=void 0;var BE=10;function p0(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 BE},set:function(r){if(typeof r!="number"||r<0||NE(r))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+r+".");BE=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||NE(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 OE(r){return r._maxListeners===void 0?Ht.defaultMaxListeners:r._maxListeners}Ht.prototype.getMaxListeners=function(){return OE(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")PE(c,this,t);else for(var d=c.length,u=jE(c,d),s=0;s<d;++s)PE(u[s],this,t);return!0};function LE(r,e,t,s){var n,i,o;if(p0(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=OE(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,jN(a)}return r}Ht.prototype.addListener=function(e,t){return LE(this,e,t,!1)};Ht.prototype.on=Ht.prototype.addListener;Ht.prototype.prependListener=function(e,t){return LE(this,e,t,!0)};function HN(){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 DE(r,e,t){var s={fired:!1,wrapFn:void 0,target:r,type:e,listener:t},n=HN.bind(s);return n.listener=t,s.wrapFn=n,n}Ht.prototype.once=function(e,t){return p0(t),this.on(e,DE(this,e,t)),this};Ht.prototype.prependOnceListener=function(e,t){return p0(t),this.prependListener(e,DE(this,e,t)),this};Ht.prototype.removeListener=function(e,t){var s,n,i,o,a;if(p0(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():FN(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 ME(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?qN(n):jE(n,n.length)}Ht.prototype.listeners=function(e){return ME(this,e,!0)};Ht.prototype.rawListeners=function(e){return ME(this,e,!1)};Ht.listenerCount=function(r,e){return typeof r.listenerCount=="function"?r.listenerCount(e):UE.call(r,e)};Ht.prototype.listenerCount=UE;function UE(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?h0(this._events):[]};function jE(r,e){for(var t=new Array(e),s=0;s<e;++s)t[s]=r[s];return t}function FN(r,e){for(;e+1<r.length;e++)r[e]=r[e+1];r.pop()}function qN(r){for(var e=new Array(r.length),t=0;t<e.length;++t)e[t]=r[t].listener||r[t];return e}function zN(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))}HE(r,e,i,{once:!0}),e!=="error"&&$N(r,n,{once:!0})})}function $N(r,e,t){typeof r.on=="function"&&HE(r,"error",e,t)}function HE(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=se(m0=>{"use strict";Object.defineProperty(m0,"__esModule",{value:!0});m0.EnhancedEventEmitter=void 0;var VN=FE(),KN=Yr(),WN=new KN.Logger("EnhancedEventEmitter"),Fx=class extends VN.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){WN.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)}};m0.EnhancedEventEmitter=Fx});var Ls=se(wd=>{"use strict";Object.defineProperty(wd,"__esModule",{value:!0});wd.InvalidStateError=wd.UnsupportedError=void 0;var qx=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=qx;var zx=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=zx});var ka=se(Af=>{"use strict";Object.defineProperty(Af,"__esModule",{value:!0});Af.clone=GN;Af.generateRandomNumber=XN;Af.deepFreeze=qE;function GN(r){if(r!==void 0)return Number.isNaN(r)?NaN:typeof structuredClone=="function"?structuredClone(r):JSON.parse(JSON.stringify(r))}function XN(){return Math.round(Math.random()*1e7)}function qE(r){let e=Reflect.ownKeys(r);for(let t of e){let s=r[t];(s&&typeof s=="object"||typeof s=="function")&&qE(s)}return Object.freeze(r)}});var zE=se(g0=>{"use strict";Object.defineProperty(g0,"__esModule",{value:!0});g0.Logger=void 0;var Sd=Tf(),_d="h264-profile-level-id",$x=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}};g0.Logger=$x});var XE=se(Tr=>{"use strict";Object.defineProperty(Tr,"__esModule",{value:!0});Tr.ProfileLevelId=Tr.Level=Tr.Profile=void 0;Tr.parseProfileLevelId=WE;Tr.profileLevelIdToString=GE;Tr.profileToString=ZN;Tr.levelToString=eO;Tr.parseSdpProfileLevelId=Pa;Tr.isSameProfile=tO;Tr.isSameProfileAndLevel=rO;Tr.generateProfileLevelIdStringForAnswer=sO;Tr.supportedLevel=nO;var YN=zE(),rn=new YN.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 JN=new Ed(zt.ConstrainedBaseline,De.L3_1),en=class{mask;masked_value;constructor(e){this.mask=~VE("x",e),this.masked_value=VE("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}},QN=[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)],$E=[{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 WE(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 QN)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 GE(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 ZN(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 eO(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?WE(e):JN}function tO(r={},e={}){let t=Pa(r),s=Pa(e);return!!(t&&s&&t.profile===s.profile)}function rO(r={},e={}){let t=Pa(r),s=Pa(e);return!!(t&&s&&t.profile===s.profile&&t.level==s.level)}function sO(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=KE(r)&&KE(e),i=t.level,o=s.level,a=oO(i,o),c=n?i:a;return rn.debug(`generateProfileLevelIdStringForAnswer() | result [profile:${t.profile}, level:${c}]`),GE(new Ed(t.profile,c))}function nO(r,e){for(let s=$E.length-1;s>=0;--s){let n=$E[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 VE(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 iO(r,e){return r===De.L1_b?e!==De.L1&&e!==De.L1_b:e===De.L1_b?r!==De.L1:r<e}function oO(r,e){return iO(r,e)?r:e}function KE(r={}){let e=r["level-asymmetry-allowed"];return e===!0||e===1||e==="1"}});var kn=se(Jr=>{"use strict";Object.defineProperty(Jr,"__esModule",{value:!0});Jr.validateAndNormalizeRtpCapabilities=fO;Jr.validateAndNormalizeRtpParameters=Kx;Jr.validateAndNormalizeSctpStreamParameters=lO;Jr.validateSctpCapabilities=hO;Jr.getExtendedRtpCapabilities=pO;Jr.getRecvRtpCapabilities=mO;Jr.getSendRtpCapabilities=gO;Jr.getSendingRtpParameters=yO;Jr.getSendingRemoteRtpParameters=xO;Jr.reduceCodecs=bO;Jr.generateProbatorRtpParameters=vO;Jr.canSend=wO;Jr.canReceive=SO;var YE=XE(),aO=ka(),cO="probator",dO=1234,uO=127;function fO(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)_O(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)EO(e)}function Kx(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)CO(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)TO(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)AO(e);if(r.rtcp&&typeof r.rtcp!="object")throw new TypeError("params.rtcp is not an object");r.rtcp||(r.rtcp={}),IO(r.rtcp)}function lO(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 hO(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");RO(r.numStreams)}function pO(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=>Vx(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:JE(n,i)};s.codecs.push(o)}else for(let n of e.codecs??[]){if(Cd(n))continue;let i=(r.codecs??[]).find(a=>Vx(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:JE(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=>kO(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 mO(r){return ZE({direction:"recvonly",extendedRtpCapabilities:r})}function gO(r){return ZE({direction:"sendonly",extendedRtpCapabilities:r})}function yO(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 xO(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 bO(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(Vx(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 vO(r){r=aO.clone(r),Kx(r);let e={mid:cO,codecs:[],headerExtensions:[],encodings:[{ssrc:dO}],rtcp:{cname:"probator"}};return e.codecs.push(r.codecs[0]),e.codecs[0].payloadType=uO,e.headerExtensions=r.headerExtensions,e}function wO(r,e){return(e.codecs??[]).some(t=>t.kind===r)}function SO(r,e){if(Kx(r),r.codecs.length===0)return!1;let t=r.codecs[0];return(e.codecs??[]).some(s=>s.preferredPayloadType===t.payloadType)}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(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)QE(s)}function QE(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 EO(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 CO(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)QE(n)}function TO(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 AO(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 IO(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 RO(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 ZE({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 Vx(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||!YE.isSameProfile(r.parameters,e.parameters))return!1;let c;try{c=YE.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 kO(r,e){return!(r.kind&&e.kind&&r.kind!==e.kind||r.uri!==e.uri)}function JE(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 eC=se(y0=>{"use strict";Object.defineProperty(y0,"__esModule",{value:!0});y0.Logger=void 0;var Td=Tf(),Ad="awaitqueue",Wx=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}};y0.Logger=Wx});var Yx=se(Id=>{"use strict";Object.defineProperty(Id,"__esModule",{value:!0});Id.AwaitQueueRemovedTaskError=Id.AwaitQueueStoppedError=void 0;var Gx=class r extends Error{constructor(e){super(e??"queue stopped"),this.name="AwaitQueueStoppedError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,r)}};Id.AwaitQueueStoppedError=Gx;var Xx=class r extends Error{constructor(e){super(e??"queue task removed"),this.name="AwaitQueueRemovedTaskError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,r)}};Id.AwaitQueueRemovedTaskError=Xx});var tC=se(x0=>{"use strict";Object.defineProperty(x0,"__esModule",{value:!0});x0.AwaitQueue=void 0;var PO=eC(),Jx=Yx(),bi=new PO.Logger("AwaitQueue"),Qx=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 Jx.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 Jx.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 Jx.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})}}};x0.AwaitQueue=Qx});var sC=se(xo=>{"use strict";Object.defineProperty(xo,"__esModule",{value:!0});xo.AwaitQueueRemovedTaskError=xo.AwaitQueueStoppedError=xo.AwaitQueue=void 0;var BO=tC();Object.defineProperty(xo,"AwaitQueue",{enumerable:!0,get:function(){return BO.AwaitQueue}});var rC=Yx();Object.defineProperty(xo,"AwaitQueueStoppedError",{enumerable:!0,get:function(){return rC.AwaitQueueStoppedError}});Object.defineProperty(xo,"AwaitQueueRemovedTaskError",{enumerable:!0,get:function(){return rC.AwaitQueueRemovedTaskError}})});var iC=se(b0=>{"use strict";Object.defineProperty(b0,"__esModule",{value:!0});b0.Producer=void 0;var NO=Yr(),nC=as(),Rd=Ls(),Pn=new NO.Logger("Producer"),Zx=class extends nC.EnhancedEventEmitter{_id;_localId;_closed=!1;_rtpSender;_track;_kind;_rtpParameters;_paused;_maxSpatialLayer;_stopTracks;_disableTrackOnPause;_zeroRtpOnPause;_appData;_observer=new nC.EnhancedEventEmitter;constructor({id:e,localId:t,rtpSender:s,track:n,rtpParameters:i,stopTracks:o,disableTrackOnPause:a,zeroRtpOnPause:c,appData:d}){super(),Pn.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||(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 Rd.InvalidStateError("closed");return new Promise((e,t)=>{this.safeEmit("@getstats",e,t)})}pause(){if(Pn.debug("pause()"),this._closed){Pn.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(Pn.debug("resume()"),this._closed){Pn.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(Pn.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){Pn.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(){Pn.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{}}};b0.Producer=Zx});var aC=se(v0=>{"use strict";Object.defineProperty(v0,"__esModule",{value:!0});v0.Consumer=void 0;var OO=Yr(),oC=as(),LO=Ls(),Bn=new OO.Logger("Consumer"),eb=class extends oC.EnhancedEventEmitter{_id;_localId;_producerId;_closed=!1;_rtpReceiver;_track;_rtpParameters;_paused;_appData;_observer=new oC.EnhancedEventEmitter;constructor({id:e,localId:t,producerId:s,rtpReceiver:n,track:i,rtpParameters:o,appData:a}){super(),Bn.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||(Bn.debug("close()"),this._closed=!0,this.destroyTrack(),this.emit("@close"),this._observer.safeEmit("close"),super.close(),this._observer.close())}transportClosed(){this._closed||(Bn.debug("transportClosed()"),this._closed=!0,this.destroyTrack(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}async getStats(){if(this._closed)throw new LO.InvalidStateError("closed");return new Promise((e,t)=>{this.safeEmit("@getstats",e,t)})}pause(){if(Bn.debug("pause()"),this._closed){Bn.error("pause() | Consumer closed");return}if(this._paused){Bn.debug("pause() | Consumer is already paused");return}this._paused=!0,this._track.enabled=!1,this.emit("@pause"),this._observer.safeEmit("pause")}resume(){if(Bn.debug("resume()"),this._closed){Bn.error("resume() | Consumer closed");return}if(!this._paused){Bn.debug("resume() | Consumer is already resumed");return}this._paused=!1,this._track.enabled=!0,this.emit("@resume"),this._observer.safeEmit("resume")}onTrackEnded(){Bn.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{}}};v0.Consumer=eb});var dC=se(w0=>{"use strict";Object.defineProperty(w0,"__esModule",{value:!0});w0.DataProducer=void 0;var DO=Yr(),cC=as(),MO=Ls(),vi=new DO.Logger("DataProducer"),tb=class extends cC.EnhancedEventEmitter{_id;_dataChannel;_closed=!1;_sctpStreamParameters;_appData;_observer=new cC.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 MO.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")})}};w0.DataProducer=tb});var fC=se(S0=>{"use strict";Object.defineProperty(S0,"__esModule",{value:!0});S0.DataConsumer=void 0;var UO=Yr(),uC=as(),Ba=new UO.Logger("DataConsumer"),rb=class extends uC.EnhancedEventEmitter{_id;_dataProducerId;_dataChannel;_closed=!1;_sctpStreamParameters;_appData;_observer=new uC.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)})}};S0.DataConsumer=rb});var hC=se(_0=>{"use strict";Object.defineProperty(_0,"__esModule",{value:!0});_0.Transport=void 0;var jO=sC(),HO=Yr(),lC=as(),yr=Ls(),sb=ka(),If=kn(),FO=iC(),qO=aC(),zO=dC(),$O=fC(),dr=new HO.Logger("Transport"),nb=class{consumerOptions;promise;resolve;reject;constructor(e){this.consumerOptions=e,this.promise=new Promise((t,s)=>{this.resolve=t,this.reject=s})}},ib=class extends lC.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 jO.AwaitQueue;_pendingConsumerTasks=[];_consumerCreationInProgress=!1;_pendingPauseConsumers=new Map;_consumerPauseInProgress=!1;_pendingResumeConsumers=new Map;_consumerResumeInProgress=!1;_pendingCloseConsumers=new Map;_consumerCloseInProgress=!1;_observer=new lC.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=sb.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{If.validateAndNormalizeRtpParameters(v);let{id:C}=await new Promise((K,z)=>{this.safeEmit("produce",{kind:e.kind,rtpParameters:v,appData:f},K,z)}),O=new FO.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=sb.clone(n);if(!If.canReceive(c,this._recvRtpCapabilities))throw new yr.UnsupportedError("cannot consume this Producer");let u=new nb({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}});If.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 zO.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=sb.clone(s);return If.validateAndNormalizeSctpStreamParameters(a),this._awaitQueue.push(async()=>{let{dataChannel:c}=await this._handler.receiveDataChannel({maxMessageSize:this._maxSctpMessageSize,sctpStreamParameters:a,label:n,protocol:i}),d=new $O.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 qO.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=If.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)})}};_0.Transport=ib});var E0=se((gK,mC)=>{"use strict";var pC=mC.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(pC).forEach(function(r){var e=pC[r];e.forEach(function(t){t.reg||(t.reg=/(.*)/),t.format||(t.format="%s")})})});var xC=se(wi=>{"use strict";var kd=function(r){return String(Number(r))===r?Number(r):r},VO=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]))},KO=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;VO(t.match(r.reg),n,r.names,r.name),r.push&&e[r.push].push(n)},gC=E0(),WO=RegExp.prototype.test.bind(/^([a-z])=(.*)/);wi.parse=function(r){var e={},t=[],s=e;return r.split(/(\r\n|\r|\n)/).filter(WO).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<(gC[i]||[]).length;a+=1){var c=gC[i][a];if(c.reg.test(o))return KO(c,s,o)}}),e.media=t,e};var yC=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(yC,{})};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(yC,{})})};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 vC=se((xK,bC)=>{"use strict";var ob=E0(),GO=/%[sdv%]/g,XO=function(r){var e=1,t=arguments,s=t.length;return r.replace(GO,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""}})},Rf=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 XO.apply(null,n)},YO=["v","o","s","i","u","e","p","c","b","t","r","z","a"],JO=["i","c","b","a"];bC.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||YO,s=e.innerOrder||JO,n=[];return t.forEach(function(i){ob[i].forEach(function(o){o.name in r&&r[o.name]!=null?n.push(Rf(i,o,r)):o.push in r&&r[o.push]!=null&&r[o.push].forEach(function(a){n.push(Rf(i,o,a))})})}),r.media.forEach(function(i){n.push(Rf("m",ob.m[0],i)),s.forEach(function(o){ob[o].forEach(function(a){a.name in i&&i[a.name]!=null?n.push(Rf(o,a,i)):a.push in i&&i[a.push]!=null&&i[a.push].forEach(function(c){n.push(Rf(o,a,c))})})})}),n.join(`\r
|
|
3
|
+
`+i),s.push(n+"m+"+$t.exports.humanize(this.diff)+"\x1B[0m")}else s[0]=Mo()+e+" "+s[0]}function Mo(){return F.inspectOpts.hideDate?"":new Date().toISOString()+" "}function Oo(...s){return process.stderr.write(qt.formatWithOptions(F.inspectOpts,...s)+`
|
|
4
|
+
`)}function Ao(s){s?process.env.DEBUG=s:delete process.env.DEBUG}function No(){return process.env.DEBUG}function jo(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]]}$t.exports=xr()(F);var{formatters:Js}=$t.exports;Js.o=function(s){return this.inspectOpts.colors=this.useColors,qt.inspect(s,this.inspectOpts).split(`
|
|
5
|
+
`).map(e=>e.trim()).join(" ")};Js.O=function(s){return this.inspectOpts.colors=this.useColors,qt.inspect(s,this.inspectOpts)}});var gt=C((yp,Ir)=>{"use strict";typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?Ir.exports=Gs():Ir.exports=Xs()});var en=C(Zs=>{"use strict";Object.defineProperty(Zs,"__esModule",{value:!0})});var z=C(Ut=>{"use strict";Object.defineProperty(Ut,"__esModule",{value:!0});Ut.Logger=void 0;var Be=gt(),Ve="media-client",Lr=class{_debug;_warn;_error;constructor(e){e?(this._debug=(0,Be.default)(`${Ve}:${e}`),this._warn=(0,Be.default)(`${Ve}:WARN:${e}`),this._error=(0,Be.default)(`${Ve}:ERROR:${e}`)):(this._debug=(0,Be.default)(Ve),this._warn=(0,Be.default)(`${Ve}:WARN`),this._error=(0,Be.default)(`${Ve}: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=Lr});var un=C((Rp,Mr)=>{"use strict";var We=typeof Reflect=="object"?Reflect:null,tn=We&&typeof We.apply=="function"?We.apply:function(e,t,r){return Function.prototype.apply.call(e,t,r)},zt;We&&typeof We.ownKeys=="function"?zt=We.ownKeys:Object.getOwnPropertySymbols?zt=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:zt=function(e){return Object.getOwnPropertyNames(e)};function Fo(s){console&&console.warn&&console.warn(s)}var sn=Number.isNaN||function(e){return e!==e};function L(){L.init.call(this)}Mr.exports=L;Mr.exports.once=zo;L.EventEmitter=L;L.prototype._events=void 0;L.prototype._eventsCount=0;L.prototype._maxListeners=void 0;var rn=10;function Bt(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 rn},set:function(s){if(typeof s!="number"||s<0||sn(s))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+s+".");rn=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||sn(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 nn(s){return s._maxListeners===void 0?L.defaultMaxListeners:s._maxListeners}L.prototype.getMaxListeners=function(){return nn(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")tn(c,this,t);else for(var d=c.length,p=pn(c,d),r=0;r<d;++r)tn(p[r],this,t);return!0};function on(s,e,t,r){var n,i,o;if(Bt(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=nn(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,Fo(a)}return s}L.prototype.addListener=function(e,t){return on(this,e,t,!1)};L.prototype.on=L.prototype.addListener;L.prototype.prependListener=function(e,t){return on(this,e,t,!0)};function qo(){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 an(s,e,t){var r={fired:!1,wrapFn:void 0,target:s,type:e,listener:t},n=qo.bind(r);return n.listener=t,r.wrapFn=n,n}L.prototype.once=function(e,t){return Bt(t),this.on(e,an(this,e,t)),this};L.prototype.prependOnceListener=function(e,t){return Bt(t),this.prependListener(e,an(this,e,t)),this};L.prototype.removeListener=function(e,t){var r,n,i,o,a;if(Bt(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():$o(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 cn(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?Uo(n):pn(n,n.length)}L.prototype.listeners=function(e){return cn(this,e,!0)};L.prototype.rawListeners=function(e){return cn(this,e,!1)};L.listenerCount=function(s,e){return typeof s.listenerCount=="function"?s.listenerCount(e):dn.call(s,e)};L.prototype.listenerCount=dn;function dn(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?zt(this._events):[]};function pn(s,e){for(var t=new Array(e),r=0;r<e;++r)t[r]=s[r];return t}function $o(s,e){for(;e+1<s.length;e++)s[e]=s[e+1];s.pop()}function Uo(s){for(var e=new Array(s.length),t=0;t<e.length;++t)e[t]=s[t].listener||s[t];return e}function zo(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))}ln(s,e,i,{once:!0}),e!=="error"&&Bo(s,n,{once:!0})})}function Bo(s,e,t){typeof s.on=="function"&&ln(s,"error",e,t)}function ln(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(Vt=>{"use strict";Object.defineProperty(Vt,"__esModule",{value:!0});Vt.EnhancedEventEmitter=void 0;var Vo=un(),Wo=z(),Ho=new Wo.Logger("EnhancedEventEmitter"),Or=class extends Vo.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){Ho.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)}};Vt.EnhancedEventEmitter=Or});var X=C(He=>{"use strict";Object.defineProperty(He,"__esModule",{value:!0});He.InvalidStateError=He.UnsupportedError=void 0;var Ar=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=Ar;var Nr=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=Nr});var ke=C(_t=>{"use strict";Object.defineProperty(_t,"__esModule",{value:!0});_t.clone=Go;_t.generateRandomNumber=Ko;_t.deepFreeze=hn;function Go(s){if(s!==void 0)return Number.isNaN(s)?NaN:typeof structuredClone=="function"?structuredClone(s):JSON.parse(JSON.stringify(s))}function Ko(){return Math.round(Math.random()*1e7)}function hn(s){let e=Reflect.ownKeys(s);for(let t of e){let r=s[t];(r&&typeof r=="object"||typeof r=="function")&&hn(r)}return Object.freeze(s)}});var fn=C(Wt=>{"use strict";Object.defineProperty(Wt,"__esModule",{value:!0});Wt.Logger=void 0;var Ge=gt(),Ke="h264-profile-level-id",jr=class{_debug;_warn;_error;constructor(e){e?(this._debug=(0,Ge.default)(`${Ke}:${e}`),this._warn=(0,Ge.default)(`${Ke}:WARN:${e}`),this._error=(0,Ge.default)(`${Ke}:ERROR:${e}`)):(this._debug=(0,Ge.default)(Ke),this._warn=(0,Ge.default)(`${Ke}:WARN`),this._error=(0,Ge.default)(`${Ke}: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}};Wt.Logger=jr});var yn=C(q=>{"use strict";Object.defineProperty(q,"__esModule",{value:!0});q.ProfileLevelId=q.Level=q.Profile=void 0;q.parseProfileLevelId=vn;q.profileLevelIdToString=wn;q.profileToString=Xo;q.levelToString=Zo;q.parseSdpProfileLevelId=xe;q.isSameProfile=ea;q.isSameProfileAndLevel=ta;q.generateProfileLevelIdStringForAnswer=ra;q.supportedLevel=sa;var Qo=fn(),ne=new Qo.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 Qe=class{profile;level;constructor(e,t){this.profile=e,this.level=t}};q.ProfileLevelId=Qe;var Yo=new Qe(M.ConstrainedBaseline,v.L3_1),re=class{mask;masked_value;constructor(e){this.mask=~gn("x",e),this.masked_value=gn("1",e)}isMatch(e){return this.masked_value===(e&this.mask)}},se=class{profile_idc;profile_iop;profile;constructor(e,t,r){this.profile_idc=e,this.profile_iop=t,this.profile=r}},Jo=[new se(66,new re("x1xx0000"),M.ConstrainedBaseline),new se(77,new re("1xxx0000"),M.ConstrainedBaseline),new se(88,new re("11xx0000"),M.ConstrainedBaseline),new se(66,new re("x0xx0000"),M.Baseline),new se(88,new re("10xx0000"),M.Baseline),new se(77,new re("0x0x0000"),M.Main),new se(100,new re("00000000"),M.High),new se(100,new re("00001100"),M.ConstrainedHigh),new se(244,new re("00000000"),M.PredictiveHigh444)],mn=[{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 vn(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:{ne.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 ne.debug(`parseProfileLevelId() | result [str:${s}, profile:${a.profile}, level:${o}]`),new Qe(a.profile,o);ne.warn(`parseProfileLevelId() | unrecognized profile_idc/profile_iop combination [str:${s}, profile_idc:${i}, profile_iop:${n}]`)}function wn(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:{ne.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:{ne.warn(`profileLevelIdToString() | unrecognized profile ${s.profile}`);return}}let t=s.level.toString(16);return t.length===1&&(t=`0${t}`),`${e}${t}`}function Xo(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:{ne.warn(`profileToString() | unrecognized profile ${s}`);return}}}function Zo(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:{ne.warn(`levelToString() | unrecognized level ${s}`);return}}}function xe(s={}){let e=s["profile-level-id"];return e?vn(e):Yo}function ea(s={},e={}){let t=xe(s),r=xe(e);return!!(t&&r&&t.profile===r.profile)}function ta(s={},e={}){let t=xe(s),r=xe(e);return!!(t&&r&&t.profile===r.profile&&t.level==r.level)}function ra(s={},e={}){if(!s["profile-level-id"]&&!e["profile-level-id"]){ne.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=_n(s)&&_n(e),i=t.level,o=r.level,a=ia(i,o),c=n?i:a;return ne.debug(`generateProfileLevelIdStringForAnswer() | result [profile:${t.profile}, level:${c}]`),wn(new Qe(t.profile,c))}function sa(s,e){for(let r=mn.length-1;r>=0;--r){let n=mn[r];if(n.max_macroblock_frame_size*256<=s&&n.max_macroblocks_per_second<=e*n.max_macroblock_frame_size)return ne.debug(`supportedLevel() | result [max_frame_pixel_count:${s}, max_fps:${e}, level:${n.level}]`),n.level}ne.warn(`supportedLevel() | no level supported [max_frame_pixel_count:${s}, max_fps:${e}]`)}function gn(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 na(s,e){return s===v.L1_b?e!==v.L1&&e!==v.L1_b:e===v.L1_b?s!==v.L1:s<e}function ia(s,e){return na(s,e)?s:e}function _n(s={}){let e=s["level-asymmetry-allowed"];return e===!0||e===1||e==="1"}});var ce=C(B=>{"use strict";Object.defineProperty(B,"__esModule",{value:!0});B.validateAndNormalizeRtpCapabilities=pa;B.validateAndNormalizeRtpParameters=qr;B.validateAndNormalizeSctpStreamParameters=la;B.validateSctpCapabilities=ua;B.getExtendedRtpCapabilities=ha;B.getRecvRtpCapabilities=fa;B.getSendRtpCapabilities=ma;B.getSendingRtpParameters=ga;B.getSendingRemoteRtpParameters=_a;B.reduceCodecs=va;B.generateProbatorRtpParameters=wa;B.canSend=ya;B.canReceive=ba;var bn=yn(),oa=ke(),aa="probator",ca=1234,da=127;function pa(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)Sa(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)Ra(e)}function qr(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)Ca(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)Ta(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)Ea(e);if(s.rtcp&&typeof s.rtcp!="object")throw new TypeError("params.rtcp is not an object");s.rtcp||(s.rtcp={}),ka(s.rtcp)}function la(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 ua(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");xa(s.numStreams)}function ha(s,e,t){let r={codecs:[],headerExtensions:[]};if(t)for(let n of s.codecs??[]){if(Ye(n))continue;let i=(e.codecs??[]).find(a=>Fr(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:Sn(n,i)};r.codecs.push(o)}else for(let n of e.codecs??[]){if(Ye(n))continue;let i=(s.codecs??[]).find(a=>Fr(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:Sn(i,n)};r.codecs.push(o)}for(let n of r.codecs){let i=s.codecs.find(a=>Ye(a)&&a.parameters?.apt===n.localPayloadType),o=e.codecs.find(a=>Ye(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=>Pa(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 fa(s){return Cn({direction:"recvonly",extendedRtpCapabilities:s})}function ma(s){return Cn({direction:"sendonly",extendedRtpCapabilities:s})}function ga(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 _a(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 va(s,e){let t=[];if(!e)t.push(s[0]),Ye(s[1])&&t.push(s[1]);else{for(let r=0;r<s.length;++r)if(Fr(s[r],e,{strict:!0})){t.push(s[r]),Ye(s[r+1])&&t.push(s[r+1]);break}if(t.length===0)throw new TypeError("no matching codec found")}return t}function wa(s){s=oa.clone(s),qr(s);let e={mid:aa,codecs:[],headerExtensions:[],encodings:[{ssrc:ca}],rtcp:{cname:"probator"}};return e.codecs.push(s.codecs[0]),e.codecs[0].payloadType=da,e.headerExtensions=s.headerExtensions,e}function ya(s,e){return(e.codecs??[]).some(t=>t.kind===s)}function ba(s,e){if(qr(s),s.codecs.length===0)return!1;let t=s.codecs[0];return(e.codecs??[]).some(r=>r.preferredPayloadType===t.payloadType)}function Sa(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)Rn(r)}function Rn(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 Ra(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 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(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)Rn(n)}function Ta(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 Ea(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 ka(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 xa(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 Cn({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 Ye(s){return s?/.+\/rtx$/i.test(s.mimeType):!1}function Fr(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||!bn.isSameProfile(s.parameters,e.parameters))return!1;let c;try{c=bn.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 Pa(s,e){return!(s.kind&&e.kind&&s.kind!==e.kind||s.uri!==e.uri)}function Sn(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 Tn=C(Ht=>{"use strict";Object.defineProperty(Ht,"__esModule",{value:!0});Ht.Logger=void 0;var Je=gt(),Xe="awaitqueue",$r=class{_debug;_warn;_error;constructor(e){e?(this._debug=Je(`${Xe}:${e}`),this._warn=Je(`${Xe}:WARN:${e}`),this._error=Je(`${Xe}:ERROR:${e}`)):(this._debug=Je(Xe),this._warn=Je(`${Xe}:WARN`),this._error=Je(`${Xe}: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}};Ht.Logger=$r});var Br=C(Ze=>{"use strict";Object.defineProperty(Ze,"__esModule",{value:!0});Ze.AwaitQueueRemovedTaskError=Ze.AwaitQueueStoppedError=void 0;var Ur=class s extends Error{constructor(e){super(e??"queue stopped"),this.name="AwaitQueueStoppedError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,s)}};Ze.AwaitQueueStoppedError=Ur;var zr=class s extends Error{constructor(e){super(e??"queue task removed"),this.name="AwaitQueueRemovedTaskError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,s)}};Ze.AwaitQueueRemovedTaskError=zr});var En=C(Gt=>{"use strict";Object.defineProperty(Gt,"__esModule",{value:!0});Gt.AwaitQueue=void 0;var Da=Tn(),Vr=Br(),me=new Da.Logger("AwaitQueue"),Wr=class{pendingTasks=new Map;nextTaskId=0;constructor(){me.debug("constructor()")}get size(){return this.pendingTasks.size}async push(e,t,r){if(t=t??e.name,me.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 Vr.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),me.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),me.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(){me.debug("stop()");for(let e of this.pendingTasks.values())me.debug(`stop() | stopping task [name:${e.name}]`),e.reject(new Vr.AwaitQueueStoppedError,{canExecuteNextTask:!1})}remove(e){me.debug(`remove() [taskIdx:${e}]`);let t=Array.from(this.pendingTasks.values())[e];if(!t){me.debug(`stop() | no task with given idx [taskIdx:${e}]`);return}t.reject(new Vr.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(me.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})}}};Gt.AwaitQueue=Wr});var xn=C(Re=>{"use strict";Object.defineProperty(Re,"__esModule",{value:!0});Re.AwaitQueueRemovedTaskError=Re.AwaitQueueStoppedError=Re.AwaitQueue=void 0;var Ia=En();Object.defineProperty(Re,"AwaitQueue",{enumerable:!0,get:function(){return Ia.AwaitQueue}});var kn=Br();Object.defineProperty(Re,"AwaitQueueStoppedError",{enumerable:!0,get:function(){return kn.AwaitQueueStoppedError}});Object.defineProperty(Re,"AwaitQueueRemovedTaskError",{enumerable:!0,get:function(){return kn.AwaitQueueRemovedTaskError}})});var Dn=C(Kt=>{"use strict";Object.defineProperty(Kt,"__esModule",{value:!0});Kt.Producer=void 0;var La=z(),Pn=G(),et=X(),de=new La.Logger("Producer"),Hr=class extends Pn.EnhancedEventEmitter{_id;_localId;_closed=!1;_rtpSender;_track;_kind;_rtpParameters;_paused;_maxSpatialLayer;_stopTracks;_disableTrackOnPause;_zeroRtpOnPause;_appData;_observer=new Pn.EnhancedEventEmitter;constructor({id:e,localId:t,rtpSender:r,track:n,rtpParameters:i,stopTracks:o,disableTrackOnPause:a,zeroRtpOnPause:c,appData:d}){super(),de.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||(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 et.InvalidStateError("closed");return new Promise((e,t)=>{this.safeEmit("@getstats",e,t)})}pause(){if(de.debug("pause()"),this._closed){de.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(de.debug("resume()"),this._closed){de.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(de.debug("replaceTrack() [track:%o]",e),this._closed){if(e&&this._stopTracks)try{e.stop()}catch{}throw new et.InvalidStateError("closed")}else if(e?.readyState==="ended")throw new et.InvalidStateError("track ended");if(e===this._track){de.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 et.InvalidStateError("closed");if(this._kind!=="video")throw new et.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 et.InvalidStateError("closed");if(typeof e!="object")throw new TypeError("invalid params");await new Promise((t,r)=>{this.safeEmit("@setrtpencodingparameters",e,t,r)})}onTrackEnded(){de.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{}}};Kt.Producer=Hr});var Ln=C(Qt=>{"use strict";Object.defineProperty(Qt,"__esModule",{value:!0});Qt.Consumer=void 0;var Ma=z(),In=G(),Oa=X(),pe=new Ma.Logger("Consumer"),Gr=class extends In.EnhancedEventEmitter{_id;_localId;_producerId;_closed=!1;_rtpReceiver;_track;_rtpParameters;_paused;_appData;_observer=new In.EnhancedEventEmitter;constructor({id:e,localId:t,producerId:r,rtpReceiver:n,track:i,rtpParameters:o,appData:a}){super(),pe.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||(pe.debug("close()"),this._closed=!0,this.destroyTrack(),this.emit("@close"),this._observer.safeEmit("close"),super.close(),this._observer.close())}transportClosed(){this._closed||(pe.debug("transportClosed()"),this._closed=!0,this.destroyTrack(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}async getStats(){if(this._closed)throw new Oa.InvalidStateError("closed");return new Promise((e,t)=>{this.safeEmit("@getstats",e,t)})}pause(){if(pe.debug("pause()"),this._closed){pe.error("pause() | Consumer closed");return}if(this._paused){pe.debug("pause() | Consumer is already paused");return}this._paused=!0,this._track.enabled=!1,this.emit("@pause"),this._observer.safeEmit("pause")}resume(){if(pe.debug("resume()"),this._closed){pe.error("resume() | Consumer closed");return}if(!this._paused){pe.debug("resume() | Consumer is already resumed");return}this._paused=!1,this._track.enabled=!0,this.emit("@resume"),this._observer.safeEmit("resume")}onTrackEnded(){pe.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{}}};Qt.Consumer=Gr});var On=C(Yt=>{"use strict";Object.defineProperty(Yt,"__esModule",{value:!0});Yt.DataProducer=void 0;var Aa=z(),Mn=G(),Na=X(),ge=new Aa.Logger("DataProducer"),Kr=class extends Mn.EnhancedEventEmitter{_id;_dataChannel;_closed=!1;_sctpStreamParameters;_appData;_observer=new Mn.EnhancedEventEmitter;constructor({id:e,dataChannel:t,sctpStreamParameters:r,appData:n}){super(),ge.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||(ge.debug("close()"),this._closed=!0,this._dataChannel.close(),this.emit("@close"),this._observer.safeEmit("close"),super.close(),this._observer.close())}transportClosed(){this._closed||(ge.debug("transportClosed()"),this._closed=!0,this._dataChannel.close(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}send(e){if(ge.debug("send()"),this._closed)throw new Na.InvalidStateError("closed");this._dataChannel.send(e)}handleDataChannel(){this._dataChannel.addEventListener("open",()=>{this._closed||(ge.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"?ge.error("DataChannel SCTP error [sctpCauseCode:%s]: %s",e.error?.sctpCauseCode,e.error.message):ge.error('DataChannel "error" event: %o',t),this.safeEmit("error",t)}),this._dataChannel.addEventListener("close",()=>{this._closed||(ge.warn('DataChannel "close" event'),this._closed=!0,this.emit("@close"),this.safeEmit("close"),this._observer.safeEmit("close"))}),this._dataChannel.addEventListener("message",()=>{this._closed||ge.warn('DataChannel "message" event in a DataProducer, message discarded')}),this._dataChannel.addEventListener("bufferedamountlow",()=>{this._closed||this.safeEmit("bufferedamountlow")})}};Yt.DataProducer=Kr});var Nn=C(Jt=>{"use strict";Object.defineProperty(Jt,"__esModule",{value:!0});Jt.DataConsumer=void 0;var ja=z(),An=G(),Pe=new ja.Logger("DataConsumer"),Qr=class extends An.EnhancedEventEmitter{_id;_dataProducerId;_dataChannel;_closed=!1;_sctpStreamParameters;_appData;_observer=new An.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)})}};Jt.DataConsumer=Qr});var Fn=C(Xt=>{"use strict";Object.defineProperty(Xt,"__esModule",{value:!0});Xt.Transport=void 0;var Fa=xn(),qa=z(),jn=G(),j=X(),Yr=ke(),vt=ce(),$a=Dn(),Ua=Ln(),za=On(),Ba=Nn(),N=new qa.Logger("Transport"),Jr=class{consumerOptions;promise;resolve;reject;constructor(e){this.consumerOptions=e,this.promise=new Promise((t,r)=>{this.resolve=t,this.reject=r})}},Xr=class extends jn.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 Fa.AwaitQueue;_pendingConsumerTasks=[];_consumerCreationInProgress=!1;_pendingPauseConsumers=new Map;_consumerPauseInProgress=!1;_pendingResumeConsumers=new Map;_consumerResumeInProgress=!1;_pendingCloseConsumers=new Map;_consumerCloseInProgress=!1;_observer=new jn.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:m,canProduceByKind:f}){super(),N.debug("constructor() [id:%s, direction:%s]",t,e),this._id=t,this._direction=e,this._getSendExtendedRtpCapabilities=u,this._recvRtpCapabilities=m,this._canProduceByKind=f,this._maxSctpMessageSize=o?.maxMessageSize;let h=Yr.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:m,rtpParameters:f,rtpSender:h}=await this._handler.send({track:e,streamId:t,encodings:u,codecOptions:n,headerExtensionOptions:i,codec:o,onRtpSender:p});try{vt.validateAndNormalizeRtpParameters(f);let{id:g}=await new Promise((y,x)=>{this.safeEmit("produce",{kind:e.kind,rtpParameters:f,appData:l},y,x)}),_=new $a.Producer({id:g,localId:m,rtpSender:h,track:e,rtpParameters:f,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(m).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=Yr.clone(n);if(!vt.canReceive(c,this._recvRtpCapabilities))throw new j.UnsupportedError("cannot consume this Producer");let p=new Jr({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}});vt.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 za.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=Yr.clone(r);return vt.validateAndNormalizeSctpStreamParameters(a),this._awaitQueue.push(async()=>{let{dataChannel:c}=await this._handler.receiveDataChannel({maxMessageSize:this._maxSctpMessageSize,sctpStreamParameters:a,label:n,protocol:i}),d=new Ba.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:m,rtpReceiver:f,track:h}=a,g=new Ua.Consumer({id:c,localId:m,producerId:d,rtpReceiver:f,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=vt.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)})}};Xt.Transport=Xr});var Zt=C((qp,$n)=>{"use strict";var qn=$n.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(qn).forEach(function(s){var e=qn[s];e.forEach(function(t){t.reg||(t.reg=/(.*)/),t.format||(t.format="%s")})})});var Bn=C(_e=>{"use strict";var tt=function(s){return String(Number(s))===s?Number(s):s},Va=function(s,e,t,r){if(r&&!t)e[r]=tt(s[1]);else for(var n=0;n<t.length;n+=1)s[n+1]!=null&&(e[t[n]]=tt(s[n+1]))},Wa=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;Va(t.match(s.reg),n,s.names,s.name),s.push&&e[s.push].push(n)},Un=Zt(),Ha=RegExp.prototype.test.bind(/^([a-z])=(.*)/);_e.parse=function(s){var e={},t=[],r=e;return s.split(/(\r\n|\r|\n)/).filter(Ha).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<(Un[i]||[]).length;a+=1){var c=Un[i][a];if(c.reg.test(o))return Wa(c,r,o)}}),e.media=t,e};var zn=function(s,e){var t=e.split(/=(.+)/,2);return t.length===2?s[t[0]]=tt(t[1]):t.length===1&&e.length>1&&(s[t[0]]=void 0),s};_e.parseParams=function(s){return s.split(/;\s?/).reduce(zn,{})};_e.parseFmtpConfig=_e.parseParams;_e.parsePayloads=function(s){return s.toString().split(" ").map(Number)};_e.parseRemoteCandidates=function(s){for(var e=[],t=s.split(" ").map(tt),r=0;r<t.length;r+=3)e.push({component:t[r],ip:t[r+1],port:t[r+2]});return e};_e.parseImageAttributes=function(s){return s.split(" ").map(function(e){return e.substring(1,e.length-1).split(",").reduce(zn,{})})};_e.parseSimulcastStreamList=function(s){return s.split(";").map(function(e){return e.split(",").map(function(t){var r,n=!1;return t[0]!=="~"?r=tt(t):(r=tt(t.substring(1,t.length)),n=!0),{scid:r,paused:n}})})}});var Wn=C((Up,Vn)=>{"use strict";var Zr=Zt(),Ga=/%[sdv%]/g,Ka=function(s){var e=1,t=arguments,r=t.length;return s.replace(Ga,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""}})},wt=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 Ka.apply(null,n)},Qa=["v","o","s","i","u","e","p","c","b","t","r","z","a"],Ya=["i","c","b","a"];Vn.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||Qa,r=e.innerOrder||Ya,n=[];return t.forEach(function(i){Zr[i].forEach(function(o){o.name in s&&s[o.name]!=null?n.push(wt(i,o,s)):o.push in s&&s[o.push]!=null&&s[o.push].forEach(function(a){n.push(wt(i,o,a))})})}),s.media.forEach(function(i){n.push(wt("m",Zr.m[0],i)),r.forEach(function(o){Zr[o].forEach(function(a){a.name in i&&i[a.name]!=null?n.push(wt(o,a,i)):a.push in i&&i[a.push]!=null&&i[a.push].forEach(function(c){n.push(wt(o,a,c))})})})}),n.join(`\r
|
|
6
6
|
`)+`\r
|
|
7
|
-
`}});var Si=se(Nn=>{"use strict";var Na=xC(),QO=vC(),ZO=E0();Nn.grammar=ZO;Nn.write=QO;Nn.parse=Na.parse;Nn.parseParams=Na.parseParams;Nn.parseFmtpConfig=Na.parseFmtpConfig;Nn.parsePayloads=Na.parsePayloads;Nn.parseRemoteCandidates=Na.parseRemoteCandidates;Nn.parseImageAttributes=Na.parseImageAttributes;Nn.parseSimulcastStreamList=Na.parseSimulcastStreamList});var Oa=se(ab=>{"use strict";Object.defineProperty(ab,"__esModule",{value:!0});ab.parse=tL;var eL=new RegExp("^[LS]([1-9]\\d{0,1})T([1-9]\\d{0,1})");function tL(r){let e=eL.exec(r??"");return e?{spatialLayers:Number(e[1]),temporalLayers:Number(e[2])}:{spatialLayers:1,temporalLayers:1}}});var _C=se(bo=>{"use strict";Object.defineProperty(bo,"__esModule",{value:!0});bo.OfferMediaSection=bo.AnswerMediaSection=bo.MediaSection=void 0;var rL=Si(),wC=ka(),kf=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=kf;var cb=class extends kf{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:SC(u),rate:u.clockRate};u.channels>1&&(f.encoding=u.channels),this._mediaObject.rtp.push(f);let h=wC.clone(u.parameters)??{},y=wC.clone(u.rtcpFeedback)??[];if(d){let{opusStereo:S,opusFec:C,opusDtx:O,opusMaxPlaybackRate:K,opusMaxAverageBitrate:z,opusPtime:Q,opusNack:oe,videoGoogleStartBitrate:te,videoGoogleMaxBitrate:Ee,videoGoogleMinBitrate:ge}=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":{te!==void 0&&(h["x-google-start-bitrate"]=te),Ee!==void 0&&(h["x-google-max-bitrate"]=Ee),ge!==void 0&&(h["x-google-min-bitrate"]=ge);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=rL.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=cb;var db=class extends kf{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:SC(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=db;function SC(r){let t=new RegExp("^(audio|video)/(.+)","i").exec(r.mimeType);if(!t)throw new TypeError("invalid codec.mimeType");return t[2]}});var Pd=se(A0=>{"use strict";Object.defineProperty(A0,"__esModule",{value:!0});A0.RemoteSdp=void 0;var sL=Si(),nL=Yr(),C0=_C(),iL=fb(),oL=["av1","h264"],T0=new nL.Logger("RemoteSdp"),ub=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${iL.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){T0.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){T0.debug("updateDtlsRole() [role:%s]",e),this._dtlsParameters.role=e;for(let t of this._mediaSections)t.setDtlsRole(e)}setSessionExtmapAllowMixed(){T0.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 C0.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=>oL.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 C0.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?(T0.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 C0.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 C0.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++,sL.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(" "))}};A0.RemoteSdp=ub});var Bd=se(La=>{"use strict";Object.defineProperty(La,"__esModule",{value:!0});La.extractRtpCapabilities=aL;La.extractDtlsParameters=cL;La.getCname=dL;La.applyCodecParameters=uL;La.addHeaderExtension=fL;var EC=Si();function aL({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=EC.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 cL({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 dL({offerMediaObject:r}){let e=(r.ssrcs??[]).find(t=>t.attribute==="cname");return e?e.value:""}function uL({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=EC.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 fL({offerMediaObject:r,headerExtensionUri:e,headerExtensionId:t}){r.ext||(r.ext=[]),r.ext.push({uri:e,value:t})}});var Nd=se(I0=>{"use strict";Object.defineProperty(I0,"__esModule",{value:!0});I0.getRtpEncodings=lL;I0.addLegacySimulcast=hL;function lL({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 hL({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=se(Pf=>{"use strict";Object.defineProperty(Pf,"__esModule",{value:!0});Pf.addNackSupportForOpus=pL;Pf.addHeaderExtensionSupport=mL;Pf.getMsidStreamIdAndTrackId=gL;function pL(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 mL(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 gL(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 IC=se(R0=>{"use strict";Object.defineProperty(R0,"__esModule",{value:!0});R0.Chrome111=void 0;var On=Si(),yL=as(),xL=Yr(),Bf=kn(),bL=Ls(),vL=Oa(),wL=Pd(),Nf=Bd(),CC=Nd(),lb=Od(),et=new xL.Logger("Chrome111"),TC="Chrome111",AC={OS:65535,MIS:65535},hb=class r extends yL.EnhancedEventEmitter{_closed=!1;_direction;_remoteSdp;_getSendExtendedRtpCapabilities;_forcedLocalDtlsRole;_pc;_mapMidTransceiver=new Map;_sendStream=new MediaStream;_hasDataChannelMediaSection=!1;_nextSendSctpStreamId=0;_transportReady=!1;static createFactory(){return{name:TC,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=On.parse(s.sdp);return r.getLocalRtpCapabilities(n)}catch(s){try{t?.close()}catch{}throw t=void 0,s}},getNativeSctpCapabilities:async()=>(et.debug("getNativeSctpCapabilities()"),{numStreams:AC})}}static getLocalRtpCapabilities(e,t=[]){let s=Nf.extractRtpCapabilities({sdpObject:e});Bf.validateAndNormalizeRtpCapabilities(s),lb.addNackSupportForOpus(s);for(let n of t)lb.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 wL.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 TC}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 te=oe.scalabilityMode?(0,vL.parse)(oe.scalabilityMode).temporalLayers:3;te>Q&&(Q=te)}s.forEach((oe,te)=>{oe.rid=`r${te}`,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=On.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=Bf.getSendingRtpParameters(e.kind,v);S.codecs=Bf.reduceCodecs(S.codecs,o);let C=Bf.getSendingRemoteRtpParameters(e.kind,v);if(C.codecs=Bf.reduceCodecs(C.codecs,o),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:f}),i?.absCaptureTime){let Q=f.media[c.idx];Nf.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:On.write(f)}}et.debug("send() | calling pc.setLocalDescription() [offer:%o]",u),await this._pc.setLocalDescription(u);let O=d.mid;S.mid=O,f=On.parse(this._pc.localDescription.sdp);let K=f.media[c.idx];if(S.rtcp.cname=Nf.getCname({offerMediaObject:K}),S.msid=`${t??this._sendStream.id} ${e.id}`,!s)S.encodings=CC.getRtpEncodings({offerMediaObject:K,codecs:S.codecs});else if(s.length===1){let Q=CC.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%AC.MIS,!this._hasDataChannelMediaSection){let i=await this._pc.createOffer(),o=On.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}=lb.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=On.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);Nf.applyCodecParameters({offerRtpParameters:d,answerMediaObject:f})}i={type:"answer",sdp:On.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=On.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:On.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=On.parse(this._pc.localDescription.sdp));let s=Nf.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')}};R0.Chrome111=hb});var PC=se(k0=>{"use strict";Object.defineProperty(k0,"__esModule",{value:!0});k0.Chrome74=void 0;var Ds=Si(),SL=Yr(),_L=as(),Of=kn(),EL=Ls(),CL=Oa(),TL=Pd(),Lf=Bd(),pb=Nd(),mb=Od(),Je=new SL.Logger("Chrome74"),RC="Chrome74",kC={OS:1024,MIS:1024},gb=class r extends _L.EnhancedEventEmitter{_closed=!1;_direction;_remoteSdp;_getSendExtendedRtpCapabilities;_forcedLocalDtlsRole;_pc;_mapMidTransceiver=new Map;_sendStream=new MediaStream;_hasDataChannelMediaSection=!1;_nextSendSctpStreamId=0;_transportReady=!1;static createFactory(){return{name:RC,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:kC})}}static getLocalRtpCapabilities(e,t=[]){let s=Lf.extractRtpCapabilities({sdpObject:e});Of.validateAndNormalizeRtpCapabilities(s),mb.addNackSupportForOpus(s);for(let n of t)mb.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 TL.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 RC}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,te)=>{oe.rid=`r${te}`});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=Of.getSendingRtpParameters(e.kind,y);v.codecs=Of.reduceCodecs(v.codecs,o);let S=Of.getSendingRemoteRtpParameters(e.kind,y);S.codecs=Of.reduceCodecs(S.codecs,o),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:u});let C=!1,O=(0,CL.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],pb.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],Lf.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=Lf.getCname({offerMediaObject:K}),v.msid=`${t??this._sendStream.id} ${e.id}`,!s)v.encodings=pb.getRtpEncodings({offerMediaObject:K,codecs:v.codecs});else if(s.length===1){let oe=pb.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%kC.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}=mb.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);Lf.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=Lf.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 EL.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')}};k0.Chrome74=gb});var DC=se(B0=>{"use strict";Object.defineProperty(B0,"__esModule",{value:!0});B0.Firefox120=void 0;var _i=Si(),AL=as(),IL=Yr(),BC=Ls(),Df=kn(),RL=Oa(),kL=Pd(),P0=Bd(),NC=Nd(),PL=Od(),tt=new IL.Logger("Firefox120"),OC="Firefox120",LC={OS:16,MIS:2048},yb=class r extends AL.EnhancedEventEmitter{_closed=!1;_direction;_remoteSdp;_getSendExtendedRtpCapabilities;_pc;_mapMidTransceiver=new Map;_sendStream=new MediaStream;_hasDataChannelMediaSection=!1;_nextSendSctpStreamId=0;_transportReady=!1;static createFactory(){return{name:OC,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:LC})}}static getLocalRtpCapabilities(e){let t=P0.extractRtpCapabilities({sdpObject:e});return Df.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 kL.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 OC}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 BC.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=Df.getSendingRtpParameters(e.kind,f);h.codecs=Df.reduceCodecs(h.codecs,i);let y=Df.getSendingRemoteRtpParameters(e.kind,f);y.codecs=Df.reduceCodecs(y.codecs,i),this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:d});let v=(0,RL.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=P0.getCname({offerMediaObject:C}),h.msid=`${t??this._sendStream.id} ${e.id}`,!s)h.encodings=NC.getRtpEncodings({offerMediaObject:C,codecs:h.codecs});else if(s.length===1){let K=NC.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%LC.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}=PL.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);P0.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=P0.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 BC.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.Firefox120=yb});var HC=se(N0=>{"use strict";Object.defineProperty(N0,"__esModule",{value:!0});N0.Safari12=void 0;var Ms=Si(),BL=as(),NL=Yr(),Mf=kn(),OL=Ls(),LL=Oa(),DL=Pd(),Uf=Bd(),MC=Nd(),xb=Od(),Qe=new NL.Logger("Safari12"),UC="Safari12",jC={OS:65535,MIS:65535},bb=class r extends BL.EnhancedEventEmitter{_closed=!1;_direction;_remoteSdp;_getSendExtendedRtpCapabilities;_forcedLocalDtlsRole;_pc;_mapMidTransceiver=new Map;_sendStream=new MediaStream;_hasDataChannelMediaSection=!1;_nextSendSctpStreamId=0;_transportReady=!1;static createFactory(){return{name:UC,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:jC})}}static getLocalRtpCapabilities(e,t=[]){let s=Uf.extractRtpCapabilities({sdpObject:e});Mf.validateAndNormalizeRtpCapabilities(s),xb.addNackSupportForOpus(s);for(let n of t)xb.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 DL.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 UC}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=Mf.getSendingRtpParameters(e.kind,v);S.codecs=Mf.reduceCodecs(S.codecs,o);let C=Mf.getSendingRemoteRtpParameters(e.kind,v);C.codecs=Mf.reduceCodecs(C.codecs,o);let O;this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:f});let K=(0,LL.parse)((s??[{}])[0].scalabilityMode);s&&s.length>1&&(Qe.debug("send() | enabling legacy simulcast"),f=Ms.parse(u.sdp),O=f.media[c.idx],MC.addLegacySimulcast({offerMediaObject:O,numStreams:s.length}),u={type:"offer",sdp:Ms.write(f)}),i?.absCaptureTime&&(O=f.media[c.idx],Uf.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=Uf.getCname({offerMediaObject:O}),S.msid=`${t??this._sendStream.id} ${e.id}`,S.encodings=MC.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%jC.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}=xb.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);Uf.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=Uf.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 OL.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.Safari12=bb});var zC=se(O0=>{"use strict";Object.defineProperty(O0,"__esModule",{value:!0});O0.ReactNative106=void 0;var Us=Si(),ML=as(),UL=Yr(),jf=kn(),jL=Ls(),HL=Oa(),FL=Pd(),Hf=Bd(),vb=Nd(),wb=Od(),Ye=new UL.Logger("ReactNative106"),FC="ReactNative106",qC={OS:65535,MIS:65535},Sb=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:FC,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:qC})}}static getLocalRtpCapabilities(e,t=[]){let s=Hf.extractRtpCapabilities({sdpObject:e});jf.validateAndNormalizeRtpCapabilities(s),wb.addNackSupportForOpus(s);for(let n of t)wb.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 FL.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 FC}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((te,Ee)=>{te.rid=`r${Ee}`});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=jf.getSendingRtpParameters(e.kind,v);S.codecs=jf.reduceCodecs(S.codecs,o);let C=jf.getSendingRemoteRtpParameters(e.kind,v);C.codecs=jf.reduceCodecs(C.codecs,o),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:f});let O=!1,K=(0,HL.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],vb.addLegacySimulcast({offerMediaObject:z,numStreams:K.spatialLayers}),u={type:"offer",sdp:Us.write(f)}),i?.absCaptureTime&&(z=f.media[c.idx],Hf.addHeaderExtension({offerMediaObject:z,headerExtensionUri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",headerExtensionId:C.headerExtensions.find(te=>te.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=Hf.getCname({offerMediaObject:z}),S.msid=`${t??this._sendStream.id} ${e.id}`,!s)S.encodings=vb.getRtpEncodings({offerMediaObject:z,codecs:S.codecs});else if(s.length===1){let te=vb.getRtpEncodings({offerMediaObject:z,codecs:S.codecs});Object.assign(te[0],s[0]),O&&(te=[te[0]]),S.encodings=te}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 te of S.encodings)te.scalabilityMode?te.scalabilityMode=`L1T${K.temporalLayers}`:te.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%qC.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}=wb.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);Hf.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=Hf.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 jL.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')}};O0.ReactNative106=Sb});var WC=se(Ld=>{"use strict";Object.defineProperty(Ld,"__esModule",{value:!0});Ld.Device=void 0;Ld.detectDevice=$C;Ld.detectDeviceAsync=VC;var qL=Yr(),zL=as(),vo=Ls(),L0=ka(),Ss=kn(),$L=hC(),VL=IC(),KL=PC(),WL=DC(),GL=HC(),XL=zC(),He=new qL.Logger("Device");function $C(r,e){return He.debug("detectDevice()"),!r&&typeof navigator=="object"&&(r=navigator.userAgent),!e&&typeof navigator=="object"&&(e=navigator.userAgentData),KC(r,e)}async function VC(r,e){return He.debug("detectDeviceAsync()"),!r&&typeof navigator=="object"&&(r=navigator.userAgent),!e&&typeof navigator=="object"&&(e=navigator.userAgentData),KC(r,e)}var _b=class r{_handlerFactory;_handlerName;_loaded=!1;_getSendExtendedRtpCapabilities;_recvRtpCapabilities;_sendRtpCapabilities;_canProduceByKind={audio:!1,video:!1};_sctpCapabilities;_observer=new zL.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 VC(),!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=$C(),e)He.debug("constructor() | detected handler: %s",e);else throw new vo.UnsupportedError("device not supported");switch(e){case"Chrome111":{this._handlerFactory=VL.Chrome111.createFactory();break}case"Chrome74":{this._handlerFactory=KL.Chrome74.createFactory();break}case"Firefox120":{this._handlerFactory=WL.Firefox120.createFactory();break}case"Safari12":{this._handlerFactory=GL.Safari12.createFactory();break}case"ReactNative106":{this._handlerFactory=XL.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=L0.clone(e);Ss.validateAndNormalizeRtpCapabilities(s);let{getNativeRtpCapabilities:n,getNativeSctpCapabilities:i}=this._handlerFactory,o=L0.clone(await n({direction:"recvonly"}));He.debug("load() | got native receiving RTP capabilities:%o",o),Ss.validateAndNormalizeRtpCapabilities(o);let a=L0.clone(await n({direction:"sendonly"}));He.debug("load() | got native sending RTP capabilities:%o",a),Ss.validateAndNormalizeRtpCapabilities(a),this._getSendExtendedRtpCapabilities=u=>L0.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 $L.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=_b;function KC(r,e){He.debug('detectDeviceImpl() [userAgent:"%s", userAgentData:%o]',r,e);let t=YL(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=JL(r);if(s){if(s>=120)return He.debug("detectDeviceImpl() | using Firefox120 handler"),"Firefox120";He.warn("detectDeviceImpl() | unsupported Firefox browser/version");return}let n=QL(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=ZL(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(Ff()){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 YL(r,e){if(He.debug("getChromiumMajorVersion()"),D0(r,e)){He.debug("getChromiumMajorVersion() | this is iOS => undefined");return}if(Ff()){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 JL(r){if(He.debug("getFirefoxMajorVersion()"),D0(r)){He.debug("getFirefoxMajorVersion() | this is iOS => undefined");return}if(Ff()){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 QL(r){if(He.debug("getMacOSWebKitMajorVersion()"),D0(r)){He.debug("getMacOSWebKitMajorVersion() | this is iOS => undefined");return}if(Ff()){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 ZL(r){if(He.debug("getIOSWebKitMajorVersion()"),!D0(r)){He.debug("getIOSWebKitMajorVersion() | this is not iOS => undefined");return}if(Ff()){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 D0(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 Ff(){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 XC=se(GC=>{"use strict";var Da=256,U0=[],M0;for(;Da--;)U0[Da]=(Da+256).toString(16).substring(1);function eD(){var r=0,e,t="";if(!M0||Da+16>256){for(M0=Array(r=256);r--;)M0[r]=256*Math.random()|0;r=Da=0}for(;r<16;r++)e=M0[Da+r],r==6?t+=U0[e&15|64]:r==8?t+=U0[e&63|128]:t+=U0[e],r&1&&r>1&&r<11&&(t+="-");return Da++,t}GC.v4=eD});var YC=se(j0=>{"use strict";Object.defineProperty(j0,"__esModule",{value:!0});j0.FakeEventTarget=void 0;var Eb=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}};j0.FakeEventTarget=Eb});var JC=se(H0=>{"use strict";Object.defineProperty(H0,"__esModule",{value:!0});H0.FakeEvent=void 0;var Cb=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){}};H0.FakeEvent=Cb});var QC=se(Tb=>{"use strict";Object.defineProperty(Tb,"__esModule",{value:!0});Tb.clone=tD;function tD(r){if(r!==void 0)return Number.isNaN(r)?NaN:typeof structuredClone=="function"?structuredClone(r):JSON.parse(JSON.stringify(r))}});var e6=se(q0=>{"use strict";Object.defineProperty(q0,"__esModule",{value:!0});q0.FakeMediaStreamTrack=void 0;var ZC=XC(),rD=YC(),Dd=JC(),F0=QC(),Ab=class r extends rD.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,ZC.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,ZC.v4)(),kind:this.#f,label:this.#l,contentHint:this.#s,enabled:this.#r,muted:this.#t,readyState:this.#e,capabilities:(0,F0.clone)(this.#h),constraints:(0,F0.clone)(this.#n),settings:(0,F0.clone)(this.#p),data:t??(0,F0.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")))}};q0.FakeMediaStreamTrack=Ab});var t6=se(z0=>{"use strict";Object.defineProperty(z0,"__esModule",{value:!0});z0.FakeEventTarget=void 0;var Ib=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}};z0.FakeEventTarget=Ib});var n6=se(V0=>{"use strict";Object.defineProperty(V0,"__esModule",{value:!0});V0.FakeHandler=void 0;var sD=e6(),nD=as(),iD=Yr(),Md=ka(),Rb=kn(),s6=Ls(),oD=t6(),Ar=new iD.Logger("FakeHandler"),r6="FakeHandler",kb=class r extends nD.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:r6,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 Rb.validateAndNormalizeRtpCapabilities(t),t}constructor({getSendExtendedRtpCapabilities:e},t){super(),Ar.debug("constructor()"),this._getSendExtendedRtpCapabilities=e,this._fakeParameters=t}get name(){return r6}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=Rb.getSendingRtpParameters(e.kind,a);c.codecs=Rb.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 $0({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 sD.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 $0({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 s6.InvalidStateError("method called in a closed handler")}};V0.FakeHandler=kb;var $0=class extends oD.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 s6.InvalidStateError("not open")}}});var i6=se(sn=>{"use strict";Object.defineProperty(sn,"__esModule",{value:!0});sn.generateRouterRtpCapabilities=aD;sn.generateNativeRtpCapabilities=cD;sn.generateNativeSctpCapabilities=dD;sn.generateLocalDtlsParameters=uD;sn.generateTransportRemoteParameters=fD;sn.generateProducerRemoteParameters=lD;sn.generateConsumerRemoteParameters=hD;sn.generateDataProducerRemoteParameters=pD;sn.generateDataConsumerRemoteParameters=mD;var Qr=ka();function _s(){return String(Qr.generateRandomNumber())}function aD(){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 cD(){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 dD(){return Qr.deepFreeze({numStreams:{OS:2048,MIS:2048}})}function uD(){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 fD(){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 lD(){return Qr.deepFreeze({id:_s()})}function hD({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 pD(){return Qr.deepFreeze({id:_s()})}function mD({id:r}={}){return{id:r??_s(),dataProducerId:_s(),sctpStreamParameters:Qr.deepFreeze({streamId:666,maxPacketLifeTime:5e3,maxRetransmits:void 0})}}});var fb=se(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 gD=Tf();Qt.debug=gD.default;Qt.types=kE();Qt.version="3.20.0";var Pb=WC();Object.defineProperty(Qt,"Device",{enumerable:!0,get:function(){return Pb.Device}});Object.defineProperty(Qt,"detectDevice",{enumerable:!0,get:function(){return Pb.detectDevice}});Object.defineProperty(Qt,"detectDeviceAsync",{enumerable:!0,get:function(){return Pb.detectDeviceAsync}});var yD=Oa();Object.defineProperty(Qt,"parseScalabilityMode",{enumerable:!0,get:function(){return yD.parse}});Qt.ortc=kn();Qt.enhancedEvents=as();var xD=n6();Object.defineProperty(Qt,"FakeHandler",{enumerable:!0,get:function(){return xD.FakeHandler}});Qt.testFakeParameters=i6()});var a6=se((FK,Bb)=>{"use strict";var bD=Object.prototype.hasOwnProperty,Zr="~";function qf(){}Object.create&&(qf.prototype=Object.create(null),new qf().__proto__||(Zr=!1));function vD(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function o6(r,e,t,s,n){if(typeof t!="function")throw new TypeError("The listener must be a function");var i=new vD(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 K0(r,e){--r._eventsCount===0?r._events=new qf:delete r._events[e]}function qr(){this._events=new qf,this._eventsCount=0}qr.prototype.eventNames=function(){var e=[],t,s;if(this._eventsCount===0)return e;for(s in t=this._events)bD.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 o6(this,e,t,s,!1)};qr.prototype.once=function(e,t,s){return o6(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 K0(this,i),this;var o=this._events[i];if(o.fn)o.fn===t&&(!n||o.once)&&(!s||o.context===s)&&K0(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:K0(this,i)}return this};qr.prototype.removeAllListeners=function(e){var t;return e?(t=Zr?Zr+e:e,this._events[t]&&K0(this,t)):(this._events=new qf,this._eventsCount=0),this};qr.prototype.off=qr.prototype.removeListener;qr.prototype.addListener=qr.prototype.on;qr.prefixed=Zr;qr.EventEmitter=qr;typeof Bb<"u"&&(Bb.exports=qr)});var wo=se(c6=>{"use strict";function wD(){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}}c6.jspack=new wD});var Ob=se(($K,d6)=>{"use strict";function SD(r){t.debug=t,t.default=t,t.coerce=c,t.disable=o,t.enable=n,t.enabled=a,t.humanize=Bx(),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,(te,Ee)=>{if(te==="%%")return"%";Q++;let ge=t.formatters[Ee];if(typeof ge=="function"){let Y=C[Q];te=ge.call(O,Y),C.splice(Q,1),Q--}return te}),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}d6.exports=SD});var u6=se((Es,W0)=>{"use strict";Es.formatArgs=ED;Es.save=CD;Es.load=TD;Es.useColors=_D;Es.storage=AD();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 _D(){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 ED(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+W0.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 CD(r){try{r?Es.storage.setItem("debug",r):Es.storage.removeItem("debug")}catch{}}function TD(){let r;try{r=Es.storage.getItem("debug")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function AD(){try{return localStorage}catch{}}W0.exports=Ob()(Es);var{formatters:ID}=W0.exports;ID.j=function(r){try{return JSON.stringify(r)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var l6=se((_r,X0)=>{"use strict";var RD=require("tty"),G0=require("util");_r.init=DD;_r.log=ND;_r.formatArgs=PD;_r.save=OD;_r.load=LD;_r.useColors=kD;_r.destroy=G0.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=(Mx(),Px(Dx));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 kD(){return"colors"in _r.inspectOpts?!!_r.inspectOpts.colors:RD.isatty(process.stderr.fd)}function PD(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+"+X0.exports.humanize(this.diff)+"\x1B[0m")}else r[0]=BD()+e+" "+r[0]}function BD(){return _r.inspectOpts.hideDate?"":new Date().toISOString()+" "}function ND(...r){return process.stderr.write(G0.formatWithOptions(_r.inspectOpts,...r)+`
|
|
10
|
-
`)}function OD(r){r?process.env.DEBUG=r:delete process.env.DEBUG}function LD(){return process.env.DEBUG}function DD(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]]}X0.exports=Ob()(_r);var{formatters:f6}=X0.exports;f6.o=function(r){return this.inspectOpts.colors=this.useColors,G0.inspect(r,this.inspectOpts).split(`
|
|
11
|
-
`).map(e=>e.trim()).join(" ")};f6.O=function(r){return this.inspectOpts.colors=this.useColors,G0.inspect(r,this.inspectOpts)}});var h6=se((VK,Lb)=>{"use strict";typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?Lb.exports=u6():Lb.exports=l6()});var Y0=se(Ud=>{"use strict";Object.defineProperty(Ud,"__esModule",{value:!0});var MD=require("net");function UD(r){switch(MD.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=UD;function jD(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=jD;var So=Object.create(null),p6=/^[0-9.]+$/;function HD(r){return p6.test(r)&&So[r]!==""?r:So[r]==null?"":So[r]}Ud.getOID=HD;function FD(r){return!p6.test(r)&&So[r]!==""||So[r]==null?r:So[r]}Ud.getOIDName=FD;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 Q0=se((WK,J0)=>{"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,ue=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,Re=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,Pe=w,qe=k,_e=N,Be=G,Oe=ue,ve=Le,U=Se,j=Pt,re=Re,W=rt,X=nt,ae=pt,Xe=lt,mt=it,yt=dt,gt=ot,E,wt=0;wt<20;wt+=2)E=Pe+Xe|0,Oe^=E<<7|E>>>25,E=Oe+Pe|0,re^=E<<9|E>>>23,E=re+Oe|0,Xe^=E<<13|E>>>19,E=Xe+re|0,Pe^=E<<18|E>>>14,E=ve+qe|0,W^=E<<7|E>>>25,E=W+ve|0,mt^=E<<9|E>>>23,E=mt+W|0,qe^=E<<13|E>>>19,E=qe+mt|0,ve^=E<<18|E>>>14,E=X+U|0,yt^=E<<7|E>>>25,E=yt+X|0,_e^=E<<9|E>>>23,E=_e+yt|0,U^=E<<13|E>>>19,E=U+_e|0,X^=E<<18|E>>>14,E=gt+ae|0,Be^=E<<7|E>>>25,E=Be+gt|0,j^=E<<9|E>>>23,E=j+Be|0,ae^=E<<13|E>>>19,E=ae+j|0,gt^=E<<18|E>>>14,E=Pe+Be|0,qe^=E<<7|E>>>25,E=qe+Pe|0,_e^=E<<9|E>>>23,E=_e+qe|0,Be^=E<<13|E>>>19,E=Be+_e|0,Pe^=E<<18|E>>>14,E=ve+Oe|0,U^=E<<7|E>>>25,E=U+ve|0,j^=E<<9|E>>>23,E=j+U|0,Oe^=E<<13|E>>>19,E=Oe+j|0,ve^=E<<18|E>>>14,E=X+W|0,ae^=E<<7|E>>>25,E=ae+X|0,re^=E<<9|E>>>23,E=re+ae|0,W^=E<<13|E>>>19,E=W+re|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;Pe=Pe+w|0,qe=qe+k|0,_e=_e+N|0,Be=Be+G|0,Oe=Oe+ue|0,ve=ve+Le|0,U=U+Se|0,j=j+Pt|0,re=re+Re|0,W=W+rt|0,X=X+nt|0,ae=ae+pt|0,Xe=Xe+lt|0,mt=mt+it|0,yt=yt+dt|0,gt=gt+ot|0,m[0]=Pe>>>0&255,m[1]=Pe>>>8&255,m[2]=Pe>>>16&255,m[3]=Pe>>>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]=Be>>>0&255,m[13]=Be>>>8&255,m[14]=Be>>>16&255,m[15]=Be>>>24&255,m[16]=Oe>>>0&255,m[17]=Oe>>>8&255,m[18]=Oe>>>16&255,m[19]=Oe>>>24&255,m[20]=ve>>>0&255,m[21]=ve>>>8&255,m[22]=ve>>>16&255,m[23]=ve>>>24&255,m[24]=U>>>0&255,m[25]=U>>>8&255,m[26]=U>>>16&255,m[27]=U>>>24&255,m[28]=j>>>0&255,m[29]=j>>>8&255,m[30]=j>>>16&255,m[31]=j>>>24&255,m[32]=re>>>0&255,m[33]=re>>>8&255,m[34]=re>>>16&255,m[35]=re>>>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]=ae>>>0&255,m[45]=ae>>>8&255,m[46]=ae>>>16&255,m[47]=ae>>>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,ue=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,Re=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,Pe=w,qe=k,_e=N,Be=G,Oe=ue,ve=Le,U=Se,j=Pt,re=Re,W=rt,X=nt,ae=pt,Xe=lt,mt=it,yt=dt,gt=ot,E,wt=0;wt<20;wt+=2)E=Pe+Xe|0,Oe^=E<<7|E>>>25,E=Oe+Pe|0,re^=E<<9|E>>>23,E=re+Oe|0,Xe^=E<<13|E>>>19,E=Xe+re|0,Pe^=E<<18|E>>>14,E=ve+qe|0,W^=E<<7|E>>>25,E=W+ve|0,mt^=E<<9|E>>>23,E=mt+W|0,qe^=E<<13|E>>>19,E=qe+mt|0,ve^=E<<18|E>>>14,E=X+U|0,yt^=E<<7|E>>>25,E=yt+X|0,_e^=E<<9|E>>>23,E=_e+yt|0,U^=E<<13|E>>>19,E=U+_e|0,X^=E<<18|E>>>14,E=gt+ae|0,Be^=E<<7|E>>>25,E=Be+gt|0,j^=E<<9|E>>>23,E=j+Be|0,ae^=E<<13|E>>>19,E=ae+j|0,gt^=E<<18|E>>>14,E=Pe+Be|0,qe^=E<<7|E>>>25,E=qe+Pe|0,_e^=E<<9|E>>>23,E=_e+qe|0,Be^=E<<13|E>>>19,E=Be+_e|0,Pe^=E<<18|E>>>14,E=ve+Oe|0,U^=E<<7|E>>>25,E=U+ve|0,j^=E<<9|E>>>23,E=j+U|0,Oe^=E<<13|E>>>19,E=Oe+j|0,ve^=E<<18|E>>>14,E=X+W|0,ae^=E<<7|E>>>25,E=ae+X|0,re^=E<<9|E>>>23,E=re+ae|0,W^=E<<13|E>>>19,E=W+re|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]=Pe>>>0&255,m[1]=Pe>>>8&255,m[2]=Pe>>>16&255,m[3]=Pe>>>24&255,m[4]=ve>>>0&255,m[5]=ve>>>8&255,m[6]=ve>>>16&255,m[7]=ve>>>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]=U>>>0&255,m[17]=U>>>8&255,m[18]=U>>>16&255,m[19]=U>>>24&255,m[20]=j>>>0&255,m[21]=j>>>8&255,m[22]=j>>>16&255,m[23]=j>>>24&255,m[24]=re>>>0&255,m[25]=re>>>8&255,m[26]=re>>>16&255,m[27]=re>>>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 te(m,b,x,l,w,k,N){var G=new Uint8Array(16),ue=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(ue,G,N,oe),Se=0;Se<64;Se++)m[b+Se]=x[l+Se]^ue[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(ue,G,N,oe),Se=0;Se<w;Se++)m[b+Se]=x[l+Se]^ue[Se];return 0}function Ee(m,b,x,l,w){var k=new Uint8Array(16),N=new Uint8Array(64),G,ue;for(ue=0;ue<16;ue++)k[ue]=0;for(ue=0;ue<8;ue++)k[ue]=l[ue];for(;x>=64;){for(z(N,k,w,oe),ue=0;ue<64;ue++)m[b+ue]=N[ue];for(G=1,ue=8;ue<16;ue++)G=G+(k[ue]&255)|0,k[ue]=G&255,G>>>=8;x-=64,b+=64}if(x>0)for(z(N,k,w,oe),ue=0;ue<x;ue++)m[b+ue]=N[ue];return 0}function ge(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 Ee(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 ue=new Uint8Array(8),Le=0;Le<8;Le++)ue[Le]=k[Le+16];return te(m,b,x,l,w,ue,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,ue;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,ue=m[14]&255|(m[15]&255)<<8,this.r[8]=(G>>>8|ue<<8)&8191,this.r[9]=ue>>>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,ue,Le,Se,Pt,Re,rt,nt,pt,lt,it,dt,ot,Pe,qe,_e,Be=this.h[0],Oe=this.h[1],ve=this.h[2],U=this.h[3],j=this.h[4],re=this.h[5],W=this.h[6],X=this.h[7],ae=this.h[8],Xe=this.h[9],mt=this.r[0],yt=this.r[1],gt=this.r[2],E=this.r[3],wt=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,Be+=w&8191,k=m[b+2]&255|(m[b+3]&255)<<8,Oe+=(w>>>13|k<<3)&8191,N=m[b+4]&255|(m[b+5]&255)<<8,ve+=(k>>>10|N<<6)&8191,G=m[b+6]&255|(m[b+7]&255)<<8,U+=(N>>>7|G<<9)&8191,ue=m[b+8]&255|(m[b+9]&255)<<8,j+=(G>>>4|ue<<12)&8191,re+=ue>>>1&8191,Le=m[b+10]&255|(m[b+11]&255)<<8,W+=(ue>>>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,ae+=(Se>>>8|Pt<<8)&8191,Xe+=Pt>>>5|l,Re=0,rt=Re,rt+=Be*mt,rt+=Oe*(5*It),rt+=ve*(5*At),rt+=U*(5*bt),rt+=j*(5*Nt),Re=rt>>>13,rt&=8191,rt+=re*(5*Bt),rt+=W*(5*wt),rt+=X*(5*E),rt+=ae*(5*gt),rt+=Xe*(5*yt),Re+=rt>>>13,rt&=8191,nt=Re,nt+=Be*yt,nt+=Oe*mt,nt+=ve*(5*It),nt+=U*(5*At),nt+=j*(5*bt),Re=nt>>>13,nt&=8191,nt+=re*(5*Nt),nt+=W*(5*Bt),nt+=X*(5*wt),nt+=ae*(5*E),nt+=Xe*(5*gt),Re+=nt>>>13,nt&=8191,pt=Re,pt+=Be*gt,pt+=Oe*yt,pt+=ve*mt,pt+=U*(5*It),pt+=j*(5*At),Re=pt>>>13,pt&=8191,pt+=re*(5*bt),pt+=W*(5*Nt),pt+=X*(5*Bt),pt+=ae*(5*wt),pt+=Xe*(5*E),Re+=pt>>>13,pt&=8191,lt=Re,lt+=Be*E,lt+=Oe*gt,lt+=ve*yt,lt+=U*mt,lt+=j*(5*It),Re=lt>>>13,lt&=8191,lt+=re*(5*At),lt+=W*(5*bt),lt+=X*(5*Nt),lt+=ae*(5*Bt),lt+=Xe*(5*wt),Re+=lt>>>13,lt&=8191,it=Re,it+=Be*wt,it+=Oe*E,it+=ve*gt,it+=U*yt,it+=j*mt,Re=it>>>13,it&=8191,it+=re*(5*It),it+=W*(5*At),it+=X*(5*bt),it+=ae*(5*Nt),it+=Xe*(5*Bt),Re+=it>>>13,it&=8191,dt=Re,dt+=Be*Bt,dt+=Oe*wt,dt+=ve*E,dt+=U*gt,dt+=j*yt,Re=dt>>>13,dt&=8191,dt+=re*mt,dt+=W*(5*It),dt+=X*(5*At),dt+=ae*(5*bt),dt+=Xe*(5*Nt),Re+=dt>>>13,dt&=8191,ot=Re,ot+=Be*Nt,ot+=Oe*Bt,ot+=ve*wt,ot+=U*E,ot+=j*gt,Re=ot>>>13,ot&=8191,ot+=re*yt,ot+=W*mt,ot+=X*(5*It),ot+=ae*(5*At),ot+=Xe*(5*bt),Re+=ot>>>13,ot&=8191,Pe=Re,Pe+=Be*bt,Pe+=Oe*Nt,Pe+=ve*Bt,Pe+=U*wt,Pe+=j*E,Re=Pe>>>13,Pe&=8191,Pe+=re*gt,Pe+=W*yt,Pe+=X*mt,Pe+=ae*(5*It),Pe+=Xe*(5*At),Re+=Pe>>>13,Pe&=8191,qe=Re,qe+=Be*At,qe+=Oe*bt,qe+=ve*Nt,qe+=U*Bt,qe+=j*wt,Re=qe>>>13,qe&=8191,qe+=re*E,qe+=W*gt,qe+=X*yt,qe+=ae*mt,qe+=Xe*(5*It),Re+=qe>>>13,qe&=8191,_e=Re,_e+=Be*It,_e+=Oe*At,_e+=ve*bt,_e+=U*Nt,_e+=j*Bt,Re=_e>>>13,_e&=8191,_e+=re*wt,_e+=W*E,_e+=X*gt,_e+=ae*yt,_e+=Xe*mt,Re+=_e>>>13,_e&=8191,Re=(Re<<2)+Re|0,Re=Re+rt|0,rt=Re&8191,Re=Re>>>13,nt+=Re,Be=rt,Oe=nt,ve=pt,U=lt,j=it,re=dt,W=ot,X=Pe,ae=qe,Xe=_e,b+=16,x-=16;this.h[0]=Be,this.h[1]=Oe,this.h[2]=ve,this.h[3]=U,this.h[4]=j,this.h[5]=re,this.h[6]=W,this.h[7]=X,this.h[8]=ae,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 vt(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 vt(N,0,x,l,w,k),S(m,b,N,0)}function $(m,b,x,l,w){var k;if(x<32)return-1;for(Y(m,0,b,0,x,l,w),vt(m,16,m,32,x-32,m),k=0;k<16;k++)m[k]=0;return 0}function V(m,b,x,l,w){var k,N=new Uint8Array(32);if(x<32||(ge(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 H(m,b){var x;for(x=0;x<16;x++)m[x]=b[x]|0}function me(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 Te(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 ne(m,b){var x,l,w,k=e(),N=e();for(x=0;x<16;x++)N[x]=b[x];for(me(N),me(N),me(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,Te(N,k,1-w)}for(x=0;x<16;x++)m[2*x]=N[x]&255,m[2*x+1]=N[x]>>8}function T(m,b){var x=new Uint8Array(32),l=new Uint8Array(32);return ne(x,m),ne(l,b),C(x,0,l,0)}function R(m){var b=new Uint8Array(32);return ne(b,m),b[0]&1}function F(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 ce(m,b,x){var l,w,k=0,N=0,G=0,ue=0,Le=0,Se=0,Pt=0,Re=0,rt=0,nt=0,pt=0,lt=0,it=0,dt=0,ot=0,Pe=0,qe=0,_e=0,Be=0,Oe=0,ve=0,U=0,j=0,re=0,W=0,X=0,ae=0,Xe=0,mt=0,yt=0,gt=0,E=x[0],wt=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*wt,G+=l*Bt,ue+=l*Nt,Le+=l*bt,Se+=l*At,Pt+=l*It,Re+=l*cr,rt+=l*Mt,nt+=l*rr,pt+=l*sr,lt+=l*nr,it+=l*gr,dt+=l*jr,ot+=l*Hr,Pe+=l*Fr,l=b[1],N+=l*E,G+=l*wt,ue+=l*Bt,Le+=l*Nt,Se+=l*bt,Pt+=l*At,Re+=l*It,rt+=l*cr,nt+=l*Mt,pt+=l*rr,lt+=l*sr,it+=l*nr,dt+=l*gr,ot+=l*jr,Pe+=l*Hr,qe+=l*Fr,l=b[2],G+=l*E,ue+=l*wt,Le+=l*Bt,Se+=l*Nt,Pt+=l*bt,Re+=l*At,rt+=l*It,nt+=l*cr,pt+=l*Mt,lt+=l*rr,it+=l*sr,dt+=l*nr,ot+=l*gr,Pe+=l*jr,qe+=l*Hr,_e+=l*Fr,l=b[3],ue+=l*E,Le+=l*wt,Se+=l*Bt,Pt+=l*Nt,Re+=l*bt,rt+=l*At,nt+=l*It,pt+=l*cr,lt+=l*Mt,it+=l*rr,dt+=l*sr,ot+=l*nr,Pe+=l*gr,qe+=l*jr,_e+=l*Hr,Be+=l*Fr,l=b[4],Le+=l*E,Se+=l*wt,Pt+=l*Bt,Re+=l*Nt,rt+=l*bt,nt+=l*At,pt+=l*It,lt+=l*cr,it+=l*Mt,dt+=l*rr,ot+=l*sr,Pe+=l*nr,qe+=l*gr,_e+=l*jr,Be+=l*Hr,Oe+=l*Fr,l=b[5],Se+=l*E,Pt+=l*wt,Re+=l*Bt,rt+=l*Nt,nt+=l*bt,pt+=l*At,lt+=l*It,it+=l*cr,dt+=l*Mt,ot+=l*rr,Pe+=l*sr,qe+=l*nr,_e+=l*gr,Be+=l*jr,Oe+=l*Hr,ve+=l*Fr,l=b[6],Pt+=l*E,Re+=l*wt,rt+=l*Bt,nt+=l*Nt,pt+=l*bt,lt+=l*At,it+=l*It,dt+=l*cr,ot+=l*Mt,Pe+=l*rr,qe+=l*sr,_e+=l*nr,Be+=l*gr,Oe+=l*jr,ve+=l*Hr,U+=l*Fr,l=b[7],Re+=l*E,rt+=l*wt,nt+=l*Bt,pt+=l*Nt,lt+=l*bt,it+=l*At,dt+=l*It,ot+=l*cr,Pe+=l*Mt,qe+=l*rr,_e+=l*sr,Be+=l*nr,Oe+=l*gr,ve+=l*jr,U+=l*Hr,j+=l*Fr,l=b[8],rt+=l*E,nt+=l*wt,pt+=l*Bt,lt+=l*Nt,it+=l*bt,dt+=l*At,ot+=l*It,Pe+=l*cr,qe+=l*Mt,_e+=l*rr,Be+=l*sr,Oe+=l*nr,ve+=l*gr,U+=l*jr,j+=l*Hr,re+=l*Fr,l=b[9],nt+=l*E,pt+=l*wt,lt+=l*Bt,it+=l*Nt,dt+=l*bt,ot+=l*At,Pe+=l*It,qe+=l*cr,_e+=l*Mt,Be+=l*rr,Oe+=l*sr,ve+=l*nr,U+=l*gr,j+=l*jr,re+=l*Hr,W+=l*Fr,l=b[10],pt+=l*E,lt+=l*wt,it+=l*Bt,dt+=l*Nt,ot+=l*bt,Pe+=l*At,qe+=l*It,_e+=l*cr,Be+=l*Mt,Oe+=l*rr,ve+=l*sr,U+=l*nr,j+=l*gr,re+=l*jr,W+=l*Hr,X+=l*Fr,l=b[11],lt+=l*E,it+=l*wt,dt+=l*Bt,ot+=l*Nt,Pe+=l*bt,qe+=l*At,_e+=l*It,Be+=l*cr,Oe+=l*Mt,ve+=l*rr,U+=l*sr,j+=l*nr,re+=l*gr,W+=l*jr,X+=l*Hr,ae+=l*Fr,l=b[12],it+=l*E,dt+=l*wt,ot+=l*Bt,Pe+=l*Nt,qe+=l*bt,_e+=l*At,Be+=l*It,Oe+=l*cr,ve+=l*Mt,U+=l*rr,j+=l*sr,re+=l*nr,W+=l*gr,X+=l*jr,ae+=l*Hr,Xe+=l*Fr,l=b[13],dt+=l*E,ot+=l*wt,Pe+=l*Bt,qe+=l*Nt,_e+=l*bt,Be+=l*At,Oe+=l*It,ve+=l*cr,U+=l*Mt,j+=l*rr,re+=l*sr,W+=l*nr,X+=l*gr,ae+=l*jr,Xe+=l*Hr,mt+=l*Fr,l=b[14],ot+=l*E,Pe+=l*wt,qe+=l*Bt,_e+=l*Nt,Be+=l*bt,Oe+=l*At,ve+=l*It,U+=l*cr,j+=l*Mt,re+=l*rr,W+=l*sr,X+=l*nr,ae+=l*gr,Xe+=l*jr,mt+=l*Hr,yt+=l*Fr,l=b[15],Pe+=l*E,qe+=l*wt,_e+=l*Bt,Be+=l*Nt,Oe+=l*bt,ve+=l*At,U+=l*It,j+=l*cr,re+=l*Mt,W+=l*rr,X+=l*sr,ae+=l*nr,Xe+=l*gr,mt+=l*jr,yt+=l*Hr,gt+=l*Fr,k+=38*qe,N+=38*_e,G+=38*Be,ue+=38*Oe,Le+=38*ve,Se+=38*U,Pt+=38*j,Re+=38*re,rt+=38*W,nt+=38*X,pt+=38*ae,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=ue+w+65535,w=Math.floor(l/65536),ue=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=Re+w+65535,w=Math.floor(l/65536),Re=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=Pe+w+65535,w=Math.floor(l/65536),Pe=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=ue+w+65535,w=Math.floor(l/65536),ue=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=Re+w+65535,w=Math.floor(l/65536),Re=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=Pe+w+65535,w=Math.floor(l/65536),Pe=l-w*65536,k+=w-1+37*(w-1),m[0]=k,m[1]=N,m[2]=G,m[3]=ue,m[4]=Le,m[5]=Se,m[6]=Pt,m[7]=Re,m[8]=rt,m[9]=nt,m[10]=pt,m[11]=lt,m[12]=it,m[13]=dt,m[14]=ot,m[15]=Pe}function he(m,b){ce(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&&ce(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&&ce(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(),ue=e(),Le=e(),Se=e(),Pt=e(),Re=e();for(N=0;N<31;N++)l[N]=b[N];for(l[31]=b[31]&127|64,l[0]&=248,F(w,x),N=0;N<16;N++)ue[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,Te(G,ue,k),Te(Le,Se,k),I(Pt,G,Le),L(G,G,Le),I(Le,ue,Se),L(ue,ue,Se),he(Se,Pt),he(Re,G),ce(G,Le,G),ce(Le,ue,Pt),I(Pt,G,Le),L(G,G,Le),he(ue,G),L(Le,Se,Re),ce(G,Le,a),I(G,G,Se),ce(Le,Le,G),ce(G,Se,Re),ce(Se,ue,w),he(ue,Pt),Te(G,ue,k),Te(Le,Se,k);for(N=0;N<16;N++)w[N+16]=G[N],w[N+32]=Le[N],w[N+48]=ue[N],w[N+64]=Se[N];var rt=w.subarray(32),nt=w.subarray(16);return ct(rt,rt),ce(nt,nt,rt),ne(m,nt),0}function _t(m,b){return Ot(m,b,n)}function Dt(m,b){return t(b,32),_t(m,b)}function Bs(m,b,x){var l=new Uint8Array(32);return Ot(l,x,b),Q(m,s,l,oe)}var Ns=$,Ca=V;function Ix(m,b,x,l,w,k){var N=new Uint8Array(32);return Bs(N,w,k),Ns(m,b,x,l,N)}function xf(m,b,x,l,w,k){var N=new Uint8Array(32);return Bs(N,w,k),Ca(m,b,x,l,N)}var bf=[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 vf(m,b,x,l){for(var w=new Int32Array(16),k=new Int32Array(16),N,G,ue,Le,Se,Pt,Re,rt,nt,pt,lt,it,dt,ot,Pe,qe,_e,Be,Oe,ve,U,j,re,W,X,ae,Xe=m[0],mt=m[1],yt=m[2],gt=m[3],E=m[4],wt=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(Oe=0;Oe<16;Oe++)ve=8*Oe+gr,w[Oe]=x[ve+0]<<24|x[ve+1]<<16|x[ve+2]<<8|x[ve+3],k[Oe]=x[ve+4]<<24|x[ve+5]<<16|x[ve+6]<<8|x[ve+7];for(Oe=0;Oe<80;Oe++)if(N=Xe,G=mt,ue=yt,Le=gt,Se=E,Pt=wt,Re=Bt,rt=Nt,nt=bt,pt=At,lt=It,it=cr,dt=Mt,ot=rr,Pe=sr,qe=nr,U=Nt,j=nr,re=j&65535,W=j>>>16,X=U&65535,ae=U>>>16,U=(E>>>14|Mt<<18)^(E>>>18|Mt<<14)^(Mt>>>9|E<<23),j=(Mt>>>14|E<<18)^(Mt>>>18|E<<14)^(E>>>9|Mt<<23),re+=j&65535,W+=j>>>16,X+=U&65535,ae+=U>>>16,U=E&wt^~E&Bt,j=Mt&rr^~Mt&sr,re+=j&65535,W+=j>>>16,X+=U&65535,ae+=U>>>16,U=bf[Oe*2],j=bf[Oe*2+1],re+=j&65535,W+=j>>>16,X+=U&65535,ae+=U>>>16,U=w[Oe%16],j=k[Oe%16],re+=j&65535,W+=j>>>16,X+=U&65535,ae+=U>>>16,W+=re>>>16,X+=W>>>16,ae+=X>>>16,_e=X&65535|ae<<16,Be=re&65535|W<<16,U=_e,j=Be,re=j&65535,W=j>>>16,X=U&65535,ae=U>>>16,U=(Xe>>>28|bt<<4)^(bt>>>2|Xe<<30)^(bt>>>7|Xe<<25),j=(bt>>>28|Xe<<4)^(Xe>>>2|bt<<30)^(Xe>>>7|bt<<25),re+=j&65535,W+=j>>>16,X+=U&65535,ae+=U>>>16,U=Xe&mt^Xe&yt^mt&yt,j=bt&At^bt&It^At&It,re+=j&65535,W+=j>>>16,X+=U&65535,ae+=U>>>16,W+=re>>>16,X+=W>>>16,ae+=X>>>16,rt=X&65535|ae<<16,qe=re&65535|W<<16,U=Le,j=it,re=j&65535,W=j>>>16,X=U&65535,ae=U>>>16,U=_e,j=Be,re+=j&65535,W+=j>>>16,X+=U&65535,ae+=U>>>16,W+=re>>>16,X+=W>>>16,ae+=X>>>16,Le=X&65535|ae<<16,it=re&65535|W<<16,mt=N,yt=G,gt=ue,E=Le,wt=Se,Bt=Pt,Nt=Re,Xe=rt,At=nt,It=pt,cr=lt,Mt=it,rr=dt,sr=ot,nr=Pe,bt=qe,Oe%16===15)for(ve=0;ve<16;ve++)U=w[ve],j=k[ve],re=j&65535,W=j>>>16,X=U&65535,ae=U>>>16,U=w[(ve+9)%16],j=k[(ve+9)%16],re+=j&65535,W+=j>>>16,X+=U&65535,ae+=U>>>16,_e=w[(ve+1)%16],Be=k[(ve+1)%16],U=(_e>>>1|Be<<31)^(_e>>>8|Be<<24)^_e>>>7,j=(Be>>>1|_e<<31)^(Be>>>8|_e<<24)^(Be>>>7|_e<<25),re+=j&65535,W+=j>>>16,X+=U&65535,ae+=U>>>16,_e=w[(ve+14)%16],Be=k[(ve+14)%16],U=(_e>>>19|Be<<13)^(Be>>>29|_e<<3)^_e>>>6,j=(Be>>>19|_e<<13)^(_e>>>29|Be<<3)^(Be>>>6|_e<<26),re+=j&65535,W+=j>>>16,X+=U&65535,ae+=U>>>16,W+=re>>>16,X+=W>>>16,ae+=X>>>16,w[ve]=X&65535|ae<<16,k[ve]=re&65535|W<<16;U=Xe,j=bt,re=j&65535,W=j>>>16,X=U&65535,ae=U>>>16,U=m[0],j=b[0],re+=j&65535,W+=j>>>16,X+=U&65535,ae+=U>>>16,W+=re>>>16,X+=W>>>16,ae+=X>>>16,m[0]=Xe=X&65535|ae<<16,b[0]=bt=re&65535|W<<16,U=mt,j=At,re=j&65535,W=j>>>16,X=U&65535,ae=U>>>16,U=m[1],j=b[1],re+=j&65535,W+=j>>>16,X+=U&65535,ae+=U>>>16,W+=re>>>16,X+=W>>>16,ae+=X>>>16,m[1]=mt=X&65535|ae<<16,b[1]=At=re&65535|W<<16,U=yt,j=It,re=j&65535,W=j>>>16,X=U&65535,ae=U>>>16,U=m[2],j=b[2],re+=j&65535,W+=j>>>16,X+=U&65535,ae+=U>>>16,W+=re>>>16,X+=W>>>16,ae+=X>>>16,m[2]=yt=X&65535|ae<<16,b[2]=It=re&65535|W<<16,U=gt,j=cr,re=j&65535,W=j>>>16,X=U&65535,ae=U>>>16,U=m[3],j=b[3],re+=j&65535,W+=j>>>16,X+=U&65535,ae+=U>>>16,W+=re>>>16,X+=W>>>16,ae+=X>>>16,m[3]=gt=X&65535|ae<<16,b[3]=cr=re&65535|W<<16,U=E,j=Mt,re=j&65535,W=j>>>16,X=U&65535,ae=U>>>16,U=m[4],j=b[4],re+=j&65535,W+=j>>>16,X+=U&65535,ae+=U>>>16,W+=re>>>16,X+=W>>>16,ae+=X>>>16,m[4]=E=X&65535|ae<<16,b[4]=Mt=re&65535|W<<16,U=wt,j=rr,re=j&65535,W=j>>>16,X=U&65535,ae=U>>>16,U=m[5],j=b[5],re+=j&65535,W+=j>>>16,X+=U&65535,ae+=U>>>16,W+=re>>>16,X+=W>>>16,ae+=X>>>16,m[5]=wt=X&65535|ae<<16,b[5]=rr=re&65535|W<<16,U=Bt,j=sr,re=j&65535,W=j>>>16,X=U&65535,ae=U>>>16,U=m[6],j=b[6],re+=j&65535,W+=j>>>16,X+=U&65535,ae+=U>>>16,W+=re>>>16,X+=W>>>16,ae+=X>>>16,m[6]=Bt=X&65535|ae<<16,b[6]=sr=re&65535|W<<16,U=Nt,j=nr,re=j&65535,W=j>>>16,X=U&65535,ae=U>>>16,U=m[7],j=b[7],re+=j&65535,W+=j>>>16,X+=U&65535,ae+=U>>>16,W+=re>>>16,X+=W>>>16,ae+=X>>>16,m[7]=Nt=X&65535|ae<<16,b[7]=nr=re&65535|W<<16,gr+=128,l-=128}return l}function Rn(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,vf(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),vf(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(),ue=e(),Le=e(),Se=e();L(x,m[1],m[0]),L(Se,b[1],b[0]),ce(x,x,Se),I(l,m[0],m[1]),I(Se,b[0],b[1]),ce(l,l,Se),ce(w,m[3],b[3]),ce(w,w,d),ce(k,m[2],b[2]),I(k,k,k),L(N,l,x),L(G,k,w),I(ue,k,w),I(Le,l,x),ce(m[0],N,G),ce(m[1],Le,ue),ce(m[2],ue,G),ce(m[3],N,Le)}function wf(m,b,x){var l;for(l=0;l<4;l++)Te(m[l],b[l],x)}function Aa(m,b){var x=e(),l=e(),w=e();ct(w,b[2]),ce(x,b[0],w),ce(l,b[1],w),ne(m,l),m[31]^=R(x)<<7}function Sf(m,b,x){var l,w;for(H(m[0],i),H(m[1],o),H(m[2],o),H(m[3],i),w=255;w>=0;--w)l=x[w/8|0]>>(w&7)&1,wf(m,b,l),Ta(b,m),Ta(m,m),wf(m,b,l)}function ud(m,b){var x=[e(),e(),e(),e()];H(x[0],u),H(x[1],f),H(x[2],o),ce(x[3],u,f),Sf(m,x,b)}function _f(m,b,x){var l=new Uint8Array(64),w=[e(),e(),e(),e()],k;for(x||t(b,32),Rn(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 Ef(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 s0(m,b,x,l){var w=new Uint8Array(64),k=new Uint8Array(64),N=new Uint8Array(64),G,ue,Le=new Float64Array(64),Se=[e(),e(),e(),e()];Rn(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(Rn(N,m.subarray(32),x+32),Ef(N),ud(Se,N),Aa(m,Se),G=32;G<64;G++)m[G]=l[G];for(Rn(k,m,x+64),Ef(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(ue=0;ue<32;ue++)Le[G+ue]+=k[G]*w[ue];return xi(m.subarray(32),Le),Pt}function Rx(m,b){var x=e(),l=e(),w=e(),k=e(),N=e(),G=e(),ue=e();return H(m[2],o),F(m[1],b),he(w,m[1]),ce(k,w,c),L(w,w,m[2]),I(k,m[2],k),he(N,k),he(G,N),ce(ue,G,N),ce(x,ue,w),ce(x,x,k),xt(x,x),ce(x,x,w),ce(x,x,k),ce(x,x,k),ce(m[0],x,k),he(l,m[0]),ce(l,l,k),T(l,w)&&ce(m[0],m[0],h),he(l,m[0]),ce(l,l,k),T(l,w)?-1:(R(m[0])===b[31]>>7&&L(m[0],i,m[0]),ce(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()],ue=[e(),e(),e(),e()];if(x<64||Rx(ue,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(Rn(N,m,x),Ef(N),Sf(G,ue,N),ud(ue,b.subarray(32)),Ta(G,ue),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,D=24,q=32,de=16,Me=32,$t=32,Wt=32,ft=32,ye=32,Ce=D,ke=q,Ne=de,st=64,kt=32,jt=64,Xr=32,ld=64;r.lowlevel={crypto_core_hsalsa20:Q,crypto_stream_xor:Y,crypto_stream:ge,crypto_stream_salsa20_xor:te,crypto_stream_salsa20:Ee,crypto_onetimeauth:vt,crypto_onetimeauth_verify:Fe,crypto_verify_16:S,crypto_verify_32:C,crypto_secretbox:$,crypto_secretbox_open:V,crypto_scalarmult:Ot,crypto_scalarmult_base:_t,crypto_box_beforenm:Bs,crypto_box_afternm:Ns,crypto_box:Ix,crypto_box_open:xf,crypto_box_keypair:Dt,crypto_hash:Rn,crypto_sign:s0,crypto_sign_keypair:_f,crypto_sign_open:Ia,crypto_secretbox_KEYBYTES:P,crypto_secretbox_NONCEBYTES:D,crypto_secretbox_ZEROBYTES:q,crypto_secretbox_BOXZEROBYTES:de,crypto_scalarmult_BYTES:Me,crypto_scalarmult_SCALARBYTES:$t,crypto_box_PUBLICKEYBYTES:Wt,crypto_box_SECRETKEYBYTES:ft,crypto_box_BEFORENMBYTES:ye,crypto_box_NONCEBYTES:Ce,crypto_box_ZEROBYTES:ke,crypto_box_BOXZEROBYTES:Ne,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:ne,unpack25519:F,M:ce,A:I,S:he,Z:L,pow2523:xt,add:Ta,set25519:H,modL:xi,scalarmult:Sf,scalarbase:ud};function n0(m,b){if(m.length!==P)throw new Error("bad key size");if(b.length!==D)throw new Error("bad nonce size")}function kx(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 wE(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),n0(x,b);for(var l=new Uint8Array(q+m.length),w=new Uint8Array(l.length),k=0;k<m.length;k++)l[k+q]=m[k];return $(w,l,l.length,b,x),w.subarray(de)},r.secretbox.open=function(m,b,x){ws(m,b,x),n0(x,b);for(var l=new Uint8Array(de+m.length),w=new Uint8Array(l.length),k=0;k<m.length;k++)l[k+de]=m[k];return l.length<32||V(w,l,l.length,b,x)!==0?null:w.subarray(q)},r.secretbox.keyLength=P,r.secretbox.nonceLength=D,r.secretbox.overheadLength=de,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 _t(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),kx(m,b);var x=new Uint8Array(ye);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 _t(b,m),{publicKey:b,secretKey:new Uint8Array(m)}},r.box.publicKeyLength=Wt,r.box.secretKeyLength=ft,r.box.sharedKeyLength=ye,r.box.nonceLength=Ce,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 s0(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 _f(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 _f(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 Rn(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];wE(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];wE(k)}))})()})(typeof J0<"u"&&J0.exports?J0.exports:self.nacl=self.nacl||{})});var Ub=se(Mb=>{"use strict";Object.defineProperty(Mb,"__esModule",{value:!0});var Db=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}};Mb.BufferVisitor=Db});var y6=se(qb=>{"use strict";Object.defineProperty(qb,"__esModule",{value:!0});var m6=require("util"),g6=64,Hb="-----BEGIN ",Fb="-----END ",zf="-----",jb="Proc-Type",Z0=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(qD(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(jb)}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=Hb+this.type+zf+`
|
|
13
|
-
`,t=Object.keys(this.headers);if(t.length>0){let i=this.procType;i!==""&&(e+=`${jb}: ${i}
|
|
14
|
-
`),t.sort();for(let o of t)o!==jb&&(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+g6)+`
|
|
17
|
-
`,n+=g6;return e+=Fb+this.type+zf+`
|
|
18
|
-
`,e}toBuffer(){return Buffer.from(this.toString(),"utf8")}valueOf(){return this.body}toJSON(){return{type:this.type,body:this.body,headers:this.headers}}[m6.inspect.custom](e,t){return`<${this.constructor.name} ${m6.inspect(this.toJSON(),t)}>`}};qb.PEM=Z0;function qD(r){let e=r.shift();if(e==null||!e.startsWith(Hb)||!e.endsWith(zf))throw new Error("pem: invalid BEGIN line");let t=e.slice(Hb.length,e.length-zf.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(Fb);)n+=e,e=r.shift();if(e==null||e!==`${Fb}${t}${zf}`)throw new Error("pem: invalid END line");let i=new Z0(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 w6=se(_o=>{"use strict";Object.defineProperty(_o,"__esModule",{value:!0});var x6=require("util"),em=Ub(),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 Et;(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"})(Et=_o.Tag||(_o.Tag={}));var $f=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=$f;var zb=class r{static Bool(e){let t=new r(ir.UNIVERSAL,Et.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,Et.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,Et.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 $f(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,Et.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 $f(e.slice(1),(e.length-1)*8-t)}static Null(){let e=new r(ir.UNIVERSAL,Et.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,Et.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,Et.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(!b6(e))throw new Error("ASN1 syntax error: invalid NumericString");let t=new r(ir.UNIVERSAL,Et.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(!b6(t))throw new Error("ASN1 syntax error: invalid NumericString");return t}static PrintableString(e){let t=new r(ir.UNIVERSAL,Et.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(!v6(e))throw new Error("ASN1 syntax error: invalid IA5String");let t=new r(ir.UNIVERSAL,Et.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(!v6(t))throw new Error("ASN1 syntax error: invalid IA5String");return t}static T61String(e){let t=new r(ir.UNIVERSAL,Et.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,Et.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,Et.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,Et.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 Et.UTCTIME:return r.parseUTCTime(t);case Et.GENERALIZEDTIME:return r.parseGeneralizedTime(t);default:throw new Error("Invalid ASN1 time tag")}}static Set(e){let t=new r(ir.UNIVERSAL,Et.SET,Buffer.concat(e.map(s=>s.toDER())));return t._value=e,t}static Seq(e){let t=new r(ir.UNIVERSAL,Et.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 em.BufferVisitor(e),t)}static parseDER(e,t,s){let n=r._fromDER(new em.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 em.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 em.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=zD(e);if(e.mustHas(a),a!==0&&o===Et.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===Et.SEQUENCE||t===Et.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=$D(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 Et.BOOLEAN:return r.parseBool(this.bytes);case Et.INTEGER:return r.parseInteger(this.bytes);case Et.BITSTRING:return r.parseBitString(this.bytes);case Et.NULL:return r.parseNull(this.bytes);case Et.OID:return r.parseOID(this.bytes);case Et.UTF8:return r.parseUTF8(this.bytes);case Et.NUMERICSTRING:return r.parseNumericString(this.bytes);case Et.PRINTABLESTRING:return r.parsePrintableString(this.bytes);case Et.T61STRING:return r.parseT61String(this.bytes);case Et.IA5STRING:return r.parseIA5String(this.bytes);case Et.GENERALSTRING:return r.parseGeneralString(this.bytes);case Et.UTCTIME:return r.parseUTCTime(this.bytes);case Et.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 ${Et[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===Et.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?Et[this.tag]:this.tag,value:e}}[x6.inspect.custom](e,t){return t.depth<=2&&(t.depth=10),`<${this.constructor.name} ${x6.inspect(this.toJSON(),t)}>`}};_o.ASN1=zb;function zD(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 $D(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 b6(r){for(let e of r){let t=e.charCodeAt(0);if(t!==32&&(t<48||t>57))return!1}return!0}function v6(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 $b=se(Eo=>{"use strict";Object.defineProperty(Eo,"__esModule",{value:!0});var VD=Ub();Eo.BufferVisitor=VD.BufferVisitor;var KD=y6();Eo.PEM=KD.PEM;var tm=w6();Eo.ASN1=tm.ASN1;Eo.Class=tm.Class;Eo.Tag=tm.Tag;Eo.BitString=tm.BitString});var Gb=se(Ln=>{"use strict";Object.defineProperty(Ln,"__esModule",{value:!0});var To=require("util"),Vf=require("crypto"),Wb=Q0(),le=$b(),zr=Y0();Ln.publicKeyValidator={name:"PublicKeyInfo",class:le.Class.UNIVERSAL,tag:le.Tag.SEQUENCE,capture:"publicKeyInfo",value:[{name:"PublicKeyInfo.AlgorithmIdentifier",class:le.Class.UNIVERSAL,tag:le.Tag.SEQUENCE,value:[{name:"PublicKeyAlgorithmIdentifier.algorithm",class:le.Class.UNIVERSAL,tag:le.Tag.OID,capture:"publicKeyOID"}]},{name:"PublicKeyInfo.PublicKey",class:le.Class.UNIVERSAL,tag:le.Tag.BITSTRING,capture:"publicKey"}]};Ln.privateKeyValidator={name:"PrivateKeyInfo",class:le.Class.UNIVERSAL,tag:le.Tag.SEQUENCE,capture:"privateKeyInfo",value:[{name:"PrivateKeyInfo.Version",class:le.Class.UNIVERSAL,tag:le.Tag.INTEGER,capture:"privateKeyVersion"},{name:"PrivateKeyInfo.AlgorithmIdentifier",class:le.Class.UNIVERSAL,tag:le.Tag.SEQUENCE,value:[{name:"PrivateKeyAlgorithmIdentifier.algorithm",class:le.Class.UNIVERSAL,tag:le.Tag.OID,capture:"privateKeyOID"}]},{name:"PrivateKeyInfo.PrivateKey",class:le.Class.UNIVERSAL,tag:le.Tag.OCTETSTRING,capture:"privateKey"}]};var WD={name:"RSAPublicKey",class:le.Class.UNIVERSAL,tag:le.Tag.SEQUENCE,value:[{name:"RSAPublicKey.modulus",class:le.Class.UNIVERSAL,tag:le.Tag.INTEGER,capture:"publicKeyModulus"},{name:"RSAPublicKey.exponent",class:le.Class.UNIVERSAL,tag:le.Tag.INTEGER,capture:"publicKeyExponent"}]},GD={name:"RSAPrivateKey",class:le.Class.UNIVERSAL,tag:le.Tag.SEQUENCE,value:[{name:"RSAPrivateKey.version",class:le.Class.UNIVERSAL,tag:le.Tag.INTEGER,capture:"privateKeyVersion"},{name:"RSAPrivateKey.modulus",class:le.Class.UNIVERSAL,tag:le.Tag.INTEGER,capture:"privateKeyModulus"},{name:"RSAPrivateKey.publicExponent",class:le.Class.UNIVERSAL,tag:le.Tag.INTEGER,capture:"privateKeyPublicExponent"},{name:"RSAPrivateKey.privateExponent",class:le.Class.UNIVERSAL,tag:le.Tag.INTEGER,capture:"privateKeyPrivateExponent"},{name:"RSAPrivateKey.prime1",class:le.Class.UNIVERSAL,tag:le.Tag.INTEGER,capture:"privateKeyPrime1"},{name:"RSAPrivateKey.prime2",class:le.Class.UNIVERSAL,tag:le.Tag.INTEGER,capture:"privateKeyPrime2"},{name:"RSAPrivateKey.exponent1",class:le.Class.UNIVERSAL,tag:le.Tag.INTEGER,capture:"privateKeyExponent1"},{name:"RSAPrivateKey.exponent2",class:le.Class.UNIVERSAL,tag:le.Tag.INTEGER,capture:"privateKeyExponent2"},{name:"RSAPrivateKey.coefficient",class:le.Class.UNIVERSAL,tag:le.Tag.INTEGER,capture:"privateKeyCoefficient"}]},XD=[zr.getOID("X25519"),zr.getOID("X448"),zr.getOID("Ed25519"),zr.getOID("Ed448")],jd=class r{constructor(e){let t={},s=e.validate(Ln.publicKeyValidator,t);if(s!=null)throw new Error("Cannot read X.509 public key: "+s.message);this.oid=le.ASN1.parseOID(t.publicKeyOID.bytes),this.algo=zr.getOIDName(this.oid),this._pkcs8=e,this._keyRaw=le.ASN1.parseBitString(t.publicKey.bytes).buf,this._finalKey=this._keyRaw,this._finalPEM=""}static fromPEM(e){let t=le.PEM.parse(e)[0];if(t.procType.includes("ENCRYPTED"))throw new Error("Could not convert public key from PEM, PEM is encrypted.");let s=le.ASN1.fromDER(t.body,!0);switch(t.type){case"PUBLIC KEY":return new r(s);case"RSA PUBLIC KEY":let n=le.ASN1.Seq([le.ASN1.Seq([le.ASN1.OID(zr.getOID("rsaEncryption")),le.ASN1.Null()]),le.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=Vf.createHash(s).update(e).digest();return n.call(this,o,t)}let i=Vf.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=Vf.createHash(e);return n.update(s),n.digest()}toASN1(){return this._pkcs8}toDER(){return this._pkcs8.DER}toPEM(){return this._finalPEM===""&&(this._finalPEM=new le.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);Ln.PublicKey=jd;var Hd=class r{constructor(e){let t=Object.create(null),s=e.validate(Ln.privateKeyValidator,t);if(s!=null)throw new Error("Cannot read X.509 private key: "+s.message);if(this.version=le.ASN1.parseIntegerNum(t.privateKeyVersion.bytes)+1,this.oid=le.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="",XD.includes(this.oid)){if(this._finalKey=this._keyRaw=le.ASN1.parseDER(this._keyRaw,le.Class.UNIVERSAL,le.Tag.OCTETSTRING).bytes,this.oid==="1.3.101.112"){let n=Wb.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===le.Class.CONTEXT_SPECIFIC&&n.tag===1&&(this._publicKeyRaw=le.ASN1.parseBitString(n.bytes).buf,this._finalKey=Buffer.concat([this._keyRaw,this._publicKeyRaw]))}}static fromPEM(e){let t=le.PEM.parse(e)[0];if(t.procType.includes("ENCRYPTED"))throw new Error("Could not convert private key from PEM, PEM is encrypted.");let s=le.ASN1.fromDER(t.body,!0);switch(t.type){case"PRIVATE KEY":return new r(s);case"RSA PRIVATE KEY":return s=le.ASN1.Seq([s.value[0],le.ASN1.Seq([le.ASN1.OID(zr.getOID("rsaEncryption")),le.ASN1.Null()]),new le.ASN1(le.Class.UNIVERSAL,le.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=Vf.createHash(t).update(e).digest();return s.call(this,i)}let n=Vf.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 le.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);Ln.PrivateKey=Hd;var Vb=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=le.ASN1.fromDER(this._keyRaw,!0);let s=this._pkcs1.validate(WD,t);if(s!=null)throw new Error("Cannot read RSA public key: "+s.message);this.modulus=le.ASN1.parseIntegerStr(t.publicKeyModulus.bytes),this.exponent=le.ASN1.parseIntegerNum(t.publicKeyExponent.bytes)}toASN1(){return this._pkcs1}toDER(){return this._keyRaw}toPEM(){return this._finalPEM===""&&(this._finalPEM=new le.PEM("RSA PUBLIC KEY",this._keyRaw).toString()),this._finalPEM}toPublicKeyPEM(){return new le.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)}>`}};Ln.RSAPublicKey=Vb;var Kb=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=le.ASN1.fromDER(this._keyRaw,!0);let s=this._pkcs1.validate(GD,t);if(s!=null)throw new Error("Cannot read RSA private key: "+s.message);this.publicExponent=le.ASN1.parseIntegerNum(t.privateKeyPublicExponent.bytes),this.privateExponent=le.ASN1.parseIntegerStr(t.privateKeyPrivateExponent.bytes),this.modulus=le.ASN1.parseIntegerStr(t.privateKeyModulus.bytes),this.prime1=le.ASN1.parseIntegerStr(t.privateKeyPrime1.bytes),this.prime2=le.ASN1.parseIntegerStr(t.privateKeyPrime2.bytes),this.exponent1=le.ASN1.parseIntegerStr(t.privateKeyExponent1.bytes),this.exponent2=le.ASN1.parseIntegerStr(t.privateKeyExponent2.bytes),this.coefficient=le.ASN1.parseIntegerStr(t.privateKeyCoefficient.bytes)}toASN1(){return this._pkcs1}toDER(){return this._keyRaw}toPEM(){return this._finalPEM===""&&(this._finalPEM=new le.PEM("RSA PRIVATE KEY",this._keyRaw).toString()),this._finalPEM}toPrivateKeyPEM(){return new le.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)}>`}};Ln.RSAPrivateKey=Kb;function Co(r){return r.length%8!==0&&r.startsWith("00")?r.slice(2):r}jd.addVerifier(zr.getOID("Ed25519"),function(r,e){return Wb.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(Wb.sign.detached(r,e))})});var A6=se(rm=>{"use strict";Object.defineProperty(rm,"__esModule",{value:!0});var S6=require("util"),YD=require("crypto"),ie=$b(),$r=Y0(),T6=Gb(),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 JD(r){return br[r]==null?"":br[r]}var QD={name:"Certificate",class:ie.Class.UNIVERSAL,tag:ie.Tag.SEQUENCE,value:[{name:"Certificate.TBSCertificate",class:ie.Class.UNIVERSAL,tag:ie.Tag.SEQUENCE,capture:"tbsCertificate",value:[{name:"Certificate.TBSCertificate.version",class:ie.Class.CONTEXT_SPECIFIC,tag:ie.Tag.NONE,optional:!0,value:[{name:"Certificate.TBSCertificate.version.integer",class:ie.Class.UNIVERSAL,tag:ie.Tag.INTEGER,capture:"certVersion"}]},{name:"Certificate.TBSCertificate.serialNumber",class:ie.Class.UNIVERSAL,tag:ie.Tag.INTEGER,capture:"certSerialNumber"},{name:"Certificate.TBSCertificate.signature",class:ie.Class.UNIVERSAL,tag:ie.Tag.SEQUENCE,value:[{name:"Certificate.TBSCertificate.signature.algorithm",class:ie.Class.UNIVERSAL,tag:ie.Tag.OID,capture:"certinfoSignatureOID"},{name:"Certificate.TBSCertificate.signature.parameters",class:ie.Class.UNIVERSAL,tag:ie.Tag.OCTETSTRING,optional:!0,capture:"certinfoSignatureParams"}]},{name:"Certificate.TBSCertificate.issuer",class:ie.Class.UNIVERSAL,tag:ie.Tag.SEQUENCE,capture:"certIssuer"},{name:"Certificate.TBSCertificate.validity",class:ie.Class.UNIVERSAL,tag:ie.Tag.SEQUENCE,value:[{name:"Certificate.TBSCertificate.validity.notBefore",class:ie.Class.UNIVERSAL,tag:[ie.Tag.UTCTIME,ie.Tag.GENERALIZEDTIME],capture:"certValidityNotBefore"},{name:"Certificate.TBSCertificate.validity.notAfter",class:ie.Class.UNIVERSAL,tag:[ie.Tag.UTCTIME,ie.Tag.GENERALIZEDTIME],capture:"certValidityNotAfter"}]},{name:"Certificate.TBSCertificate.subject",class:ie.Class.UNIVERSAL,tag:ie.Tag.SEQUENCE,capture:"certSubject"},T6.publicKeyValidator,{name:"Certificate.TBSCertificate.issuerUniqueID",class:ie.Class.CONTEXT_SPECIFIC,tag:ie.Tag.BOOLEAN,optional:!0,value:[{name:"Certificate.TBSCertificate.issuerUniqueID.id",class:ie.Class.UNIVERSAL,tag:ie.Tag.BITSTRING,capture:"certIssuerUniqueId"}]},{name:"Certificate.TBSCertificate.subjectUniqueID",class:ie.Class.CONTEXT_SPECIFIC,tag:ie.Tag.INTEGER,optional:!0,value:[{name:"Certificate.TBSCertificate.subjectUniqueID.id",class:ie.Class.UNIVERSAL,tag:ie.Tag.BITSTRING,capture:"certSubjectUniqueId"}]},{name:"Certificate.TBSCertificate.extensions",class:ie.Class.CONTEXT_SPECIFIC,tag:ie.Tag.BITSTRING,capture:"certExtensions",optional:!0}]},{name:"Certificate.signatureAlgorithm",class:ie.Class.UNIVERSAL,tag:ie.Tag.SEQUENCE,value:[{name:"Certificate.signatureAlgorithm.algorithm",class:ie.Class.UNIVERSAL,tag:ie.Tag.OID,capture:"certSignatureOID"},{name:"Certificate.TBSCertificate.signature.parameters",class:ie.Class.UNIVERSAL,tag:ie.Tag.OCTETSTRING,optional:!0,capture:"certSignatureParams"}]},{name:"Certificate.signatureValue",class:ie.Class.UNIVERSAL,tag:ie.Tag.BITSTRING,capture:"certSignature"}]},Kf=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=YD.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){E6([e]),this.attributes.push(e)}setAttrs(e){E6(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:""}};rm.DistinguishedName=Kf;var Xb=class r{static fromPEMs(e){let t=[],s=ie.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=ie.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(QD,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:ie.ASN1.parseIntegerNum(t.certVersion.bytes)+1,this.serialNumber=ie.ASN1.parseIntegerStr(t.certSerialNumber.bytes),this.signatureOID=ie.ASN1.parseOID(t.certSignatureOID.bytes),this.signatureAlgorithm=$r.getOIDName(this.signatureOID),this.infoSignatureOID=ie.ASN1.parseOID(t.certinfoSignatureOID.bytes),this.signature=ie.ASN1.parseBitString(t.certSignature.bytes).buf,this.validFrom=ie.ASN1.parseTime(t.certValidityNotBefore.tag,t.certValidityNotBefore.bytes),this.validTo=ie.ASN1.parseTime(t.certValidityNotAfter.tag,t.certValidityNotAfter.bytes),this.issuer=new Kf,this.issuer.setAttrs(C6(t.certIssuer)),t.certIssuerUniqueId!=null&&(this.issuer.uniqueId=ie.ASN1.parseBitString(t.certIssuerUniqueId.bytes)),this.subject=new Kf,this.subject.setAttrs(C6(t.certSubject)),t.certSubjectUniqueId!=null&&(this.subject.uniqueId=ie.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=ZD(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 T6.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=fM(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]=lM(this[t]);return delete e.tbsCertificate,e}[S6.inspect.custom](e,t){return t.depth<=2&&(t.depth=10),`<${this.constructor.name} ${S6.inspect(this.toJSON(),t)}>`}};rm.Certificate=Xb;function ZD(r){let e=[];for(let t of r.mustCompound())for(let s of t.mustCompound())e.push(eM(s));return e}function eM(r){let e={};switch(e.oid=ie.ASN1.parseOID(r.value[0].bytes),e.critical=!1,r.value[1].tag===ie.Tag.BOOLEAN?(e.critical=ie.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":tM(e);break;case"basicConstraints":rM(e);break;case"extKeyUsage":sM(e);break;case"nsCertType":nM(e);break;case"subjectAltName":_6(e);break;case"issuerAltName":_6(e);break;case"subjectKeyIdentifier":oM(e);break;case"authorityKeyIdentifier":cM(e);break;case"authorityInfoAccess":uM(e);break}return e}function tM(r){let e=ie.ASN1.parseBitString(ie.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 rM(r){let t=ie.ASN1.fromDER(r.value).mustCompound();t.length>0&&t[0].tag===ie.Tag.BOOLEAN?r.isCA=ie.ASN1.parseBool(t[0].bytes):r.isCA=!1;let s=null;t.length>0&&t[0].tag===ie.Tag.INTEGER?s=t[0].bytes:t.length>1&&(s=t[1].bytes),s!==null?r.maxPathLen=ie.ASN1.parseInteger(s):r.maxPathLen=-1,r.basicConstraintsValid=!0}function sM(r){let t=ie.ASN1.fromDER(r.value).mustCompound();for(let s of t)r[$r.getOIDName(ie.ASN1.parseOID(s.bytes))]=!0}function nM(r){let e=ie.ASN1.parseBitString(ie.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 _6(r){r.altNames=[];let t=ie.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=ie.ASN1.parseOID(s.bytes);break;default:}}}var iM={name:"subjectKeyIdentifier",class:ie.Class.UNIVERSAL,tag:ie.Tag.OCTETSTRING,capture:"subjectKeyIdentifier"};function oM(r){let e=ie.ASN1.parseDERWithTemplate(r.value,iM);r.subjectKeyIdentifier=e.subjectKeyIdentifier.bytes.toString("hex")}var aM={name:"authorityKeyIdentifier",class:ie.Class.UNIVERSAL,tag:ie.Tag.SEQUENCE,value:[{name:"authorityKeyIdentifier.value",class:ie.Class.CONTEXT_SPECIFIC,tag:ie.Tag.NONE,capture:"authorityKeyIdentifier"}]};function cM(r){let e=ie.ASN1.parseDERWithTemplate(r.value,aM);r.authorityKeyIdentifier=e.authorityKeyIdentifier.bytes.toString("hex")}var dM={name:"authorityInfoAccess",class:ie.Class.UNIVERSAL,tag:ie.Tag.SEQUENCE,value:[{name:"authorityInfoAccess.authorityInfoAccessOcsp",class:ie.Class.UNIVERSAL,tag:ie.Tag.SEQUENCE,optional:!0,value:[{name:"authorityInfoAccess.authorityInfoAccessOcsp.oid",class:ie.Class.UNIVERSAL,tag:ie.Tag.OID},{name:"authorityInfoAccess.authorityInfoAccessOcsp.value",class:ie.Class.CONTEXT_SPECIFIC,tag:ie.Tag.OID,capture:"authorityInfoAccessOcsp"}]},{name:"authorityInfoAccess.authorityInfoAccessIssuers",class:ie.Class.UNIVERSAL,tag:ie.Tag.SEQUENCE,optional:!0,value:[{name:"authorityInfoAccess.authorityInfoAccessIssuers.oid",class:ie.Class.UNIVERSAL,tag:ie.Tag.OID},{name:"authorityInfoAccess.authorityInfoAccessIssuers.value",class:ie.Class.CONTEXT_SPECIFIC,tag:ie.Tag.OID,capture:"authorityInfoAccessIssuers"}]}]};function uM(r){let e=ie.ASN1.parseDERWithTemplate(r.value,dM);e.authorityInfoAccessOcsp!=null&&(r.authorityInfoAccessOcsp=e.authorityInfoAccessOcsp.bytes.toString()),e.authorityInfoAccessIssuers!=null&&(r.authorityInfoAccessIssuers=e.authorityInfoAccessIssuers.bytes.toString())}function E6(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 fM(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 C6(r){let e=[];for(let t of r.mustCompound())for(let s of t.mustCompound()){let n=s.mustCompound(),i={};i.oid=ie.ASN1.parseOID(n[0].bytes),i.value=n[1].value,i.valueTag=n[1].tag,i.name=$r.getOIDName(i.oid),i.shortName=JD(i.name),e.push(i)}return e}function lM(r){return r!=null&&!(r instanceof Buffer)&&typeof r.toJSON=="function"?r.toJSON():r}});var Yb=se(js=>{"use strict";Object.defineProperty(js,"__esModule",{value:!0});var sm=Y0();js.bytesFromIP=sm.bytesFromIP;js.bytesToIP=sm.bytesToIP;js.getOID=sm.getOID;js.getOIDName=sm.getOIDName;var nm=Gb();js.PublicKey=nm.PublicKey;js.PrivateKey=nm.PrivateKey;js.RSAPublicKey=nm.RSAPublicKey;js.RSAPrivateKey=nm.RSAPrivateKey;var I6=A6();js.Certificate=I6.Certificate;js.DistinguishedName=I6.DistinguishedName});var k6=se(()=>{"use strict";var R6;(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,D){return s.call(P,D)}:function(P,D){return D in P},get:d?function(P,D){return s.call(P,D)?P[D]:void 0}:function(P,D){return P[D]}},f=Object.getPrototypeOf(Function),h=typeof Map=="function"&&typeof Map.prototype.entries=="function"?Map:Ef(),y=typeof Set=="function"&&typeof Set.prototype.entries=="function"?Set:s0(),v=typeof WeakMap=="function"?WeakMap:Rx(),S=n?Symbol.for("@reflect-metadata:registry"):void 0,C=ud(),O=_f(C);function K(P,D,q,de){if(I(q)){if(!Bs(P))throw new TypeError;if(!Ca(D))throw new TypeError;return Fe(P,D)}else{if(!Bs(P))throw new TypeError;if(!he(D))throw new TypeError;if(!he(de)&&!I(de)&&!L(de))throw new TypeError;return L(de)&&(de=void 0),q=Dt(q),$(P,D,q,de)}}e("decorate",K);function z(P,D){function q(de,Me){if(!he(de))throw new TypeError;if(!I(Me)&&!Ix(Me))throw new TypeError;ne(P,D,de,Me)}return q}e("metadata",z);function Q(P,D,q,de){if(!he(q))throw new TypeError;return I(de)||(de=Dt(de)),ne(P,D,q,de)}e("defineMetadata",Q);function oe(P,D,q){if(!he(D))throw new TypeError;return I(q)||(q=Dt(q)),V(P,D,q)}e("hasMetadata",oe);function te(P,D,q){if(!he(D))throw new TypeError;return I(q)||(q=Dt(q)),H(P,D,q)}e("hasOwnMetadata",te);function Ee(P,D,q){if(!he(D))throw new TypeError;return I(q)||(q=Dt(q)),me(P,D,q)}e("getMetadata",Ee);function ge(P,D,q){if(!he(D))throw new TypeError;return I(q)||(q=Dt(q)),Te(P,D,q)}e("getOwnMetadata",ge);function Y(P,D){if(!he(P))throw new TypeError;return I(D)||(D=Dt(D)),T(P,D)}e("getMetadataKeys",Y);function Ze(P,D){if(!he(P))throw new TypeError;return I(D)||(D=Dt(D)),R(P,D)}e("getOwnMetadataKeys",Ze);function vt(P,D,q){if(!he(D))throw new TypeError;if(I(q)||(q=Dt(q)),!he(D))throw new TypeError;I(q)||(q=Dt(q));var de=xi(D,q,!1);return I(de)?!1:de.OrdinaryDeleteMetadata(P,D,q)}e("deleteMetadata",vt);function Fe(P,D){for(var q=P.length-1;q>=0;--q){var de=P[q],Me=de(D);if(!I(Me)&&!L(Me)){if(!Ca(Me))throw new TypeError;D=Me}}return D}function $(P,D,q,de){for(var Me=P.length-1;Me>=0;--Me){var $t=P[Me],Wt=$t(D,q,de);if(!I(Wt)&&!L(Wt)){if(!he(Wt))throw new TypeError;de=Wt}}return de}function V(P,D,q){var de=H(P,D,q);if(de)return!0;var Me=Aa(D);return L(Me)?!1:V(P,Me,q)}function H(P,D,q){var de=xi(D,q,!1);return I(de)?!1:Ot(de.OrdinaryHasOwnMetadata(P,D,q))}function me(P,D,q){var de=H(P,D,q);if(de)return Te(P,D,q);var Me=Aa(D);if(!L(Me))return me(P,Me,q)}function Te(P,D,q){var de=xi(D,q,!1);if(!I(de))return de.OrdinaryGetOwnMetadata(P,D,q)}function ne(P,D,q,de){var Me=xi(q,de,!0);Me.OrdinaryDefineOwnMetadata(P,D,q,de)}function T(P,D){var q=R(P,D),de=Aa(P);if(de===null)return q;var Me=T(de,D);if(Me.length<=0)return q;if(q.length<=0)return Me;for(var $t=new y,Wt=[],ft=0,ye=q;ft<ye.length;ft++){var Ce=ye[ft],ke=$t.has(Ce);ke||($t.add(Ce),Wt.push(Ce))}for(var Ne=0,st=Me;Ne<st.length;Ne++){var Ce=st[Ne],ke=$t.has(Ce);ke||($t.add(Ce),Wt.push(Ce))}return Wt}function R(P,D){var q=xi(P,D,!1);return q?q.OrdinaryOwnMetadataKeys(P,D):[]}function F(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 ce(P){return typeof P=="symbol"}function he(P){return typeof P=="object"?P!==null:typeof P=="function"}function ct(P,D){switch(F(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 q=D===3?"string":D===5?"number":"default",de=bf(P,i);if(de!==void 0){var Me=de.call(P,q);if(he(Me))throw new TypeError;return Me}return xt(P,q==="default"?"number":q)}function xt(P,D){if(D==="string"){var q=P.toString;if(Ns(q)){var de=q.call(P);if(!he(de))return de}var Me=P.valueOf;if(Ns(Me)){var de=Me.call(P);if(!he(de))return de}}else{var Me=P.valueOf;if(Ns(Me)){var de=Me.call(P);if(!he(de))return de}var $t=P.toString;if(Ns($t)){var de=$t.call(P);if(!he(de))return de}}throw new TypeError}function Ot(P){return!!P}function _t(P){return""+P}function Dt(P){var D=ct(P,3);return ce(D)?D:_t(D)}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 Ix(P){switch(F(P)){case 3:return!0;case 4:return!0;default:return!1}}function xf(P,D){return P===D||P!==P&&D!==D}function bf(P,D){var q=P[D];if(q!=null){if(!Ns(q))throw new TypeError;return q}}function vf(P){var D=bf(P,o);if(!Ns(D))throw new TypeError;var q=D.call(P);if(!he(q))throw new TypeError;return q}function Rn(P){return P.value}function Ta(P){var D=P.next();return D.done?!1:D}function wf(P){var D=P.return;D&&D.call(P)}function Aa(P){var D=Object.getPrototypeOf(P);if(typeof P!="function"||P===f||D!==f)return D;var q=P.prototype,de=q&&Object.getPrototypeOf(q);if(de==null||de===Object.prototype)return D;var Me=de.constructor;return typeof Me!="function"||Me===P?D:Me}function Sf(){var P;!I(S)&&typeof t.Reflect<"u"&&!(S in t.Reflect)&&typeof t.Reflect.defineMetadata=="function"&&(P=fd(t.Reflect));var D,q,de,Me=new v,$t={registerProvider:Wt,getProvider:ye,setProvider:ke};return $t;function Wt(Ne){if(!Object.isExtensible($t))throw new Error("Cannot add provider to a frozen registry.");switch(!0){case P===Ne:break;case I(D):D=Ne;break;case D===Ne:break;case I(q):q=Ne;break;case q===Ne:break;default:de===void 0&&(de=new y),de.add(Ne);break}}function ft(Ne,st){if(!I(D)){if(D.isProviderFor(Ne,st))return D;if(!I(q)){if(q.isProviderFor(Ne,st))return D;if(!I(de))for(var kt=vf(de);;){var jt=Ta(kt);if(!jt)return;var Xr=Rn(jt);if(Xr.isProviderFor(Ne,st))return wf(kt),Xr}}}if(!I(P)&&P.isProviderFor(Ne,st))return P}function ye(Ne,st){var kt=Me.get(Ne),jt;return I(kt)||(jt=kt.get(st)),I(jt)&&(jt=ft(Ne,st),I(jt)||(I(kt)&&(kt=new h,Me.set(Ne,kt)),kt.set(st,jt))),jt}function Ce(Ne){if(I(Ne))throw new TypeError;return D===Ne||q===Ne||!I(de)&&de.has(Ne)}function ke(Ne,st,kt){if(!Ce(kt))throw new Error("Metadata provider not registered.");var jt=ye(Ne,st);if(jt!==kt){if(!I(jt))return!1;var Xr=Me.get(Ne);I(Xr)&&(Xr=new h,Me.set(Ne,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=Sf()),!I(S)&&he(t.Reflect)&&Object.isExtensible(t.Reflect)&&Object.defineProperty(t.Reflect,S,{enumerable:!1,configurable:!1,writable:!1,value:P}),P}function _f(P){var D=new v,q={isProviderFor:function(Ce,ke){var Ne=D.get(Ce);return I(Ne)?!1:Ne.has(ke)},OrdinaryDefineOwnMetadata:Wt,OrdinaryHasOwnMetadata:Me,OrdinaryGetOwnMetadata:$t,OrdinaryOwnMetadataKeys:ft,OrdinaryDeleteMetadata:ye};return C.registerProvider(q),q;function de(Ce,ke,Ne){var st=D.get(Ce),kt=!1;if(I(st)){if(!Ne)return;st=new h,D.set(Ce,st),kt=!0}var jt=st.get(ke);if(I(jt)){if(!Ne)return;if(jt=new h,st.set(ke,jt),!P.setProvider(Ce,ke,q))throw st.delete(ke),kt&&D.delete(Ce),new Error("Wrong provider for target.")}return jt}function Me(Ce,ke,Ne){var st=de(ke,Ne,!1);return I(st)?!1:Ot(st.has(Ce))}function $t(Ce,ke,Ne){var st=de(ke,Ne,!1);if(!I(st))return st.get(Ce)}function Wt(Ce,ke,Ne,st){var kt=de(Ne,st,!0);kt.set(Ce,ke)}function ft(Ce,ke){var Ne=[],st=de(Ce,ke,!1);if(I(st))return Ne;for(var kt=st.keys(),jt=vf(kt),Xr=0;;){var ld=Ta(jt);if(!ld)return Ne.length=Xr,Ne;var n0=Rn(ld);try{Ne[Xr]=n0}catch(kx){try{wf(jt)}finally{throw kx}}Xr++}}function ye(Ce,ke,Ne){var st=de(ke,Ne,!1);if(I(st)||!st.delete(Ce))return!1;if(st.size===0){var kt=D.get(ke);I(kt)||(kt.delete(Ne),kt.size===0&&D.delete(kt))}return!0}}function fd(P){var D=P.defineMetadata,q=P.hasOwnMetadata,de=P.getOwnMetadata,Me=P.getOwnMetadataKeys,$t=P.deleteMetadata,Wt=new v,ft={isProviderFor:function(ye,Ce){var ke=Wt.get(ye);return!I(ke)&&ke.has(Ce)?!0:Me(ye,Ce).length?(I(ke)&&(ke=new y,Wt.set(ye,ke)),ke.add(Ce),!0):!1},OrdinaryDefineOwnMetadata:D,OrdinaryHasOwnMetadata:q,OrdinaryGetOwnMetadata:de,OrdinaryOwnMetadataKeys:Me,OrdinaryDeleteMetadata:$t};return ft}function xi(P,D,q){var de=C.getProvider(P,D);if(!I(de))return de;if(q){if(C.setProvider(P,D,O))return O;throw new Error("Illegal state.")}}function Ef(){var P={},D=[],q=(function(){function ft(ye,Ce,ke){this._index=0,this._keys=ye,this._values=Ce,this._selector=ke}return ft.prototype["@@iterator"]=function(){return this},ft.prototype[o]=function(){return this},ft.prototype.next=function(){var ye=this._index;if(ye>=0&&ye<this._keys.length){var Ce=this._selector(this._keys[ye],this._values[ye]);return ye+1>=this._keys.length?(this._index=-1,this._keys=D,this._values=D):this._index++,{value:Ce,done:!1}}return{value:void 0,done:!0}},ft.prototype.throw=function(ye){throw this._index>=0&&(this._index=-1,this._keys=D,this._values=D),ye},ft.prototype.return=function(ye){return this._index>=0&&(this._index=-1,this._keys=D,this._values=D),{value:ye,done:!0}},ft})(),de=(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(ye){return this._find(ye,!1)>=0},ft.prototype.get=function(ye){var Ce=this._find(ye,!1);return Ce>=0?this._values[Ce]:void 0},ft.prototype.set=function(ye,Ce){var ke=this._find(ye,!0);return this._values[ke]=Ce,this},ft.prototype.delete=function(ye){var Ce=this._find(ye,!1);if(Ce>=0){for(var ke=this._keys.length,Ne=Ce+1;Ne<ke;Ne++)this._keys[Ne-1]=this._keys[Ne],this._values[Ne-1]=this._values[Ne];return this._keys.length--,this._values.length--,xf(ye,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 q(this._keys,this._values,Me)},ft.prototype.values=function(){return new q(this._keys,this._values,$t)},ft.prototype.entries=function(){return new q(this._keys,this._values,Wt)},ft.prototype["@@iterator"]=function(){return this.entries()},ft.prototype[o]=function(){return this.entries()},ft.prototype._find=function(ye,Ce){if(!xf(this._cacheKey,ye)){this._cacheIndex=-1;for(var ke=0;ke<this._keys.length;ke++)if(xf(this._keys[ke],ye)){this._cacheIndex=ke;break}}return this._cacheIndex<0&&Ce&&(this._cacheIndex=this._keys.length,this._keys.push(ye),this._values.push(void 0)),this._cacheIndex},ft})();return de;function Me(ft,ye){return ft}function $t(ft,ye){return ye}function Wt(ft,ye){return[ft,ye]}}function s0(){var P=(function(){function D(){this._map=new h}return Object.defineProperty(D.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),D.prototype.has=function(q){return this._map.has(q)},D.prototype.add=function(q){return this._map.set(q,q),this},D.prototype.delete=function(q){return this._map.delete(q)},D.prototype.clear=function(){this._map.clear()},D.prototype.keys=function(){return this._map.keys()},D.prototype.values=function(){return this._map.keys()},D.prototype.entries=function(){return this._map.entries()},D.prototype["@@iterator"]=function(){return this.keys()},D.prototype[o]=function(){return this.keys()},D})();return P}function Rx(){var P=16,D=u.create(),q=de();return(function(){function ye(){this._key=de()}return ye.prototype.has=function(Ce){var ke=Me(Ce,!1);return ke!==void 0?u.has(ke,this._key):!1},ye.prototype.get=function(Ce){var ke=Me(Ce,!1);return ke!==void 0?u.get(ke,this._key):void 0},ye.prototype.set=function(Ce,ke){var Ne=Me(Ce,!0);return Ne[this._key]=ke,this},ye.prototype.delete=function(Ce){var ke=Me(Ce,!1);return ke!==void 0?delete ke[this._key]:!1},ye.prototype.clear=function(){this._key=de()},ye})();function de(){var ye;do ye="@@WeakMap@@"+ft();while(u.has(D,ye));return D[ye]=!0,ye}function Me(ye,Ce){if(!s.call(ye,q)){if(!Ce)return;Object.defineProperty(ye,q,{value:u.create()})}return ye[q]}function $t(ye,Ce){for(var ke=0;ke<Ce;++ke)ye[ke]=Math.random()*255|0;return ye}function Wt(ye){if(typeof Uint8Array=="function"){var Ce=new Uint8Array(ye);return typeof crypto<"u"?crypto.getRandomValues(Ce):typeof msCrypto<"u"?msCrypto.getRandomValues(Ce):$t(Ce,ye),Ce}return $t(new Array(ye),ye)}function ft(){var ye=Wt(P);ye[6]=ye[6]&79|64,ye[8]=ye[8]&191|128;for(var Ce="",ke=0;ke<P;++ke){var Ne=ye[ke];(ke===4||ke===6||ke===8)&&(Ce+="-"),Ne<16&&(Ce+="0"),Ce+=Ne.toString(16).toLowerCase()}return Ce}}function Ia(P){return P.__=void 0,delete P.__,P}})})(R6||(R6={}))});function P6(...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 B6(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 hM,be,Jb,pM,mM,gM,im,Hs,Ue,Qb=A(()=>{"use strict";hM="[object ArrayBuffer]",be=class r{static isArrayBuffer(e){return Object.prototype.toString.call(e)===hM}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}},Jb="string",pM=/^[0-9a-f\s]+$/i,mM=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,gM=/^[a-zA-Z0-9-_]+$/,im=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=be.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=be.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===Jb&&pM.test(e)}static isBase64(e){return typeof e===Jb&&mM.test(e)}static isBase64Url(e){return typeof e===Jb&&gM.test(e)}static ToString(e,t="utf8"){let s=be.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=be.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 im.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 im.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=be.toUint8Array(e),s="";for(let n=0;n<t.length;n++)s+=String.fromCharCode(t[n]);return s}static ToHex(e){let t=be.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 om(...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 Zb(){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 N6(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 O6(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 sW,L6=A(()=>{"use strict";sW=Math.log(2)});var Hn={};Cf(Hn,{Any:()=>Mn,BaseBlock:()=>ur,BaseStringBlock:()=>Yf,BitString:()=>an,BmpString:()=>Fa,Boolean:()=>Ua,CharacterString:()=>Ya,Choice:()=>qd,Constructed:()=>fr,DATE:()=>rl,DEFAULT_MAX_CONTENT_LENGTH:()=>V6,DEFAULT_MAX_DEPTH:()=>z6,DEFAULT_MAX_NODES:()=>$6,DateTime:()=>nl,Duration:()=>il,EndOfContent:()=>Jf,Enumerated:()=>ja,GeneralString:()=>Xa,GeneralizedTime:()=>Ja,GraphicString:()=>Ga,HexBlock:()=>jn,IA5String:()=>Wa,Integer:()=>Ai,Null:()=>nn,NumericString:()=>za,ObjectIdentifier:()=>Ha,OctetString:()=>on,Primitive:()=>Ti,PrintableString:()=>$a,RawData:()=>t1,RelativeObjectIdentifier:()=>tl,Repeated:()=>Qa,Sequence:()=>Vr,Set:()=>es,TIME:()=>ol,TeletexString:()=>Va,TimeOfDay:()=>sl,UTCTime:()=>Ro,UniversalString:()=>qa,Utf8String:()=>Fs,ValueBlock:()=>Er,VideotexString:()=>Ka,ViewWriter:()=>Fd,VisibleString:()=>Io,compareSchema:()=>Ei,fromBER:()=>Ri,verifySchema:()=>MM});function am(){if(typeof BigInt>"u")throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function r1(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 jn(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?be.toUint8Array(i.valueHex):Sm}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",Un)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:Ue.ToHex(this.valueHexView)}}},e.NAME="hexBlock",e}function F6(r){var e;if(r instanceof Ae.Constructed)for(let t of r.valueBlock.value)F6(t)&&(r.lenBlock.isIndefiniteForm=!0);return!!(!((e=r.lenBlock)===null||e===void 0)&&e.isIndefiniteForm)}function al(r={}){var e,t,s;return{depth:0,maxDepth:(e=r.maxDepth)!==null&&e!==void 0?e:z6,nodesCount:0,maxNodes:(t=r.maxNodes)!==null&&t!==void 0?t:$6,maxContentLength:(s=r.maxContentLength)!==null&&s!==void 0?s:V6}}function kM(r){let e=new ur({},Er);return e.error=r,{offset:-1,result:e}}function PM(r){if(r.nodesCount+=1,r.nodesCount>r.maxNodes)return IM}function BM(r,e){if(r>e.maxContentLength)return RM}function s1(r,e,t,s){let n=s.depth+1;if(n>s.maxDepth)return kM(AM);s.depth=n;try{return _m(r,e,t,s)}finally{s.depth-=1}}function NM(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 _m(r,e=0,t=r.length,s=al()){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=PM(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=BM(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=Ae.EndOfContent;break;case 1:h=Ae.Boolean;break;case 2:h=Ae.Integer;break;case 3:h=Ae.BitString;break;case 4:h=Ae.OctetString;break;case 5:h=Ae.Null;break;case 6:h=Ae.ObjectIdentifier;break;case 10:h=Ae.Enumerated;break;case 12:h=Ae.Utf8String;break;case 13:h=Ae.RelativeObjectIdentifier;break;case 14:h=Ae.TIME;break;case 15:return i.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:i};case 16:h=Ae.Sequence;break;case 17:h=Ae.Set;break;case 18:h=Ae.NumericString;break;case 19:h=Ae.PrintableString;break;case 20:h=Ae.TeletexString;break;case 21:h=Ae.VideotexString;break;case 22:h=Ae.IA5String;break;case 23:h=Ae.UTCTime;break;case 24:h=Ae.GeneralizedTime;break;case 25:h=Ae.GraphicString;break;case 26:h=Ae.VisibleString;break;case 27:h=Ae.GeneralString;break;case 28:h=Ae.UniversalString;break;case 29:h=Ae.CharacterString;break;case 30:h=Ae.BmpString;break;case 31:h=Ae.DATE;break;case 32:h=Ae.TimeOfDay;break;case 33:h=Ae.DateTime;break;case 34:h=Ae.Duration;break;default:{let y=i.idBlock.isConstructed?new Ae.Constructed:new Ae.Primitive;y.idBlock=i.idBlock,y.lenBlock=i.lenBlock,y.warnings=i.warnings,i=y}}break;default:h=i.idBlock.isConstructed?Ae.Constructed:Ae.Primitive}return i=NM(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 _m(be.toUint8Array(r).slice(),0,r.byteLength,al(e))}function OM(r,e){return r?1:e}function LM(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=om(new Uint8Array([d%10]),i):i[o-f]=d%10;return t[0]>0&&(i=om(t,i)),i}function U6(r){if(r>=Wf.length)for(let e=Wf.length;e<=r;e++){let t=new Uint8Array([0]),s=Wf[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=om(t,s)),Wf.push(s)}return Wf[r]}function DM(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(e1)&&(i.name=t.name),i}}if(t instanceof Mn)return t.hasOwnProperty(e1)&&(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(!(vM in t))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(!(EM in t.idBlock))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(!(CM 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(wM)===!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(SM)===!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(_M)===!1)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(t.idBlock.isConstructed!==e.idBlock.isConstructed)return{verified:!1,result:r};if(!(bM 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(!(M6 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 Ae.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(e1 in t.valueBlock.value[0]&&t.valueBlock.value[0].name.length>0){let d={};TM 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&&M6 in e.valueBlock){let i=_m(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 MM(r,e){if(!(e instanceof Object))return{verified:!1,result:{error:"Wrong ASN.1 schema type"}};let t=_m(be.toUint8Array(r));return t.offset===-1?{verified:!1,result:t.result}:Ei(t.result,t.result,e)}var Fd,Wf,D6,e1,M6,bM,vM,wM,SM,_M,EM,CM,TM,ds,Un,Sm,Xf,j6,H6,Ci,Er,cm,dm,Ae,ur,Yf,um,q6,Ti,z6,$6,V6,AM,IM,RM,Dn,K6,fr,fm,W6,Jf,G6,nn,lm,X6,Ua,hm,n1,on,pm,Y6,an,J6,Qf,Gf,Ai,Q6,ja,Zf,mm,Z6,Ha,el,gm,e3,tl,t3,Vr,r3,es,ym,xm,ts,bm,s3,Fs,vm,n3,Fa,wm,i3,qa,o3,za,a3,$a,c3,Va,d3,Ka,u3,Wa,f3,Ga,l3,Io,h3,Xa,p3,Ya,m3,Ro,g3,Ja,y3,rl,x3,sl,b3,nl,v3,il,w3,ol,Mn,qd,Qa,t1,ko=A(()=>{"use strict";Qb();L6();Fd=class{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return r1(this.items)}},Wf=[new Uint8Array([1])],D6="0123456789",e1="name",M6="valueHexView",bM="isHexOnly",vM="idBlock",wM="tagClass",SM="tagNumber",_M="isConstructed",EM="fromBER",CM="toBER",TM="local",ds="",Un=new ArrayBuffer(0),Sm=new Uint8Array(0),Xf="EndOfContent",j6="OCTET STRING",H6="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=Sm}={}){this.blockLength=e,this.error=t,this.warnings=s,this.valueBeforeDecodeView=be.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";cm=class extends jn(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?be.toUint8Array(e.valueHex):Sm,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",Un}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=be.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}}};cm.NAME="identificationBlock";dm=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=be.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",Un;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}}};dm.NAME="lengthBlock";Ae={},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 cm(n),this.lenBlock=new dm(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||F6(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?Un: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 O6(t,s)}};ur.NAME="BaseBlock";Yf=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}'`}};Yf.NAME="BaseStringBlock";um=class extends jn(Er){constructor({isHexOnly:e=!0,...t}={}){super(t),this.isHexOnly=e}};um.NAME="PrimitiveValueBlock";Ti=class extends ur{constructor(e={}){super(e,um),this.idBlock.isConstructed=!1}};q6=Ti;Ae.Primitive=q6;Ti.NAME="PRIMITIVE";z6=100,$6=1e4,V6=16*1024*1024,AM="Maximum ASN.1 nesting depth exceeded",IM="Maximum ASN.1 node count exceeded",RM="Maximum ASN.1 content length exceeded";Dn=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=be.toUint8Array(e),o=n??al();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(;OM(this.isIndefiniteForm,s)>0;){let c=s1(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===Xf)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===Xf?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?Un:s.final()}toJSON(){let e={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(let t of this.value)e.value.push(t.toJSON());return e}};Dn.NAME="ConstructedValueBlock";fr=class extends ur{constructor(e={}){super(e,Dn),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} :`}};K6=fr;Ae.Constructed=K6;fr.NAME="CONSTRUCTED";fm=class extends Er{fromBER(e,t,s){return t}toBER(e){return Un}};fm.override="EndOfContentValueBlock";Jf=class extends ur{constructor(e={}){super(e,fm),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};W6=Jf;Ae.EndOfContent=W6;Jf.NAME=Xf;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}`}};G6=nn;Ae.Null=G6;nn.NAME="NULL";lm=class extends jn(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=be.toUint8Array(t.valueHex):this.valueHexView=new Uint8Array(1),e&&(this.value=e)}fromBER(e,t,s){let n=be.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,Zb.call(this),this.blockLength=s,t+s):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};lm.NAME="BooleanValueBlock";Ua=class extends ur{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor(e={}){super(e,lm),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}};X6=Ua;Ae.Boolean=X6;Ua.NAME="BOOLEAN";hm=class extends jn(Dn){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=Dn.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===Xf){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(a!==j6)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?Dn.prototype.toBER.call(this,e,t):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}};hm.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},hm),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??al(),c=s1(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 n1&&e.push(t.valueBlock.valueHexView);return be.concat(e)}};n1=on;Ae.OctetString=n1;on.NAME=j6;pm=class extends jn(Dn){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=Dn.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===Xf){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(d!==H6)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=be.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??al(),u=s1(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 Dn.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}}};pm.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},pm),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}`}}};Y6=an;Ae.BitString=Y6;an.NAME=H6;Qf=class extends jn(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=Zb.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(N6(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=DM(U6(s),t),o="-"):t=LM(t,U6(s))),s++,n>>=1}for(let c=0;c<t.length;c++)t[c]&&(a=!0),a&&(o+=D6.charAt(t[c]));return a===!1&&(o+=D6.charAt(0)),o}};J6=Qf;Qf.NAME="IntegerValueBlock";Object.defineProperty(J6.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,Qf),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return am(),BigInt(this.valueBlock.toString())}static fromBigInt(e){am();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=be.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 Gf({valueHex:s.final()})}convertToDER(){let e=new Gf({valueHex:this.valueBlock.valueHexView});return e.valueBlock.toDER(),e}convertFromDER(){return new Gf({valueHex:this.valueBlock.valueHexView[0]===0?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}};Gf=Ai;Ae.Integer=Gf;Ai.NAME="INTEGER";ja=class extends Ai{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};Q6=ja;Ae.Enumerated=Q6;ja.NAME="ENUMERATED";Zf=class extends jn(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=be.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){am();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",Un;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}}};Zf.NAME="sidBlock";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.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,Un;t.push(n)}return r1(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 Zf;if(n>Number.MAX_SAFE_INTEGER){am();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}};mm.NAME="ObjectIdentifierValueBlock";Ha=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=6}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};Z6=Ha;Ae.ObjectIdentifier=Z6;Ha.NAME="OBJECT IDENTIFIER";el=class extends jn(Ci){constructor({valueDec:e=0,...t}={}){super(t),this.valueDec=e}fromBER(e,t,s){if(s===0)return t;let n=be.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",Un;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}}};el.NAME="relativeSidBlock";gm=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 el;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,Un;s.push(i)}return r1(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 el;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}};gm.NAME="RelativeObjectIdentifierValueBlock";tl=class extends ur{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(e={}){super(e,gm),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};e3=tl;Ae.RelativeObjectIdentifier=e3;tl.NAME="RelativeObjectIdentifier";Vr=class extends fr{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};t3=Vr;Ae.Sequence=t3;Vr.NAME="SEQUENCE";es=class extends fr{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};r3=es;Ae.Set=r3;es.NAME="SET";ym=class extends jn(Er){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=ds}toJSON(){return{...super.toJSON(),value:this.value}}};ym.NAME="StringValueBlock";xm=class extends ym{};xm.NAME="SimpleStringValueBlock";ts=class extends Yf{constructor({...e}={}){super(e,xm)}fromBuffer(e){this.valueBlock.value=String.fromCharCode.apply(null,be.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";bm=class extends ts{fromBuffer(e){this.valueBlock.valueHexView=be.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}};bm.NAME="Utf8StringValueBlock";Fs=class extends bm{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};s3=Fs;Ae.Utf8String=s3;Fs.NAME="UTF8String";vm=class extends ts{fromBuffer(e){this.valueBlock.value=Ue.ToUtf16String(e),this.valueBlock.valueHexView=be.toUint8Array(e)}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array(Ue.FromUtf16String(e))}};vm.NAME="BmpStringValueBlock";Fa=class extends vm{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};n3=Fa;Ae.BmpString=n3;Fa.NAME="BMPString";wm=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}};wm.NAME="UniversalStringValueBlock";qa=class extends wm{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};i3=qa;Ae.UniversalString=i3;qa.NAME="UniversalString";za=class extends ts{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};o3=za;Ae.NumericString=o3;za.NAME="NumericString";$a=class extends ts{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};a3=$a;Ae.PrintableString=a3;$a.NAME="PrintableString";Va=class extends ts{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};c3=Va;Ae.TeletexString=c3;Va.NAME="TeletexString";Ka=class extends ts{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};d3=Ka;Ae.VideotexString=d3;Ka.NAME="VideotexString";Wa=class extends ts{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};u3=Wa;Ae.IA5String=u3;Wa.NAME="IA5String";Ga=class extends ts{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};f3=Ga;Ae.GraphicString=f3;Ga.NAME="GraphicString";Io=class extends ts{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};l3=Io;Ae.VisibleString=l3;Io.NAME="VisibleString";Xa=class extends ts{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};h3=Xa;Ae.GeneralString=h3;Xa.NAME="GeneralString";Ya=class extends ts{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};p3=Ya;Ae.CharacterString=p3;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,be.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}}};m3=Ro;Ae.UTCTime=m3;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}}};g3=Ja;Ae.GeneralizedTime=g3;Ja.NAME="GeneralizedTime";rl=class extends Fs{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};y3=rl;Ae.DATE=y3;rl.NAME="DATE";sl=class extends Fs{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};x3=sl;Ae.TimeOfDay=x3;sl.NAME="TimeOfDay";nl=class extends Fs{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};b3=nl;Ae.DateTime=b3;nl.NAME="DateTime";il=class extends Fs{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};v3=il;Ae.Duration=v3;il.NAME="Duration";ol=class extends Fs{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};w3=ol;Ae.TIME=w3;ol.NAME="TIME";Mn=class{constructor({name:e=ds,optional:t=!1}={}){this.name=e,this.optional=t}},qd=class extends Mn{constructor({value:e=[],...t}={}){super(t),this.value=e}},Qa=class extends Mn{constructor({value:e=new Mn,local:t=!1,...s}={}){super(s),this.value=e,this.local=t}},t1=class{get data(){return this.dataView.slice().buffer}set data(e){this.dataView=be.toUint8Array(e)}constructor({data:e=Sm}={}){this.dataView=be.toUint8Array(e)}fromBER(e,t,s){let n=t+s;return this.dataView=be.toUint8Array(e).subarray(t,n),n}toBER(e){return this.dataView.slice().buffer}}});function S3(r){return Object.prototype.toString.call(r)}function HM(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"&&Em(e.buffer)}function i1(r){return S3(r)===UM}function _3(r){return typeof SharedArrayBuffer<"u"&&S3(r)===jM}function Em(r){return i1(r)||_3(r)}function E3(r){return HM(r)}function ki(r){return Em(r)||E3(r)}function o1(r){if(!ki(r))throw new TypeError("Expected ArrayBuffer, SharedArrayBuffer, or ArrayBufferView")}function qs(r){return o1(r),Em(r)?new Uint8Array(r):new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}function vr(r){if(o1(r),i1(r))return r;let e=new ArrayBuffer(r.byteLength);return new Uint8Array(e).set(qs(r)),e}var UM,jM,cl=A(()=>{"use strict";UM="[object ArrayBuffer]",jM="[object SharedArrayBuffer]"});var C3=A(()=>{"use strict";cl()});function a1(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 T3=A(()=>{"use strict";cl()});var A3=A(()=>{"use strict";cl()});var Cs=A(()=>{"use strict";cl();C3();T3();A3()});var B,_,Za=A(()=>{"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 Fn,I3=A(()=>{"use strict";ko();Cs();Fn=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,R3=A(()=>{"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 c1=A(()=>{"use strict";I3();R3()});function zs(r){return{fromASN:e=>e.valueBlock.value,toASN:e=>new r({value:e})}}function Po(r){switch(r){case _.Any:return zM;case _.BitString:return KM;case _.BmpString:return XM;case _.Boolean:return GM;case _.CharacterString:return iU;case _.Enumerated:return VM;case _.GeneralString:return nU;case _.GeneralizedTime:return aU;case _.GraphicString:return rU;case _.IA5String:return tU;case _.Integer:return $M;case _.Null:return cU;case _.NumericString:return JM;case _.ObjectIdentifier:return WM;case _.OctetString:return zd;case _.PrintableString:return QM;case _.TeletexString:return ZM;case _.UTCTime:return oU;case _.UniversalString:return YM;case _.Utf8String:return d1;case _.VideotexString:return eU;case _.VisibleString:return sU;default:return null}}var zM,$M,VM,Ct,KM,WM,GM,zd,k3,d1,XM,YM,JM,QM,ZM,eU,tU,rU,sU,nU,iU,oU,aU,cU,dl=A(()=>{"use strict";ko();Cs();Za();c1();zM={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}},$M={fromASN:r=>r.valueBlock.valueHexView.byteLength>=4?r.valueBlock.toString():r.valueBlock.valueDec,toASN:r=>new Ai({value:+r})},VM={fromASN:r=>r.valueBlock.valueDec,toASN:r=>new ja({value:r})},Ct={fromASN:r=>vr(r.valueBlock.valueHexView),toASN:r=>new Ai({valueHex:r})},KM={fromASN:r=>vr(r.valueBlock.valueHexView),toASN:r=>new an({valueHex:r})},WM={fromASN:r=>r.valueBlock.toString(),toASN:r=>new Ha({value:r})},GM={fromASN:r=>r.valueBlock.value,toASN:r=>new Ua({value:r})},zd={fromASN:r=>vr(r.valueBlock.valueHexView),toASN:r=>new on({valueHex:r})},k3={fromASN:r=>new ze(r.getValue()),toASN:r=>r.toASN()};d1=zs(Fs),XM=zs(Fa),YM=zs(qa),JM=zs(za),QM=zs($a),ZM=zs(Va),eU=zs(Ka),tU=zs(Wa),rU=zs(Ga),sU=zs(Io),nU=zs(Xa),iU=zs(Ya),oU={fromASN:r=>r.toDate(),toASN:r=>new Ro({valueDate:r})},aU={fromASN:r=>r.toDate(),toASN:r=>new Ja({valueDate:r})},cU={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 f1(r){if(r){let e=Object.getPrototypeOf(r);return e?.prototype?.constructor===Array?!0:f1(e)}return!1}function P3(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 Cm=A(()=>{"use strict"});var Tm,B3=A(()=>{"use strict";ko();Za();Cm();Tm=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=Hn[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 Mn({name:a}):(c=this.create(o.type,!1),c.name=a):c=new Mn({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,Am=A(()=>{"use strict";B3();lr=new Tm});var M,g,N3=A(()=>{"use strict";dl();Za();Am();M=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,O3=A(()=>{"use strict";Bo=class extends Error{schemas=[]}});var l1=A(()=>{"use strict";O3()});var ul,h1=A(()=>{"use strict";ko();Cs();Za();dl();l1();Cm();Am();ul=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 f1(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=Hn[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 fl,p1=A(()=>{"use strict";ko();Cs();dl();Za();Cm();Am();fl=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"&&P3(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,L3=A(()=>{"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,D3=A(()=>{"use strict";ko();Cs();h1();p1();pe=class r{static serialize(e){return fl.serialize(e)}static parse(e,t,s){return ul.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=A(()=>{"use strict";dl();c1();N3();Za();h1();p1();l1();L3();D3()});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=A(()=>{"use strict"});var m1=A(()=>{"use strict";Cs()});var $d={};Cf($d,{decode:()=>y1,encode:()=>g1,format:()=>F3,formats:()=>q3,hex:()=>vU,is:()=>j3,normalize:()=>ll,parse:()=>H3});function lU(r){return r.separators==="none"?[]:!r.separators||r.separators==="common"?fU:r.separators}function hU(r){if(!r)throw new TypeError("Hex separators must be non-empty strings")}function pU(r,e,t){for(let s of t)if(r.startsWith(s,e))return s}function mU(r){let e=/[A-F]/.test(r),t=/[a-f]/.test(r);return e&&!t?"upper":"lower"}function gU(r){let e=/\r\n|\n/.exec(r);if(e)return e[0]===`\r
|
|
23
|
-
`?`\r
|
|
24
|
-
`:`
|
|
25
|
-
`}function M3(r){return r.replace(/[^0-9a-f]/gi,"")}function yU(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 xU(r){let e=r.trim(),t=/^0x/i.test(e)?"0x":"",s=t?e.slice(2):e,n=gU(s),i=s.split(/\r\n|\n/).filter(d=>d.length>0),o=i[0]?.trim()??"",a=yU(o),c={case:mU(e),prefix:t};if(a&&(c.group=a),n&&i.length>1){let d=M3(i[0]??"").length/2;d>0&&i.slice(0,-1).every(u=>M3(u).length/2===d)&&(c.line={bytesPerLine:d,separator:n})}return c}function bU(r,e){let t=e.allowPrefix??!0,s=[...lU(e)].sort((a,c)=>c.length-a.length);for(let a of s)hU(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(uU.test(c)){i+=c,o=!1,a+=1;continue}let d=pU(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 U3(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 ll(r,e={}){return bU(r,e)}function j3(r,e={}){if(typeof r!="string")return!1;try{return ll(r,e),!0}catch{return!1}}function g1(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(U3(n.slice(d,d+o),e.group));i=c.join(a)}else i=U3(n,e.group);return`${e.prefix??""}${i}`}function y1(r,e={}){let t=ll(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 H3(r,e={}){let t=ll(r,e);return{bytes:y1(t),format:xU(r),normalized:t}}function F3(r,e){return g1(r,e)}var uU,fU,q3,vU,z3=A(()=>{"use strict";Cs();uU=/^[0-9a-f]$/i,fU=[" "," ",`
|
|
27
|
-
`,"\r",":","-","."];q3={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"})},vU={encode:g1,decode:y1,format:F3,formats:q3,is:j3,normalize:ll,parse:H3}});var $3=A(()=>{"use strict";Cs()});var V3=A(()=>{"use strict";Cs()});var x1=A(()=>{"use strict";Cs();m1()});var K3=A(()=>{"use strict";x1()});var b1=A(()=>{"use strict";m1();z3();$3();V3();x1();K3()});var hl,W3=A(()=>{"use strict";b1();hl=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 v1,w1,S1,hr,Vd,ec,No,_1,Ft,Kd=A(()=>{"use strict";ee();J();b1();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([M({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([M({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=v1=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,v1.prototype)}};No=v1=p([M({type:B.Set,itemType:ec})],No);_1=w1=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,w1.prototype)}};_1=w1=p([M({type:B.Sequence,itemType:No})],_1);Ft=S1=class extends _1{constructor(e){super(e),Object.setPrototypeOf(this,S1.prototype)}};Ft=S1=p([M({type:B.Sequence})],Ft)});var CU,Oo,pl,We,tc=A(()=>{"use strict";ee();J();W3();Kd();CU={fromASN:r=>hl.toString(zd.fromASN(r)),toASN:r=>zd.toASN(hl.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);pl=class{nameAssigner;partyName=new hr;constructor(e={}){Object.assign(this,e)}};p([g({type:hr,optional:!0,context:0,implicit:!0})],pl.prototype,"nameAssigner",void 0);p([g({type:hr,context:1,implicit:!0})],pl.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:pl,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:CU})],We.prototype,"iPAddress",void 0);p([g({type:_.ObjectIdentifier,context:8,implicit:!0})],We.prototype,"registeredID",void 0);We=p([M({type:B.Choice})],We)});var Lo,Do,G3,rc,Im,sX,nX,E1,C1,T1,A1,at,Vt=A(()=>{"use strict";Lo="1.3.6.1.5.5.7",Do=`${Lo}.1`,G3=`${Lo}.2`,rc=`${Lo}.3`,Im=`${Lo}.48`,sX=`${G3}.1`,nX=`${G3}.2`,E1=`${Im}.1`,C1=`${Im}.2`,T1=`${Im}.3`,A1=`${Im}.5`,at="2.5.29"});var I1,Rm,Pi,sc,R1=A(()=>{"use strict";ee();J();tc();Vt();Rm=`${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=I1=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,I1.prototype)}};sc=I1=p([M({type:B.Sequence,itemType:Pi})],sc)});var km,nc,qn,k1=A(()=>{"use strict";ee();J();tc();Vt();km=`${at}.35`,nc=class extends ze{},qn=class{keyIdentifier;authorityCertIssuer;authorityCertSerialNumber;constructor(e={}){e&&Object.assign(this,e)}};p([g({type:nc,context:0,optional:!0,implicit:!0})],qn.prototype,"keyIdentifier",void 0);p([g({type:We,context:1,optional:!0,implicit:!0,repeated:"sequence"})],qn.prototype,"authorityCertIssuer",void 0);p([g({type:_.Integer,context:2,optional:!0,implicit:!0,converter:Ct})],qn.prototype,"authorityCertSerialNumber",void 0)});var Pm,ic,X3=A(()=>{"use strict";ee();J();Vt();Pm=`${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 P1,Xt,ml=A(()=>{"use strict";ee();J();tc();Xt=P1=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,P1.prototype)}};Xt=P1=p([M({type:B.Sequence,itemType:We})],Xt)});var B1,TU,Y3,J3=A(()=>{"use strict";ee();J();ml();Vt();TU=`${at}.29`,Y3=B1=class extends Xt{constructor(e){super(e),Object.setPrototypeOf(this,B1.prototype)}};Y3=B1=p([M({type:B.Sequence})],Y3)});var N1,Nm,LX,Bi,gl,yl,Bm,xl,oc,bl,Q3=A(()=>{"use strict";ee();J();Vt();Nm=`${at}.32`,LX=`${Nm}.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([M({type:B.Choice})],Bi);gl=class{organization=new Bi;noticeNumbers=[];constructor(e={}){Object.assign(this,e)}};p([g({type:Bi})],gl.prototype,"organization",void 0);p([g({type:_.Integer,repeated:"sequence"})],gl.prototype,"noticeNumbers",void 0);yl=class{noticeRef;explicitText;constructor(e={}){Object.assign(this,e)}};p([g({type:gl,optional:!0})],yl.prototype,"noticeRef",void 0);p([g({type:Bi,optional:!0})],yl.prototype,"explicitText",void 0);Bm=class{cPSuri;userNotice;constructor(e={}){Object.assign(this,e)}};p([g({type:_.IA5String})],Bm.prototype,"cPSuri",void 0);p([g({type:yl})],Bm.prototype,"userNotice",void 0);Bm=p([M({type:B.Choice})],Bm);xl=class{policyQualifierId="";qualifier=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};p([g({type:_.ObjectIdentifier})],xl.prototype,"policyQualifierId",void 0);p([g({type:_.Any})],xl.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:xl,repeated:"sequence",optional:!0})],oc.prototype,"policyQualifiers",void 0);bl=N1=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,N1.prototype)}};bl=N1=p([M({type:B.Sequence,itemType:oc})],bl)});var zX,vl,O1=A(()=>{"use strict";ee();J();Vt();zX=`${at}.20`,vl=class{value;constructor(e=0){this.value=e}};p([g({type:_.Integer})],vl.prototype,"value",void 0);vl=p([M({type:B.Choice})],vl)});var YX,Z3,eT=A(()=>{"use strict";ee();J();Vt();O1();YX=`${at}.27`,Z3=class extends vl{};Z3=p([M({type:B.Choice})],Z3)});var L1,Om,cn,wl,Ni,zn,Mo,Lm=A(()=>{"use strict";ee();J();Kd();tc();Vt();Om=`${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={}));wl=class extends Fn{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([M({type:B.Choice})],Ni);zn=class{distributionPoint;reasons;cRLIssuer;constructor(e={}){Object.assign(this,e)}};p([g({type:Ni,context:0,optional:!0})],zn.prototype,"distributionPoint",void 0);p([g({type:wl,context:1,optional:!0,implicit:!0})],zn.prototype,"reasons",void 0);p([g({type:We,context:2,optional:!0,repeated:"sequence",implicit:!0})],zn.prototype,"cRLIssuer",void 0);Mo=L1=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,L1.prototype)}};Mo=L1=p([M({type:B.Sequence,itemType:zn})],Mo)});var D1,fY,tT,rT=A(()=>{"use strict";ee();J();Vt();Lm();fY=`${at}.46`,tT=D1=class extends Mo{constructor(e){super(e),Object.setPrototypeOf(this,D1.prototype)}};tT=D1=p([M({type:B.Sequence,itemType:zn})],tT)});var xY,Vs,sT=A(()=>{"use strict";ee();J();Vt();Lm();xY=`${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:wl,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 nT,Sl,_l,iT=A(()=>{"use strict";ee();J();Vt();nT=`${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"})(Sl||(Sl={}));_l=class{reason=Sl.unspecified;constructor(e=Sl.unspecified){this.reason=e}toJSON(){return Sl[this.reason]}toString(){return this.toJSON()}};p([g({type:_.Enumerated})],_l.prototype,"reason",void 0);_l=p([M({type:B.Choice})],_l)});var M1,Dm,El,RY,oT,aT,cT,dT,uT,fT,lT=A(()=>{"use strict";ee();J();Vt();Dm=`${at}.37`,El=M1=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,M1.prototype)}};El=M1=p([M({type:B.Sequence,itemType:_.ObjectIdentifier})],El);RY=`${Dm}.0`,oT=`${rc}.1`,aT=`${rc}.2`,cT=`${rc}.3`,dT=`${rc}.4`,uT=`${rc}.8`,fT=`${rc}.9`});var OY,U1,hT=A(()=>{"use strict";ee();J();Vt();OY=`${at}.54`,U1=class{value;constructor(e=new ArrayBuffer(0)){this.value=e}};p([g({type:_.Integer,converter:Ct})],U1.prototype,"value",void 0);U1=p([M({type:B.Choice})],U1)});var pT,Cl,mT=A(()=>{"use strict";ee();J();Vt();pT=`${at}.24`,Cl=class{value=new Date;constructor(e){e&&(this.value=e)}};p([g({type:_.GeneralizedTime})],Cl.prototype,"value",void 0);Cl=p([M({type:B.Choice})],Cl)});var j1,H1,gT,yT=A(()=>{"use strict";ee();J();ml();Vt();H1=`${at}.18`,gT=j1=class extends Xt{constructor(e){super(e),Object.setPrototypeOf(this,j1.prototype)}};gT=j1=p([M({type:B.Sequence})],gT)});var Mm,dn,Wd,xT=A(()=>{"use strict";J();Vt();Mm=`${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 Fn{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 F1,tJ,Gd,Um,jm,bT=A(()=>{"use strict";ee();J();tc();Vt();tJ=`${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);Um=F1=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,F1.prototype)}};Um=F1=p([M({type:B.Sequence,itemType:Gd})],Um);jm=class{permittedSubtrees;excludedSubtrees;constructor(e={}){Object.assign(this,e)}};p([g({type:Um,context:0,optional:!0,implicit:!0})],jm.prototype,"permittedSubtrees",void 0);p([g({type:Um,context:1,optional:!0,implicit:!0})],jm.prototype,"excludedSubtrees",void 0)});var aJ,Hm,vT=A(()=>{"use strict";ee();J();Vt();aJ=`${at}.36`,Hm=class{requireExplicitPolicy;inhibitPolicyMapping;constructor(e={}){Object.assign(this,e)}};p([g({type:_.Integer,context:0,implicit:!0,optional:!0,converter:Ct})],Hm.prototype,"requireExplicitPolicy",void 0);p([g({type:_.Integer,context:1,implicit:!0,optional:!0,converter:Ct})],Hm.prototype,"inhibitPolicyMapping",void 0)});var q1,lJ,Tl,wT,ST=A(()=>{"use strict";ee();J();Vt();lJ=`${at}.33`,Tl=class{issuerDomainPolicy="";subjectDomainPolicy="";constructor(e={}){Object.assign(this,e)}};p([g({type:_.ObjectIdentifier})],Tl.prototype,"issuerDomainPolicy",void 0);p([g({type:_.ObjectIdentifier})],Tl.prototype,"subjectDomainPolicy",void 0);wT=q1=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,q1.prototype)}};wT=q1=p([M({type:B.Sequence,itemType:Tl})],wT)});var z1,$1,Fm,_T=A(()=>{"use strict";ee();J();ml();Vt();$1=`${at}.17`,Fm=z1=class extends Xt{constructor(e){super(e),Object.setPrototypeOf(this,z1.prototype)}};Fm=z1=p([M({type:B.Sequence})],Fm)});var Ir,V1=A(()=>{"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 K1,IJ,ET,CT=A(()=>{"use strict";ee();J();V1();Vt();IJ=`${at}.9`,ET=K1=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,K1.prototype)}};ET=K1=p([M({type:B.Sequence,itemType:Ir})],ET)});var W1,us,TT=A(()=>{"use strict";Vt();k1();W1=`${at}.14`,us=class extends nc{}});var MJ,qm,AT=A(()=>{"use strict";ee();J();Vt();MJ=`${at}.16`,qm=class{notBefore;notAfter;constructor(e={}){Object.assign(this,e)}};p([g({type:_.GeneralizedTime,context:0,implicit:!0,optional:!0})],qm.prototype,"notBefore",void 0);p([g({type:_.GeneralizedTime,context:1,implicit:!0,optional:!0})],qm.prototype,"notAfter",void 0)});var Al,zm,$m,IT=A(()=>{"use strict";ee();J();(function(r){r[r.keyUpdateAllowed=1]="keyUpdateAllowed",r[r.newExtensions=2]="newExtensions",r[r.pKIXCertificate=4]="pKIXCertificate"})(Al||(Al={}));zm=class extends Fn{toJSON(){let e=[],t=this.toNumber();return t&Al.pKIXCertificate&&e.push("pKIXCertificate"),t&Al.newExtensions&&e.push("newExtensions"),t&Al.keyUpdateAllowed&&e.push("keyUpdateAllowed"),e}toString(){return`[${this.toJSON().join(", ")}]`}},$m=class{entrustVers="";entrustInfoFlags=new zm;constructor(e={}){Object.assign(this,e)}};p([g({type:_.GeneralString})],$m.prototype,"entrustVers",void 0);p([g({type:zm})],$m.prototype,"entrustInfoFlags",void 0)});var G1,KJ,RT,kT=A(()=>{"use strict";ee();J();Vt();R1();KJ=`${Do}.11`,RT=G1=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,G1.prototype)}};RT=G1=p([M({type:B.Sequence,itemType:Pi})],RT)});var PT=A(()=>{"use strict";R1();k1();X3();J3();Q3();eT();Lm();rT();sT();O1();iT();lT();hT();mT();yT();xT();bT();vT();ST();_T();CT();TT();AT();IT();kT()});var fe,ac=A(()=>{"use strict";ee();J();Cs();fe=class r{algorithm="";parameters;constructor(e={}){Object.assign(this,e)}isEqual(e){return e instanceof r&&e.algorithm==this.algorithm&&(e.parameters&&this.parameters&&a1(e.parameters,this.parameters)||e.parameters===this.parameters)}};p([g({type:_.ObjectIdentifier})],fe.prototype,"algorithm",void 0);p([g({type:_.Any,optional:!0})],fe.prototype,"parameters",void 0)});var Rr,X1=A(()=>{"use strict";ee();J();ac();Rr=class{algorithm=new fe;subjectPublicKey=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};p([g({type:fe})],Rr.prototype,"algorithm",void 0);p([g({type:_.BitString})],Rr.prototype,"subjectPublicKey",void 0)});var or,Vm=A(()=>{"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([M({type:B.Choice})],or)});var Oi,Y1=A(()=>{"use strict";ee();J();Vm();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 J1,Kr,Ts,Km=A(()=>{"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=J1=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,J1.prototype)}};Ts=J1=p([M({type:B.Sequence,itemType:Kr})],Ts)});var $n,Q1=A(()=>{"use strict";(function(r){r[r.v1=0]="v1",r[r.v2=1]="v2",r[r.v3=2]="v3"})($n||($n={}))});var kr,Z1=A(()=>{"use strict";ee();J();ac();Kd();X1();Y1();Km();Q1();kr=class{version=$n.v1;serialNumber=new ArrayBuffer(0);signature=new fe;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:$n.v1})],kr.prototype,"version",void 0);p([g({type:_.Integer,converter:Ct})],kr.prototype,"serialNumber",void 0);p([g({type:fe})],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,BT=A(()=>{"use strict";ee();J();ac();Z1();Ks=class{tbsCertificate=new kr;tbsCertificateRaw;signatureAlgorithm=new fe;signatureValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};p([g({type:kr,raw:!0})],Ks.prototype,"tbsCertificate",void 0);p([g({type:fe})],Ks.prototype,"signatureAlgorithm",void 0);p([g({type:_.BitString})],Ks.prototype,"signatureValue",void 0)});var cc,As,ev=A(()=>{"use strict";ee();J();ac();Kd();Vm();Km();cc=class{userCertificate=new ArrayBuffer(0);revocationDate=new or;crlEntryExtensions;constructor(e={}){Object.assign(this,e)}};p([g({type:_.Integer,converter:Ct})],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 fe;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:fe})],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,NT=A(()=>{"use strict";ee();J();ac();ev();dc=class{tbsCertList=new As;tbsCertListRaw;signatureAlgorithm=new fe;signature=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};p([g({type:As,raw:!0})],dc.prototype,"tbsCertList",void 0);p([g({type:fe})],dc.prototype,"signatureAlgorithm",void 0);p([g({type:_.BitString})],dc.prototype,"signature",void 0)});var Tt=A(()=>{"use strict";PT();ac();V1();BT();NT();Km();tc();ml();Kd();Vt();X1();ev();Z1();Vm();Q1();Y1()});var un,Il=A(()=>{"use strict";ee();J();Tt();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:Ct})],un.prototype,"serialNumber",void 0)});var uc,tv=A(()=>{"use strict";ee();J();Tt();Il();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([M({type:B.Choice})],uc)});var Pr,fc,Rl,fs,kl,LT,Wm,Vn=A(()=>{"use strict";ee();Tt();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 fe{};fc=p([M({type:B.Sequence})],fc);Rl=class extends fe{};Rl=p([M({type:B.Sequence})],Rl);fs=class extends fe{};fs=p([M({type:B.Sequence})],fs);kl=class extends fe{};kl=p([M({type:B.Sequence})],kl);LT=class extends fe{};LT=p([M({type:B.Sequence})],LT);Wm=class extends fe{};Wm=p([M({type:B.Sequence})],Wm)});var fn,Gm=A(()=>{"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 rv,ls,Pl,Xm=A(()=>{"use strict";ee();J();tv();Vn();Gm();ls=class{version=Pr.v0;sid=new uc;digestAlgorithm=new fc;signedAttrs;signedAttrsRaw;signatureAlgorithm=new Rl;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:Rl})],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);Pl=rv=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,rv.prototype)}};Pl=rv=p([M({type:B.Set,itemType:ls})],Pl)});var DT,MT=A(()=>{"use strict";ee();J();Xm();DT=class extends ls{};DT=p([M({type:B.Sequence})],DT)});var UT=A(()=>{"use strict";J()});var jT,HT=A(()=>{"use strict";ee();Tt();J();jT=class extends or{};jT=p([M({type:B.Choice})],jT)});var FT=A(()=>{"use strict";MT();UT();HT()});var Bl,qT=A(()=>{"use strict";ee();J();Tt();Bl=class{acIssuer=new We;acSerial=0;attrs=[];constructor(e={}){Object.assign(this,e)}};p([g({type:We})],Bl.prototype,"acIssuer",void 0);p([g({type:_.Integer})],Bl.prototype,"acSerial",void 0);p([g({type:Ir,repeated:"sequence"})],Bl.prototype,"attrs",void 0)});var sv,Nl,nv=A(()=>{"use strict";ee();J();Nl=sv=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,sv.prototype)}};Nl=sv=p([M({type:B.Sequence,itemType:_.ObjectIdentifier})],Nl)});var Xd,zT=A(()=>{"use strict";ee();J();nv();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:Nl,implicit:!0,context:0,optional:!0})],Xd.prototype,"permittedAttrs",void 0);p([g({type:Nl,implicit:!0,context:1,optional:!0})],Xd.prototype,"excludedAttrs",void 0);p([g({type:_.Boolean,defaultValue:!0})],Xd.prototype,"permitUnSpecified",void 0)});var Ws,Ol=A(()=>{"use strict";ee();J();Tt();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:Ct})],Ws.prototype,"serial",void 0);p([g({type:_.BitString,optional:!0})],Ws.prototype,"issuerUID",void 0)});var iv,Gs,Ll=A(()=>{"use strict";ee();J();Tt();(function(r){r[r.publicKey=0]="publicKey",r[r.publicKeyCert=1]="publicKeyCert",r[r.otherObjectTypes=2]="otherObjectTypes"})(iv||(iv={}));Gs=class{digestedObjectType=iv.publicKey;otherObjectTypeID;digestAlgorithm=new fe;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:fe})],Gs.prototype,"digestAlgorithm",void 0);p([g({type:_.BitString})],Gs.prototype,"objectDigest",void 0)});var lc,ov=A(()=>{"use strict";ee();J();Tt();Ol();Ll();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,av=A(()=>{"use strict";ee();J();Tt();ov();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([M({type:B.Choice})],hc)});var pc,cv=A(()=>{"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,dv=A(()=>{"use strict";ee();J();Tt();Ol();Ll();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 uv,hs,fv=A(()=>{"use strict";ee();J();Tt();dv();av();cv();(function(r){r[r.v2=1]="v2"})(uv||(uv={}));hs=class{version=uv.v2;holder=new Uo;issuer=new hc;signature=new fe;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:fe})],hs.prototype,"signature",void 0);p([g({type:_.Integer,converter:Ct})],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,$T=A(()=>{"use strict";ee();J();Tt();fv();mc=class{acinfo=new hs;signatureAlgorithm=new fe;signatureValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};p([g({type:hs})],mc.prototype,"acinfo",void 0);p([g({type:fe})],mc.prototype,"signatureAlgorithm",void 0);p([g({type:_.BitString})],mc.prototype,"signatureValue",void 0)});var Dl,Yd,lv=A(()=>{"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"})(Dl||(Dl={}));Yd=class extends Fn{}});var Jd,hv=A(()=>{"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 Ml,VT=A(()=>{"use strict";ee();J();lv();hv();Ml=class{policyId="";classList=new Yd(Dl.unclassified);securityCategories;constructor(e={}){Object.assign(this,e)}};p([g({type:_.ObjectIdentifier})],Ml.prototype,"policyId",void 0);p([g({type:Yd,defaultValue:new Yd(Dl.unclassified)})],Ml.prototype,"classList",void 0);p([g({type:Jd,repeated:"set"})],Ml.prototype,"securityCategories",void 0)});var Qd,Ym,KT=A(()=>{"use strict";ee();J();Tt();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);Ym=class{policyAuthority;values=[];constructor(e={}){Object.assign(this,e)}};p([g({type:Xt,implicit:!0,context:0,optional:!0})],Ym.prototype,"policyAuthority",void 0);p([g({type:Qd,repeated:"sequence"})],Ym.prototype,"values",void 0)});var Dte,Mte,Ute,jte,Ul,Hte,Fte,qte,zte,$te,pv,Vte,WT=A(()=>{"use strict";Tt();Dte=`${Do}.4`,Mte=`${Do}.6`,Ute=`${Do}.10`,jte=`${at}.55`,Ul=`${Lo}.10`,Hte=`${Ul}.1`,Fte=`${Ul}.2`,qte=`${Ul}.3`,zte=`${Ul}.4`,$te=`${Ul}.6`,pv="2.5.4",Vte=`${pv}.72`});var mv,Zd,eu,Jm,gv=A(()=>{"use strict";ee();J();Tt();Ol();Ll();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([M({type:B.Choice})],eu);Jm=mv=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,mv.prototype)}};Jm=mv=p([M({type:B.Sequence,itemType:eu})],Jm)});var yv,GT,XT=A(()=>{"use strict";ee();J();gv();GT=yv=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,yv.prototype)}};GT=yv=p([M({type:B.Sequence,itemType:Jm})],GT)});var Qm,YT=A(()=>{"use strict";ee();J();Tt();Qm=class{roleAuthority;roleName;constructor(e={}){Object.assign(this,e)}};p([g({type:Xt,implicit:!0,context:0,optional:!0})],Qm.prototype,"roleAuthority",void 0);p([g({type:We,implicit:!0,context:1})],Qm.prototype,"roleName",void 0)});var jl,JT=A(()=>{"use strict";ee();J();Tt();jl=class{service=new We;ident=new We;authInfo;constructor(e={}){Object.assign(this,e)}};p([g({type:We})],jl.prototype,"service",void 0);p([g({type:We})],jl.prototype,"ident",void 0);p([g({type:ze,optional:!0})],jl.prototype,"authInfo",void 0)});var xv=A(()=>{"use strict";qT();zT();av();cv();nv();$T();fv();lv();VT();dv();KT();Ol();Ll();WT();XT();YT();hv();JT();gv();ov()});var bv,Hl,gc,yc,Zm=A(()=>{"use strict";ee();J();Tt();xv();Hl=class{otherCertFormat="";otherCert=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};p([g({type:_.ObjectIdentifier})],Hl.prototype,"otherCertFormat",void 0);p([g({type:_.Any})],Hl.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:Hl,context:3,implicit:!0})],gc.prototype,"other",void 0);gc=p([M({type:B.Choice})],gc);yc=bv=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,bv.prototype)}};yc=bv=p([M({type:B.Set,itemType:gc})],yc)});var Xs,QT=A(()=>{"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,vv=A(()=>{"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([M({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 Fl,jo,wv=A(()=>{"use strict";ee();J();Vn();Fl=class{value;constructedValue;constructor(e={}){Object.assign(this,e)}};p([g({type:ze,context:0,implicit:!0,optional:!0})],Fl.prototype,"value",void 0);p([g({type:ze,converter:k3,context:0,implicit:!0,optional:!0,repeated:"sequence"})],Fl.prototype,"constructedValue",void 0);Fl=p([M({type:B.Choice})],Fl);jo=class{contentType="";contentEncryptionAlgorithm=new kl;encryptedContent;constructor(e={}){Object.assign(this,e)}};p([g({type:_.ObjectIdentifier})],jo.prototype,"contentType",void 0);p([g({type:kl})],jo.prototype,"contentEncryptionAlgorithm",void 0);p([g({type:Fl,optional:!0})],jo.prototype,"encryptedContent",void 0)});var Ho,Sv=A(()=>{"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 _v,ru,su,ql,eg,zl,bc,Li,Ev=A(()=>{"use strict";ee();J();Tt();Vn();Il();Sv();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([M({type:B.Choice})],su);ql=class{rid=new su;encryptedKey=new ze;constructor(e={}){Object.assign(this,e)}};p([g({type:su})],ql.prototype,"rid",void 0);p([g({type:ze})],ql.prototype,"encryptedKey",void 0);eg=_v=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,_v.prototype)}};eg=_v=p([M({type:B.Sequence,itemType:ql})],eg);zl=class{algorithm=new fe;publicKey=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};p([g({type:fe})],zl.prototype,"algorithm",void 0);p([g({type:_.BitString})],zl.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:zl,context:1,implicit:!0,optional:!0})],bc.prototype,"originatorKey",void 0);p([g({type:un,optional:!0})],bc.prototype,"issuerAndSerialNumber",void 0);bc=p([M({type:B.Choice})],bc);Li=class{version=Pr.v3;originator=new bc;ukm;keyEncryptionAlgorithm=new fs;recipientEncryptedKeys=new eg;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:eg})],Li.prototype,"recipientEncryptedKeys",void 0)});var nu,Fo,Cv=A(()=>{"use strict";ee();J();Tt();Vn();Il();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([M({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,Tv=A(()=>{"use strict";ee();J();Sv();Vn();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,Av=A(()=>{"use strict";ee();J();Vn();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:Wm,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 $l,Di,Iv=A(()=>{"use strict";ee();J();Ev();Cv();Tv();Av();$l=class{oriType="";oriValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};p([g({type:_.ObjectIdentifier})],$l.prototype,"oriType",void 0);p([g({type:_.Any})],$l.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:$l,context:4,implicit:!0,optional:!0})],Di.prototype,"ori",void 0);Di=p([M({type:B.Choice})],Di)});var Rv,Vl,kv=A(()=>{"use strict";ee();J();Iv();Vl=Rv=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,Rv.prototype)}};Vl=Rv=p([M({type:B.Set,itemType:Di})],Vl)});var Pv,ZT,$se,Vse,iu,tg,ou,rg=A(()=>{"use strict";ee();J();Tt();ZT=`${Lo}.16`,$se=`${ZT}.2`,Vse=`${ZT}.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);tg=class{other=new iu;constructor(e={}){Object.assign(this,e)}};p([g({type:iu,context:1,implicit:!0})],tg.prototype,"other",void 0);tg=p([M({type:B.Choice})],tg);ou=Pv=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,Pv.prototype)}};ou=Pv=p([M({type:B.Set,itemType:tg})],ou)});var au,Bv=A(()=>{"use strict";ee();J();Zm();rg();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 Nv,Ov,wc,e4=A(()=>{"use strict";ee();J();Vn();Gm();kv();Bv();wv();Ov=Nv=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,Nv.prototype)}};Ov=Nv=p([M({type:B.Set,itemType:fn})],Ov);wc=class{version=Pr.v0;originatorInfo;recipientInfos=new Vl;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:Vl})],wc.prototype,"recipientInfos",void 0);p([g({type:jo})],wc.prototype,"encryptedContentInfo",void 0);p([g({type:Ov,context:1,implicit:!0,optional:!0})],wc.prototype,"unprotectedAttrs",void 0)});var t4,r4=A(()=>{"use strict";t4="1.2.840.113549.1.7.2"});var Lv,sg,Mi,s4=A(()=>{"use strict";ee();J();Zm();Vn();vv();rg();Xm();sg=Lv=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,Lv.prototype)}};sg=Lv=p([M({type:B.Set,itemType:fc})],sg);Mi=class{version=Pr.v0;digestAlgorithms=new sg;encapContentInfo=new xc;certificates;crls;signerInfos=new Pl;constructor(e={}){Object.assign(this,e)}};p([g({type:_.Integer})],Mi.prototype,"version",void 0);p([g({type:sg})],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:Pl})],Mi.prototype,"signerInfos",void 0)});var Kl=A(()=>{"use strict";FT();Gm();Zm();QT();vv();wv();e4();Il();Tv();Ev();Cv();r4();Bv();Av();Iv();kv();rg();s4();tv();Xm();Vn()});var Sc,Wl,ng,Gl,Xl,Yl,Dv,Mv,Uv,jv=A(()=>{"use strict";Sc="1.2.840.10045.2.1",Wl="1.2.840.10045.4.1",ng="1.2.840.10045.4.3.1",Gl="1.2.840.10045.4.3.2",Xl="1.2.840.10045.4.3.3",Yl="1.2.840.10045.4.3.4",Dv="1.2.840.10045.3.1.7",Mv="1.3.132.0.34",Uv="1.3.132.0.35"});function Jl(r){return new fe({algorithm:r})}var i4,Fne,o4,a4,c4,d4=A(()=>{"use strict";Tt();jv();i4=Jl(Wl),Fne=Jl(ng),o4=Jl(Gl),a4=Jl(Xl),c4=Jl(Yl)});var Ql,Hv,cu,Fv,Kn,qv=A(()=>{"use strict";ee();J();Ql=class{fieldType;parameters;constructor(e={}){Object.assign(this,e)}};p([g({type:_.ObjectIdentifier})],Ql.prototype,"fieldType",void 0);p([g({type:_.Any})],Ql.prototype,"parameters",void 0);Ql=p([M({type:B.Sequence})],Ql);Hv=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([M({type:B.Sequence})],cu);(function(r){r[r.ecpVer1=1]="ecpVer1"})(Fv||(Fv={}));Kn=class{version=Fv.ecpVer1;fieldID;curve;base;order;cofactor;constructor(e={}){Object.assign(this,e)}};p([g({type:_.Integer})],Kn.prototype,"version",void 0);p([g({type:Ql})],Kn.prototype,"fieldID",void 0);p([g({type:cu})],Kn.prototype,"curve",void 0);p([g({type:Hv})],Kn.prototype,"base",void 0);p([g({type:_.Integer,converter:Ct})],Kn.prototype,"order",void 0);p([g({type:_.Integer,optional:!0})],Kn.prototype,"cofactor",void 0);Kn=p([M({type:B.Sequence})],Kn)});var Wn,zv=A(()=>{"use strict";ee();J();qv();Wn=class{namedCurve;implicitCurve;specifiedCurve;constructor(e={}){Object.assign(this,e)}};p([g({type:_.ObjectIdentifier})],Wn.prototype,"namedCurve",void 0);p([g({type:_.Null})],Wn.prototype,"implicitCurve",void 0);p([g({type:Kn})],Wn.prototype,"specifiedCurve",void 0);Wn=p([M({type:B.Choice})],Wn)});var du,u4=A(()=>{"use strict";ee();J();zv();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:Wn,context:0,optional:!0})],du.prototype,"parameters",void 0);p([g({type:_.BitString,context:1,optional:!0})],du.prototype,"publicKey",void 0)});var _c,f4=A(()=>{"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:Ct})],_c.prototype,"r",void 0);p([g({type:_.Integer,converter:Ct})],_c.prototype,"s",void 0)});var $v=A(()=>{"use strict";d4();zv();u4();f4();jv();qv()});var ps,Gn,l4,h4,$o,p4,m4,uu,g4,ig,fu,lu,Vv,Kv,Ec,og,Cc,Tc,Ac,y4,x4,b4,v4,Vo,Zl=A(()=>{"use strict";ps="1.2.840.113549.1.1",Gn=`${ps}.1`,l4=`${ps}.7`,h4=`${ps}.9`,$o=`${ps}.10`,p4=`${ps}.2`,m4=`${ps}.4`,uu=`${ps}.5`,g4=`${ps}.14`,ig=`${ps}.11`,fu=`${ps}.12`,lu=`${ps}.13`,Vv=`${ps}.15`,Kv=`${ps}.16`,Ec="1.3.14.3.2.26",og="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",y4="2.16.840.1.101.3.4.2.5",x4="2.16.840.1.101.3.4.2.6",b4="1.2.840.113549.2.2",v4="1.2.840.113549.2.5",Vo=`${ps}.8`});function wr(r){return new fe({algorithm:r,parameters:null})}var mie,gie,Ui,yie,xie,bie,vie,wie,Sie,ag,Wv,_ie,Eie,Cie,Tie,Aie,Iie,Rie,kie,Pie,Bie,cg=A(()=>{"use strict";J();Tt();Zl();mie=wr(b4),gie=wr(v4),Ui=wr(Ec),yie=wr(og),xie=wr(Cc),bie=wr(Tc),vie=wr(Ac),wie=wr(y4),Sie=wr(x4),ag=new fe({algorithm:Vo,parameters:pe.serialize(Ui)}),Wv=new fe({algorithm:h4,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))}),_ie=wr(Gn),Eie=wr(p4),Cie=wr(m4),Tie=wr(uu),Aie=wr(Vv),Iie=wr(Kv),Rie=wr(fu),kie=wr(lu),Pie=wr(Vv),Bie=wr(Kv)});var hu,jie,w4=A(()=>{"use strict";ee();J();Tt();Zl();cg();hu=class{hashAlgorithm=new fe(Ui);maskGenAlgorithm=new fe({algorithm:Vo,parameters:pe.serialize(Ui)});pSourceAlgorithm=new fe(Wv);constructor(e={}){Object.assign(this,e)}};p([g({type:fe,context:0,defaultValue:Ui})],hu.prototype,"hashAlgorithm",void 0);p([g({type:fe,context:1,defaultValue:ag})],hu.prototype,"maskGenAlgorithm",void 0);p([g({type:fe,context:2,defaultValue:Wv})],hu.prototype,"pSourceAlgorithm",void 0);jie=new fe({algorithm:l4,parameters:pe.serialize(new hu)})});var Xn,Kie,S4=A(()=>{"use strict";ee();J();Tt();Zl();cg();Xn=class{hashAlgorithm=new fe(Ui);maskGenAlgorithm=new fe({algorithm:Vo,parameters:pe.serialize(Ui)});saltLength=20;trailerField=1;constructor(e={}){Object.assign(this,e)}};p([g({type:fe,context:0,defaultValue:Ui})],Xn.prototype,"hashAlgorithm",void 0);p([g({type:fe,context:1,defaultValue:ag})],Xn.prototype,"maskGenAlgorithm",void 0);p([g({type:_.Integer,context:2,defaultValue:20})],Xn.prototype,"saltLength",void 0);p([g({type:_.Integer,context:3,defaultValue:1})],Xn.prototype,"trailerField",void 0);Kie=new fe({algorithm:$o,parameters:pe.serialize(new Xn)})});var Ic,_4=A(()=>{"use strict";ee();Tt();J();Ic=class{digestAlgorithm=new fe;digest=new ze;constructor(e={}){Object.assign(this,e)}};p([g({type:fe})],Ic.prototype,"digestAlgorithm",void 0);p([g({type:ze})],Ic.prototype,"digest",void 0)});var E4=A(()=>{"use strict";w4();S4();_4()});var Gv,pu,dg,Xv=A(()=>{"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:Ct})],pu.prototype,"prime",void 0);p([g({type:_.Integer,converter:Ct})],pu.prototype,"exponent",void 0);p([g({type:_.Integer,converter:Ct})],pu.prototype,"coefficient",void 0);dg=Gv=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,Gv.prototype)}};dg=Gv=p([M({type:B.Sequence,itemType:pu})],dg)});var Ys,C4=A(()=>{"use strict";ee();J();Xv();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:Ct})],Ys.prototype,"modulus",void 0);p([g({type:_.Integer,converter:Ct})],Ys.prototype,"publicExponent",void 0);p([g({type:_.Integer,converter:Ct})],Ys.prototype,"privateExponent",void 0);p([g({type:_.Integer,converter:Ct})],Ys.prototype,"prime1",void 0);p([g({type:_.Integer,converter:Ct})],Ys.prototype,"prime2",void 0);p([g({type:_.Integer,converter:Ct})],Ys.prototype,"exponent1",void 0);p([g({type:_.Integer,converter:Ct})],Ys.prototype,"exponent2",void 0);p([g({type:_.Integer,converter:Ct})],Ys.prototype,"coefficient",void 0);p([g({type:dg,optional:!0})],Ys.prototype,"otherPrimeInfos",void 0)});var mu,T4=A(()=>{"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:Ct})],mu.prototype,"modulus",void 0);p([g({type:_.Integer,converter:Ct})],mu.prototype,"publicExponent",void 0)});var ug=A(()=>{"use strict";E4();cg();Zl();Xv();C4();T4()});var Yv,Br,Jv=A(()=>{"use strict";(function(r){r[r.Transient=0]="Transient",r[r.Singleton=1]="Singleton",r[r.ResolutionScoped=2]="ResolutionScoped",r[r.ContainerScoped=3]="ContainerScoped"})(Yv||(Yv={}));Br=Yv});var A4=A(()=>{"use strict";Jv()});function eh(r,e){Qv(r,e);function t(){this.constructor=r}r.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}function I4(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 R4(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 th(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 Yn(){for(var r=[],e=0;e<arguments.length;e++)r=r.concat(gu(arguments[e]));return r}var Qv,yu=A(()=>{"use strict";Qv=function(r,e){return Qv=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])},Qv(r,e)}});function Zv(r){var e=Reflect.getMetadata("design:paramtypes",r)||[],t=Reflect.getOwnMetadata(BU,r)||{};return Object.keys(t).forEach(function(s){e[+s]=t[s]}),e}var BU,Rc=A(()=>{"use strict";BU="injectionTokens"});function rh(r){return!!r.useClass}var ew=A(()=>{"use strict"});function xu(r){return!!r.useFactory}var tw=A(()=>{"use strict"});var fg,lg=A(()=>{"use strict";yu();fg=(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,Yn(i))}};return this.reflectMethods.forEach(s),t},r})()});function Ko(r){return typeof r=="string"||typeof r=="symbol"}function rw(r){return typeof r=="object"&&"token"in r&&"multiple"in r}function hg(r){return typeof r=="object"&&"token"in r&&"transform"in r}function k4(r){return typeof r=="function"||r instanceof fg}var pg=A(()=>{"use strict";lg()});function kc(r){return!!r.useToken}var sw=A(()=>{"use strict"});function Pc(r){return r.useValue!=null}var nw=A(()=>{"use strict"});var iw=A(()=>{"use strict";ew();tw();pg();sw();nw()});function P4(r){return rh(r)||Pc(r)||kc(r)||xu(r)}var B4=A(()=>{"use strict";ew();nw();sw();tw()});var NU,sh,ow=A(()=>{"use strict";NU=(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})(),sh=NU});var OU,N4,O4=A(()=>{"use strict";yu();ow();OU=(function(r){eh(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e})(sh),N4=OU});var LU,nh,L4=A(()=>{"use strict";LU=(function(){function r(){this.scopedResolutions=new Map}return r})(),nh=LU});function DU(r,e){if(r===null)return"at position #"+e;var t=r.split(",")[e].trim();return'"'+t+'" at position #'+e}function MU(r,e,t){return t===void 0&&(t=" "),Yn([r],e.message.split(`
|
|
28
|
-
`).map(function(s){return t+s})).join(`
|
|
29
|
-
`)}function aw(r,e,t){var s=gu(r.toString().match(/constructor\(([\w, ]+)\)/)||[],2),n=s[1],i=n===void 0?null:n,o=DU(i,e);return MU("Cannot inject the dependency "+o+' of "'+r.name+'" constructor. Reason:',t)}var cw=A(()=>{"use strict";yu()});function D4(r){if(typeof r.dispose!="function")return!1;var e=r.dispose;return!(e.length>0)}var M4=A(()=>{"use strict"});var UU,jU,HU,U4,j4=A(()=>{"use strict";yu();ow();UU=(function(r){eh(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e})(sh),jU=(function(r){eh(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e})(sh),HU=(function(){function r(){this.preResolution=new UU,this.postResolution=new jU}return r})(),U4=HU});var dw,FU,Kt,Wo=A(()=>{"use strict";yu();iw();B4();pg();O4();Jv();L4();cw();lg();M4();j4();dw=new Map,FU=(function(){function r(e){this.parent=e,this._registry=new N4,this.interceptors=new U4,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(P4(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! "+Yn(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 nh),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(k4(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=th(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=th(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):rh(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 nh),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=th(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=th(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 I4(this,void 0,void 0,function(){var e;return R4(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 fg)return e.createProxy(function(i){return s.resolve(i,t)});var n=(function(){var i=dw.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,Yn([void 0],o)))})();return D4(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 rw(n)?hg(n)?n.multiple?(o=s.resolve(n.transform)).transform.apply(o,Yn([s.resolveAll(n.token,new nh,n.isOptional)],n.transformArgs)):(a=s.resolve(n.transform)).transform.apply(a,Yn([s.resolve(n.token,e,n.isOptional)],n.transformArgs)):n.multiple?s.resolveAll(n.token,new nh,n.isOptional):s.resolve(n.token,e,n.isOptional):hg(n)?(c=s.resolve(n.transform,e)).transform.apply(c,Yn([s.resolve(n.token,e)],n.transformArgs)):s.resolve(n,e)}catch(d){throw new Error(aw(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 FU});var H4=A(()=>{"use strict";Rc();Wo();pg();cw()});var F4=A(()=>{"use strict";Rc()});function qU(r){return function(e){dw.set(e,Zv(e)),r&&r.token&&(Array.isArray(r.token)?r.token.forEach(function(t){Kt.register(t,e)}):Kt.register(r.token,e))}}var Go,mg=A(()=>{"use strict";Rc();Wo();Wo();Go=qU});var q4=A(()=>{"use strict";Wo()});var z4=A(()=>{"use strict";mg();Wo()});var $4=A(()=>{"use strict";Rc()});var V4=A(()=>{"use strict";Rc()});var K4=A(()=>{"use strict";Rc()});var W4=A(()=>{"use strict";mg();Wo()});var G4=A(()=>{"use strict";H4();F4();mg();q4();z4();$4();V4();K4();W4()});var X4=A(()=>{"use strict"});var Y4=A(()=>{"use strict"});var J4=A(()=>{"use strict"});var Q4=A(()=>{"use strict";X4();Y4();J4()});var Z4=A(()=>{"use strict";A4();G4();Q4();iw();lg();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 fw,Bc,e8,lw=A(()=>{"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);e8=fw=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,fw.prototype)}};e8=fw=p([M({type:B.Sequence,itemType:Bc})],e8)});var hw,t8,r8=A(()=>{"use strict";ee();J();Kl();t8=hw=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,hw.prototype)}};t8=hw=p([M({type:B.Sequence,itemType:Xs})],t8)});var zU,$U,s8,bu,Rce,kce,Pce,Bce,Nce,Oce,Nc,pw=A(()=>{"use strict";zU="1.2.840.113549",$U=`${zU}.1`,s8=`${$U}.12`,bu=`${s8}.1`,Rce=`${bu}.1`,kce=`${bu}.2`,Pce=`${bu}.3`,Bce=`${bu}.4`,Nce=`${bu}.5`,Oce=`${bu}.6`,Nc=`${s8}.10.1`});var Mce,Uce,jce,Hce,Fce,qce,gg,yg=A(()=>{"use strict";pw();Mce=`${Nc}.1`,Uce=`${Nc}.2`,jce=`${Nc}.3`,Hce=`${Nc}.4`,Fce=`${Nc}.5`,qce=`${Nc}.6`,gg="1.2.840.113549.1.9"});var xg,n8,Wce,Gce,i8=A(()=>{"use strict";ee();J();yg();xg=class{certId="";certValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};p([g({type:_.ObjectIdentifier})],xg.prototype,"certId",void 0);p([g({type:_.Any,context:0})],xg.prototype,"certValue",void 0);n8=`${gg}.22`,Wce=`${n8}.1`,Gce=`${n8}.2`});var bg,VU,Zce,o8=A(()=>{"use strict";ee();J();yg();bg=class{crlId="";crltValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};p([g({type:_.ObjectIdentifier})],bg.prototype,"crlId",void 0);p([g({type:_.Any,context:0})],bg.prototype,"crltValue",void 0);VU=`${gg}.23`,Zce=`${VU}.1`});var vg,Xo,a8=A(()=>{"use strict";ee();J();Tt();vg=class extends ze{},Xo=class{encryptionAlgorithm=new fe;encryptedData=new vg;constructor(e={}){Object.assign(this,e)}};p([g({type:fe})],Xo.prototype,"encryptionAlgorithm",void 0);p([g({type:vg})],Xo.prototype,"encryptedData",void 0)});var mw,gw,wg,yw,Yo,c8=A(()=>{"use strict";ee();J();Tt();(function(r){r[r.v1=0]="v1"})(gw||(gw={}));wg=class extends ze{},yw=mw=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,mw.prototype)}};yw=mw=p([M({type:B.Sequence,itemType:Ir})],yw);Yo=class{version=gw.v1;privateKeyAlgorithm=new fe;privateKey=new wg;attributes;constructor(e={}){Object.assign(this,e)}};p([g({type:_.Integer})],Yo.prototype,"version",void 0);p([g({type:fe})],Yo.prototype,"privateKeyAlgorithm",void 0);p([g({type:wg})],Yo.prototype,"privateKey",void 0);p([g({type:yw,implicit:!0,context:0,optional:!0})],Yo.prototype,"attributes",void 0)});var Sg=A(()=>{"use strict";a8();c8()});var d8,u8=A(()=>{"use strict";ee();Sg();J();d8=class extends Yo{};d8=p([M({type:B.Sequence})],d8)});var f8,l8=A(()=>{"use strict";ee();Sg();J();f8=class extends Xo{};f8=p([M({type:B.Sequence})],f8)});var _g,h8=A(()=>{"use strict";ee();J();_g=class{secretTypeId="";secretValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};p([g({type:_.ObjectIdentifier})],_g.prototype,"secretTypeId",void 0);p([g({type:_.Any,context:0})],_g.prototype,"secretValue",void 0)});var p8=A(()=>{"use strict";i8();o8();u8();l8();h8();yg()});var Jo,xw=A(()=>{"use strict";ee();ug();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,m8=A(()=>{"use strict";ee();J();Kl();xw();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 bw,vu,g8,y8=A(()=>{"use strict";ee();J();lw();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);g8=bw=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,bw.prototype)}};g8=bw=p([M({type:B.Sequence,itemType:vu})],g8)});var x8=A(()=>{"use strict";lw();r8();p8();xw();pw();m8();y8()});var vw,ww,Sw,ar,tue,B8,oh,N8,O8,rue,sue,nue,iue,oue,aue,cue,due,kw,uue,fue,lue,ah,hue,pue,mue,gue,yue,xue,bue,vue,ch,wue,Sue,_ue,Eue,Cue,Tue,Aue,Iue,Rue,kue,Pue,Bue,Nue,Eg,b8,v8,w8,_w,S8,_8,Ew,E8,Cw,Cg,C8,T8,Tw,A8,Aw,I8,ih,R8,k8,Iw,Rw,P8,Pw=A(()=>{"use strict";ee();J();Kl();x8();Sg();Tt();xv();ar="1.2.840.113549.1.9",tue=`${ar}.0`,B8=`${ar}.24`,oh=`${ar}.25`,N8=`${ar}.26`,O8=`${ar}.27`,rue=`${B8}.1`,sue=`${B8}.2`,nue=`${ar}.1`,iue=`${ar}.2`,oue=`${ar}.3`,aue=`${ar}.4`,cue=`${ar}.5`,due=`${ar}.6`,kw=`${ar}.7`,uue=`${ar}.8`,fue=`${ar}.9`,lue=`${ar}.13`,ah=`${ar}.14`,hue=`${ar}.15`,pue=`${ar}.20`,mue=`${ar}.21`,gue=`${oh}.1`,yue=`${oh}.2`,xue=`${oh}.3`,bue=`${oh}.4`,vue=`${oh}.5`,ch="1.3.6.1.5.5.7.9",wue=`${ch}.1`,Sue=`${ch}.2`,_ue=`${ch}.3`,Eue=`${ch}.4`,Cue=`${ch}.5`,Tue=`${N8}.1`,Aue=`${N8}.2`,Iue=`${O8}.1`,Rue=`${O8}.2`,kue=`${ar}.16`,Pue=`${ar}.22`,Bue=`${ar}.23`,Nue=`${pv}.65`,Eg=class extends hr{ia5String;constructor(e={}){super(e)}toString(){return{}.toString(),this.ia5String||super.toString()}};p([g({type:_.IA5String})],Eg.prototype,"ia5String",void 0);Eg=p([M({type:B.Choice})],Eg);b8=class extends Xs{};b8=p([M({type:B.Sequence})],b8);v8=class extends Oc{};v8=p([M({type:B.Sequence})],v8);w8=class extends Xo{};w8=p([M({type:B.Sequence})],w8);_w=class{value;constructor(e=""){this.value=e}toString(){return this.value}};p([g({type:_.IA5String})],_w.prototype,"value",void 0);_w=p([M({type:B.Choice})],_w);S8=class extends Eg{};S8=p([M({type:B.Choice})],S8);_8=class extends hr{};_8=p([M({type:B.Choice})],_8);Ew=class{value;constructor(e=new Date){this.value=e}};p([g({type:_.GeneralizedTime})],Ew.prototype,"value",void 0);Ew=p([M({type:B.Choice})],Ew);E8=class extends hr{};E8=p([M({type:B.Choice})],E8);Cw=class{value;constructor(e="M"){this.value=e}toString(){return this.value}};p([g({type:_.PrintableString})],Cw.prototype,"value",void 0);Cw=p([M({type:B.Choice})],Cw);Cg=class{value;constructor(e=""){this.value=e}toString(){return this.value}};p([g({type:_.PrintableString})],Cg.prototype,"value",void 0);Cg=p([M({type:B.Choice})],Cg);C8=class extends Cg{};C8=p([M({type:B.Choice})],C8);T8=class extends hr{};T8=p([M({type:B.Choice})],T8);Tw=class{value;constructor(e=""){this.value=e}toString(){return this.value}};p([g({type:_.ObjectIdentifier})],Tw.prototype,"value",void 0);Tw=p([M({type:B.Choice})],Tw);A8=class extends or{};A8=p([M({type:B.Choice})],A8);Aw=class{value;constructor(e=0){this.value=e}toString(){return this.value.toString()}};p([g({type:_.Integer})],Aw.prototype,"value",void 0);Aw=p([M({type:B.Choice})],Aw);I8=class extends ls{};I8=p([M({type:B.Sequence})],I8);ih=class extends hr{};ih=p([M({type:B.Choice})],ih);R8=vw=class extends Ts{constructor(e){super(e),Object.setPrototypeOf(this,vw.prototype)}};R8=vw=p([M({type:B.Sequence})],R8);k8=ww=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,ww.prototype)}};k8=ww=p([M({type:B.Set,itemType:fn})],k8);Iw=class{value;constructor(e=""){this.value=e}toString(){return this.value}};p([g({type:_.BmpString})],Iw.prototype,"value",void 0);Iw=p([M({type:B.Choice})],Iw);Rw=class extends fe{};Rw=p([M({type:B.Sequence})],Rw);P8=Sw=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,Sw.prototype)}};P8=Sw=p([M({type:B.Sequence,itemType:Rw})],P8)});var Bw,dh,Nw=A(()=>{"use strict";ee();J();Tt();dh=Bw=class extends je{constructor(e){super(e),Object.setPrototypeOf(this,Bw.prototype)}};dh=Bw=p([M({type:B.Sequence,itemType:Ir})],dh)});var Jn,Ow=A(()=>{"use strict";ee();J();Tt();Nw();Jn=class{version=0;subject=new Ft;subjectPKInfo=new Rr;attributes=new dh;constructor(e={}){Object.assign(this,e)}};p([g({type:_.Integer})],Jn.prototype,"version",void 0);p([g({type:Ft})],Jn.prototype,"subject",void 0);p([g({type:Rr})],Jn.prototype,"subjectPKInfo",void 0);p([g({type:dh,implicit:!0,context:0,optional:!0})],Jn.prototype,"attributes",void 0)});var Qo,L8=A(()=>{"use strict";ee();J();Tt();Ow();Qo=class{certificationRequestInfo=new Jn;certificationRequestInfoRaw;signatureAlgorithm=new fe;signature=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};p([g({type:Jn,raw:!0})],Qo.prototype,"certificationRequestInfo",void 0);p([g({type:fe})],Qo.prototype,"signatureAlgorithm",void 0);p([g({type:_.BitString})],Qo.prototype,"signature",void 0)});var D8=A(()=>{"use strict";Nw();L8();Ow()});function YU(r){return new RegExp(XU).test(r)}function JU(r,e){return`\\${Ue.ToHex(Ue.FromUtf8String(e)).toUpperCase()}`}function QU(r){return r.replace(/([,+"\\<>;])/g,"\\$1").replace(/^([ #])/,"\\$1").replace(/([ ]$)/,"\\$1").replace(/([\r\n\t])/,JU)}function aj(r,e){return r.algorithm=new fe({algorithm:Gn,parameters:null}),e=pe.serialize(r),e}function Ag(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 Ig(r,e,t,s){let n=e[s];n&&(Array.isArray(n)?n:[n]).forEach(o=>{typeof o=="string"&&(o=new Qn("url",o)),r.push(new Pi({accessMethod:t,accessLocation:pe.parse(o.rawData,We)}))})}function cj(r,e=pr.get()){let t=be.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 _fe,Nh,$w,Lc,Rg,gs,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,dA,uA,tr,Rh,wA,SA,Rt,Vw,Zn,Hi,wu,Zo,Is,_A,kh,pr,XU,Pg,ms,ln,EA,fA,ZU,lA,hA,pA,Lw,Dw,Mw,Uw,jw,Hw,Fw,Tg,Qn,Fi,Ih,Ph,ej,tj,rj,Eu,sj,nj,ij,oj,mA,Nr,ea,ji,Bg,Ng,gA,Og,yA,Lg,Dg,Mg,rs,Ug,jg,Hg,Fg,Cu,qg,Bh,Tu,Oh,Kw,kg,Ww,Gw,qi,qw,xA,zw,bA,Xw,uh,fh,lh,hh,ph,mh,gh,Su,Yw,yh,xh,bh,vh,wh,Sh,_h,Eh,Ch,Th,_u,Ah,zg,$g,dj,uj,fj,lj,hj,vA,pj,mj,gj,yj,xj,bj,vj,CA=A(()=>{"use strict";_fe=Ge(k6());J();Tt();Tt();Qb();ee();Kl();$v();$v();ug();ug();Z4();Pw();Pw();D8();Nh="crypto.algorithm",$w=class{getAlgorithms(){return Kt.resolveAll(Nh)}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 fe({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,$w);gs="1.3.36.3.3.2.8.1.1",M8=`${gs}.1`,U8=`${gs}.2`,j8=`${gs}.3`,H8=`${gs}.4`,F8=`${gs}.5`,q8=`${gs}.6`,z8=`${gs}.7`,$8=`${gs}.8`,V8=`${gs}.9`,K8=`${gs}.10`,W8=`${gs}.11`,G8=`${gs}.12`,X8=`${gs}.13`,Y8=`${gs}.14`,J8="brainpoolP160r1",Q8="brainpoolP160t1",Z8="brainpoolP192r1",eA="brainpoolP192t1",tA="brainpoolP224r1",rA="brainpoolP224t1",sA="brainpoolP256r1",nA="brainpoolP256t1",iA="brainpoolP320r1",oA="brainpoolP320t1",aA="brainpoolP384r1",cA="brainpoolP384t1",dA="brainpoolP512r1",uA="brainpoolP512t1",tr="ECDSA",Rh=Rg=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 i4;case"sha-256":return o4;case"sha-384":return a4;case"sha-512":return c4}else if("namedCurve"in e){let t="";switch(e.namedCurve){case"P-256":t=Dv;break;case"K-256":t=Rg.SECP256K1;break;case"P-384":t=Mv;break;case"P-521":t=Uv;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;case dA:t=X8;break;case uA:t=Y8;break}if(t)return new fe({algorithm:Sc,parameters:pe.serialize(new Wn({namedCurve:t}))})}}return null}toWebAlgorithm(e){switch(e.algorithm){case Wl:return{name:tr,hash:{name:"SHA-1"}};case Gl:return{name:tr,hash:{name:"SHA-256"}};case Xl:return{name:tr,hash:{name:"SHA-384"}};case Yl: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,Wn).namedCurve){case Dv:return{name:tr,namedCurve:"P-256"};case Rg.SECP256K1:return{name:tr,namedCurve:"K-256"};case Mv:return{name:tr,namedCurve:"P-384"};case Uv:return{name:tr,namedCurve:"P-521"};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};case X8:return{name:tr,namedCurve:dA};case Y8:return{name:tr,namedCurve:uA}}}}return null}};Rh.SECP256K1="1.3.132.0.10";Rh=Rg=p([Go()],Rh);Kt.registerSingleton(Nh,Rh);wA=Symbol("name"),SA=Symbol("value"),Rt=class{constructor(e,t={},s=""){this[wA]=e,this[SA]=s;for(let n in t)this[n]=t[n]}};Rt.NAME=wA;Rt.VALUE=SA;Vw=class{static toTextObject(e){let t=new Rt("Algorithm Identifier",{},Zn.toString(e.algorithm));if(e.parameters)if(e.algorithm===Sc){let s=new Rh().toWebAlgorithm(e);s&&"namedCurve"in s?t["Named Curve"]=s.namedCurve:t.Parameters=e.parameters}else t.Parameters=e.parameters;return t}},Zn=class{static toString(e){let t=this.items[e];return t||e}};Zn.items={[Ec]:"sha1",[og]:"sha224",[Cc]:"sha256",[Tc]:"sha384",[Ac]:"sha512",[Gn]:"rsaEncryption",[uu]:"sha1WithRSAEncryption",[g4]:"sha224WithRSAEncryption",[ig]:"sha256WithRSAEncryption",[fu]:"sha384WithRSAEncryption",[lu]:"sha512WithRSAEncryption",[Sc]:"ecPublicKey",[Wl]:"ecdsaWithSHA1",[ng]:"ecdsaWithSHA224",[Gl]:"ecdsaWithSHA256",[Xl]:"ecdsaWithSHA384",[Yl]:"ecdsaWithSHA512",[oT]:"TLS WWW server authentication",[aT]:"TLS WWW client authentication",[cT]:"Code Signing",[dT]:"E-mail Protection",[uT]:"Time Stamping",[fT]:"OCSP Signing",[t4]:"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(be.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=be.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=Zn;Hi.algorithmSerializer=Vw;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),be.isBufferSource(e[0])?(this.asn=pe.parse(e[0],e[1]),Gt(this,wu,be.toArrayBuffer(e[0]),"f"),this.onInit(this.asn)):(this.asn=e[0],this.onInit(this.asn))}equal(e){return e instanceof r?B6(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;be.isBufferSource(e[0])?t=be.toArrayBuffer(e[0]):t=pe.serialize(new Kr({extnID:e[0],critical:e[1],extnValue:new ze(be.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]=Zn.toString(this.type)),e}},kh=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[_A]="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}};_A=Symbol.toStringTag;kh.DEFAULT="default";pr=new kh,XU=/^[0-2](?:\.[1-9][0-9]*)+$/;Pg=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 YU(e)?e:this.get(e)}register(e,t){this.items[e]=t,this.items[t]=e}},ms=new Pg;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 Pg,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:be.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)}`:QU(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())}},EA="Cannot initialize GeneralName from ASN.1 data.",fA=`${EA} Unsupported string format in use.`,ZU=`${EA} Value doesn't match to GUID regular expression.`,lA=/^([0-9a-f]{8})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{12})$/i,hA="1.3.6.1.4.1.311.25.1",pA="1.3.6.1.4.1.311.20.2.3",Lw="dns",Dw="dn",Mw="email",Uw="ip",jw="url",Hw="guid",Fw="upn",Tg="id",Qn=class extends Zo{constructor(...e){let t;if(e.length===2)switch(e[0]){case Dw:{let s=new ln(e[1]).toArrayBuffer(),n=pe.parse(s,Ft);t=new We({directoryName:n});break}case Lw:t=new We({dNSName:e[1]});break;case Mw:t=new We({rfc822Name:e[1]});break;case Hw:{let s=new RegExp(lA,"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:hA,value:pe.serialize(new ze(Ue.FromHex(n)))})});break}case Uw:t=new We({iPAddress:e[1]});break;case Tg:t=new We({registeredID:e[1]});break;case Fw:{t=new We({otherName:new Oo({typeId:pA,value:pe.serialize(d1.toASN(e[1]))})});break}case jw:t=new We({uniformResourceIdentifier:e[1]});break;default:throw new Error("Cannot create GeneralName. Unsupported type of the name")}else be.isBufferSource(e[0])?t=pe.parse(e[0],We):t=e[0];super(t)}onInit(e){if(e.dNSName!=null)this.type=Lw,this.value=e.dNSName;else if(e.rfc822Name!=null)this.type=Mw,this.value=e.rfc822Name;else if(e.iPAddress!=null)this.type=Uw,this.value=e.iPAddress;else if(e.uniformResourceIdentifier!=null)this.type=jw,this.value=e.uniformResourceIdentifier;else if(e.registeredID!=null)this.type=Tg,this.value=e.registeredID;else if(e.directoryName!=null)this.type=Dw,this.value=new ln(e.directoryName).toString();else if(e.otherName!=null)if(e.otherName.typeId===hA){this.type=Hw;let t=pe.parse(e.otherName.value,ze),s=new RegExp(lA,"i").exec(Ue.ToHex(t));if(!s)throw new Error(ZU);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===pA)this.type=Fw,this.value=pe.parse(e.otherName.value,hr).toString();else throw new Error(fA);else throw new Error(fA)}toJSON(){return{type:this.type,value:this.value}}toTextObject(){let e;switch(this.type){case Dw:case Lw:case Hw:case Uw:case Tg:case Fw:case jw:e=this.type.toUpperCase();break;case Mw:e="Email";break;default:throw new Error("Unsupported GeneralName type")}let t=this.value;return this.type===Tg&&(t=Zn.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 Qn(n.type,n.value).rawData,We);s.push(i)}t=new Xt(s)}else if(be.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 Qn(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";Ih="-{5}",Ph="\\n",ej=`[^${Ph}]+`,tj=`${Ih}BEGIN (${ej}(?=${Ih}))${Ih}`,rj=`${Ih}END \\1${Ih}`,Eu="\\n",sj=`[^:${Ph}]+`,nj=`(?:[^${Ph}]+${Eu}(?: +[^${Ph}]+${Eu})*)`,ij="[a-zA-Z0-9=+/]+",oj=`(?:${ij}${Eu})+`,mA=`${tj}${Eu}(?:((?:${sj}: ${nj})+))?${Eu}?(${oj})${rj}`,Nr=class{static isPem(e){return typeof e=="string"&&new RegExp(mA,"g").test(e.replace(/\r/g,""))}static decodeWithHeaders(e){e=e.replace(/\r/g,"");let t=new RegExp(mA,"g"),s=[],n=null;for(;n=t.exec(e);){let i=n[3].replace(new RegExp(`[${Ph}]+`,"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(!be.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:be.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:be.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 be.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=be.toUint8Array(e);if(t.length>0&&t[0]===48)return be.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(kh.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(be.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=aj(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===Gn){let n=pe.parse(e.subjectPublicKey,mu),i=be.toUint8Array(n.modulus);s.publicExponent=be.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 Gn:default:e["Raw Data"]=t.subjectPublicKey}return e}};Bg=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(be.isBufferSource(e[0]))super(e[0]);else if(typeof e[0]=="string"){let t=new qn({keyIdentifier:new nc(Ue.FromHex(e[0]))});super(km,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 qn({authorityCertIssuer:s,authorityCertSerialNumber:Ue.FromHex(t.serialNumber)});super(km,e[1],pe.serialize(n))}}onInit(e){super.onInit(e);let t=pe.parse(e.extnValue,qn);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,qn);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}};Bg.NAME="Authority Key Identifier";Ng=class extends Is{constructor(...e){if(be.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(Pm,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}};Ng.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"})(gA||(gA={}));Og=class extends Is{constructor(...e){if(be.isBufferSource(e[0])){super(e[0]);let t=pe.parse(this.value,El);this.usages=t.map(s=>s)}else{let t=new El(e[0]);super(Dm,e[1],pe.serialize(t)),this.usages=e[0]}}toTextObject(){let e=this.toTextObjectWithoutValue();return e[""]=this.usages.map(t=>Zn.toString(t)).join(", "),e}};Og.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"})(yA||(yA={}));Lg=class extends Is{constructor(...e){if(be.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(Mm,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}};Lg.NAME="Key Usages";Dg=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(be.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(W1,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}};Dg.NAME="Subject Key Identifier";Mg=class extends Is{constructor(...e){be.isBufferSource(e[0])?super(e[0]):super($1,e[1],new Fi(e[0]||[]).rawData)}onInit(e){super.onInit(e);let t=pe.parse(e.extnValue,Fm);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}};Mg.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;Ug=class extends Is{constructor(...e){var t;if(be.isBufferSource(e[0])){super(e[0]);let s=pe.parse(this.value,bl);this.policies=s.map(n=>n.policyIdentifier)}else{let s=e[0],n=(t=e[1])!==null&&t!==void 0?t:!1,i=new bl(s.map(o=>new oc({policyIdentifier:o})));super(Nm,n,pe.serialize(i)),this.policies=s}}toTextObject(){let e=this.toTextObjectWithoutValue();return e.Policy=this.policies.map(t=>new Rt("",{},Zn.toString(t))),e}};Ug.NAME="Certificate Policies";rs.register(Nm,Ug);jg=class extends Is{constructor(...e){var t;if(be.isBufferSource(e[0]))super(e[0]);else if(Array.isArray(e[0])&&typeof e[0][0]=="string"){let n=e[0].map(o=>new zn({distributionPoint:new Ni({fullName:[new We({uniformResourceIdentifier:o})]})})),i=new Mo(n);super(Om,e[1],pe.serialize(i))}else{let s=new Mo(e[0]);super(Om,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 Qn(i).toString()).join(", ")),t.reasons&&(n.Reasons=t.reasons.toString()),t.cRLIssuer&&(n["CRL Issuer"]=t.cRLIssuer.map(i=>i.toString()).join(", ")),n}),e}};jg.NAME="CRL Distribution Points";Hg=class extends Is{constructor(...e){var t,s,n,i;if(be.isBufferSource(e[0]))super(e[0]);else if(e[0]instanceof sc){let o=new sc(e[0]);super(Rm,e[1],pe.serialize(o))}else{let o=e[0],a=new sc;Ig(a,o,E1,"ocsp"),Ig(a,o,C1,"caIssuers"),Ig(a,o,T1,"timeStamping"),Ig(a,o,A1,"caRepository"),super(Rm,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 E1:this.ocsp.push(new Qn(s.accessLocation));break;case C1:this.caIssuers.push(new Qn(s.accessLocation));break;case T1:this.timeStamping.push(new Qn(s.accessLocation));break;case A1:this.caRepository.push(new Qn(s.accessLocation));break}})}toTextObject(){let e=this.toTextObjectWithoutValue();return this.ocsp.length&&Ag(e,"OCSP",this.ocsp),this.caIssuers.length&&Ag(e,"CA Issuers",this.caIssuers),this.timeStamping.length&&Ag(e,"Time Stamping",this.timeStamping),this.caRepository.length&&Ag(e,"CA Repository",this.caRepository),e}};Hg.NAME="Authority Info Access";Fg=class extends Is{constructor(...e){be.isBufferSource(e[0])?super(e[0]):super(H1,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}};Fg.NAME="Issuer Alternative Name";Cu=class r extends Zo{constructor(...e){let t;if(be.isBufferSource(e[0]))t=be.toArrayBuffer(e[0]);else{let s=e[0],n=Array.isArray(e[1])?e[1].map(i=>be.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]=Zn.toString(this.type)),e}};Cu.NAME="Attribute";qg=class extends Cu{constructor(...e){var t;if(be.isBufferSource(e[0]))super(e[0]);else{let s=new ih({printableString:e[0]});super(kw,[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],ih);this.password=t.toString()}}toTextObject(){let e=this.toTextObjectWithoutValue();return e[Rt.VALUE]=this.password,e}};qg.NAME="Challenge Password";Bh=class extends Cu{constructor(...e){var t;if(be.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(ah,[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}};Bh.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;Oh="crypto.signatureFormatter",Kw=class{toAsnSignature(e,t){return be.toArrayBuffer(t)}toWebSignature(e,t){return be.toArrayBuffer(t)}},Ww=kg=class{static createPssParams(e,t){let s=kg.getHashAlgorithm(e);return s?new Xn({hashAlgorithm:s,maskGenAlgorithm:new fe({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 fe({algorithm:uu,parameters:null});case"sha-256":return new fe({algorithm:ig,parameters:null});case"sha-384":return new fe({algorithm:fu,parameters:null});case"sha-512":return new fe({algorithm:lu,parameters:null})}}else return new fe({algorithm:Gn,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=kg.createPssParams(e.hash,e.saltLength);if(!t)throw new Error("Cannot create PSS parameters");return new fe({algorithm:$o,parameters:pe.serialize(t)})}else return new fe({algorithm:$o,parameters:null})}return null}toWebAlgorithm(e){switch(e.algorithm){case Gn:return{name:"RSASSA-PKCS1-v1_5"};case uu:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-1"}};case ig: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,Xn);return{name:"RSA-PSS",hash:Kt.resolve(Lc).toWebAlgorithm(t.hashAlgorithm),saltLength:t.saltLength}}else return{name:"RSA-PSS"}}return null}};Ww=kg=p([Go()],Ww);Kt.registerSingleton(Nh,Ww);Gw=class{toAsnAlgorithm(e){switch(e.name.toLowerCase()){case"sha-1":return new fe({algorithm:Ec});case"sha-256":return new fe({algorithm:Cc});case"sha-384":return new fe({algorithm:Tc});case"sha-512":return new fe({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}};Gw=p([Go()],Gw);Kt.registerSingleton(Nh,Gw);qi=class r{addPadding(e,t){let s=be.toUint8Array(t),n=new Uint8Array(e);return n.set(s,e-s.length),n.buffer}removePadding(e,t=!1){let s=be.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=be.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 P6(o,a)}return null}};qi.namedCurveSize=new Map;qi.defaultNamedCurveSize=32;qw="1.3.101.110",xA="1.3.101.111",zw="1.3.101.112",bA="1.3.101.113",Xw=class{toAsnAlgorithm(e){let t=null;switch(e.name.toLowerCase()){case"ed25519":t=zw;break;case"x25519":t=qw;break;case"eddsa":switch(e.namedCurve.toLowerCase()){case"ed25519":t=zw;break;case"ed448":t=bA;break}break;case"ecdh-es":switch(e.namedCurve.toLowerCase()){case"x25519":t=qw;break;case"x448":t=xA;break}}return t?new fe({algorithm:t}):null}toWebAlgorithm(e){switch(e.algorithm){case zw:return{name:"Ed25519"};case bA:return{name:"EdDSA",namedCurve:"Ed448"};case qw:return{name:"X25519"};case xA:return{name:"ECDH-ES",namedCurve:"X448"}}return null}};Xw=p([Go()],Xw);Kt.registerSingleton(Nh,Xw);Yw=class extends ea{get subjectName(){return ht(this,fh,"f")||Gt(this,fh,new ln(this.asn.certificationRequestInfo.subject),"f"),ht(this,fh,"f")}get subject(){return ht(this,lh,"f")||Gt(this,lh,this.subjectName.toString(),"f"),ht(this,lh,"f")}get signatureAlgorithm(){if(!ht(this,hh,"f")){let e=Kt.resolve(Lc);Gt(this,hh,e.toWebAlgorithm(this.asn.signatureAlgorithm),"f")}return ht(this,hh,"f")}get signature(){return ht(this,ph,"f")||Gt(this,ph,this.asn.signature,"f"),ht(this,ph,"f")}get publicKey(){return ht(this,mh,"f")||Gt(this,mh,new ji(this.asn.certificationRequestInfo.subjectPKInfo),"f"),ht(this,mh,"f")}get attributes(){return ht(this,gh,"f")||Gt(this,gh,this.asn.certificationRequestInfo.attributes.map(e=>Tu.create(pe.serialize(e))),"f"),ht(this,gh,"f")}get extensions(){if(!ht(this,Su,"f")){Gt(this,Su,[],"f");let e=this.getAttribute(ah);e instanceof Bh&&Gt(this,Su,e.items,"f")}return ht(this,Su,"f")}get tbs(){return ht(this,uh,"f")||Gt(this,uh,this.asn.certificationRequestInfoRaw||pe.serialize(this.asn.certificationRequestInfo),"f"),ht(this,uh,"f")}constructor(e){let t=ea.isAsnEncoded(e)?[e,Qo]:[e];super(t[0],t[1]),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),gh.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(Oh).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:`${$n[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}};uh=new WeakMap,fh=new WeakMap,lh=new WeakMap,hh=new WeakMap,ph=new WeakMap,mh=new WeakMap,gh=new WeakMap,Su=new WeakMap;Yw.NAME="PKCS#10 Certificate Request";zg=class extends ea{get publicKey(){return ht(this,Ah,"f")||Gt(this,Ah,new ji(this.asn.tbsCertificate.subjectPublicKeyInfo),"f"),ht(this,Ah,"f")}get serialNumber(){if(!ht(this,xh,"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,xh,Ue.ToHex(t),"f")}return ht(this,xh,"f")}get subjectName(){return ht(this,bh,"f")||Gt(this,bh,new ln(this.asn.tbsCertificate.subject),"f"),ht(this,bh,"f")}get subject(){return ht(this,vh,"f")||Gt(this,vh,this.subjectName.toString(),"f"),ht(this,vh,"f")}get issuerName(){return ht(this,wh,"f")||Gt(this,wh,new ln(this.asn.tbsCertificate.issuer),"f"),ht(this,wh,"f")}get issuer(){return ht(this,Sh,"f")||Gt(this,Sh,this.issuerName.toString(),"f"),ht(this,Sh,"f")}get notBefore(){if(!ht(this,_h,"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,_h,e,"f")}return ht(this,_h,"f")}get notAfter(){if(!ht(this,Eh,"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,Eh,e,"f")}return ht(this,Eh,"f")}get signatureAlgorithm(){if(!ht(this,Ch,"f")){let e=Kt.resolve(Lc);Gt(this,Ch,e.toWebAlgorithm(this.asn.signatureAlgorithm),"f")}return ht(this,Ch,"f")}get signature(){return ht(this,Th,"f")||Gt(this,Th,this.asn.signatureValue,"f"),ht(this,Th,"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,yh,"f")||Gt(this,yh,this.asn.tbsCertificateRaw||pe.serialize(this.asn.tbsCertificate),"f"),ht(this,yh,"f")}constructor(e){let t=ea.isAsnEncoded(e)?[e,Ks]:[e];super(t[0],t[1]),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),Th.set(this,void 0),_u.set(this,void 0),Ah.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(be.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(Oh).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:`${$n[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}};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,Th=new WeakMap,_u=new WeakMap,Ah=new WeakMap;zg.NAME="Certificate";$g=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:be.isBufferSource(e.publicKey)?n=e.publicKey:n=await t.subtle.exportKey("spki",e.publicKey);let i=cj(e.serialNumber,t),o=e.notBefore||new Date,a=e.notAfter||new Date(o.getTime()+31536e6),c=new Ks({tbsCertificate:new kr({version:$n.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(Oh).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 zg(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"})(vA||(vA={}));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,bj=new WeakMap,vj=new WeakMap;rs.register(Pm,Ng);rs.register(Dm,Og);rs.register(Mm,Lg);rs.register(W1,Dg);rs.register(km,Bg);rs.register($1,Mg);rs.register(Om,jg);rs.register(Rm,Hg);rs.register(H1,Fg);Tu.register(kw,qg);Tu.register(ah,Bh);Kt.registerSingleton(Oh,Kw);Kt.registerSingleton(Oh,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 AA=se((Mfe,TA)=>{"use strict";function Sj(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)}TA.exports=Sj});var Lh=se((Ufe,DA)=>{"use strict";var IA=require("util"),BA=AA(),RA=/[\{\[]/,kA=/[\}\]]/,PA=["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"],NA={};for(Vg=0;Vg<PA.length;Vg++)NA[PA[Vg]]=!0;var Vg,_j=function(r){return BA(r)&&!NA.hasOwnProperty(r)},OA={s:function(r){return""+r},d:function(r){return""+Number(r)},o:function(r){return JSON.stringify(r)}},LA=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(kA.test(o.trim()[0])&&RA.test(o[o.length-1])){e--,s(o),e++;return}if(RA.test(o[o.length-1])){s(o),e++;return}if(kA.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(IA.format.apply(IA,arguments));return i};return i.scope={},i.formats=OA,i.sym=function(o){return(!o||!_j(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+"",BA(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};LA.formats=OA;DA.exports=LA});var UA=se((jfe,MA)=>{"use strict";var Wg=class{constructor(){this.next=null,this.buffer=null}};MA.exports=class Kg{constructor(){this.head=null,this.tail=null,this.length=0,this.count=0}push(e){let t=new Wg;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 Wg;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 Kg;if(t<0||t>this.length||t<e)return new Kg;let s=new Kg,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 qA=se((Hfe,FA)=>{"use strict";var Gg=Lh(),Ej=UA(),Dc=class r{constructor(){this.queue=new Ej,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}},jA={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(jA).forEach(r=>{let e=Gg();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(jA[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 Cj=["readIntBE","readIntLE","readUIntBE","readUIntLE"];Cj.forEach(r=>{let e=Gg();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 HA={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(HA).forEach(r=>{let e=Gg();e(`
|
|
58
|
-
function bufferlist_${r}(value) {
|
|
59
|
-
const size = ${e.formats.d(HA[r])};
|
|
60
|
-
const buf = Buffer.allocUnsafe(size);
|
|
61
|
-
buf.${r}(value, 0);
|
|
62
|
-
this.append(buf);
|
|
63
|
-
}
|
|
64
|
-
`),Dc.prototype[r]=e.toFunction()});var Tj=["writeIntBE","writeIntLE","writeUIntBE","writeUIntLE"];Tj.forEach(r=>{let e=Gg();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()});FA.exports=Dc});var Au=se((qfe,zA)=>{"use strict";zA.exports=class extends Error{constructor(e,t){let s=`requested ${e} bytes but only ${t} available`;super(s),this.name="NotEnoughDataError"}}});var Dh=se((zfe,KA)=>{"use strict";var{Transform:Aj}=require("stream"),Xg=Lh(),Ij=qA(),Rj=Au(),$A=Symbol("buffer"),Mc=class extends Aj{constructor(e={}){super(e),this[$A]=new Ij}get buffer(){return this[$A]}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){Jw(e,this.length);let t=this.slice(0,e);return this.consume(e),t}writeBuffer(e){this.append(e)}},VA={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},kj=["readIntBE","readIntLE","readUIntBE","readUIntLE"];Object.keys(VA).forEach(r=>{let e=Xg();e(`
|
|
71
|
-
function binary_${r}() {
|
|
72
|
-
const bytes = ${e.formats.d(VA[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:Jw})});kj.forEach(r=>{let e=Xg();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:Jw})});var Pj=["writeDoubleBE","writeDoubleLE","writeFloatBE","writeFloatLE","writeInt32BE","writeInt32LE","writeUInt32BE","writeUInt32LE","writeInt16BE","writeInt16LE","writeUInt16BE","writeUInt16LE","writeInt8","writeUInt8"];Pj.forEach(r=>{let e=Xg();e(`
|
|
89
|
-
function binary_${r}(value) {
|
|
90
|
-
this.buffer.${r}(value);
|
|
91
|
-
}
|
|
92
|
-
`),Mc.prototype[r]=e.toFunction()});var Bj=["writeIntBE","writeIntLE","writeUIntBE","writeUIntLE"];Bj.forEach(r=>{let e=Xg();e(`
|
|
93
|
-
function binary_${r}(value, size) {
|
|
94
|
-
this.buffer.${r}(value, size);
|
|
95
|
-
}
|
|
96
|
-
`),Mc.prototype[r]=e.toFunction()});function Jw(r,e){if(r>e)throw new Rj(r,e)}KA.exports=Mc});var GA=se(($fe,WA)=>{"use strict";WA.exports=function(e){return e!=null&&typeof e=="object"&&Array.isArray(e)===!1}});var JA=se((Vfe,YA)=>{"use strict";var Nj=GA();function XA(r){return Nj(r)===!0&&Object.prototype.toString.call(r)==="[object Object]"}YA.exports=function(e){var t,s;return!(XA(e)===!1||(t=e.constructor,typeof t!="function")||(s=t.prototype,XA(s)===!1)||s.hasOwnProperty("isPrototypeOf")===!1)}});var ei=se((Kfe,QA)=>{"use strict";var Oj=JA();QA.exports={isType:Lj,isUserType:Oj,isFunction:Mh,isDecodeType:Dj,isEncodeType:Mj};function Lj(r){return Qw(r)&&Mh(r.encode)&&Mh(r.decode)}function Mh(r){return typeof r=="function"}function Qw(r){return typeof r=="object"&&r!==null}function Dj(r){return Qw(r)&&Mh(r.decode)}function Mj(r){return Qw(r)&&Mh(r.encode)}});var ta=se((Wfe,ZA)=>{"use strict";var Uj=Symbol("skip"),jj=Symbol("bytes");ZA.exports={skip:Uj,bytes:jj}});var ra=se((Gfe,t5)=>{"use strict";var e5=ta();t5.exports=class Yg{constructor(){this[e5.bytes]=0,this.node=void 0,this.current=void 0}get bytes(){return this[e5.bytes]}static clone(e){let t=new Yg;return e instanceof Yg&&(t.node=e.node,t.current=e.current),t}static clean(e){e instanceof Yg&&(e.node=void 0,e.current=void 0)}}});var Iu=se((Xfe,o5)=>{"use strict";var{isType:Hj,isUserType:Fj,isDecodeType:qj}=ei(),zj=Dh(),Zw=ta(),r5=ra();o5.exports={decode:s5,decodeCommon:n5};function s5(r,e){let t=r;Buffer.isBuffer(r)&&(t=new zj,t.append(r));let s=new r5,n=n5(t,e,s);return s5.bytes=s.bytes,r5.clean(s),n}function n5(r,e,t){if(Hj(e)){let s=e.decode.call(t,r);return t[Zw.bytes]+=e.decode.bytes,s}return i5(r,e,t)}function i5(r,e,t){$j(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(!qj(a)){s[o]=i5(r,a,t),t.current=s;continue}let c=a.decode.call(t,r);t[Zw.bytes]+=a.decode.bytes,a[Zw.skip]!==!0&&(s[o]=c)}return s}function $j(r){if(!Fj(r))throw new TypeError("Argument #2 should be a plain object.")}});var Uh=se((Yfe,l5)=>{"use strict";var{isUserType:Vj,isEncodeType:Kj,isType:Wj}=ei(),c5=ta(),a5=ra(),eS=Dh();l5.exports={encode:d5,encodeCommon:u5};function d5(r,e,t){let s=new a5;if(e instanceof eS){let n=t;t=e,e=n}return t instanceof eS||(t=new eS),u5(r,t,e,s),d5.bytes=s.bytes,a5.clean(s),t}function u5(r,e,t,s){Wj(t)?(t.encode.call(s,r,e),s[c5.bytes]+=t.encode.bytes):f5(r,e,t,s)}function f5(r,e,t,s){Gj(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(!Kj(a)){f5(c,e,a,s),s.current=r;continue}a.encode.call(s,c,e),s[c5.bytes]+=a.encode.bytes}}function Gj(r){if(!Vj(r))throw new TypeError("Argument `schema` should be a plain object.")}});var jh=se((Jfe,x5)=>{"use strict";var{isUserType:Xj,isType:p5}=ei(),h5=ra(),m5=ta();x5.exports={encodingLength:Yj,encodingLengthCommon:g5};function Yj(r,e){let t=new h5;return g5(r,e,t),h5.clean(t),t.bytes}function g5(r,e,t){p5(e)?t[m5.bytes]+=e.encodingLength.call(t,r):y5(r,e,t)}function y5(r,e,t){if(!Xj(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(!p5(o)){y5(a,o,t),t.current=r;continue}t[m5.bytes]+=o.encodingLength.call(t,a)}}});var T5=se((Qfe,C5)=>{"use strict";var{decodeCommon:E5}=Iu(),{encodeCommon:Jj}=Uh(),{encodingLengthCommon:b5}=jh(),{isType:v5,isUserType:Qj,isFunction:Zj}=ei(),sa=ra();C5.exports=eH;function eH(r,e,t="count"){if(!v5(r)&&!Qj(r))throw new TypeError("Argument #1 should be a valid type.");let s=t==="bytes",n=typeof e=="number",i=v5(e),o=Zj(e);if(!n&&!i&&!o)throw new TypeError("Unknown type of argument #1.");return{encode:a,decode:c,encodingLength:d};function a(u,f){w5(u);let h=sa.clone(this);a.bytes=0;let y=0;if(i?y=u.length:n?y=e:o&&(y=e(h),S5(y)),s||_5(y,u.length),s){let v=sa.clone(h);for(let S of u)b5(S,r,v);i&&(y=v.bytes),_5(v.bytes,y),sa.clean(v)}i&&(e.encode.call(h,y,f),a.bytes+=e.encode.bytes),u.forEach(v=>{Jj(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)),S5(f);let y;return s?y=tH(r,f,u,h):y=rH(r,f,u,h),c.bytes+=h.bytes,sa.clean(h),y}function d(u){w5(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)b5(y,r,f);return sa.clean(f),h+=f.bytes,i&&s&&(h+=e.encodingLength(h)),h}}function w5(r){if(!Array.isArray(r))throw new TypeError("Argument #1 should be an Array.")}function S5(r){if(typeof r!="number")throw new TypeError("Length of an array should be a number.")}function _5(r,e){if(r!==e)throw new Error(`Argument #1 required length ${r} instead of ${e}`)}function tH(r,e,t,s){let n=[],i=s.bytes,o=0;for(;o<e;)n.push(E5(t,r,s)),o=s.bytes-i;if(o>e)throw new Error("Incorrect length of an array.");return n}function rH(r,e,t,s){let n=new Array(e);for(let i=0;i<e;i+=1)n[i]=E5(t,r,s);return n}});var k5=se((Zfe,R5)=>{"use strict";var{isType:sH,isFunction:nH}=ei(),iH=Au(),oH=Dh();R5.exports=aH;function aH(r){let e=typeof r=="number",t=sH(r),s=nH(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){A5(c),i.bytes=0;let u=this;if(e&&I5(r,c.length),t&&(r.encode.call(u,c.length,d),i.bytes+=r.encode.bytes),s){let f=r(u);tS(f),I5(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,tS(d);else if(s)d=r(u),tS(d);else if(n&&(d=c.indexOf(0),d===-1))throw new iH(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){A5(c);let d=0;return e?r:(n?d=1:t&&(d=r.encodingLength(c.length)),d+c.length)}}function A5(r){if(!Buffer.isBuffer(r)&&!(r instanceof oH))throw new TypeError("Argument 1 should be a Buffer or a BinaryStream.")}function I5(r,e){if(r!==e)throw new Error(`Buffer required length ${r} instead of ${e}`)}function tS(r){if(typeof r!="number")throw new TypeError("Length of a buffer should be a number.")}});var B5=se((ele,P5)=>{"use strict";var{isType:cH}=ei();P5.exports=dH;function dH(r){if(!cH(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 O5=se((tle,N5)=>{"use strict";var{decodeCommon:uH}=Iu(),{encodeCommon:fH}=Uh(),{encodingLengthCommon:lH}=jh(),{isType:hH,isFunction:Jg}=ei(),pH=ta(),na=ra();N5.exports=mH;function mH(r,e=1){if(!hH(r))throw new TypeError("Invalid data type.");if(!Number.isInteger(e)&&!Jg(e))throw new TypeError("Argument #2 should be a valid integer or function.");return{[pH.skip]:!0,encodingLength:t,decode:s,encode:n};function t(i){let o=na.clone(this),a=Jg(e)?e(o):e;return lH(i,r,o),na.clean(o),o.bytes*a}function s(i){let o=na.clone(this);s.bytes=0;let a=Jg(e)?e(o):e;if(a===0){na.clean(o);return}for(let c=a;c>0;c-=1)uH(i,r,o);s.bytes=o.bytes,na.clean(o)}function n(i,o){n.bytes=0;let a=na.clone(this),c=Jg(e)?e(a):e;if(c===0){na.clean(a);return}for(let d=c;d>0;d-=1)fH(0,o,r,a);n.bytes=a.bytes,na.clean(a)}}});var M5=se((rle,D5)=>{"use strict";var{isType:gH}=ei(),yH=Au();D5.exports=xH;function xH(r,e="ascii"){if(!Buffer.isEncoding(e))throw new Error("Argument #2 should be an encoding name.");if(typeof r=="number")return{encode:wH(r,e),decode:SH(r,e),encodingLength:()=>r};if(gH(r))return{encode:_H(r,e),decode:EH(r,e),encodingLength:CH(r,e)};if(r===null)return{encode:bH(e),decode:vH(e),encodingLength(t){return Buffer.byteLength(t,e)+1}};if(typeof r=="function")return{encode:TH(r,e),decode:AH(r,e),encodingLength(t){return Buffer.byteLength(t,e)}};throw new TypeError("Unknown type of argument #1.")}function bH(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 vH(r){return function e(t){let s=t.indexOf(0);if(s===-1)throw new yH(t.length+1,t.length);let n=s+1,i=t.readBuffer(n);return e.bytes=n,i.toString(r,0,s)}}function wH(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 SH(r,e){return function t(s){let n=s.readBuffer(r);return t.bytes=r,n.toString(e)}}function _H(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 EH(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 CH(r,e){return function(s){let n=Buffer.byteLength(s,e);return r.encodingLength(n)+n}}function TH(r,e){return function t(s,n){t.bytes=0;let o=r(this),a=Buffer.from(s.toString(),e);L5(o),IH(o,a.length),n.writeBuffer(a),t.bytes+=a.length}}function AH(r,e){return function t(s){let n=r(this);L5(n);let i=s.readBuffer(n);return t.bytes=n,i.toString(e)}}function L5(r){if(typeof r!="number")throw new TypeError("Length of a buffer should be a number.")}function IH(r,e){if(r!==e)throw new Error(`Buffer required length ${r} instead of ${e}`)}});var j5=se((sle,U5)=>{"use strict";var Qg=Lh();U5.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=Qg(),n=Qg();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=Qg(),n=Qg();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 F5=se((nle,H5)=>{"use strict";var{isType:RH,isFunction:rS,isUserType:kH}=ei(),sS=ta(),{decodeCommon:PH}=Iu(),{encodeCommon:BH}=Uh(),{encodingLengthCommon:NH}=jh(),ia=ra();H5.exports=OH;function OH(r,e){if(!RH(e)&&!kH(e))throw new TypeError("Argument #2 should be a valid type.");let t={encode:s,decode:n,encodingLength:i,[sS.skip]:!1};return t;function s(o,a){let c=ia.clone(this);s.bytes=0;let d=rS(r)?!!r(c):!!r;if(t[sS.skip]=!d,!d){ia.clean(c);return}BH(o,a,e,c),s.bytes=c.bytes,ia.clean(c)}function n(o){let a=ia.clone(this);n.bytes=0;let c=rS(r)?!!r(a):!!r;if(t[sS.skip]=!c,!c){ia.clean(a);return}let d=PH(o,e,a);return n.bytes=a.bytes,ia.clean(a),d}function i(o){let a=ia.clone(this);return(rS(r)?r(a):r)&&NH(o,e,a),ia.clean(a),a.bytes}}});var $5=se((ile,z5)=>{"use strict";var Zg=ta(),{decodeCommon:LH}=Iu(),q5=ra();z5.exports=DH;function DH(...r){if(r.length===0)throw new TypeError("You should set at least one condition type.");let e={decode:t,encode:()=>{},[Zg.skip]:!0};return e;function t(s){t.bytes=0;let n=q5.clone(this);for(let i of r){let o=LH(s,i,n);if(i[Zg.skip]!==!0)return t.bytes=n.bytes,q5.clean(n),e[Zg.skip]=!1,o}e[Zg.skip]=!0}}});var G5=se((ole,W5)=>{"use strict";var K5=Lh(),MH=Au(),Hh=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){nS(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}},V5={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(V5).forEach(r=>{let e=K5(),t=V5[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
|
-
`),Hh.prototype[r]=e.toFunction({assertSize:nS})});["readIntBE","readIntLE","readUIntBE","readUIntLE"].forEach(r=>{let e=K5();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
|
-
`),Hh.prototype[r]=e.toFunction({assertSize:nS})});W5.exports=Hh;function nS(r,e){if(r>e)throw new MH(r,e)}});var Zt=se((ale,rI)=>{"use strict";var iS=Dh(),UH=T5(),jH=k5(),HH=B5(),FH=O5(),qH=M5(),X5=j5(),zH=F5(),$H=$5(),{encode:Q5}=Uh(),{decode:Z5}=Iu(),{encodingLength:VH}=jh(),KH=G5(),eI=Au(),tI={array:UH,bool:HH,buffer:jH,reserved:FH,string:qH,when:zH,select:$H};for(let r of Object.keys(X5))tI[r]=X5[r];var ey=Symbol("schema");function Y5(r){let e=new iS({readableObjectMode:!1,writableObjectMode:!0,transform:WH});return e[ey]=r,e}function J5(r){let e=null,t=Buffer.isBuffer(r);t||(e=r);let s=new iS({transform:GH,readableObjectMode:!0,writableObjectMode:!1});return s[ey]=e,t&&s.append(r),s}function WH(r,e,t){try{Q5(r,this[ey],this);let s=this.slice();this.consume(s.length),t(null,s)}catch(s){t(s)}}function GH(r,e,t){this.append(r);try{for(;this.length>0;){let s=new KH(this),n=Z5(s,this[ey]);s.commit(),this.push(n)}t()}catch(s){s instanceof eI?t():t(s)}}rI.exports={createEncodeStream:Y5,createDecodeStream:J5,encode:Q5,decode:Z5,encodingLength:VH,createEncode:Y5,createDecode:J5,types:tI,BinaryStream:iS,NotEnoughDataError:eI}});var zi,Uc,sI=A(()=>{"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 Fh(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 ty(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");Fh(r.outputLen),Fh(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 iI(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 ry(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),oI)return r.toHex();let e="";for(let t=0;t<r.length;t++)e+=XH[r[t]];return e}function nI(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(oI)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=nI(r.charCodeAt(i)),a=nI(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 aI(r){if(typeof r!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(r))}function qh(r){return typeof r=="string"&&(r=aI(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 sy(r){let e=s=>r().update(qh(s)).digest(),t=r();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>r(),e}function ny(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 oI,XH,$i,Ru,Fc=A(()=>{"use strict";sI();oI=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",XH=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 zh(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 $h(r){let e=r.toString(16);return e.length&1?"0"+e:e}function cI(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?cS:BigInt("0x"+r)}function Pu(r){return cI(Ki(r))}function dS(r){return hn(r),cI(Ki(Uint8Array.from(r).reverse()))}function iy(r,e){return Hc(r.toString(16).padStart(e*2,"0"))}function uS(r,e){return iy(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 dI(r,e,t){return oS(r)&&oS(e)&&oS(t)&&e<=r&&r<t}function uI(r,e,t,s){if(!dI(e,t,s))throw new Error("expected valid "+r+": "+t+" <= n < "+s+", got "+e)}function oy(r){let e;for(e=0;r>cS;r>>=aS,e+=1);return e}function fI(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 Vh(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 fS(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 cS,aS,oS,aa,ay=A(()=>{"use strict";Fc();Fc();cS=BigInt(0),aS=BigInt(1);oS=r=>typeof r=="bigint"&&cS<=r;aa=r=>(aS<<BigInt(r))-aS});function gn(r,e){let t=r%e;return t>=xs?t:e+t}function lI(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 lS(r,e,t){if(!r.eql(r.sqr(e),t))throw new Error("Cannot find square root")}function bI(r,e){let t=(r.ORDER+Gr)/mI,s=r.pow(e,t);return lS(r,s,e),s}function QH(r,e){let t=(r.ORDER-gI)/yI,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 lS(r,a,e),a}function ZH(r){let e=ti(r),t=vI(r),s=t(e,e.neg(e.ONE)),n=t(e,s),i=t(e,e.neg(s)),o=(r+YH)/xI;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 lS(a,C,c),C}}function vI(r){if(r<pI)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=ti(r);for(;hI(n,s)===1;)if(s++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return bI;let i=n.pow(s,e),o=(e+Gr)/qc;return function(c,d){if(c.is0(d))return d;if(hI(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 eF(r){return r%mI===pI?bI:r%yI===gI?QH:r%xI===JH?ZH(r):vI(r)}function hS(r){let e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},t=tF.reduce((s,n)=>(s[n]="function",s),e);return Vh(r,t),r}function rF(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 cy(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 hI(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 dy(r,e){e!==void 0&&Fh(e);let t=e!==void 0?e:r.toString(2).length,s=Math.ceil(t/8);return{nBitLength:t,nByteLength:s}}function ti(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}=dy(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)=>rF(f,h,y),div:(h,y)=>gn(h*lI(y,r),r),sqrN:h=>h*h,addN:(h,y)=>h+y,subN:(h,y)=>h-y,mulN:(h,y)=>h*y,inv:h=>lI(h,r),sqrt:i||(h=>(u||(u=eF(r)),u(f,h))),toBytes:h=>t?uS(h,d):iy(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?dS(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=>cy(f,h),cmov:(h,y,v)=>v?y:h});return Object.freeze(f)}function wI(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 pS(r){let e=wI(r);return e+Math.ceil(e/2)}function SI(r,e,t=!1){let s=r.length,n=wI(e),i=pS(e);if(s<16||s<i||s>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+s);let o=t?dS(r):Pu(r),a=gn(o,e-Gr)+Gr;return t?uS(a,n):iy(a,n)}var xs,Gr,qc,pI,mI,gI,YH,yI,JH,xI,tF,uy=A(()=>{"use strict";ay();xs=BigInt(0),Gr=BigInt(1),qc=BigInt(2),pI=BigInt(3),mI=BigInt(4),gI=BigInt(5),YH=BigInt(7),yI=BigInt(8),JH=BigInt(9),xI=BigInt(16);tF=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"]});function sF(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 _I(r,e,t){return r&e^~r&t}function EI(r,e,t){return r&e^r&t^e&t}var Kh,Wi,Or,Lr,CI=A(()=>{"use strict";Fc();Kh=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=ry(this.buffer)}update(e){ku(this),e=qh(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=ry(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),iI(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;sF(s,n-8,BigInt(this.length*8),i),this.process(s,0);let a=ry(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 nF(r,e=!1){return e?{h:Number(r&fy),l:Number(r>>TI&fy)}:{h:Number(r>>TI&fy)|0,l:Number(r&fy)|0}}function AI(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}=nF(r[i],e);[s[i],n[i]]=[o,a]}return[s,n]}function ri(r,e,t,s){let n=(e>>>0)+(s>>>0);return{h:r+t+(n/2**32|0)|0,l:n|0}}var fy,TI,mS,gS,zc,$c,Wh,Gh,II,RI,kI,PI,BI,NI,OI=A(()=>{"use strict";fy=BigInt(4294967295),TI=BigInt(32);mS=(r,e,t)=>r>>>t,gS=(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,Wh=(r,e,t)=>r<<64-t|e>>>t-32,Gh=(r,e,t)=>r>>>t-32|e<<64-t;II=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),RI=(r,e,t,s)=>e+t+s+(r/2**32|0)|0,kI=(r,e,t,s)=>(r>>>0)+(e>>>0)+(t>>>0)+(s>>>0),PI=(r,e,t,s,n)=>e+t+s+n+(r/2**32|0)|0,BI=(r,e,t,s,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(s>>>0)+(n>>>0),NI=(r,e,t,s,n,i)=>e+t+s+n+i+(r/2**32|0)|0});var oF,ca,yS,LI,aF,cF,da,ua,ly,xS,DI,MI,UI,jI=A(()=>{"use strict";CI();OI();Fc();oF=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),yS=class extends Kh{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+_I(a,c,d)+oF[f]+ca[f]|0,S=(pn(s,2)^pn(s,13)^pn(s,22))+EI(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)}},LI=AI(["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))),aF=LI[0],cF=LI[1],da=new Uint32Array(80),ua=new Uint32Array(80),ly=class extends Kh{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,te=zc(Q,oe,1)^zc(Q,oe,8)^mS(Q,oe,7),Ee=$c(Q,oe,1)^$c(Q,oe,8)^gS(Q,oe,7),ge=da[z-2]|0,Y=ua[z-2]|0,Ze=zc(ge,Y,19)^Wh(ge,Y,61)^mS(ge,Y,6),vt=$c(ge,Y,19)^Gh(ge,Y,61)^gS(ge,Y,6),Fe=kI(Ee,vt,ua[z-7],ua[z-16]),$=PI(Fe,te,Ze,da[z-7],da[z-16]);da[z]=$|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)^Wh(f,h,41),oe=$c(f,h,14)^$c(f,h,18)^Gh(f,h,41),te=f&y^~f&S,Ee=h&v^~h&C,ge=BI(K,oe,Ee,cF[z],ua[z]),Y=NI(ge,O,Q,te,aF[z],da[z]),Ze=ge|0,vt=zc(s,n,28)^Wh(s,n,34)^Wh(s,n,39),Fe=$c(s,n,28)^Gh(s,n,34)^Gh(s,n,39),$=s&i^s&a^i&a,V=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}=ri(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 H=II(Ze,Fe,V);s=RI(H,Y,vt,$),n=H|0}({h:s,l:n}=ri(this.Ah|0,this.Al|0,s|0,n|0)),{h:i,l:o}=ri(this.Bh|0,this.Bl|0,i|0,o|0),{h:a,l:c}=ri(this.Ch|0,this.Cl|0,a|0,c|0),{h:d,l:u}=ri(this.Dh|0,this.Dl|0,d|0,u|0),{h:f,l:h}=ri(this.Eh|0,this.El|0,f|0,h|0),{h:y,l:v}=ri(this.Fh|0,this.Fl|0,y|0,v|0),{h:S,l:C}=ri(this.Gh|0,this.Gl|0,S|0,C|0),{h:O,l:K}=ri(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)}},xS=class extends ly{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}},DI=sy(()=>new yS),MI=sy(()=>new ly),UI=sy(()=>new xS)});var hy,bS,HI=A(()=>{"use strict";Fc();hy=class extends Ru{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,ty(e);let s=qh(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()}},bS=(r,e,t)=>new hy(r,e).update(t).digest();bS.create=(r,e)=>new hy(r,e)});function Xh(r,e){let t=e.negate();return r?t:e}function my(r,e){let t=cy(r.Fp,e.map(s=>s.Z));return e.map((s,n)=>r.fromAffine(s.toAffine(t[n])))}function $I(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function vS(r,e){$I(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 FI(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 dF(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 uF(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 SS(r){return VI.get(r)||1}function qI(r){if(r!==Bu)throw new Error("invalid wNAF")}function KI(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 WI(r,e,t,s){dF(t,r),uF(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=oy(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 zI(r,e,t){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return hS(e),e}else return ti(r,{isLE:t})}function GI(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=zI(e.p,t.Fp,s),i=zI(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,wS,VI,py,XI=A(()=>{"use strict";ay();uy();Bu=BigInt(0),Vc=BigInt(1);wS=new WeakMap,VI=new WeakMap;py=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}=vS(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=vS(e,this.bits);for(let a=0;a<o.windows;a++){let{nextN:c,offset:d,isZero:u,isNeg:f,isNegF:h,offsetF:y}=FI(s,a,o);s=c,u?i=i.add(Xh(h,t[y])):n=n.add(Xh(f,t[d]))}return qI(s),{p:n,f:i}}wNAFUnsafe(e,t,s,n=this.ZERO){let i=vS(e,this.bits);for(let o=0;o<i.windows&&s!==Bu;o++){let{nextN:a,offset:c,isZero:d,isNeg:u}=FI(s,o,i);if(s=a,!d){let f=t[c];n=n.add(u?f.negate():f)}}return qI(s),n}getPrecomputes(e,t,s){let n=wS.get(t);return n||(n=this.precomputeWindow(t,e),e!==1&&(typeof s=="function"&&(n=s(n)),wS.set(t,n))),n}cached(e,t,s){let n=SS(e);return this.wNAF(n,this.getPrecomputes(n,e,s),t)}unsafe(e,t,s,n){let i=SS(e);return i===1?this._unsafeLadder(e,t,n):this.wNAFUnsafe(i,this.getPrecomputes(i,e,s),t,n)}createCache(e,t){$I(t,this.bits),VI.set(e,t),wS.delete(e)}hasCache(e){return SS(e)!==1}}});function fF(r,e,t){let[[s,n],[i,o]]=e,a=YI(o*r,t),c=YI(-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(oy(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 ES(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function _S(r,e){let t={};for(let s of Object.keys(e))t[s]=r[s]===void 0?e[s]:r[s];return zh(t.lowS,"lowS"),zh(t.prehash,"prehash"),t.format!==void 0&&ES(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 hF(r,e={}){let t=GI("weierstrass",r,e),{Fp:s,Fn:n}=t,i=t.CURVE,{h:o,n:a}=i;Vh(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=ZI(s,n);function u(){if(!s.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function f(Fe,$,V){let{x:H,y:me}=$.toAffine(),Te=s.toBytes(H);if(zh(V,"isCompressed"),V){u();let ne=!s.isOdd(me);return mn(QI(ne),Te)}else return mn(Uint8Array.of(4),Te,s.toBytes(me))}function h(Fe){oa(Fe,void 0,"Point");let{publicKey:$,publicKeyUncompressed:V}=d,H=Fe.length,me=Fe[0],Te=Fe.subarray(1);if(H===$&&(me===2||me===3)){let ne=s.fromBytes(Te);if(!s.isValid(ne))throw new Error("bad point: is not on curve, wrong x");let T=S(ne),R;try{R=s.sqrt(T)}catch(L){let ce=L instanceof Error?": "+L.message:"";throw new Error("bad point: is not on curve, sqrt error"+ce)}u();let F=s.isOdd(R);return(me&1)===1!==F&&(R=s.neg(R)),{x:ne,y:R}}else if(H===V&&me===4){let ne=s.BYTES,T=s.fromBytes(Te.subarray(0,ne)),R=s.fromBytes(Te.subarray(ne,ne*2));if(!C(T,R))throw new Error("bad point: is not on curve");return{x:T,y:R}}else throw new Error(`bad point: got length ${H}, expected compressed=${$} or uncompressed=${V}`)}let y=e.toBytes||f,v=e.fromBytes||h;function S(Fe){let $=s.sqr(Fe),V=s.mul($,Fe);return s.add(s.add(V,s.mul(Fe,i.a)),i.b)}function C(Fe,$){let V=s.sqr($),H=S(Fe);return s.eql(V,H)}if(!C(i.Gx,i.Gy))throw new Error("bad curve params: generator point");let O=s.mul(s.pow(i.a,gy),lF),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=!1){if(!s.isValid($)||V&&s.is0($))throw new Error(`bad point coordinate ${Fe}`);return $}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 fF(Fe,c.basises,n.ORDER)}let te=fS((Fe,$)=>{let{X:V,Y:H,Z:me}=Fe;if(s.eql(me,s.ONE))return{x:V,y:H};let Te=Fe.is0();$==null&&($=Te?s.ONE:s.inv(me));let ne=s.mul(V,$),T=s.mul(H,$),R=s.mul(me,$);if(Te)return{x:s.ZERO,y:s.ZERO};if(!s.eql(R,s.ONE))throw new Error("invZ was invalid");return{x:ne,y:T}}),Ee=fS(Fe=>{if(Fe.is0()){if(e.allowInfinityPoint&&!s.is0(Fe.Y))return;throw new Error("bad point: ZERO")}let{x:$,y:V}=Fe.toAffine();if(!s.isValid($)||!s.isValid(V))throw new Error("bad point: x or y not field elements");if(!C($,V))throw new Error("bad point: equation left != right");if(!Fe.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function ge(Fe,$,V,H,me){return V=new Y(s.mul(V.X,Fe),V.Y,V.Z),$=Xh(H,$),V=Xh(me,V),$.add(V)}class Y{constructor($,V,H){this.X=z("x",$),this.Y=z("y",V,!0),this.Z=z("z",H),Object.freeze(this)}static CURVE(){return i}static fromAffine($){let{x:V,y:H}=$||{};if(!$||!s.isValid(V)||!s.isValid(H))throw new Error("invalid affine point");if($ instanceof Y)throw new Error("projective point not allowed");return s.is0(V)&&s.is0(H)?Y.ZERO:new Y(V,H,s.ONE)}static fromBytes($){let V=Y.fromAffine(v(oa($,void 0,"point")));return V.assertValidity(),V}static fromHex($){return Y.fromBytes(Wr("pointHex",$))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute($=8,V=!0){return vt.createCache(this,$),V||this.multiply(gy),this}assertValidity(){Ee(this)}hasEvenY(){let{y:$}=this.toAffine();if(!s.isOdd)throw new Error("Field doesn't support isOdd");return!s.isOdd($)}equals($){Q($);let{X:V,Y:H,Z:me}=this,{X:Te,Y:ne,Z:T}=$,R=s.eql(s.mul(V,T),s.mul(Te,me)),F=s.eql(s.mul(H,T),s.mul(ne,me));return R&&F}negate(){return new Y(this.X,s.neg(this.Y),this.Z)}double(){let{a:$,b:V}=i,H=s.mul(V,gy),{X:me,Y:Te,Z:ne}=this,T=s.ZERO,R=s.ZERO,F=s.ZERO,I=s.mul(me,me),L=s.mul(Te,Te),ce=s.mul(ne,ne),he=s.mul(me,Te);return he=s.add(he,he),F=s.mul(me,ne),F=s.add(F,F),T=s.mul($,F),R=s.mul(H,ce),R=s.add(T,R),T=s.sub(L,R),R=s.add(L,R),R=s.mul(T,R),T=s.mul(he,T),F=s.mul(H,F),ce=s.mul($,ce),he=s.sub(I,ce),he=s.mul($,he),he=s.add(he,F),F=s.add(I,I),I=s.add(F,I),I=s.add(I,ce),I=s.mul(I,he),R=s.add(R,I),ce=s.mul(Te,ne),ce=s.add(ce,ce),I=s.mul(ce,he),T=s.sub(T,I),F=s.mul(ce,L),F=s.add(F,F),F=s.add(F,F),new Y(T,R,F)}add($){Q($);let{X:V,Y:H,Z:me}=this,{X:Te,Y:ne,Z:T}=$,R=s.ZERO,F=s.ZERO,I=s.ZERO,L=i.a,ce=s.mul(i.b,gy),he=s.mul(V,Te),ct=s.mul(H,ne),xt=s.mul(me,T),Ot=s.add(V,H),_t=s.add(Te,ne);Ot=s.mul(Ot,_t),_t=s.add(he,ct),Ot=s.sub(Ot,_t),_t=s.add(V,me);let Dt=s.add(Te,T);return _t=s.mul(_t,Dt),Dt=s.add(he,xt),_t=s.sub(_t,Dt),Dt=s.add(H,me),R=s.add(ne,T),Dt=s.mul(Dt,R),R=s.add(ct,xt),Dt=s.sub(Dt,R),I=s.mul(L,_t),R=s.mul(ce,xt),I=s.add(R,I),R=s.sub(ct,I),I=s.add(ct,I),F=s.mul(R,I),ct=s.add(he,he),ct=s.add(ct,he),xt=s.mul(L,xt),_t=s.mul(ce,_t),ct=s.add(ct,xt),xt=s.sub(he,xt),xt=s.mul(L,xt),_t=s.add(_t,xt),he=s.mul(ct,_t),F=s.add(F,he),he=s.mul(Dt,_t),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,F,I)}subtract($){return this.add($.negate())}is0(){return this.equals(Y.ZERO)}multiply($){let{endo:V}=e;if(!n.isValidNot0($))throw new Error("invalid scalar: out of range");let H,me,Te=ne=>vt.cached(this,ne,T=>my(Y,T));if(V){let{k1neg:ne,k1:T,k2neg:R,k2:F}=oe($),{p:I,f:L}=Te(T),{p:ce,f:he}=Te(F);me=L.add(he),H=ge(V.beta,I,ce,ne,R)}else{let{p:ne,f:T}=Te($);H=ne,me=T}return my(Y,[H,me])[0]}multiplyUnsafe($){let{endo:V}=e,H=this;if(!n.isValid($))throw new Error("invalid scalar: out of range");if($===Xi||H.is0())return Y.ZERO;if($===Ou)return H;if(vt.hasCache(this))return this.multiply($);if(V){let{k1neg:me,k1:Te,k2neg:ne,k2:T}=oe($),{p1:R,p2:F}=KI(Y,H,Te,T);return ge(V.beta,R,F,me,ne)}else return vt.unsafe(H,$)}multiplyAndAddUnsafe($,V,H){let me=this.multiplyUnsafe(V).add($.multiplyUnsafe(H));return me.is0()?void 0:me}toAffine($){return te(this,$)}isTorsionFree(){let{isTorsionFree:$}=e;return o===Ou?!0:$?$(Y,this):vt.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:$}=e;return o===Ou?this:$?$(Y,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes($=!0){return zh($,"isCompressed"),this.assertValidity(),y(Y,this,$)}toHex($=!0){return Ki(this.toBytes($))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes($=!0){return this.toBytes($)}_setWindowSize($){this.precompute($)}static normalizeZ($){return my(Y,$)}static msm($,V){return WI(Y,n,$,V)}static fromPrivateKey($){return Y.BASE.multiply(Nu(n,$))}}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,vt=new py(Y,e.endo?Math.ceil(Ze/2):Ze);return Y.BASE.precompute(8),Y}function QI(r){return Uint8Array.of(r?2:3)}function ZI(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function pF(r,e={}){let{Fn:t}=r,s=e.randomBytes||ny,n=Object.assign(ZI(r.Fp,t),{seed:pS(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 SI(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 mF(r,e,t={}){ty(e),Vh(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let s=t.randomBytes||ny,n=t.hmac||((V,...H)=>bS(e,V,mn(...H))),{Fp:i,Fn:o}=r,{ORDER:a,BITS:c}=o,{keygen:d,getPublicKey:u,getSharedSecret:f,utils:h,lengths:y}=pF(r,t),v={prehash:!1,lowS:typeof t.lowS=="boolean"?t.lowS:!1,format:void 0,extraEntropy:!1},S="compact";function C(V){let H=a>>Ou;return V>H}function O(V,H){if(!o.isValidNot0(H))throw new Error(`invalid signature ${V}: out of range 1..Point.Fn.ORDER`);return H}function K(V,H){ES(H);let me=y.signature,Te=H==="compact"?me:H==="recovered"?me+1:void 0;return oa(V,Te,`${H} signature`)}class z{constructor(H,me,Te){this.r=O("r",H),this.s=O("s",me),Te!=null&&(this.recovery=Te),Object.freeze(this)}static fromBytes(H,me=S){K(H,me);let Te;if(me==="der"){let{r:F,s:I}=Gi.toSig(oa(H));return new z(F,I)}me==="recovered"&&(Te=H[0],me="compact",H=H.subarray(1));let ne=o.BYTES,T=H.subarray(0,ne),R=H.subarray(ne,ne*2);return new z(o.fromBytes(T),o.fromBytes(R),Te)}static fromHex(H,me){return this.fromBytes(Hc(H),me)}addRecoveryBit(H){return new z(this.r,this.s,H)}recoverPublicKey(H){let me=i.ORDER,{r:Te,s:ne,recovery:T}=this;if(T==null||![0,1,2,3].includes(T))throw new Error("recovery id invalid");if(a*JI<me&&T>1)throw new Error("recovery id is ambiguous for h>1 curve");let F=T===2||T===3?Te+a:Te;if(!i.isValid(F))throw new Error("recovery id 2 or 3 invalid");let I=i.toBytes(F),L=r.fromBytes(mn(QI((T&1)===0),I)),ce=o.inv(F),he=oe(Wr("msgHash",H)),ct=o.create(-he*ce),xt=o.create(ne*ce),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(H=S){if(ES(H),H==="der")return Hc(Gi.hexFromSig(this));let me=o.toBytes(this.r),Te=o.toBytes(this.s);if(H==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return mn(Uint8Array.of(this.recovery),me,Te)}return mn(me,Te)}toHex(H){return Ki(this.toBytes(H))}assertValidity(){}static fromCompact(H){return z.fromBytes(Wr("sig",H),"compact")}static fromDER(H){return z.fromBytes(Wr("sig",H),"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(H){if(H.length>8192)throw new Error("input is too large");let me=Pu(H),Te=H.length*8-c;return Te>0?me>>BigInt(Te):me},oe=t.bits2int_modN||function(H){return o.create(Q(H))},te=aa(c);function Ee(V){return uI("num < 2^"+c,V,Xi,te),o.toBytes(V)}function ge(V,H){return oa(V,void 0,"message"),H?oa(e(V),void 0,"prehashed message"):V}function Y(V,H,me){if(["recovered","canonical"].some(ct=>ct in me))throw new Error("sign() legacy options not supported");let{lowS:Te,prehash:ne,extraEntropy:T}=_S(me,v);V=ge(V,ne);let R=oe(V),F=Nu(o,H),I=[Ee(F),Ee(R)];if(T!=null&&T!==!1){let ct=T===!0?s(y.secretKey):T;I.push(Wr("extraEntropy",ct))}let L=mn(...I),ce=R;function he(ct){let xt=Q(ct);if(!o.isValidNot0(xt))return;let Ot=o.inv(xt),_t=r.BASE.multiply(xt).toAffine(),Dt=o.create(_t.x);if(Dt===Xi)return;let Bs=o.create(Ot*o.create(ce+Dt*F));if(Bs===Xi)return;let Ns=(_t.x===Dt?0:2)|Number(_t.y&Ou),Ca=Bs;return Te&&C(Bs)&&(Ca=o.neg(Bs),Ns^=1),new z(Dt,Ca,Ns)}return{seed:L,k2sig:he}}function Ze(V,H,me={}){V=Wr("message",V);let{seed:Te,k2sig:ne}=Y(V,H,me);return fI(e.outputLen,o.BYTES,n)(Te,ne)}function vt(V){let H,me=typeof V=="string"||jc(V),Te=!me&&V!==null&&typeof V=="object"&&typeof V.r=="bigint"&&typeof V.s=="bigint";if(!me&&!Te)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(Te)H=new z(V.r,V.s);else if(me){try{H=z.fromBytes(Wr("sig",V),"der")}catch(ne){if(!(ne instanceof Gi.Err))throw ne}if(!H)try{H=z.fromBytes(Wr("sig",V),"compact")}catch{return!1}}return H||!1}function Fe(V,H,me,Te={}){let{lowS:ne,prehash:T,format:R}=_S(Te,v);if(me=Wr("publicKey",me),H=ge(Wr("message",H),T),"strict"in Te)throw new Error("options.strict was renamed to lowS");let F=R===void 0?vt(V):z.fromBytes(Wr("sig",V),R);if(F===!1)return!1;try{let I=r.fromBytes(me);if(ne&&F.hasHighS())return!1;let{r:L,s:ce}=F,he=oe(H),ct=o.inv(ce),xt=o.create(he*ct),Ot=o.create(L*ct),_t=r.BASE.multiplyUnsafe(xt).add(I.multiplyUnsafe(Ot));return _t.is0()?!1:o.create(_t.x)===L}catch{return!1}}function $(V,H,me={}){let{prehash:Te}=_S(me,v);return H=ge(H,Te),z.fromBytes(V,"recovered").recoverPublicKey(H).toBytes()}return Object.freeze({keygen:d,getPublicKey:u,getSharedSecret:f,utils:h,lengths:y,Point:r,sign:Ze,verify:Fe,recoverPublicKey:$,Signature:z,hash:e})}function gF(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=ti(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 yF(r){let{CURVE:e,curveOpts:t}=gF(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 xF(r,e){let t=e.Point;return Object.assign({},e,{ProjectivePoint:t,CURVE:Object.assign({},r,dy(t.Fn.ORDER,t.Fn.BITS))})}function eR(r){let{CURVE:e,curveOpts:t,hash:s,ecdsaOpts:n}=yF(r),i=hF(e,t),o=mF(i,s,n);return xF(r,o)}var YI,CS,Gi,Xi,Ou,JI,gy,lF,tR=A(()=>{"use strict";HI();Fc();ay();XI();uy();YI=(r,e)=>(r+(r>=0?e:-e)/JI)/e;CS=class extends Error{constructor(e=""){super(e)}},Gi={Err:CS,_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=$h(s);if(n.length/2&128)throw new t("tlv.encode: long form length too big");let i=s>127?$h(n.length/2|128):"";return $h(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=$h(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),JI=BigInt(2),gy=BigInt(3),lF=BigInt(4)});function yy(r,e){let t=s=>eR({...r,hash:s});return{...t(e),create:t}}var rR=A(()=>{"use strict";tR();});var sR,nR,iR,bF,vF,wF,oR,Hle,Fle,aR=A(()=>{"use strict";jI();rR();uy();sR={p:BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),h:BigInt(1),a:BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")},nR={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff"),n:BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),h:BigInt(1),a:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc"),b:BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"),Gx:BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"),Gy:BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f")},iR={p:BigInt("0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),n:BigInt("0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409"),h:BigInt(1),a:BigInt("0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc"),b:BigInt("0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00"),Gx:BigInt("0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66"),Gy:BigInt("0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650")},bF=ti(sR.p),vF=ti(nR.p),wF=ti(iR.p),oR=yy({...sR,Fp:bF,lowS:!1},DI),Hle=yy({...nR,Fp:vF,lowS:!1},UI),Fle=yy({...iR,Fp:wF,lowS:!1,allowedPrivateKeyLengths:[130,131,132]},MI)});var xy,cR=A(()=>{"use strict";aR();xy=oR});var uR=se(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 dR=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(!dR(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 Yh=class{static $ceil7mul(e){let t=e;for(;t%7;)t++;return t}static check(e){if(!dR(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=Yh;var Jh=class{};fa.LEB128=Jh;Jh.encode=r=>(r>=0?Kc:Yh).encode(r);Jh.decode=(r,e=0,t=!1)=>(t?Yh:Kc).decode(r,e)});var lR=se((TS,fR)=>{"use strict";(function(r){"use strict";function e(T){return parseInt(T)===T}function t(T){if(!e(T.length))return!1;for(var R=0;R<T.length;R++)if(!e(T[R])||T[R]<0||T[R]>255)return!1;return!0}function s(T,R){if(T.buffer&&T.name==="Uint8Array")return R&&(T.slice?T=T.slice():T=Array.prototype.slice.call(T)),T;if(Array.isArray(T)){if(!t(T))throw new Error("Array contains invalid value: "+T);return new Uint8Array(T)}if(e(T.length)&&t(T))return new Uint8Array(T);throw new Error("unsupported array-like object")}function n(T){return new Uint8Array(T)}function i(T,R,F,I,L){(I!=null||L!=null)&&(T.slice?T=T.slice(I,L):T=Array.prototype.slice.call(T,I,L)),R.set(T,F)}var o=(function(){function T(F){var I=[],L=0;for(F=encodeURI(F);L<F.length;){var ce=F.charCodeAt(L++);ce===37?(I.push(parseInt(F.substr(L,2),16)),L+=2):I.push(ce)}return s(I)}function R(F){for(var I=[],L=0;L<F.length;){var ce=F[L];ce<128?(I.push(String.fromCharCode(ce)),L++):ce>191&&ce<224?(I.push(String.fromCharCode((ce&31)<<6|F[L+1]&63)),L+=2):(I.push(String.fromCharCode((ce&15)<<12|(F[L+1]&63)<<6|F[L+2]&63)),L+=3)}return I.join("")}return{toBytes:T,fromBytes:R}})(),a=(function(){function T(I){for(var L=[],ce=0;ce<I.length;ce+=2)L.push(parseInt(I.substr(ce,2),16));return L}var R="0123456789abcdef";function F(I){for(var L=[],ce=0;ce<I.length;ce++){var he=I[ce];L.push(R[(he&240)>>4]+R[he&15])}return L.join("")}return{toBytes:T,fromBytes:F}})(),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],te=[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],Ee=[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 ge(T){for(var R=[],F=0;F<T.length;F+=4)R.push(T[F]<<24|T[F+1]<<16|T[F+2]<<8|T[F+3]);return R}var Y=function(T){if(!(this instanceof Y))throw Error("AES must be instanitated with `new`");Object.defineProperty(this,"key",{value:s(T,!0)}),this._prepare()};Y.prototype._prepare=function(){var T=c[this.key.length];if(T==null)throw new Error("invalid key size (must be 16, 24 or 32 bytes)");this._Ke=[],this._Kd=[];for(var R=0;R<=T;R++)this._Ke.push([0,0,0,0]),this._Kd.push([0,0,0,0]);for(var F=(T+1)*4,I=this.key.length/4,L=ge(this.key),ce,R=0;R<I;R++)ce=R>>2,this._Ke[ce][R%4]=L[R],this._Kd[T-ce][R%4]=L[R];for(var he=0,ct=I,xt;ct<F;){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,_t;R<I&&ct<F;)Ot=ct>>2,_t=ct%4,this._Ke[Ot][_t]=L[R],this._Kd[T-Ot][_t]=L[R++],ct++}for(var Ot=1;Ot<T;Ot++)for(var _t=0;_t<4;_t++)xt=this._Kd[Ot][_t],this._Kd[Ot][_t]=Q[xt>>24&255]^oe[xt>>16&255]^te[xt>>8&255]^Ee[xt&255]},Y.prototype.encrypt=function(T){if(T.length!=16)throw new Error("invalid plaintext size (must be 16 bytes)");for(var R=this._Ke.length-1,F=[0,0,0,0],I=ge(T),L=0;L<4;L++)I[L]^=this._Ke[0][L];for(var ce=1;ce<R;ce++){for(var L=0;L<4;L++)F[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[ce][L];I=F.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(T){if(T.length!=16)throw new Error("invalid ciphertext size (must be 16 bytes)");for(var R=this._Kd.length-1,F=[0,0,0,0],I=ge(T),L=0;L<4;L++)I[L]^=this._Kd[0][L];for(var ce=1;ce<R;ce++){for(var L=0;L<4;L++)F[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[ce][L];I=F.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(T){if(!(this instanceof Ze))throw Error("AES must be instanitated with `new`");this.description="Electronic Code Block",this.name="ecb",this._aes=new Y(T)};Ze.prototype.encrypt=function(T){if(T=s(T),T.length%16!==0)throw new Error("invalid plaintext size (must be multiple of 16 bytes)");for(var R=n(T.length),F=n(16),I=0;I<T.length;I+=16)i(T,F,0,I,I+16),F=this._aes.encrypt(F),i(F,R,I);return R},Ze.prototype.decrypt=function(T){if(T=s(T),T.length%16!==0)throw new Error("invalid ciphertext size (must be multiple of 16 bytes)");for(var R=n(T.length),F=n(16),I=0;I<T.length;I+=16)i(T,F,0,I,I+16),F=this._aes.decrypt(F),i(F,R,I);return R};var vt=function(T,R){if(!(this instanceof vt))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(T)};vt.prototype.encrypt=function(T){if(T=s(T),T.length%16!==0)throw new Error("invalid plaintext size (must be multiple of 16 bytes)");for(var R=n(T.length),F=n(16),I=0;I<T.length;I+=16){i(T,F,0,I,I+16);for(var L=0;L<16;L++)F[L]^=this._lastCipherblock[L];this._lastCipherblock=this._aes.encrypt(F),i(this._lastCipherblock,R,I)}return R},vt.prototype.decrypt=function(T){if(T=s(T),T.length%16!==0)throw new Error("invalid ciphertext size (must be multiple of 16 bytes)");for(var R=n(T.length),F=n(16),I=0;I<T.length;I+=16){i(T,F,0,I,I+16),F=this._aes.decrypt(F);for(var L=0;L<16;L++)R[I+L]=F[L]^this._lastCipherblock[L];i(T,this._lastCipherblock,0,I,I+16)}return R};var Fe=function(T,R,F){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)");F||(F=1),this.segmentSize=F,this._shiftRegister=s(R,!0),this._aes=new Y(T)};Fe.prototype.encrypt=function(T){if(T.length%this.segmentSize!=0)throw new Error("invalid plaintext size (must be segmentSize bytes)");for(var R=s(T,!0),F,I=0;I<R.length;I+=this.segmentSize){F=this._aes.encrypt(this._shiftRegister);for(var L=0;L<this.segmentSize;L++)R[I+L]^=F[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(T){if(T.length%this.segmentSize!=0)throw new Error("invalid ciphertext size (must be segmentSize bytes)");for(var R=s(T,!0),F,I=0;I<R.length;I+=this.segmentSize){F=this._aes.encrypt(this._shiftRegister);for(var L=0;L<this.segmentSize;L++)R[I+L]^=F[L];i(this._shiftRegister,this._shiftRegister,0,this.segmentSize),i(T,this._shiftRegister,16-this.segmentSize,I,I+this.segmentSize)}return R};var $=function(T,R){if(!(this instanceof $))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(T)};$.prototype.encrypt=function(T){for(var R=s(T,!0),F=0;F<R.length;F++)this._lastPrecipherIndex===16&&(this._lastPrecipher=this._aes.encrypt(this._lastPrecipher),this._lastPrecipherIndex=0),R[F]^=this._lastPrecipher[this._lastPrecipherIndex++];return R},$.prototype.decrypt=$.prototype.encrypt;var V=function(T){if(!(this instanceof V))throw Error("Counter must be instanitated with `new`");T!==0&&!T&&(T=1),typeof T=="number"?(this._counter=n(16),this.setValue(T)):this.setBytes(T)};V.prototype.setValue=function(T){if(typeof T!="number"||parseInt(T)!=T)throw new Error("invalid counter value (must be an integer)");if(T>Number.MAX_SAFE_INTEGER)throw new Error("integer value out of safe range");for(var R=15;R>=0;--R)this._counter[R]=T%256,T=parseInt(T/256)},V.prototype.setBytes=function(T){if(T=s(T,!0),T.length!=16)throw new Error("invalid counter bytes size (must be 16 bytes)");this._counter=T},V.prototype.increment=function(){for(var T=15;T>=0;T--)if(this._counter[T]===255)this._counter[T]=0;else{this._counter[T]++;break}};var H=function(T,R){if(!(this instanceof H))throw Error("AES must be instanitated with `new`");this.description="Counter",this.name="ctr",R instanceof V||(R=new V(R)),this._counter=R,this._remainingCounter=null,this._remainingCounterIndex=16,this._aes=new Y(T)};H.prototype.encrypt=function(T){for(var R=s(T,!0),F=0;F<R.length;F++)this._remainingCounterIndex===16&&(this._remainingCounter=this._aes.encrypt(this._counter._counter),this._remainingCounterIndex=0,this._counter.increment()),R[F]^=this._remainingCounter[this._remainingCounterIndex++];return R},H.prototype.decrypt=H.prototype.encrypt;function me(T){T=s(T,!0);var R=16-T.length%16,F=n(T.length+R);i(T,F);for(var I=T.length;I<F.length;I++)F[I]=R;return F}function Te(T){if(T=s(T,!0),T.length<16)throw new Error("PKCS#7 invalid length");var R=T[T.length-1];if(R>16)throw new Error("PKCS#7 padding byte out of range");for(var F=T.length-R,I=0;I<R;I++)if(T[F+I]!==R)throw new Error("PKCS#7 invalid padding byte");var L=n(F);return i(T,L,0,0,F),L}var ne={AES:Y,Counter:V,ModeOfOperation:{ecb:Ze,cbc:vt,cfb:Fe,ofb:$,ctr:H},utils:{hex:a,utf8:o},padding:{pkcs7:{pad:me,strip:Te}},_arrayTest:{coerceArray:s,createArray:n,copyArray:i}};typeof TS<"u"?fR.exports=ne:typeof define=="function"&&define.amd?define([],function(){return ne}):(r.aesjs&&(ne._aesjs=r.aesjs),r.aesjs=ne)})(TS)});function mR(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?TF:IF,u=e?AF:RF,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=EF,Uu&&(f.toBuffer=CF),Mu&&(f.toArrayBuffer=gR),v[h]=S,v;function v(te,Ee,ge,Y){return this instanceof v?C(this,te,Ee,ge,Y):new v(te,Ee,ge,Y)}function S(te){return!!(te&&te[y])}function C(te,Ee,ge,Y,Ze){if(Mu&&by&&(Ee instanceof by&&(Ee=new Mu(Ee)),Y instanceof by&&(Y=new Mu(Y))),!Ee&&!ge&&!Y&&!ju){te.buffer=yR(hR,0);return}if(!pR(Ee,ge)){var vt=ju||Array;Ze=ge,Y=Ee,ge=0,Ee=ju===Uu?Uu.alloc(8):new vt(8)}te.buffer=Ee,te.offset=ge|=0,vy!==typeof Y&&(typeof Y=="string"?O(Ee,ge,Y,Ze||10):pR(Y,Ze)?AS(Ee,ge,Y,Ze):typeof Ze=="number"?(Q(Ee,ge+s,Y),Q(Ee,ge+n,Ze)):Y>0?d(Ee,ge,Y):Y<0?u(Ee,ge,Y):AS(Ee,ge,hR,0))}function O(te,Ee,ge,Y){var Ze=0,vt=ge.length,Fe=0,$=0;ge[0]==="-"&&Ze++;for(var V=Ze;Ze<vt;){var H=parseInt(ge[Ze++],Y);if(!(H>=0))break;$=$*Y+H,Fe=Fe*Y+Math.floor($/Du),$%=Du}V&&(Fe=~Fe,$?$=Du-$:Fe++),Q(te,Ee+s,Fe),Q(te,Ee+n,$)}function K(){var te=this.buffer,Ee=this.offset,ge=oe(te,Ee+s),Y=oe(te,Ee+n);return t||(ge|=0),ge?ge*Du+Y:Y}function z(te){var Ee=this.buffer,ge=this.offset,Y=oe(Ee,ge+s),Ze=oe(Ee,ge+n),vt="",Fe=!t&&Y&2147483648;for(Fe&&(Y=~Y,Ze=Du-Ze),te=te||10;;){var $=Y%te*Du+Ze;if(Y=Math.floor(Y/te),Ze=Math.floor($/te),vt=($%te).toString(te)+vt,!Y&&!Ze)break}return Fe&&(vt="-"+vt),vt}function Q(te,Ee,ge){te[Ee+c]=ge&255,ge=ge>>8,te[Ee+a]=ge&255,ge=ge>>8,te[Ee+o]=ge&255,ge=ge>>8,te[Ee+i]=ge&255}function oe(te,Ee){return te[Ee+i]*_F+(te[Ee+o]<<16)+(te[Ee+a]<<8)+te[Ee+c]}}function EF(r){var e=this.buffer,t=this.offset;return ju=null,r!==!1&&SF(e)?e.length===8?e:e.slice(t,t+8):yR(e,t)}function CF(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(gR.call(this,r))}function gR(r){var e=this.buffer,t=this.offset,s=e.buffer;if(ju=Mu,r!==!1&&!e.offset&&s instanceof by)return s.byteLength===8?s:s.slice(t,t+8);var n=new Mu(8);return AS(n,0,e,t),n.buffer}function pR(r,e){var t=r&&r.length;return e|=0,t&&e+8<=t&&typeof r[e]!="string"}function AS(r,e,t,s){e|=0,s|=0;for(var n=0;n<8;n++)r[e++]=t[s++]&255}function yR(r,e){return Array.prototype.slice.call(r,e,e+8)}function TF(r,e,t){for(var s=e+8;s>e;)r[--s]=t&255,t/=256}function AF(r,e,t){var s=e+8;for(t++;s>e;)r[--s]=-t&255^255,t/=256}function IF(r,e,t){for(var s=e+8;e<s;)r[e++]=t&255,t/=256}function RF(r,e,t){var s=e+8;for(t++;e<s;)r[e++]=-t&255^255,t/=256}function kF(r){return!!r&&Object.prototype.toString.call(r)=="[object Array]"}var vy,Uu,Mu,by,hR,SF,Du,_F,ju,wy,IS,Sy=A(()=>{"use strict";vy="undefined",Uu=vy!==typeof Buffer&&Buffer,Mu=vy!==typeof Uint8Array&&Uint8Array,by=vy!==typeof ArrayBuffer&&ArrayBuffer,hR=[0,0,0,0,0,0,0,0],SF=Array.isArray||kF,Du=4294967296,_F=16777216,wy=mR("Uint64BE",!0,!0),IS=mR("Int64BE",!0,!1)});var kS=se(xR=>{"use strict";var $e=xR,{Buffer:_y}=require("buffer"),PF=require("os");$e.toBuffer=function(r,e,t){t=~~t;let s;if(this.isV4Format(r))s=e||_y.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||_y.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 BF=/^(\d{1,3}\.){3,3}\d{1,3}$/,NF=/^(::)?(((\d{1,3}\.){3}(\d{1,3}){1})?([0-9a-f]){0,4}:{0,2}){1,8}(::)?$/i;$e.isV4Format=function(r){return BF.test(r)};$e.isV6Format=function(r){return NF.test(r)};function Qh(r){return r===4?"ipv4":r===6?"ipv6":r?r.toLowerCase():"ipv4"}$e.fromPrefixLen=function(r,e){r>32?e="ipv6":e=Qh(e);let t=4;e==="ipv6"&&(t=16);let s=_y.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=_y.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=Qh(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=PF.networkInterfaces();if(e=Qh(e),r&&r!=="private"&&r!=="public"){let n=t[r].filter(i=>Qh(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=Qh(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 vR=se((Gle,bR)=>{"use strict";bR.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 wR=se(PS=>{"use strict";PS.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};PS.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 SR=se(BS=>{"use strict";BS.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};BS.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 _R=se(NS=>{"use strict";NS.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};NS.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 ER=se(OS=>{"use strict";OS.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};OS.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 CR=se(LS=>{"use strict";LS.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}`};LS.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 IR=se((AR,DS)=>{"use strict";var TR=(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 te=h.charCodeAt(oe);te===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):te===46?(v<S&&(y[v]=K),v++,K=0,O=0,z=!1,Q=!0):(z=!1,te>=97?te-=87:te>=65?te-=55:(te-=48,K=K*10+te),O=(O<<4)+te)}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 TR}):typeof DS=="object"&&typeof AR=="object"&&(DS.exports=TR)});var PR=se(Ve=>{"use strict";var Ke=require("buffer").Buffer,io=wR(),OF=SR(),LF=_R(),Cy=ER(),MS=CR(),Wc=IR(),DF=0,RR=32768,US=32768,MF=~US,kR=32768,UF=~kR,we=Ve.name={};we.encode=function(r,e,t,{mail:s=!1}={}){e||(e=Ke.alloc(we.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,we.encode.bytes=t-n,e};we.encode.bytes=0;we.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 we.decode.bytes=o,s.length===0?".":s.join(".")};we.decode.bytes=0;we.encodingLength=function(r){return r==="."||r===".."?1:Ke.byteLength(r.replace(/^\.|\.$/gm,""))+2};var St={};St.encode=function(r,e,t){e||(e=Ke.alloc(St.encodingLength(r))),t||(t=0);let s=e.write(r,t+1);return e[t]=s,St.encode.bytes=s+1,e};St.encode.bytes=0;St.decode=function(r,e){e||(e=0);let t=r[e],s=r.toString("utf-8",e+1,e+1+t);return St.decode.bytes=t+1,s};St.decode.bytes=0;St.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"?RR:DF;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&RR?"response":"query",flags:t&32767,flag_qr:(t>>15&1)===1,opcode:LF.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:OF.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),we.encode(r,e,t+2),e.writeUInt16BE(we.encode.bytes,t),Ji.encode.bytes=we.encode.bytes+2,e};Ji.encode.bytes=0;Ji.decode=function(r,e){e||(e=0);let t=r.readUInt16BE(e),s=we.decode(r,e+2);return Ji.decode.bytes=t+2,s};Ji.decode.bytes=0;Ji.encodingLength=function(r){return we.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,we.encode(r.mname,e,t),t+=we.encode.bytes,we.encode(r.rname,e,t,{mail:!0}),t+=we.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=we.decode(r,e),e+=we.decode.bytes,s.rname=we.decode(r,e,{mail:!0}),e+=we.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+we.encodingLength(r.mname)+we.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,St.encode(r.cpu,e,t),t+=St.encode.bytes,St.encode(r.os,e,t),t+=St.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=St.decode(r,e),e+=St.decode.bytes,s.os=St.decode(r,e),e+=St.decode.bytes,to.decode.bytes=e-t,s};to.decode.bytes=0;to.encodingLength=function(r){return St.encodingLength(r.cpu)+St.encodingLength(r.os)+2};var yn=Ve.ptr={},jF=Ve.cname=yn,HF=Ve.dname=yn;yn.encode=function(r,e,t){return e||(e=Ke.alloc(yn.encodingLength(r))),t||(t=0),we.encode(r,e,t+2),e.writeUInt16BE(we.encode.bytes,t),yn.encode.bytes=we.encode.bytes+2,e};yn.encode.bytes=0;yn.decode=function(r,e){e||(e=0);let t=we.decode(r,e+2);return yn.decode.bytes=we.decode.bytes+2,t};yn.decode.bytes=0;yn.encodingLength=function(r){return we.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),we.encode(r.target,e,t+8);let s=we.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=we.decode(r,e+8),ro.decode.bytes=t+2,s};ro.decode.bytes=0;ro.encodingLength=function(r){return 8+we.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,St.encode(r.tag,e,t),t+=St.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=St.decode(r,e),e+=St.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 St.encodingLength(r.tag)+St.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,we.encode(r.exchange,e,t),t+=we.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=we.decode(r,e),e+=we.decode.bytes,la.decode.bytes=e-t,s};la.encodingLength=function(r){return 4+we.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=MS.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=MS.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(MS.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=Zh(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 si=Ve.rrsig={};si.encode=function(r,e,t){e||(e=Ke.alloc(si.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,we.encode(r.signersName,e,t),t+=we.encode.bytes,n.copy(e,t,0,n.length),t+=n.length,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;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=we.decode(r,e),e+=we.decode.bytes,s.signature=r.slice(e,t+n+2),e+=s.signature.length,si.decode.bytes=e-t,s};si.decode.bytes=0;si.encodingLength=function(r){return 20+we.encodingLength(r.signersName)+Ke.byteLength(r.signature)};var ni=Ve.rp={};ni.encode=function(r,e,t){e||(e=Ke.alloc(ni.encodingLength(r))),t||(t=0);let s=t;return t+=2,we.encode(r.mbox||".",e,t,{mail:!0}),t+=we.encode.bytes,we.encode(r.txt||".",e,t),t+=we.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,s={};return e+=2,s.mbox=we.decode(r,e,{mail:!0})||".",e+=we.decode.bytes,s.txt=we.decode(r,e)||".",e+=we.decode.bytes,ni.decode.bytes=e-t,s};ni.decode.bytes=0;ni.encodingLength=function(r){return 2+we.encodingLength(r.mbox||".")+we.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 ii=Ve.nsec={};ii.encode=function(r,e,t){e||(e=Ke.alloc(ii.encodingLength(r))),t||(t=0);let s=t;return t+=2,we.encode(r.nextDomain,e,t),t+=we.encode.bytes,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);return e+=2,s.nextDomain=we.decode(r,e),e+=we.decode.bytes,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 2+we.encodingLength(r.nextDomain)+Cr.encodingLength(r.rrtypes)};var oi=Ve.nsec3={};oi.encode=function(r,e,t){e||(e=Ke.alloc(oi.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,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);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,oi.decode.bytes=e-t,s};oi.decode.bytes=0;oi.encodingLength=function(r){return 8+r.salt.length+r.nextDomain.length+Cr.encodingLength(r.rrtypes)};var ai=Ve.ds={};ai.encode=function(r,e,t){e||(e=Ke.alloc(ai.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,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;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,ai.decode.bytes=e-t,s};ai.decode.bytes=0;ai.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 ci=Ve.naptr={};ci.encode=function(r,e,t){e||(e=Ke.alloc(ci.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,St.encode(r.flags,e,t),t+=St.encode.bytes,St.encode(r.services,e,t),t+=St.encode.bytes,St.encode(r.regexp,e,t),t+=St.encode.bytes,we.encode(r.replacement,e,t),t+=we.encode.bytes,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={};return e+=2,s.order=r.readUInt16BE(e),e+=2,s.preference=r.readUInt16BE(e),e+=2,s.flags=St.decode(r,e),e+=St.decode.bytes,s.services=St.decode(r,e),e+=St.decode.bytes,s.regexp=St.decode(r,e),e+=St.decode.bytes,s.replacement=we.decode(r,e),e+=we.decode.bytes,ci.decode.bytes=e-t,s};ci.decode.bytes=0;ci.encodingLength=function(r){return St.encodingLength(r.flags)+St.encodingLength(r.services)+St.encodingLength(r.regexp)+we.encodingLength(r.replacement)+6};var di=Ve.tlsa={};di.encode=function(r,e,t){e||(e=Ke.alloc(di.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,di.encode.bytes=t-s,e.writeUInt16BE(di.encode.bytes-2,s),e};di.encode.bytes=0;di.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,di.decode.bytes=e-t,s};di.decode.bytes=0;di.encodingLength=function(r){return 5+Ke.byteLength(r.certificate)};var jS=Ve.record=function(r){switch(r.toUpperCase()){case"A":return so;case"PTR":return yn;case"CNAME":return jF;case"DNAME":return HF;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 si;case"RP":return ni;case"NSEC":return ii;case"NSEC3":return oi;case"SSHFP":return ks;case"DS":return ai;case"NAPTR":return ci;case"TLSA":return di}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(we.encode(r.name,e,t),t+=we.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=Cy.toClass(r.class===void 0?"IN":r.class);r.flush&&(n|=US),e.writeUInt16BE(n,t+2),e.writeUInt32BE(r.ttl||0,t+4),t+=8;let i=jS(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=we.decode(r,e),e+=we.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=Cy.toString(n&MF),t.flush=!!(n&US);let i=jS(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 we.encodingLength(r.name)+8+jS(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 we.encode(r.name,e,t),t+=we.encode.bytes,e.writeUInt16BE(io.toType(r.type),t),t+=2,e.writeUInt16BE(Cy.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=we.decode(r,e),e+=we.decode.bytes,s.type=io.toString(r.readUInt16BE(e)),e+=2,s.class=Cy.toString(r.readUInt16BE(e)),e+=2,s.class&kR&&(s.class&=UF),xn.decode.bytes=e-t,s};xn.decode.bytes=0;xn.encodingLength=function(r){return we.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=Zh(r.questions,xn,e,t),t=Zh(r.answers,Dr,e,t),t=Zh(r.authorities,Dr,e,t),t=Zh(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=Ey(s.questions,xn,r,e),e=Ey(s.answers,Dr,r,e),e=Ey(s.authorities,Dr,r,e),e=Ey(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 Zh(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 Ey(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 OR=se((the,NR)=>{"use strict";var BR=KF;process.nextTick(VF,42);NR.exports=FF;function FF(r){var e=s;return t;function t(n){e(n||zF)}function s(n){var i=[n];e=o,r(a);function o(c){i.push(c)}function a(c){var d=arguments;for(e=qF(c)?s:u;i.length;)u(i.shift());function u(f){BR($F,f,d)}}}}function qF(r){return Object.prototype.toString.call(r)==="[object Error]"}function zF(){}function $F(r,e){r.apply(null,e)}function VF(r){r===42&&(BR=process.nextTick)}function KF(r,e,t){process.nextTick(function(){r(e,t)})}});var MR=se((rhe,DR)=>{"use strict";var HS=PR(),WF=require("dgram"),GF=OR(),XF=require("events"),qS=require("os"),FS=function(){};DR.exports=function(r){r||(r={});var e=new XF.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||WF.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=HS.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=GF(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=FS),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=HS.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)|HS.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=FS),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=FS),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):JF(),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||YF())}catch(S){e.emit("warning",S)}e.emit("networkInterface")}},e};function YF(){for(var r=qS.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(LR(i.family)&&!i.internal)return qS.platform()==="darwin"&&e[t]==="en0"?i.address:"0.0.0.0"}return"127.0.0.1"}function JF(){for(var r=qS.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(LR(o.family)){t.push(o.address);break}}return t}function LR(r){return r===4||r==="IPv4"}});var D7={};Cf(D7,{AV1Obu:()=>D9,AV1RtpPayload:()=>f_,AttributeKeys:()=>bz,BitStream:()=>ba,BitWriter:()=>Cp,BitWriter2:()=>dx,BufferChain:()=>tq,CONSENT_FAILURES:()=>M_,CONSENT_INTERVAL:()=>uB,COOKIE:()=>vx,Candidate:()=>Sa,CandidatePair:()=>L_,CandidatePairState:()=>fB,CipherContext:()=>Rp,CipherSuite:()=>Yy,CipherSuiteList:()=>n9,Connection:()=>bB,ConnectionStates:()=>Z$,CurveType:()=>x2,DEFAULT_MAX_MESSAGE_SIZE:()=>Xu,DePacketizerBase:()=>Kq,Directions:()=>jy,DtlsClient:()=>A_,DtlsServer:()=>UP,DtlsSocket:()=>I2,DtlsStates:()=>p$,Event:()=>Ie,EventDisposer:()=>Jk,ExtensionProfiles:()=>ya,FINGERPRINT_LENGTH:()=>jP,FINGERPRINT_XOR:()=>HP,GenericNack:()=>Lp,GroupDescription:()=>Zu,H264RtpPayload:()=>H9,HEADER_LENGTH:()=>co,HashAlgorithm:()=>Ip,ICE_COMPLETED:()=>D_,ICE_FAILED:()=>bp,INTEGRITY_LENGTH:()=>R2,IPV4_PROTOCOL:()=>k2,IPV6_PROTOCOL:()=>P2,IceCandidate:()=>sE,IceGathererStates:()=>v$,IceTransportStates:()=>b$,Inactive:()=>DB,Int:()=>Bp,MediaDescription:()=>ax,MediaStream:()=>MB,MediaStreamTrack:()=>Hp,MediaStreamTrackFactory:()=>c$,Message:()=>Qs,NalUnitType:()=>ga,NamedCurveAlgorithm:()=>ho,NamedCurveAlgorithmList:()=>y2,OpusRtpPayload:()=>q9,PacketChunk:()=>eP,PacketResult:()=>rP,PacketStatus:()=>tP,PictureLossIndication:()=>Np,Profiles:()=>Hq,PromiseQueue:()=>dq,ProtectionProfileAeadAes128Gcm:()=>ad,ProtectionProfileAes128CmHmacSha1_80:()=>df,RETRY_MAX:()=>FP,RETRY_RTO:()=>qP,RTCCertificate:()=>rE,RTCDataChannel:()=>H2,RTCDataChannelParameters:()=>F2,RTCDtlsFingerprint:()=>nx,RTCDtlsParameters:()=>ix,RTCDtlsTransport:()=>z_,RTCIceCandidate:()=>e7,RTCIceGatherer:()=>QB,RTCIceParameters:()=>nE,RTCIceTransport:()=>JB,RTCP_HEADER_SIZE:()=>Zy,RTCPeerConnection:()=>X$,RTCRtcpFeedback:()=>_B,RTCRtcpParameters:()=>Hz,RTCRtpCodecParameters:()=>_a,RTCRtpCodingParameters:()=>CB,RTCRtpHeaderExtensionParameters:()=>gi,RTCRtpReceiver:()=>dE,RTCRtpRtxParameters:()=>EB,RTCRtpSender:()=>P7,RTCRtpSimulcastParameters:()=>q2,RTCRtpTransceiver:()=>LB,RTCSctpCapabilities:()=>oE,RTCSctpTransport:()=>T7,RTCSessionDescription:()=>R7,RTCStatsReport:()=>OB,RTP_EXTENSION_URI:()=>Yt,ReceiverEstimatedMaxBitrate:()=>Op,RecvDelta:()=>Sp,Recvonly:()=>G2,Red:()=>C2,RedEncoder:()=>SP,RedHandler:()=>_P,RedHeader:()=>__,RtcpHeader:()=>go,RtcpPacketConverter:()=>aP,RtcpPayloadSpecificFeedback:()=>tf,RtcpReceiverInfo:()=>bx,RtcpRrPacket:()=>rf,RtcpSenderInfo:()=>E2,RtcpSourceDescriptionPacket:()=>Mp,RtcpSrPacket:()=>sd,RtcpTransportLayerFeedback:()=>rd,RtpBuilder:()=>uz,RtpHeader:()=>po,RtpPacket:()=>mo,RtpRouter:()=>k7,RunLengthChunk:()=>Qu,SDPManager:()=>N7,Sendonly:()=>W2,Sendrecv:()=>X2,SessionDescription:()=>Ep,SignalingStates:()=>Q$,SignatureAlgorithm:()=>mi,SignatureScheme:()=>s_,SourceDescriptionChunk:()=>S2,SourceDescriptionItem:()=>_2,SrtcpSession:()=>NP,SrtpAuthenticationError:()=>nd,SrtpContext:()=>kp,SrtpSession:()=>OP,SsrcDescription:()=>cx,StatusVectorChunk:()=>Q9,StunOverTurnProtocol:()=>ZP,StunProtocol:()=>ex,TcpTransport:()=>r9,TransceiverManager:()=>L7,TransportWideCC:()=>Dp,TurnProtocol:()=>tB,UdpTransport:()=>Xy,Vp8RtpPayload:()=>$9,Vp9RtpPayload:()=>K9,WeriftError:()=>fq,addSDPHeader:()=>i2,andDirection:()=>Z2,buffer2ArrayBuffer:()=>sq,bufferArrayXor:()=>ZF,bufferReader:()=>is,bufferWriter:()=>er,bufferWriterLE:()=>Hk,bufferXor:()=>QF,candidateFoundation:()=>tx,candidateFromIce:()=>of,candidateFromSdp:()=>cE,candidatePairPriority:()=>rx,candidatePriority:()=>_p,candidateToIce:()=>ZB,candidateToSdp:()=>aE,certificateTypes:()=>i9,classes:()=>B2,codecParametersFromString:()=>$p,codecParametersToString:()=>F$,compactNtp:()=>tE,crc32:()=>Kk,crc32c:()=>p2,createBufferWriter:()=>wp,createSelfSignedCertificate:()=>a$,createStunOverTurnClient:()=>P_,createTurnClient:()=>sB,dePacketizeRtpPackets:()=>Wq,debug:()=>ut,deepMerge:()=>zB,defaultOptions:()=>lB,defaultPeerConfig:()=>Y$,depacketizerCodecs:()=>Gq,deserializeAbsSendTime:()=>yP,deserializeAudioLevelIndication:()=>xP,deserializeString:()=>mP,deserializeUint16BE:()=>gP,deserializeVideoOrientation:()=>bP,dumpBuffer:()=>rq,enumerate:()=>Xq,findCodecByMimeType:()=>u2,findPort:()=>Xk,fingerprint:()=>J2,generateStatsId:()=>qt,getBit:()=>xe,getDataChannelMessageSize:()=>wB,getGlobalIp:()=>Lz,getHostAddresses:()=>xB,getStatsTimestamp:()=>Ea,growBufferSize:()=>l_,int:()=>Yu,interfaceAddress:()=>fx,isDtls:()=>UB,isLinkLocalAddress:()=>yB,isMedia:()=>G9,isRtcp:()=>cP,keyLength:()=>B9,leb128decode:()=>U9,makeIntegrityKey:()=>nB,methods:()=>N2,microTime:()=>HB,milliTime:()=>eE,nodeIpAddress:()=>H_,normalizeFamilyNodeV18:()=>Ap,normalizeFingerprintAlgorithm:()=>Q2,normalizeFingerprintValue:()=>sx,ntpTime:()=>FB,ntpTime2Sec:()=>oP,paddingBits:()=>eq,paddingByte:()=>Tp,paddingLength:()=>R_,parseGroup:()=>Wy,parseIceServers:()=>qB,parseMessage:()=>wx,random16:()=>h2,random32:()=>Gy,randomPort:()=>g2,randomPorts:()=>uq,reverseDirection:()=>jB,reverseSimulcastDirection:()=>i$,rtpHeaderExtensionsParser:()=>dP,saltLength:()=>N9,serializeAbsSendTime:()=>pP,serializeAudioLevelIndication:()=>tz,serializeRepairedRtpStreamId:()=>lP,serializeSdesMid:()=>uP,serializeSdesRTPStreamID:()=>fP,serializeTransportWideCC:()=>hP,serverReflexiveCandidate:()=>pB,signatures:()=>b2,sortCandidatePairs:()=>hB,supportedAudioCodecs:()=>qz,supportedCodecs:()=>K2,supportedVideoCodecs:()=>Fz,timer:()=>Yq,timestampSeconds:()=>Fp,uint16Add:()=>Ur,uint16Gt:()=>ux,uint16Gte:()=>cq,uint24:()=>Gk,uint32Add:()=>Yc,uint32Gt:()=>li,uint32Gte:()=>Gu,uint8Add:()=>Wk,unwrapRtx:()=>CP,url2Address:()=>Dz,useAV1X:()=>IB,useAbsSendTime:()=>Wz,useAudioLevelIndication:()=>Xz,useDependencyDescriptor:()=>Gz,useFIR:()=>jz,useH264:()=>TB,useNACK:()=>Qp,useOPUS:()=>$2,usePCMU:()=>V2,usePLI:()=>ff,useREMB:()=>Zp,useRepairedRtpStreamId:()=>Vz,useSdesMid:()=>zz,useSdesRTPStreamId:()=>$z,useTWCC:()=>SB,useTransportWideCC:()=>Kz,useVP8:()=>z2,useVP9:()=>AB,useVideoOrientation:()=>Yz,validateAddress:()=>j_,validateRemoteCandidate:()=>U_,wrapRtx:()=>TP});function h2(){return l2.jspack.Unpack("!H",(0,f2.randomBytes)(2))[0]}function Gy(){return l2.jspack.Unpack("!L",(0,f2.randomBytes)(4))[0]}function QF(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 ZF(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 xe(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 Tp(r){let e=r.toString(2).split("");return[...[...Array(8-e.length)].map(()=>"0"),...e].join("")}function eq(r,e){let t=r.toString(2);return[...[...Array(e-t.length)].map(()=>"0"),...t].join("")}function er(r,e){return wp(r)(e)}function wp(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 Hk(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 sq(r){return r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength)}function Fk(r){return typeof r!="string"}function qk(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 zk(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 $k(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 Vk(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 Kk(r,e=0){return Fk(r)?Vk(r,e,t_,oq):$k(r,e,t_)}function p2(r,e=0){return Fk(r)?Vk(r,e,r_,aq):$k(r,e,r_)}function Wk(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 Gk(r){return r&16777215}function ux(r,e){return r<e&&e-r>32768||r>e&&r-e<32768}function cq(r,e){return r===e||ux(r,e)}function li(r,e){return r<e&&e-r>2147483648||r>e&&r-e<2147483648}function Gu(r,e){return r===e||li(r,e)}async function g2(r="udp4",e){let t=(0,m2.createSocket)(r);setImmediate(()=>t.bind({port:0,address:fx(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 uq(r,e="udp4",t){return Promise.all([...Array(r)].map(()=>g2(e,t)))}async function Xk(r,e,t="udp4",s){let n;for(let i=r;i<=e;i++){let o=(0,m2.createSocket)(t);if(setImmediate(()=>o.bind({port:i,address:fx(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 Ap(r){return r==="IPv4"?4:r==="IPv6"?6:r}function c9(r,e,t){switch(t){case ho.secp256r1_23:return hq({publicKey:r,privateKey:e});case ho.x25519_29:return Buffer.from(a9.default.scalarMult(e,r));default:throw new Error}}function jR(r,e,t){let s=(0,hx.createHmac)(r,e);return s.update(t),s.digest()}function Vp(r,e,t,s="sha256"){let n=t,i=[],o=e;do{o=jR(s,r,o);let a=jR(s,r,Buffer.concat([o,e]));i.push(a),t-=a.length}while(t>0);return Buffer.concat(i,n)}function d9(r,e,t){let s=Buffer.concat([Buffer.from("master secret"),e,t]);return Vp(r,s,48)}function u9(r,e){let t=f9("sha256",e);return Vp(r,Buffer.concat([Buffer.from("extended master secret"),t]),48)}function pq(r,e,t,s,n,i){let o=i?s:n,a=i?n:s,c=Buffer.concat([Buffer.from(r),o,a]);return Vp(t,c,e)}function f9(r,e){return(0,hx.createHash)(r).update(e).digest()}function l9(r,e,t,s=12){let n=f9("sha256",e);return Vp(r,Buffer.concat([Buffer.from(t),n]),s)}function mq(r,e){return l9(r,e,"client finished")}function gq(r,e){return l9(r,e,"server finished")}function yq(r,e,t,s,n,i,o="sha256"){let a=s*2+n*2,c=r,d=Buffer.concat([t,e]),u=Vp(c,Buffer.concat([Buffer.from("key expansion"),d]),a,o),f=(0,o9.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 Bq(){let r=new Yp;return r.id=Xp.RSA,r.name="RSA",r.keyType=Gp.RSA,r}function Nq(){let r=new Yp;return r.id=Xp.ECDHE_RSA,r.name="ECDHE_RSA",r.signType=px.ECDHE,r.keyType=Gp.RSA,r}function Oq(){let r=new Yp;return r.id=Xp.ECDHE_ECDSA,r.name="ECDHE_ECDSA",r.signType=px.ECDHE,r.keyType=Gp.ECDSA,r}function Lq(){let r=new Yp;return r.id=Xp.PSK,r.name="PSK",r.signType=px.NULL,r.keyType=Gp.PSK,r}function Dq(){let r=new Yp;return r.id=Xp.ECDHE_PSK,r.name="ECDHE_PSK",r.signType=px.ECDHE,r.keyType=Gp.PSK,r}function w9(r){switch(r){case mr.TLS_RSA_WITH_AES_128_GCM_SHA256:return ui(mr.TLS_RSA_WITH_AES_128_GCM_SHA256,"TLS_RSA_WITH_AES_128_GCM_SHA256","aes-128-gcm",HR,ep);case mr.TLS_RSA_WITH_AES_256_GCM_SHA384:return ui(mr.TLS_RSA_WITH_AES_256_GCM_SHA384,"TLS_RSA_WITH_AES_256_GCM_SHA384","aes-256-gcm",HR,tp,"sha384");case mr.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:return ui(mr.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,"TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256","aes-128-gcm",FR,ep);case mr.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:return ui(mr.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,"TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384","aes-256-gcm",FR,tp,"sha384");case mr.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:return ui(mr.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,"TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256","aes-128-gcm",qR,ep);case mr.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:return ui(mr.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,"TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384","aes-256-gcm",qR,tp,"sha384");case mr.TLS_PSK_WITH_AES_128_GCM_SHA256:return ui(mr.TLS_PSK_WITH_AES_128_GCM_SHA256,"TLS_PSK_WITH_AES_128_GCM_SHA256","aes-128-gcm",zR,ep,"sha256");case mr.TLS_PSK_WITH_AES_256_GCM_SHA384:return ui(mr.TLS_PSK_WITH_AES_256_GCM_SHA384,"TLS_PSK_WITH_AES_256_GCM_SHA384","aes-256-gcm",zR,tp,"sha384");case mr.TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256:return ui(mr.TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256,"TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256","aes-128-gcm",$R,ep,"sha256");case mr.TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384:return ui(mr.TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384,"TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384","aes-256-gcm",$R,tp,"sha384");default:break}return null}function ui(r,e,t,s,n,i="sha256"){let o=new Uq;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 _9(r){switch(r){case ho.secp256r1_23:{let{privateKey:e,publicKey:t}=lq();return{curve:r,privateKey:e,publicKey:t}}case ho.x25519_29:{let e=S9.default.box.keyPair();return{curve:r,privateKey:Buffer.from(e.secretKey.buffer),publicKey:Buffer.from(e.publicKey.buffer)}}default:throw new Error}}function jq(r,e){return Buffer.from((0,k9.encode)(r,e).slice())}function U9(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 Wq(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=>f_.deSerialize(a.payload)),i=!!n.find(a=>a.isKeyframe),o=f_.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(H9);case"VP8":return s($9);case"VP9":return s(K9);case"OPUS":return s(q9);default:throw new Error}}function Xq(r){return r.map((e,t)=>[t,e])}function l_(r,e){let t=Buffer.alloc(e);return r.copy(t),t}function Bp(r){return Number.parseInt(r.toString(),10)}function G9(r){let e=r[0];return e>127&&e<192}function KR(r){return r%4==0?0:4-r%4}function cP(r){return r.length>=2&&r[1]>=192&&r[1]<=208}function dP(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:mP(t.payload)};case Yt.transportWideCC:return{uri:s,value:gP(t.payload)};case Yt.absSendTime:return{uri:s,value:yP(t.payload)};case Yt.audioLevelIndication:return{uri:s,value:xP(t.payload)};case Yt.videoOrientation:return{uri:s,value:bP(t.payload)};default:return{uri:s,value:t.payload}}}).reduce((t,s)=>(s&&(t[s.uri]=s.value),t),{})}function uP(r){return Buffer.from(r)}function fP(r){return Buffer.from(r)}function lP(r){return Buffer.from(r)}function hP(r){return er([2],[r])}function pP(r){let e=Buffer.alloc(3),t=r>>14n&0x00ffffffn;return e.writeUIntBE(Number(t),0,3),e}function tz(r){let e=new ba(Buffer.alloc(1));return e.writeBits(1,1),e.writeBits(7,r),e.uint8Array}function mP(r){return r.toString()}function gP(r){return r.readUInt16BE()}function yP(r){return is(r,[3])[0]}function xP(r){let e=new ba(r);return{v:e.readBits(1)===1,level:e.readBits(7)}}function bP(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 CP(r,e,t){return new mo(new po({payloadType:e,marker:r.header.marker,sequenceNumber:T2.jspack.Unpack("!H",r.payload.subarray(0,2))[0],timestamp:r.header.timestamp,ssrc:t}),r.payload.subarray(2))}function TP(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(T2.jspack.Pack("!H",[r.header.sequenceNumber])),r.payload]))}function A2(r,e,t="Failed to authenticate SRTP packet"){let s=r.length-e;Up(r.length>=QR+e,t);let n=RP(()=>po.deSerialize(r.subarray(0,s)),t);return n.paddingSize=0,Up(n.payloadOffset>=QR&&n.payloadOffset<=s,t),n}function IP(r,e,t,s="Failed to authenticate SRTCP packet"){return Up(r.length>=nz+e+t,s),RP(()=>go.deSerialize(r.subarray(0,Zy)),s)}function Up(r,e){if(!r)throw new nd(e)}function RP(r,e){try{return r()}catch{throw new nd(e)}}function kP(r,e,t="Failed to authenticate SRTP packet"){if(!r.padding)return r.paddingSize=0,r;Up(e.length>r.payloadOffset,t);let s=e[e.length-1];return Up(s>0&&s<=e.length-r.payloadOffset,t),r.paddingSize=s,r}function ek(r,e,t){if(r.length!==e.length||!(0,An.timingSafeEqual)(r,e))throw new nd(t)}function rk(r,e){try{r.final()}catch{throw new nd(`Failed to authenticate ${e} packet`)}}function sp(r){return(0,L2.randomBytes)(r).toString("hex").substring(0,r)}function zP(){return(0,L2.randomBytes)(12)}function Vu(r){let[e]=r,t=jp.default.isV4Format(e)?k2:P2,s=Buffer.alloc(4);return s.writeUInt8(0,0),s.writeUInt8(t,1),s.writeUInt16BE(r[1],2),Buffer.concat([s,jp.default.toBuffer(e)])}function vz(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 k2:if(s.length!=4)throw new Error("STUN address has invalid length for IPv4");return[jp.default.toString(s),t];case P2:if(s.length!=16)throw new Error("STUN address has invalid length for IPv6");return[jp.default.toString(s),t];default:throw new Error("STUN address has unknown protocol")}}function $P(r,e){let t=[...D2,...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 Oy(r,e){return Ku($P(r,e))}function wz(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 Ly(r,e){return $P(Vu(r),e)}function wx(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 KP;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(hk).includes(c.toString())){let[,y,,v]=hk[c];if(v.name===Oy.name?i.setAttribute(y,v(u,n)):i.setAttribute(y,v(u)),y==="FINGERPRINT"){let S=WP(r.slice(0,a));if(i.getAttributeValue("FINGERPRINT")!==S)return}else if(y==="MESSAGE-INTEGRITY"&&e){let S=Az(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 WP(r){let e=M2(r,r.length-co+jP);return(Kk(e)^HP)>>>0}function Az(r,e){let t=M2(r,r.length-co+R2);return Buffer.from((0,O2.createHmac)("sha1",e).update(t).digest("hex"),"hex")}function R_(r){let e=r%4;return e===0?0:4-e}async function sB({address:r,username:e,password:t},{lifetime:s,portRange:n,interfaceAddresses:i,transport:o}={}){s??=kz,o??="udp";let a=o==="udp"?await Xy.init("udp4",{portRange:n,interfaceAddresses:i}):await r9.init(r),c=new tB(r,e,t,s,a);return await c.connectionMade(),c}async function P_({address:r,username:e,password:t},{lifetime:s,portRange:n,interfaceAddresses:i,transport:o}={}){let a=await sB({address:r,username:e,password:t},{lifetime:s,portRange:n,interfaceAddresses:i,transport:o});return new ZP(a)}function nB(r,e,t){return(0,JP.createHash)("md5").update(Buffer.from([r,e,t].join(":"))).digest()}function mk(r){return(r[0]&192)==64}function tx(r,e,t){let s=`${r}|${e}|${t}`;return(0,iB.createHash)("md5").update(s,"ascii").digest("hex").slice(7)}function _p(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 U_(r){if(!["host","relay","srflx"].includes(r.type))throw new Error(`Unexpected candidate type "${r.type}"`);return r}function hB(r,e){return r.sort((t,s)=>rx(t.localCandidate,t.remoteCandidate,e)-rx(s.localCandidate,s.remoteCandidate,e)).reverse()}function rx(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 pB(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(tx("srflx","udp",n.host),n.component,n.transport,_p("srflx"),s.getAttributeValue("XOR-MAPPED-ADDRESS")[0],s.getAttributeValue("XOR-MAPPED-ADDRESS")[1],"srflx",n.host,n.port)}catch(s){Nz("error serverReflexiveCandidate",s)}}function j_(r){return r&&Number.isNaN(r[1])?[r[0],443]:r}async function Lz(r,e){let t=new ex;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 yB(r){return Ap(r.family)===4&&r.address?.startsWith("169.254.")||Ap(r.family)===6&&r.address?.startsWith("fe80::")}function H_(r,{useLinkLocalAddress:e}={}){let t=["ipsec","tun","utun","tap"],s=["vmnet","veth"],n=mB.networkInterfaces();Oz(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=>Ap(c.family)===r&&!gB.default.isLoopback(c.address)&&(e?!0:!yB(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 xB(r,e,t={}){let s=[];return r&&s.push(...H_(4,t)),e&&s.push(...H_(6,t)),s}function yk(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 wB(r){return Buffer.isBuffer(r)?r.length:Buffer.byteLength(r)}function zz(){return new gi({uri:Yt.sdesMid})}function $z(){return new gi({uri:Yt.sdesRTPStreamID})}function Vz(){return new gi({uri:Yt.repairedRtpStreamId})}function Kz(){return new gi({uri:Yt.transportWideCC})}function Wz(){return new gi({uri:Yt.absSendTime})}function Gz(){return new gi({uri:Yt.dependencyDescriptor})}function Xz(){return new gi({uri:Yt.audioLevelIndication})}function Yz(){return new gi({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 J2(r,e){let t=i=>i.toUpperCase(),s=i=>i.match(/(.{2})/g).join(":"),n=(0,kB.createHash)(e).update(r).digest("hex");return s(t(n))}function Q2(r){return n$[r.trim().toLowerCase()]}function sx(r){return r.replace(/[^0-9a-f]/gi,"").toLowerCase()}function UB(r){let e=r[0];return e>19&&e<64}function i$(r){return r==="recv"?"send":"recv"}function jB(r){return r==="sendonly"?"recvonly":r==="recvonly"?"sendonly":r}function qB(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 s$("iceOptions",o),o}function of(r){let e=new sE(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 ZB(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 t0(r){let e=r%4;return e?4-e:0}function S7(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(t0(i))].map(()=>Buffer.from("\0")))}),e}function _7(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+t0(n)}return e}function E$(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=p2(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=_$[c.toString()];if(h)o.push(new h(d,f));else throw new Error("unknown");a+=u+t0(u)}return[e,t,s,o]}function C$(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=p2(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 T$(r){return r.map((e,t)=>[t,e])}function A$(r){return r.reduce((e,t)=>(e[t]=new Ie,e),{})}function Gc(r){return(r-1)%ox}function Wu(r){return(r+1)%ox}function QS(r){let e=r.match(/^IN (IP4|IP6) ([^ ]+)$/);if(!e)throw new Error("exception");return e[2]}function n2(r){return`IN IP${(0,KB.isIPv4)(r)?4:6} ${r}`}function aE(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 H$(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 ZS(r){if(r.includes(":")){let e=ao(r.slice(2),":");return[e[0],e[1]]}else return[r.slice(2),void 0]}function Wy(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 cE(r){let e=Sa.fromSdp(r);return of(e)}function i2(r,e){let s=new wy((0,VB.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 $p(r){let e={};return r.split(";").forEach(t=>{if(t.includes("=")){let[s,n]=ao(t,"=");t$.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 F$(r,e="="){let t=Object.entries(r).map(([s,n])=>n?`${s}${e}${n}`:s);if(t.length>0)return t.join(";")}function O7(){return{codecs:{audio:[$2(),V2()],video:[z2()]},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 f2,l2,m2,Yk,Qk,Zk,e9,af,lx,Ju,hx,o9,a9,Mr,En,p9,g9,Jc,x9,uo,mx,S9,Zc,va,ed,cf,wa,td,Cn,Tn,xx,_n,k9,O9,T2,Py,By,An,sf,id,Xc,DP,pi,hi,od,MP,O2,L2,jp,JP,k_,QP,iB,B_,aB,N_,O_,Dy,cB,dB,mB,gB,vB,RB,My,kB,PB,F_,BB,Y2,$B,VB,KB,qp,WB,GB,YB,t7,Hy,zp,Fy,fo,o2,a2,c2,d2,B7,Cp,dx,tq,rq,ba,nq,iq,t_,oq,r_,aq,Yu,dq,fx,fq,ut,Ie,Jk,UR,Xy,r9,mi,Ip,Yy,n9,ho,y2,x2,s_,i9,b2,lq,hq,lo,xq,n_,Rp,kp,v2,h9,Zs,Jy,bq,m9,vq,Pp,wq,Sq,i_,_q,Eq,Cq,Tq,w2,Qc,y9,Aq,b9,v9,Kp,a_,Iq,zS,Wp,Rq,kq,Pq,px,Gp,Xp,Yp,Mq,Uq,mr,ep,tp,HR,FR,qR,zR,$R,gx,yx,ef,Qy,E9,C9,T9,d_,A9,I9,R9,P9,df,ad,Hq,B9,N9,Fq,f_,D9,j9,qq,H9,ga,zq,$q,Vq,q9,$9,K9,Kq,Gq,Yq,Zy,go,VR,Np,Op,Jq,tf,rf,bx,Y9,Lp,Qq,Dp,Qu,Q9,Sp,eP,tP,rP,Zq,rd,Mp,S2,_2,sd,E2,oP,ez,aP,Yt,rz,C2,__,SP,sz,_P,ya,WR,GR,XR,YR,JR,po,mo,AP,nd,QR,nz,iz,ZR,oz,$S,tk,PP,rp,sk,az,cz,BP,NP,dz,OP,uz,ns,fz,uf,LP,lz,nk,hz,C_,T_,ik,ok,VS,pz,mz,ak,ck,I2,KS,A_,fi,gz,dk,yz,nf,xz,Jp,Fu,UP,vx,jP,HP,co,R2,k2,P2,FP,qP,bz,B2,N2,uk,I_,D2,np,ip,Sz,_z,fk,lk,WS,GS,XS,YS,Ez,Cz,VP,KP,hk,Tz,Qs,M2,GP,XP,Iz,JS,U2,pk,ex,vs,Rz,kz,Pz,ZP,tB,Sa,Bz,Nz,L_,D_,bp,uB,M_,fB,lB,Oz,Dz,Ut,bB,Mz,gk,j2,Uz,H2,F2,jz,Qp,ff,Zp,SB,_a,gi,Hz,_B,EB,CB,q2,TB,z2,AB,IB,$2,V2,K2,Fz,qz,xk,bk,Jz,Ty,vk,wk,Qz,Zz,e$,Sk,q_,_k,t$,NB,Ek,Uy,r$,OB,LB,DB,W2,G2,X2,jy,Hp,MB,s$,n$,Z2,eE,o$,HB,Fp,FB,tE,a$,c$,zB,d$,Ck,u$,f$,l$,h$,vn,z_,p$,rE,nx,ix,m$,g$,y$,x$,Tk,Ak,JB,b$,v$,QB,e7,sE,nE,yi,iE,qy,$_,w$,zy,$y,V_,K_,e0,W_,Vy,X_,l7,Y_,J_,g7,x7,v7,S$,_$,Q_,E7,Ay,Ky,Ik,Lt,I$,R$,Rk,wn,vp,C7,r2,kk,k$,Pk,Bk,Nk,P$,B$,ox,N$,O$,Ok,Lk,Dk,Mk,L$,D$,M$,U$,qu,Xu,T7,oE,j$,Ep,ax,Zu,R7,cx,Iy,dE,op,k7,q$,zu,z$,$$,e_,Uk,jk,P7,V$,K$,N7,ap,W$,G$,Sn,X$,u2,Y$,J$,L7,Q$,Z$,M7=A(()=>{"use strict";f2=require("crypto"),l2=Ge(wo(),1),m2=require("dgram"),Yk=Ge(h6(),1),Qk=require("dgram"),Zk=Ge(require("net"),1),e9=require("net"),af=require("crypto"),lx=Ge(Yb(),1);CA();Ju=Ge(Zt(),1),hx=require("crypto"),o9=Ge(Zt(),1),a9=Ge(Q0(),1);cR();Mr=Ge(Zt(),1),En=Ge(Zt(),1),p9=Ge(Zt(),1),g9=require("crypto"),Jc=Ge(Zt(),1),x9=require("timers/promises"),uo=Ge(Zt(),1),mx=require("crypto"),S9=Ge(Q0(),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),xx=Ge(Zt(),1),_n=Ge(Zt(),1),k9=Ge(Zt(),1),O9=Ge(uR(),1),T2=Ge(wo(),1),Py=require("crypto"),By=Ge(lR(),1),An=require("crypto"),sf=require("crypto"),id=Ge(Zt(),1),Xc=Ge(Zt(),1),DP=require("timers/promises"),pi=Ge(Zt(),1),hi=Ge(Zt(),1),od=Ge(Zt(),1),MP=require("crypto"),O2=require("crypto"),L2=require("crypto");Sy();jp=Ge(kS(),1),JP=require("crypto"),k_=Ge(wo(),1),QP=require("timers/promises"),iB=require("crypto"),B_=require("net"),aB=require("crypto"),N_=require("net");Sy();O_=Ge(require("timers/promises"),1),Dy=Ge(vR(),1),cB=Ge(MR(),1),dB=require("crypto"),mB=Ge(require("os"),1),gB=Ge(kS(),1),vB=require("events"),RB=require("crypto"),My=require("timers/promises"),kB=require("crypto"),PB=require("dgram"),F_=require("perf_hooks"),BB=require("crypto"),Y2=require("crypto"),$B=require("timers/promises"),VB=require("crypto"),KB=require("net");Sy();qp=Ge(Yb(),1),WB=require("crypto"),GB=require("timers/promises"),YB=require("crypto"),t7=require("crypto"),Hy=Ge(wo(),1),zp=require("crypto"),Fy=Ge(wo(),1),fo=Ge(wo(),1),o2=require("crypto"),a2=Ge(wo(),1),c2=require("crypto"),d2=require("timers/promises"),B7=require("crypto");Cp=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}},dx=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}};tq=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}},rq=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++)}},nq=3988292384,iq=2197175160;t_=qk(nq),oq=zk(t_),r_=qk(iq),aq=zk(r_);Yu=r=>Number.parseInt(r,10),dq=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=[]}},fx=(r,e)=>e?e[r]:void 0;fq=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=Yk.default.debug,Ie=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}},Jk=class{_disposer=[];push(r){this._disposer.push(r)}dispose(){this._disposer.forEach(r=>r()),this._disposer=[]}},UR=ut("werift-ice:packages/ice/src/transport.ts"),Xy=class t9{constructor(e,t={}){this.socketType=e,this.options=t,this.socket=(0,Qk.createSocket)(e),this.socket.on("message",(s,n)=>{Ap(n.family)===6&&([n.address]=n.address.split("%")),this.rinfo=n;try{this.onData(s,[n.address,n.port])}catch(i){UR("onData error",i)}})}type="udp";socket;rinfo;onData=()=>{};closed=!1;static async init(e,t={}){let s=new t9(e,t);return await s.init(),s}async init(){let e=fx(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 Xk(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&&!Zk.isIP(t[0]))return new Promise((s,n)=>{this.socket.send(e,t[1],t[0],i=>{i?(UR("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()}})},r9=class s9{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,e9.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 s9(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()}},mi={rsa_1:1,ecdsa_3:3},Ip={sha256_4:4},Yy={TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256_49195:49195,TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256_49199:49199},n9=Object.values(Yy),ho={x25519_29:29,secp256r1_23:23},y2=Object.values(ho),x2={named_curve_3:3},s_={rsa_pkcs1_sha256:1025,ecdsa_secp256r1_sha256:1027},i9=[1,64],b2=[{hash:Ip.sha256_4,signature:mi.rsa_1},{hash:Ip.sha256_4,signature:mi.ecdsa_3}],lq=()=>{let r=xy.utils.randomPrivateKey(),e=xy.getPublicKey(r,!1),t=Buffer.from(r),s=Buffer.from(e);return{privateKey:t,publicKey:s}},hq=({publicKey:r,privateKey:e})=>{let t=xy.getSharedSecret(e,r);return Buffer.from(t).subarray(1)};lo={CLIENT:1,SERVER:2},xq=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}},n_=af.webcrypto;pr.set(n_);Rp=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 mi.rsa_1:return"RSASSA-PKCS1-v1_5";case mi.ecdsa_3:return"ECDSA"}})(),s=(()=>{if(r.hash===Ip.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 n_.subtle.generateKey(i,!0,["sign","verify"]),c=(await $g.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 n_.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?mq(this.masterSecret,r):gq(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=lx.Certificate.fromPEM(Buffer.from(r)),n=lx.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:x2.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])}},kp=class{srtpProfile;static findMatchingSRTPProfile(r,e){for(let t of e)if(r.includes(t))return t}},v2=r=>"0x"+r.toString("hex").replace(/(.)(.)/g,"$1$2 ").split(" ").filter(e=>e!=null&&e.length>0).join(",0x"),h9=r=>Object.entries({...r}).reduce((e,[t,s])=>((typeof s=="number"||typeof s=="string")&&(e[t]=s),Buffer.isBuffer(s)&&(e[t]=v2(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 h9(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:Jy,uint24be:bq,buffer:m9,array:vq,uint8:Pp,string:wq}=p9.types,Sq={type:Jy,data:m9(Jy)},i_=vq(Sq,Jy,"bytes"),_q=m9(bq),Eq=Pp,Cq=wq(Jy),Tq={hash:Pp,signature:Pp},w2={major:Pp,minor:Pp},Qc=class cp{constructor(e=Math.floor(Date.now()/1e3),t=(0,g9.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 cp(...Object.values((0,Jc.decode)(e,cp.spec)))}static from(e){return new cp(...Object.values(e))}serialize(){let e=(0,Jc.encode)(this,cp.spec).slice();return Buffer.from(e)}},y9=class dp{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:i_};static createEmpty(){return new dp(void 0,void 0,void 0,void 0,void 0,void 0,void 0)}static deSerialize(e){return new dp(...Object.values((0,Mr.decode)(e,dp.spec)))}serialize(){let e=(0,Mr.encode)(this,dp.spec).slice();return Buffer.from(e)}toFragment(){let e=this.serialize();return new Zs(this.msgType,e.length,this.messageSeq,0,e.length,e)}},Aq=class up{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:w2,contentLen:uo.types.uint16be};static createEmpty(){return new up(void 0,void 0,void 0,void 0,void 0)}static deSerialize(e){return new up(...Object.values((0,uo.decode)(e,up.spec)))}serialize(){let e=(0,uo.encode)(this,up.spec).slice();return Buffer.from(e)}},b9=class o_{constructor(e,t){this.recordLayerHeader=e,this.fragment=t}get summary(){return{header:this.recordLayerHeader,fragment:v2(this.fragment)}}static createEmpty(){return new o_(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 o_({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 Aq(this.recordLayerHeader.epoch,this.recordLayerHeader.sequenceNumber,this.recordLayerHeader.contentType,this.recordLayerHeader.protocolVersion,this.recordLayerHeader.contentLen).serialize()}},v9=r=>e=>(r.lastFlight=e,e.flatMap(t=>(t.messageSeq=r.sequenceNumber++,t.toFragment().chunk()))),Kp=r=>(e,t)=>e.map(s=>new b9({contentType:s.type,protocolVersion:r.version,epoch:r.epoch,sequenceNumber:t,contentLen:s.fragment.length},s.fragment)),a_=(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))(a_||{}),Iq=ut("werift-dtls : packages/dtls/src/flight/flight.ts : warn"),zS=ut("werift-dtls : packages/dtls/src/flight/flight.ts : err"),Wp=class c_{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=v9(this.dtls)(e);return this.dtls.bufferHandshakeCache(t,!0,this.flight),Kp(this.dtls)(t.map(n=>({type:22,fragment:n.serialize()})),++this.dtls.recordSequenceNumber)}async transmit(e){let t=0;for(;t<=c_.RetransmitCount;t++){if(this.setState("SENDING"),this.send(e).catch(s=>{zS("fail to send",zS)}),this.setState("WAITING"),this.nextFlight===void 0){this.setState("FINISHED");break}if(await(0,x9.setTimeout)(1e3*((t+1)/2)),this.dtls.flight>=this.nextFlight){this.setState("FINISHED");break}else Iq(this.dtls.sessionId,"retransmit",t,this.dtls.flight)}if(t>c_.RetransmitCount)throw zS(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}},Rq=class extends Wp{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 y9({major:254,minor:253},new Qc,Buffer.from([]),Buffer.from([]),n9,[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])}},kq=ut("werift-dtls : packages/dtls/src/flight/client/flight3.ts : log"),Pq=class extends Wp{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;kq("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])}},px={NULL:0,ECDHE:1},Gp={NULL:0,RSA:1,ECDSA:2,PSK:3},Xp={NULL:0,RSA:1,ECDHE_RSA:2,ECDHE_ECDSA:3,PSK:4,ECDHE_PSK:5},Yp=class{id=0;name;signType;keyType;toString(){return this.name}};Mq=ut("werift-dtls : packages/dtls/src/cipher/suites/aead.ts : err"),Uq=class extends xq{keyLength=0;nonceLength=0;ivLength=0;authTagLength=0;nonceImplicitLength=0;nonceExplicitLength=0;clientWriteKey;serverWriteKey;clientNonce;serverNonce;constructor(){super()}get summary(){return h9(this)}init(r,e,t){let s=yq(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,mx.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,mx.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 Mq("decrypt failed",h,r,v2(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},ep={K_LEN:16,N_MIN:12,N_MAX:12,P_MAX:2**36-31,A_MAX:2**53-1,C_MAX:2**36-15},tp={K_LEN:32,N_MIN:12,N_MAX:12,P_MAX:2**36-31,A_MAX:2**53-1,C_MAX:2**36-15},HR=Bq(),FR=Nq(),qR=Oq(),zR=Lq(),$R=Dq();gx=class{static type=23},yx=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)}}},Qy=class fp{constructor(e){this.certificateList=e}msgType=11;messageSeq;static spec={certificateList:ed.types.array(_q,ed.types.uint24be,"bytes")};static createEmpty(){return new fp(void 0)}static deSerialize(e){return new fp(...Object.values((0,ed.decode)(e,fp.spec)))}serialize(){let e=(0,ed.encode)(this,fp.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 lp{constructor(e=1){this.type=e}static spec={type:cf.types.uint8};static createEmpty(){return new lp}static deSerialize(e){return new lp(...Object.values((0,cf.decode)(e,lp.spec)))}serialize(){let e=(0,cf.encode)(this,lp.spec).slice();return Buffer.from(e)}},C9=class hp{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 hp(void 0,void 0)}static deSerialize(e){let t=(0,wa.decode)(e,hp.spec);return new hp(...Object.values(t))}serialize(){let e=(0,wa.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)}},T9=class pp{constructor(e){this.publicKey=e}msgType=16;messageSeq;static spec={publicKey:td.types.buffer(td.types.uint8)};static createEmpty(){return new pp(void 0)}static deSerialize(e){let t=(0,td.decode)(e,pp.spec);return new pp(...Object.values(t))}serialize(){let e=(0,td.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)}},d_=class u_{constructor(e){this.verifyData=e}msgType=20;messageSeq;static createEmpty(){return new u_(void 0)}static deSerialize(e){return new u_(e)}serialize(){return this.verifyData}toFragment(){let e=this.serialize();return new Zs(this.msgType,e.length,this.messageSeq,0,e.length,e)}},A9=class mp{constructor(e,t,s){this.certificateTypes=e,this.signatures=t,this.authorities=s}msgType=13;messageSeq;static spec={certificateTypes:Cn.types.array(Eq,Cn.types.uint8,"bytes"),signatures:Cn.types.array(Tq,Cn.types.uint16be,"bytes"),authorities:Cn.types.array(Cq,Cn.types.uint16be,"bytes")};static createEmpty(){return new mp(void 0,void 0,void 0)}static deSerialize(e){return new mp(...Object.values((0,Cn.decode)(e,mp.spec)))}serialize(){let e=(0,Cn.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)}},I9=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:w2,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:i_}))):s}serialize(){let e=this.extensions===void 0?(0,Tn.encode)(this,ma.spec).slice():(0,Tn.encode)(this,{...ma.spec,extensions:i_}).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{msgType=14;messageSeq;static spec={};static createEmpty(){return new gp}static deSerialize(e){return new gp(...Object.values((0,xx.decode)(e,gp.spec)))}serialize(){let e=(0,xx.encode)(this,gp.spec).slice();return Buffer.from(e)}toFragment(){let e=this.serialize();return new Zs(this.msgType,e.length,this.messageSeq,0,e.length,e)}};P9=class yp{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 yp(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,yp.spec);return new yp(...Object.values(t))}serialize(){return jq(this,yp.spec)}toFragment(){let e=this.serialize();return new Zs(this.msgType,e.length,this.messageSeq,0,e.length,e)}},df=1,ad=7,Hq=[df,ad],B9=r=>{switch(r){case df:case ad:return 16}},N9=r=>{switch(r){case df:return 14;case ad:return 12}},Fq=ut("werift-rtp : packages/rtp/src/codec/av1.ts"),f_=class L9{zBit_RtpStartsWithFragment;yBit_RtpEndsWithFragment;w_RtpNumObus;nBit_RtpStartsNewCodedVideoSequence;obu_or_fragment=[];static deSerialize=e=>{let t=new L9,s=0;if(t.zBit_RtpStartsWithFragment=xe(e[s],0),t.yBit_RtpEndsWithFragment=xe(e[s],1),t.w_RtpNumObus=xe(e[s],2,2),t.nBit_RtpStartsNewCodedVideoSequence=xe(e[s],4),s++,t.nBit_RtpStartsNewCodedVideoSequence&&t.zBit_RtpStartsWithFragment)throw new Error;[...Array(t.w_RtpNumObus-1).keys()].forEach(i=>{let[o,a]=U9(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&&(Fq("fragment lost, maybe packet lost"),f=[]),t.push(Buffer.concat(f))}else t.push(d)}let i=t.map(a=>D9.deSerialize(a)),o=i.pop();return Buffer.concat([...i.map(a=>(a.obu_has_size_field=1,a.serialize())),o.serialize()])}},D9=class M9{obu_forbidden_bit;obu_type;obu_extension_flag;obu_has_size_field;obu_reserved_1bit;payload;static deSerialize(e){let t=new M9,s=0;return t.obu_forbidden_bit=xe(e[s],0),t.obu_type=j9[xe(e[s],1,4)],t.obu_extension_flag=xe(e[s],5),t.obu_has_size_field=xe(e[s],6),t.obu_reserved_1bit=xe(e[s],7),s++,t.payload=e.subarray(s),t}serialize(){let e=new dx(8).set(this.obu_forbidden_bit).set(qq[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=O9.LEB128.encode(this.payload.length)),Buffer.concat([e,t,this.payload])}};j9={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"},qq=Object.entries(j9).reduce((r,[e,t])=>(r[t]=Number(e),r),{}),H9=class F9{f;nri;nalUnitType;s;e;r;nalUnitPayloadType;payload;fragment;static deSerialize(e,t){let s=new F9,n=0,i=e[n];if(s.f=xe(i,0),s.nri=xe(i,1,2),s.nalUnitType=xe(i,3,5),n++,s.s=xe(e[n],0),s.e=xe(e[n],1),s.r=xe(e[n],2),s.nalUnitPayloadType=xe(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=$q,a=Buffer.alloc(0);for(;o<e.length;){let c=e.readUInt16BE(o);o+=Vq,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([zq,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},zq=Buffer.from([0,0,0,1]),$q=1,Vq=2,q9=class z9{payload;static deSerialize(e){let t=new z9;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]),Hk([2,4,2,1],[312,e,0,0])])}},$9=class V9{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 V9,s=0;if(t.xBit=xe(e[s],0),t.nBit=xe(e[s],2),t.sBit=xe(e[s],3),t.pid=xe(e[s],5,3),s++,t.xBit&&(t.iBit=xe(e[s],0),t.lBit=xe(e[s],1),t.tBit=xe(e[s],2),t.kBit=xe(e[s],3),s++),t.iBit)if(t.mBit=xe(e[s],0),t.mBit){let n=Tp(xe(e[s],1,7)),i=Tp(e[s+1]);t.pictureId=Number.parseInt(n+i,2),s+=2}else t.pictureId=xe(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=xe(e[s],0,3),t.hBit=xe(e[s],3),t.ver=xe(e[s],4,3),t.pBit=xe(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}},K9=class W9{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 W9,s=0;if(t.iBit=xe(e[s],0),t.pBit=xe(e[s],1),t.lBit=xe(e[s],2),t.fBit=xe(e[s],3),t.bBit=xe(e[s],4),t.eBit=xe(e[s],5),t.vBit=xe(e[s],6),t.zBit=xe(e[s],7),s++,t.iBit)if(t.m=xe(e[s],0),t.m){let n=Tp(xe(e[s],1,7)),i=Tp(e[s+1]);t.pictureId=Number.parseInt(n+i,2),s+=2}else t.pictureId=xe(e[s],1,7),s++;if(t.lBit&&(t.tid=xe(e[s],0,3),t.u=xe(e[s],3),t.sid=xe(e[s],4,3),t.d=xe(e[s],7),s++,t.fBit===0&&(t.tl0PicIdx=e[s],s++)),t.fBit&&t.pBit)for(;;){t.pDiff=[...t.pDiff,xe(e[s],0,7)];let n=xe(e[s],7);if(s++,n===0)break}return t.vBit&&(t.n_s=xe(e[s],0,3),t.y=xe(e[s],3),t.g=xe(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(xe(e[s],0,3)),t.pgU.push(xe(e[s],3));let i=xe(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)}},Kq=class{payload;fragment;static deSerialize(r,e){return{}}static isDetectedFinalPacketInSequence(r){return!0}get isKeyframe(){return!0}};Gq=["MPEG4/ISO/AVC","VP8","VP9","OPUS","AV1"];Yq={setTimeout:(...r)=>{let e=setTimeout(...r);return()=>clearTimeout(e)},setInterval:(...r)=>{let e=setInterval(()=>{r[0]()},...r.slice(1));return()=>clearInterval(e)}};Zy=4,go=class h_{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 h_({type:e,count:t,version:2,length:n}).serialize();return Buffer.concat([o,s])}serialize(){let e=new Cp(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=xe(t,0,2),o=xe(t,2,1)>0,a=xe(t,3,5);return new h_({version:i,padding:o,count:a,type:s,length:n})}},VR=class p_{static count=4;count=p_.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 p_({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])}},Np=class m_{static count=1;count=m_.count;length=2;senderSsrc;mediaSsrc;constructor(e={}){Object.assign(this,e)}static deSerialize(e){let[t,s]=is(e,[4,4]);return new m_({senderSsrc:t,mediaSsrc:s})}serialize(){return er([4,4],[this.senderSsrc,this.mediaSsrc])}},Op=class g_{static count=15;length;count=g_.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=xe(o,0,6),c=(xe(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 g_({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 Cp(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}},Jq=ut("werift-rtp: /rtcp/psfb/index"),tf=class y_{static type=206;type=y_.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 VR.count:s=VR.deSerialize(e);break;case Np.count:s=Np.deSerialize(e);break;case Op.count:s=Op.deSerialize(e);break;default:Jq("unknown psfb packet",t.count);break}return new y_({feedback:s})}},rf=class Ry{ssrc=0;reports=[];static type=201;type=Ry.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(Ry.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(bx.deSerialize(e.slice(n,n+24))),n+=24;return new Ry({ssrc:s,reports:i})}},bx=class X9{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 X9({ssrc:t,fractionLost:s,packetsLost:n,highestSequence:i,jitter:o,lsr:a,dlsr:c})}},Y9=205,Lp=class x_{static count=1;count=x_.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:Y9,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 x_({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])}},Qq=ut("werift/rtp/rtcp/rtpfb/twcc"),Dp=class b_{static count=15;count=b_.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=xe(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 Sp({type:C.packetStatus}));y+=O}break;case 1:{let C=Q9.deSerialize(e.slice(f,f+2));S=C,C.symbolSize===0&&C.symbolList.forEach(O=>{O===1&&u.push(new Sp({type:1}))}),C.symbolSize===1&&C.symbolList.forEach(O=>{(O===1||O===2)&&u.push(new Sp({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 b_({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){Qq(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 J9{type;packetStatus;runLength;constructor(e={}){Object.assign(this,e),this.type=0}static deSerialize(e){let t=xe(e[0],1,2),s=(xe(e[0],3,5)<<8)+e[1];return new J9({type:0,packetStatus:t,runLength:s})}serialize(){return new dx(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 rP({sequenceNumber:++e,received:t}));return s}},Q9=class Z9{type;symbolSize;symbolList=[];constructor(e={}){Object.assign(this,e)}static deSerialize(e){let s=xe(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(xe(e[0],2+o,1))),i(8,o=>n.push(xe(e[1],o,1)));break;case 1:i(3,o=>n.push(xe(e[0],2+o*2,2))),i(4,o=>n.push(xe(e[1],o*2,2)));break;default:s=(xe(e[0],2,6)<<8)+e[1]}return new Z9({type:1,symbolSize:s,symbolList:n})}serialize(){let e=Buffer.alloc(2),t=new dx(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}},Sp=class v_{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 v_({type:t,delta:s})}deSerialize(e){let t=v_.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)}},eP=(r=>(r[r.TypeTCCRunLengthChunk=0]="TypeTCCRunLengthChunk",r[r.TypeTCCStatusVectorChunk=1]="TypeTCCStatusVectorChunk",r[r.packetStatusChunkLength=2]="packetStatusChunkLength",r))(eP||{}),tP=(r=>(r[r.TypeTCCPacketNotReceived=0]="TypeTCCPacketNotReceived",r[r.TypeTCCPacketReceivedSmallDelta=1]="TypeTCCPacketReceivedSmallDelta",r[r.TypeTCCPacketReceivedLargeDelta=2]="TypeTCCPacketReceivedLargeDelta",r[r.TypeTCCPacketReceivedWithoutDelta=3]="TypeTCCPacketReceivedWithoutDelta",r))(tP||{}),rP=class{sequenceNumber=0;delta=0;received=!1;receivedAtMs=0;constructor(r){Object.assign(this,r)}},Zq=ut("werift-rtp:packages/rtp/rtcp/rtpfb/index"),rd=class w_{static type=Y9;type=w_.type;feedback;header;constructor(e={}){Object.assign(this,e)}serialize(){return this.feedback.serialize()}static deSerialize(e,t){let s;switch(t.count){case Lp.count:s=Lp.deSerialize(e,t);break;case Dp.count:s=Dp.deSerialize(e,t);break;default:Zq("unknown rtpfb packet",t.count);break}return new w_({feedback:s,header:t})}},Mp=class S_{static type=202;type=S_.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=S2.deSerialize(e.slice(n));s.push(i),n+=i.length}return new S_({chunks:s})}},S2=class sP{source;items=[];constructor(e={}){Object.assign(this,e)}get length(){let e=4;return this.items.forEach(t=>e+=t.length),e+=1,e+=KR(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(KR(e.length))])}static deSerialize(e){let t=e.readUInt32BE(),s=[];for(let n=4;n<e.length&&e[n]!==0;){let o=_2.deSerialize(e.slice(n));s.push(o),n+=o.length}return new sP({source:t,items:s})}},_2=class nP{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 nP({type:t,text:n})}};sd=class ky{ssrc=0;senderInfo;reports=[];static type=200;type=ky.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(ky.type,this.reports.length,e,Math.floor(e.length/4))}static deSerialize(e,t){let s=e.readUInt32BE(),n=E2.deSerialize(e.subarray(4,24)),i=24,o=[];for(let c=0;c<t;c++)o.push(bx.deSerialize(e.subarray(i,i+24))),i+=24;return new ky({ssrc:s,senderInfo:n,reports:o})}},E2=class iP{ntpTimestamp;rtpTimestamp;packetCount;octetCount;constructor(e={}){Object.assign(this,e)}toJSON(){return{ntpTimestamp:oP(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 iP({ntpTimestamp:t,rtpTimestamp:s,packetCount:n,octetCount:i})}},oP=r=>{let[e,t]=is(er([8],[r]),[4,4]);return+`${e}.${t}`},ez=ut("werift-rtp:packages/rtp/src/rtcp/rtcp.ts"),aP=class{static deSerialize(r){let e=0,t=[];for(;e<r.length;){let s=go.deSerialize(r.subarray(e,e+Zy));e+=Zy;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 Mp.type:t.push(Mp.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){ez("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"};rz=ut("packages/rtp/src/rtp/red/packet.ts"),C2=class vP{header;blocks=[];static deSerialize(e){let t=e instanceof ArrayBuffer?Buffer.from(e):e,s=new vP,n=0;return[s.header,n]=__.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 __;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}},__=class wP{fields=[];static deSerialize(e){let t=0,s=new wP;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){rz(s?.message)}return e}},SP=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 C2,e=this.cache.slice(-(this.distance+1)),t=e.pop();return t&&(e.forEach(s=>{let n=Yc(t.timestamp,-s.timestamp);n>sz||r.blocks.push({block:s.block,blockPT:s.blockPT,timestampOffset:n})}),r.blocks.push({block:t.block,blockPT:t.blockPT})),r}},sz=16383,_P=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},WR=2,GR=4,XR=8,YR=12,JR=4,po=class EP{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 EP,s=0,n=e[s++];t.version=xe(n,0,2),t.padding=xe(n,2)>0,t.extension=xe(n,3)>0,t.csrcLength=xe(n,4,4),t.csrc=[...Array(t.csrcLength)].map(()=>{let o=e.readUInt32BE(s);return s+=4,o}),s+=YR-1;let i=e[1];t.marker=xe(i,0)>0,t.payloadType=xe(i,1,7),t.sequenceNumber=e.readUInt16BE(WR),t.timestamp=e.readUInt32BE(GR),t.ssrc=e.readUInt32BE(XR);for(let o=0;o<t.csrc.length;o++){let a=YR+o*JR;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*JR;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 Cp(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 Cp(8);this.marker&&i.set(1,0,1),i.set(7,1,this.payloadType),t.writeUInt8(i.value,s++),t.writeUInt16BE(this.sequenceNumber,WR),s+=2,t.writeUInt32BE(this.timestamp,GR),s+=4,t.writeUInt32BE(this.ssrc,XR),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 E_{constructor(e,t){this.header=e,this.payload=t}get serializeSize(){return this.header.serializeSize+this.payload.length}clone(){return new E_(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 E_(t,e.subarray(t.payloadOffset,e.length-t.paddingSize))}clear(){this.payload=null}};AP=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"}},QR=12,nz=8;iz=class extends AP{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=A2(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));ek(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,kP(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=IP(r,this.authTagLength,ZR),t=r.length-(this.authTagLength+ZR),s=r.subarray(0,r.length-this.authTagLength),n=r.subarray(r.length-this.authTagLength),i=this.generateSrtcpAuthTag(s);ek(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)}},ZR=4;oz=class extends AP{aeadAuthTagLen=16;rtpIvWriter=wp([2,4,4,2],!0);rtcpIvWriter=wp([2,4,2,4],!0);aadWriter=wp([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=A2(r,this.aeadAuthTagLen)){let s=r.subarray(0,t.payloadOffset),n=r.length-this.aeadAuthTagLen,i=r.subarray(n),o=Buffer.from([]);o=l_(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 rk(d,"SRTP"),u.copy(o,t.payloadOffset),[o,kP(t,o,"Failed to authenticate SRTP packet")]}encryptRTCP(r,e){let t=r.readUInt32BE(4),s=r.length+this.aeadAuthTagLen,n=Buffer.from([]);n=l_(n,s+$S),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=IP(r,this.aeadAuthTagLen,$S),t=r.length-$S,s=t-this.aeadAuthTagLen,n=r.readUInt32BE(4),i=r.readUInt32BE(t),o=i>>>31===1,a=i&~(tk<<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 rk(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]|=tk,t}},$S=4,tk=128;PP=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,Py.createHmac)("sha1",this.srtpSessionAuthTag),this.srtcpSessionKey=this.generateSessionKey(3),this.srtcpSessionSalt=this.generateSessionSalt(5),this.srtcpSessionAuthTag=this.generateSessionAuthTag(4),this.srtcpSessionAuth=(0,Py.createHmac)("sha1",this.srtcpSessionAuthTag),t){case df:this.cipher=new iz(this.srtpSessionKey,this.srtpSessionSalt,this.srtcpSessionKey,this.srtcpSessionSalt,this.srtpSessionAuthTag,this.srtcpSessionAuthTag);break;case ad:this.cipher=new oz(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 By.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 By.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 By.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>rp&&e.rolloverCounter++:e.lastSequenceNumber<rp&&r>sk-rp?e.rolloverCounter>0&&e.rolloverCounter--:r<rp&&e.lastSequenceNumber>sk-rp&&e.rolloverCounter++:e.rolloverHasProcessed=!0,e.lastSequenceNumber=r}generateSrtpAuthTag(r,e){this.srtpSessionAuth=(0,Py.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}},rp=100,sk=65535,az=class extends PP{constructor(r,e,t){super(r,e,t)}encryptRTCP(r){let e=r.readUInt32BE(4),t=this.getSrtcpSsrcState(e);return t.srtcpIndex++,t.srtcpIndex>>cz&&(t.srtcpIndex=0),this.cipher.encryptRTCP(r,t.srtcpIndex)}decryptRTCP(r){return this.cipher.decryptRTCP(r)}},cz=2147483647,BP=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)}},NP=class extends BP{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.decryptRTCP(r);return e};encrypt(r){return this.localContext.encryptRTCP(r)}},dz=class extends PP{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=A2(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}},OP=class extends BP{constructor(r){super(dz),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)}},uz=class{constructor(r){this.props=r}sequenceNumber=h2();timestamp=Gy();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"),fz=class extends Wp{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 I9.deSerialize(r.fragment);case 11:return Qy.deSerialize(r.fragment);case 12:return P9.deSerialize(r.fragment);case 13:return A9.deSerialize(r.fragment);case 14:return R9.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 Qy([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 T9(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=c9(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?u9(i,o):d9(i,this.cipher.localRandom.serialize(),this.cipher.remoteRandom.serialize()),this.cipher.cipher=w9(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 mi.ecdsa_3:return s_.ecdsa_secp256r1_sha256;case mi.rsa_1:return s_.rsa_pkcs1_sha256}})();if(!t)throw new Error;ns(this.dtls.sessionId,"signatureScheme",this.cipher.signatureHashAlgorithm?.signature,t);let s=new C9(t,e),n=this.createPacket([s]);return Buffer.concat(n.map(o=>o.serialize()))}sendChangeCipherSpec(){let r=E9.createEmpty().serialize(),e=Kp(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 d_(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=kp.findMatchingSRTPProfile(i.profiles,t.options.srtpProfiles||[]);if(ns(t.sessionId,"selected srtp profile",o),o==null)return;e.srtpProfile=o}break;case gx.type:t.remoteExtendedMasterSecret=!0;break;case yx.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=_9(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)};LP=class xp{constructor(e,t){this.serverVersion=e,this.cookie=t}msgType=3;messageSeq;static spec={serverVersion:w2,cookie:id.types.buffer(id.types.uint8)};static createEmpty(){return new xp(void 0,void 0)}static deSerialize(e){return new xp(...Object.values((0,id.decode)(e,xp.spec)))}serialize(){let e=(0,id.encode)(this,xp.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)}},lz=ut("werift-dtls : packages/dtls/src/context/dtls.ts : log"),nk=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?(lz(this.sessionId,"exist",i.summary,e,t),!1):!0});this.handshakeCache[t].data=[...this.handshakeCache[t].data,...s]}},hz=class{constructor(r){this.socket=r}send=r=>this.socket.send(r)},C_=class oo{static type=10;static spec={type:pi.types.uint16be,data:pi.types.array(pi.types.uint16be,pi.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,pi.decode)(e,oo.spec.data)})}static deSerialize(e){return new oo((0,pi.decode)(e,oo.spec))}serialize(){return Buffer.from((0,pi.encode)(this,oo.spec).slice())}get extension(){return{type:this.type,data:this.serialize().slice(2)}}},T_=class xa{static type=13;static spec={type:hi.types.uint16be,data:hi.types.array({hash:hi.types.uint8,signature:hi.types.uint8},hi.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,hi.decode)(e,xa.spec))}serialize(){let e=(0,hi.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)}}},ik=class Ny{constructor(e,t){this.level=e,this.description=t}static spec={level:od.types.uint8,description:od.types.uint8};static deSerialize(e){return new Ny(...Object.values((0,od.decode)(e,Ny.spec)))}serialize(){let e=(0,od.encode)(this,Ny.spec).slice();return Buffer.from(e)}},ok=ut("werift-dtls : packages/dtls/record/receive.ts : log"),VS=ut("werift-dtls : packages/dtls/record/receive.ts : err"),pz=r=>{let e=0,t=[];for(;r.length>e;){let s=r.readUInt16BE(e+11);if(r.length<e+(12+s))break;let n=b9.deSerialize(r.subarray(e));t.push(n),e+=13+s}return t},mz=(r,e)=>t=>{switch(t.recordLayerHeader.contentType){case 20:return ok(r.sessionId,"change cipher spec"),[{type:20,data:void 0}];case 22:{let n=t.fragment;try{t.recordLayerHeader.epoch>0&&(ok(r.sessionId,"decrypt handshake"),n=e.decryptPacket(t))}catch(i){throw VS(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 VS(r.sessionId,"decSerialize failed",i,n),i}}case 23:return[{type:23,data:e.decryptPacket(t)}];case 21:{let n=ik.deSerialize(t.fragment);if(a_[n.description]==null){let i=e.decryptPacket(t);n=ik.deSerialize(i)}if(VS(r.sessionId,"ContentType.alert",n,a_[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}]}},ak=ut("werift-dtls : packages/dtls/src/socket.ts : log"),ck=ut("werift-dtls : packages/dtls/src/socket.ts : err"),I2=class{constructor(r,e){this.options=r,this.sessionType=e,this.dtls=new nk(this.options,this.sessionType),this.cipher=new Rp(this.sessionType,this.options.cert,this.options.key,this.options.signatureHash),this.transport=new hz(this.options.transport),this.setupExtensions(),this.transport.socket.onData=this.udpOnMessage}onConnect=new Ie;onData=new Ie;onError=new Ie;onClose=new Ie;transport;cipher;dtls;srtp=new kp;connected=!1;extensions=[];onHandleHandshakes;bufferFragmentedHandshakes=[];renegotiation(){ak("renegotiation",this.sessionType),this.connected=!1,this.cipher=new Rp(this.sessionType,this.options.cert,this.options.key,this.options.signatureHash),this.dtls=new nk(this.options,this.sessionType),this.srtp=new kp,this.extensions=[],this.bufferFragmentedHandshakes=[]}udpOnMessage=r=>{let e=pz(r);for(let t of e)try{let s=mz(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=>{ck(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){ck(this.dtls.sessionId,"catch udpOnMessage error",s)}};setupExtensions(){if(ak(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=C_.createEmpty();r.data=y2,this.extensions.push(r.extension)}{let r=T_.createEmpty();r.data=b2,this.extensions.push(r.extension)}this.options.extendedMasterSecret&&this.extensions.push({type:gx.type,data:Buffer.alloc(0)});{let r=yx.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,DP.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=Kp(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 pq(r,e,this.cipher.masterSecret,this.cipher.localRandom.serialize(),this.cipher.remoteRandom.serialize(),this.sessionType===lo.CLIENT)}get remoteCertificate(){return this.cipher.remoteCertificate}},KS=ut("werift-dtls : packages/dtls/src/client.ts : log"),A_=class extends I2{constructor(r){super(r,lo.CLIENT),this.onHandleHandshakes=this.handleHandshakes,KS(this.dtls.sessionId,"start client")}async connect(){await new Rq(this.transport,this.dtls,this.cipher).exec(this.extensions)}flight5;handleHandshakes=async r=>{KS(this.dtls.sessionId,"handleHandshakes",r.map(e=>e.msg_type));for(let e of r)switch(e.msg_type){case 3:{let t=LP.deSerialize(e.fragment);await new Pq(this.transport,this.dtls).exec(t)}break;case 2:{if(this.connected)return;this.flight5=new fz(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(),KS(this.dtls.sessionId,"dtls connected");break}}},fi=ut("werift-dtls : packages/dtls/flight/server/flight2.ts : log"),gz=(r,e,t,s)=>n=>{fi("dtls version",n.clientVersion),e.flight=2,e.recordSequenceNumber=0,e.sequenceNumber=0,n.extensions.forEach(f=>{switch(f.type){case C_.type:{let h=C_.fromData(f.data).data;fi(e.sessionId,"curves",h);let y=h.filter(v=>y2.includes(v))[0];t.namedCurve=y,fi(e.sessionId,"curve selected",t.namedCurve)}break;case T_.type:{if(!t.signatureHashAlgorithm)throw new Error("need to set certificate");let h=T_.fromData(f.data).data;fi(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);fi(e.sessionId,"srtp profiles",h.profiles);let y=kp.findMatchingSRTPProfile(h.profiles,e.options?.srtpProfiles);if(!y)throw new Error;s.srtpProfile=y,fi(e.sessionId,"srtp profile selected",s.srtpProfile)}break;case gx.type:e.remoteExtendedMasterSecret=!0;break;case yx.type:fi(e.sessionId,"RenegotiationIndication",f.data);break;case 43:{let y=[...f.data.subarray(1)].map(v=>v.toString(10));fi("dtls supported version",y)}break}}),t.localRandom=new Qc,t.remoteRandom=Qc.from(n.random);let i=n.cipherSuites;fi(e.sessionId,"cipher suites",i);let o=(()=>{switch(t.signatureHashAlgorithm?.signature){case mi.ecdsa_3:return Yy.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256_49195;case mi.rsa_1:return Yy.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,fi(e.sessionId,"selected cipherSuite",t.cipherSuite),t.localKeyPair=_9(t.namedCurve),e.cookie||=(0,MP.randomBytes)(20);let a=new LP({major:254,minor:253},e.cookie),c=v9(e)([a]),u=Kp(e)(c.map(f=>({type:22,fragment:f.serialize()})),++e.recordSequenceNumber).map(f=>f.serialize());for(let f of u)r.send(f)},dk=ut("werift-dtls : packages/dtls/flight/server/flight4.ts : log"),yz=class extends Wp{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){dk(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:gx.type,data:Buffer.alloc(0)});let e=yx.createEmpty();r.push(e.extension);let t=new I9(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 Qy([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 P9(x2.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 A9(i9,b2,[]);dk(this.dtls.sessionId,"sendCertificateRequest",r);let e=this.createPacket([r]);return Buffer.concat(e.map(t=>t.serialize()))}sendServerHelloDone(){let r=new R9,e=this.createPacket([r]);return Buffer.concat(e.map(t=>t.serialize()))}},nf=ut("werift-dtls : packages/dtls/flight/server/flight6.ts"),xz=class extends Wp{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 Qy.deSerialize(r.fragment);case 15:return C9.deSerialize(r.fragment);case 16:return T9.deSerialize(r.fragment);case 20:return d_.deSerialize(r.fragment)}})();if(e){let t=Jp[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=E9.createEmpty().serialize(),e=Kp(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 d_(e);this.dtls.epoch=1;let[s]=this.createPacket([t]);return this.dtls.recordSequenceNumber=0,this.cipher.encryptPacket(s).serialize()}},Jp={};Jp[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=c9(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?u9(s,n):d9(s,r.remoteRandom.serialize(),r.localRandom.serialize()),r.cipher=w9(r.cipherSuite),r.cipher.init(r.masterSecret,r.localRandom.serialize(),r.remoteRandom.serialize()),nf(e.sessionId,"setup cipher",r.cipher.summary)};Jp[11]=({cipher:r,dtls:e})=>t=>{nf(e.sessionId,"handshake certificate",t),r.remoteCertificate=t.certificateList[0]};Jp[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)};Jp[20]=({dtls:r})=>e=>{nf(r.sessionId,"finished",e)};Fu=ut("werift-dtls : packages/dtls/src/server.ts : log"),UP=class extends I2{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=y9.deSerialize(e.fragment);t.cookie.length===0?(Fu(this.dtls.sessionId,"send flight2"),gz(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 yz(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 xz(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}}},vx=554869826,jP=8,HP=1398035790,co=20,R2=24,k2=1,P2=2,FP=6,qP=50,bz=["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"],B2=(r=>(r[r.REQUEST=0]="REQUEST",r[r.INDICATION=16]="INDICATION",r[r.RESPONSE=256]="RESPONSE",r[r.ERROR=272]="ERROR",r))(B2||{}),N2=(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))(N2||{});uk=class{queue=[];wait=new Ie;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)})})}},I_=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 Ie;return r(e,t,n).catch(()=>{}),{awaitable:s,resolve:e,reject:t}};D2=Buffer.alloc(6);D2.writeUInt16BE(vx>>16,0);D2.writeUInt32BE(vx,2);np=r=>{let e=Buffer.alloc(4);return e.writeUInt32BE(r,0),e},ip=r=>r.readUInt32BE(0),Sz=r=>{let e=Buffer.alloc(4);return e.writeUInt16BE(r,0),e},_z=r=>r.readUInt16BE(0),fk=r=>new IS(r.toString()).toBuffer(),lk=r=>{let e=new IS(r);return BigInt(e.toString())},WS=r=>Buffer.from(r,"utf8"),GS=r=>r.toString("utf8"),XS=r=>r,YS=r=>r,Ez=r=>Buffer.from([]),Cz=r=>null,VP=[[1,"MAPPED-ADDRESS",Vu,Ku],[3,"CHANGE-REQUEST",np,ip],[4,"SOURCE-ADDRESS",Vu,Ku],[5,"CHANGED-ADDRESS",Vu,Ku],[6,"USERNAME",WS,GS],[8,"MESSAGE-INTEGRITY",XS,YS],[9,"ERROR-CODE",wz,vz],[12,"CHANNEL-NUMBER",Sz,_z],[13,"LIFETIME",np,ip],[18,"XOR-PEER-ADDRESS",Ly,Oy],[19,"DATA",XS,YS],[20,"REALM",WS,GS],[21,"NONCE",XS,YS],[22,"XOR-RELAYED-ADDRESS",Ly,Oy],[25,"REQUESTED-TRANSPORT",np,ip],[32,"XOR-MAPPED-ADDRESS",Ly,Oy],[36,"PRIORITY",np,ip],[37,"USE-CANDIDATE",Ez,Cz],[32802,"SOFTWARE",WS,GS],[32808,"FINGERPRINT",np,ip],[32809,"ICE-CONTROLLED",fk,lk],[32810,"ICE-CONTROLLING",fk,lk],[32811,"RESPONSE-ORIGIN",Vu,Ku],[32812,"OTHER-ADDRESS",Vu,Ku]],KP=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=[]}},hk=VP.reduce((r,e)=>(r[e[0]]=e,r),{}),Tz=VP.reduce((r,e)=>(r[e[1]]=e,r),{});Qs=class extends KP{constructor(r,e,t=zP(),s=[]){super(s),this.messageMethod=r,this.messageClass=e,this.transactionId=t}toJSON(){return this.json}get json(){return{messageMethod:N2[this.messageMethod],messageClass:B2[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]=Tz[t],o=i.name===Ly.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(vx,4),Buffer.concat([e,this.transactionId,r])}addMessageIntegrity(r){return this.setAttribute("MESSAGE-INTEGRITY",this.messageIntegrity(r)),this}messageIntegrity(r){let e=M2(this.bytes,this.bytes.length-co+R2);return Buffer.from((0,O2.createHmac)("sha1",r).update(e).digest("hex"),"hex")}addFingerprint(){this.setAttribute("FINGERPRINT",WP(this.bytes))}},M2=(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};GP=class extends Error{response;addr},XP=class extends GP{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}},Iz=class extends GP{get str(){return"STUN transaction timed out"}},JS=ut("werift-ice:packages/ice/src/stun/transaction.ts"),U2=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:FP)}timeoutDelay=qP;ended=!1;tries=0;triesMax;onResponse=new Ie;responseReceived=(r,e)=>{this.onResponse.length>0&&(r.messageClass===256?(this.onResponse.execute(r,e),this.onResponse.complete()):this.onResponse.error(new XP(r,e)))};run=async()=>{try{return this.retry().catch(e=>{JS("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=>{JS("send stun failed",r)}),await new Promise(r=>setTimeout(r,this.timeoutDelay)),!this.ended);)this.timeoutDelay*=2,this.tries++;this.tries>=this.triesMax&&(JS(`retry failed times:${this.tries} maxLimit:${this.triesMax}`),this.onResponse.error(new Iz))};cancel(){this.ended=!0}},pk=ut("werift-ice : packages/ice/src/stun/protocol.ts"),ex=class YP{static type="stun";type=YP.type;transport;transactions={};get transactionsKeys(){return Object.keys(this.transactions)}localCandidate;sentMessage;localIp;onRequestReceived=new Ie;onDataReceived=new Ie;constructor(){}connectionMade=async(e,t,s)=>{e?this.transport=await Xy.init("udp4",{portRange:t,interfaceAddresses:s}):this.transport=await Xy.init("udp6",{portRange:t,interfaceAddresses:s}),this.transport.onData=(n,i)=>{this.datagramReceived(n,i)}};datagramReceived(e,t){try{let s=wx(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){pk("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(()=>{pk("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 U2(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"),Rz=500,kz=600,Pz=285212672,ZP=class eB{constructor(e){this.turn=e,e.onData.subscribe((t,s)=>{this.handleStunMessage(t,s)}).disposer(this.disposer)}static type="turn";type=eB.type;localCandidate;disposer=new Jk;onRequestReceived=new Ie;onDataReceived=new Ie;handleStunMessage=(e,t)=>{try{let s=wx(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 U2(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()}},tB=class rB{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??Rz}static type="turn";type=rB.type;onData=new Ie;onRequestReceived=new Ie;onDataReceived=new Ie;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",Pz);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]=k_.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=wx(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&&mk(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+=R_(n);let i=mk(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=R_(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=I_(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,QP.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 U2(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 XP))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=nB(this.username,this.realm,this.password),e.transactionId=zP(),[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=k_.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 oB{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 oB(n,i,o,a,c,d,u,s.related_address,s.related_port,s.tcptype,s.generation,s.ufrag)}canPairWith(e){let t=(0,B_.isIPv4)(this.host),s=(0,B_.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}};Bz=class{cache=new Map;mdnsInstance=(0,cB.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()}},Nz=ut("werift-ice : packages/ice/src/ice.ts : log"),L_=class{constructor(r,e,t){this.protocol=r,this.remoteCandidate=e,this.iceControlling=t}id=(0,dB.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 rx(this.localCandidate,this.remoteCandidate,this.iceControlling)}get foundation(){return this.localCandidate.foundation}},D_=1,bp=2,uB=5,M_=6,fB=(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))(fB||{}),lB={useIpv4:!0,useIpv6:!0};Oz=ut("werift-ice : packages/ice/src/utils.ts");Dz=r=>{if(!r)return;let[e,t]=r.split(":");return[e,Number.parseInt(t)]},Ut=ut("werift-ice : packages/ice/src/ice.ts : log"),bB=class{constructor(r,e){this._iceControlling=r,this.options={...lB,...e};let{stunServer:t,turnServer:s}=this.options;this.stunServer=j_(t)??["stun.l.google.com",19302],this.turnServer=j_(s),this.restart(),Ut("new Connection",this.options)}localUsername=sp(4);localPassword=sp(22);remoteIsLite=!1;remotePassword="";remoteUsername="";checkList=[];localCandidates=[];stunServer;turnServer;options;remoteCandidatesEnd=!1;localCandidatesEnd=!1;generation=-1;userHistory={};tieBreaker=BigInt(new wy((0,aB.randomBytes)(64)).toString());state="new";lookup;_remoteCandidates=[];nominated;nominating=!1;checkListDone=!1;checkListState=new uk;earlyChecks=[];earlyChecksDone=!1;localCandidatesStart=!1;protocols=[];queryConsentHandle;onData=new Ie;stateChanged=new Ie;onIceCandidate=new Ie;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=sp(4),this.localPassword=sp(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 uk,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=xB(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}=gk(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 ex;this.ensureProtocol(d);try{await d.connectionMade((0,N_.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(tx("host","udp",u[0]),1,"udp",_p("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,N_.isIPv4)(u.localCandidate?.host)){let S=await pB(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 P_({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 P_({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(tx("relay","udp",u[0]),1,"udp",_p("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 O_.setTimeout(20);let r=bp;for(;this.checkList.length>0&&r===bp;)r=await this.checkListState.get(),Ut("checkListState",r);for(let e of this.checkList)e.handle?.resolve?.();if(r!==D_)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===ex.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=I_(async(r,e,t)=>{let s=0,n=!1,i=new AbortController;t.once(()=>{n=!0,s+=M_,i.abort(),this.queryConsentHandle=void 0});let{localUsername:o,remoteUsername:a,iceControlling:c}=this;try{for(;this.state!=="closed"&&!n;){await O_.setTimeout(uB*(.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>=M_){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(bp)})),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 Bz);let e=await this.lookup.lookup(r.host);r.host=e}catch{return}try{U_(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{U_(e)}catch{continue}this._remoteCandidates.push(e)}this.remoteCandidatesEnd=!0}get remoteCandidates(){return this._remoteCandidates}get candidatePairs(){return this.checkList}sortCheckList(){hB(this.checkList,this.iceControlling)}findPair(r,e){return this.checkList.find(s=>(0,Dy.default)(s.protocol,r)&&(0,Dy.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(D_))),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(bp)})))}checkStart=r=>I_(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,Dy.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}=gk(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(sp(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 L_(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 L_(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=Mz({remoteUsername:e,localUsername:t}),i=new Qs(1,0);return i.setAttribute("USERNAME",n).setAttribute("PRIORITY",_p("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)})}},Mz=({remoteUsername:r,localUsername:e})=>`${r}:${e}`,gk=r=>{let[e,t]=r.split(":");return{remoteUsername:e,localUsername:t}};j2=class extends vB.EventEmitter{addEventListener=(r,e)=>{this.addListener(r,e)};removeEventListener=(r,e)=>{this.removeListener(r,e)}},Uz=ut("werift:packages/webrtc/src/dataChannel.ts");H2=class extends j2{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 Ie;stateChanged=new Ie;onMessage=new Ie;error=new Ie;bufferedAmountLow=new Ie;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}Uz("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)}},F2=class{label="";maxPacketLifeTime;maxRetransmits;ordered=!0;protocol="";negotiated=!1;id;constructor(r={}){Object.assign(this,r)}},jz=()=>({type:"ccm",parameter:"fir"}),Qp=()=>({type:"nack"}),ff=()=>({type:"nack",parameter:"pli"}),Zp=()=>({type:"goog-remb"}),SB=()=>({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}},gi=class{id;uri;constructor(r){Object.assign(this,r)}},Hz=class{cname;mux=!1;ssrc;constructor(r={}){Object.assign(this,r)}},_B=class{type;parameter;constructor(r={}){Object.assign(this,r)}},EB=class{ssrc;constructor(r={}){Object.assign(this,r)}},CB=class{ssrc;payloadType;rtx;constructor(r){Object.assign(this,r)}},q2=class{rid;direction;constructor(r){Object.assign(this,r)}},TB=(r={})=>new _a({mimeType:"video/h264",clockRate:9e4,rtcpFeedback:[Qp(),ff(),Zp()],parameters:"profile-level-id=42e01f;packetization-mode=1;level-asymmetry-allowed=1",...r}),z2=(r={})=>new _a({mimeType:"video/VP8",clockRate:9e4,rtcpFeedback:[Qp(),ff(),Zp()],...r}),AB=(r={})=>new _a({mimeType:"video/VP9",clockRate:9e4,rtcpFeedback:[Qp(),ff(),Zp()],...r}),IB=(r={})=>new _a({mimeType:"video/AV1X",clockRate:9e4,rtcpFeedback:[Qp(),ff(),Zp()],...r}),$2=(r={})=>new _a({mimeType:"audio/OPUS",clockRate:48e3,channels:2,...r}),V2=(r={})=>new _a({mimeType:"audio/PCMU",clockRate:8e3,channels:1,payloadType:0,...r}),K2=[IB(),AB(),z2(),TB(),$2(),V2()].map(r=>r.mimeType),Fz=K2.filter(r=>r.toLowerCase().startsWith("video/")),qz=K2.filter(r=>r.toLowerCase().startsWith("audio/"));xk=2,bk=3,Jz=0,Ty=50,vk=51,wk=53,Qz=56,Zz=57,e$="0.0.0.0",Sk=9,q_={auto:"actpass",client:"active",server:"passive"},_k=Object.keys(q_).reduce((r,e)=>{let t=q_[e];return r[t]=e,r},{}),t$=["apt","max-fr","max-fs","maxplaybackrate","minptime","stereo","useinbandfec"],NB=["cname","msid","mslabel","label"],Ek={SRTP_AES128_CM_HMAC_SHA1_80:df,SRTP_AEAD_AES_128_GCM:ad},Uy=["sendonly","sendrecv"],r$=["sendrecv","recvonly"],OB=class extends Map{constructor(r){if(super(),r)for(let e of r)this.set(e.id,e)}};LB=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,BB.randomUUID)().toString();onTrack=new Ie;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,Uy.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}},DB="inactive",W2="sendonly",G2="recvonly",X2="sendrecv",jy=[DB,W2,G2,X2],Hp=class extends j2{uuid=(0,Y2.randomUUID)().toString();streamId;remote=!1;label;kind;id;ssrc;rid;header;codec;enabled=!0;onReceiveRtp=new Ie;onReceiveRtcp=new Ie;onSourceChanged=new Ie;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)}},MB=class{id;tracks=[];constructor(r){Array.isArray(r)?this.tracks=r:Object.assign(this,r),this.id??=(0,Y2.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")}},s$=ut("werift:packages/webrtc/src/utils.ts");n$={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"};Z2=(r,e)=>jy[jy.indexOf(r)&jy.indexOf(e)];eE=Date.now,o$=BigInt(Date.now())*1000n-process.hrtime.bigint()/1000n,HB=()=>o$+process.hrtime.bigint()/1000n,Fp=()=>Date.now()/1e3,FB=()=>{let e=(F_.performance.timeOrigin+F_.performance.now()-Date.UTC(1900,0,1))/1e3,[t,s]=e.toString().split(".").map(Number);return er([4,4],[t,s]).readBigUInt64BE()},tE=r=>{let e=er([8],[r]),[,t,s]=is(e,[2,2,2,2]);return er([2,2],[t,s]).readUInt32BE()};a$=Rp.createSelfSignedCertificateWithKey,c$=class{static async rtpSource({port:r,kind:e,cb:t}){r??=await g2();let s=new Hp({kind:e}),n=(0,PB.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{}}]}},zB=(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},d$=ut("werift:packages/webrtc/src/media/receiver/nack.ts"),Ck=150,u$=class{constructor(r){this.receiver=r}newEstSeqNum=0;_lost={};nackLoop;onPacketLost=new Ie;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){d$("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>Ck&&(this._lost=Object.entries(this._lost).slice(-Ck).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 Lp({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)}})},f$=ut("werift:packages/webrtc/media/receiver/receiverTwcc"),l$=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:HB()},Object.keys(this.extensionInfo).length>10&&this.sendTWCC()}async runTWCC(){for(;this.twccRunning;)this.sendTWCC(),await(0,$B.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 Sp({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 Dp({senderSsrc:this.rtcpSsrc,mediaSourceSsrc:this.mediaSourceSsrc,baseSequenceNumber:n,packetStatusCount:i,referenceTime:Gk(Math.floor(Number(o/1000n/64n))),fbPktCount:this.fbPktCount,recvDeltas:c,packetChunks:s})});this.dtlsTransport.sendRtcp([d]).catch(u=>{f$(u)}),this.extensionInfo={},this.fbPktCount=Wk(this.fbPktCount,1)}},h$=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||ux(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"),z_=class XB{constructor(e,t,s,n=[]){this.config=e,this.iceTransport=t,this.localCertificate=s,this.srtpProfiles=n,this.localCertificate??=XB.localCertificate}id=(0,WB.randomUUID)().toString();state="new";role="auto";srtpStarted=!1;transportSequenceNumber=0;bytesSent=0;bytesReceived=0;packetsSent=0;packetsReceived=0;dataReceiver=()=>{};dtls;srtp;srtcp;onStateChange=new Ie;onRtcp=new Ie;onRtp=new Ie;static localCertificate;static localCertificatePromise;remoteParameters;get localParameters(){return new ix(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 Rp.createSelfSignedCertificateWithKey({signature:mi.ecdsa_3,hash:Ip.sha256_4},ho.secp256r1_23);return this.localCertificate=new rE(t,e,s),this.localCertificate})(),this.localCertificatePromise)}setRemoteParams(e){let t=m$([...this.remoteParameters?.fingerprints??[],...e.fingerprints]),s=e.role==="auto"&&this.remoteParameters?.role?this.remoteParameters.role:e.role;this.remoteParameters=new ix(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 UP({cert:this.localCertificate?.certPem,key:this.localCertificate?.privateKey,signatureHash:this.localCertificate?.signatureHash,transport:Tk(this.iceTransport.connection),srtpProfiles:this.srtpProfiles,extendedMasterSecret:!0,certificateRequest:!0}):this.dtls=new A_({cert:this.localCertificate?.certPem,key:this.localCertificate?.privateKey,signatureHash:this.localCertificate?.signatureHash,transport:Tk(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 A_&&(await(0,GB.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=Q2(a);if(!d)return[];let u=sx(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=y$(t),n=t.filter(({normalizedAlgorithm:a})=>a===s),i=n.reduce((a,{normalizedAlgorithm:c})=>(a.has(c)||a.set(c,sx(J2(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(B9(e),N9(e)),o={keys:{localMasterKey:t,localMasterSalt:s,remoteMasterKey:n,remoteMasterSalt:i},profile:e};this.srtp=new OP(o),this.srtcp=new NP(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())&&G9(e))if(this.bytesReceived+=e.length,this.packetsReceived++,cP(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=aP.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}},p$=["new","connecting","connected","closed","failed"],rE=class{constructor(r,e,t){this.certPem=e,this.signatureHash=t;let s=qp.Certificate.fromPEM(Buffer.from(e));this.publicKey=s.publicKey.toPEM(),this.privateKey=qp.PrivateKey.fromPEM(Buffer.from(r)).toPEM()}publicKey;privateKey;getFingerprints(){return[new nx("sha-256",J2(qp.Certificate.fromPEM(Buffer.from(this.certPem)).raw,"sha256"))]}},nx=class{constructor(r,e){this.algorithm=r,this.value=e}},ix=class{constructor(r=[],e){this.fingerprints=r,this.role=e}},m$=r=>{let e=new Set;return r.filter(({algorithm:t,value:s})=>{let n=`${Q2(t)??t.trim().toLowerCase()}:${sx(s)}`;return e.has(n)?!1:(e.add(n),!0)})},g$=["sha512","sha384","sha256","sha224","sha1"],y$=r=>g$.find(e=>r.some(({normalizedAlgorithm:t})=>t===e))??r[0].normalizedAlgorithm,x$=class{constructor(r){this.ice=r,r.onData.subscribe(e=>{UB(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()}},Tk=r=>new x$(r),Ak=ut("werift:packages/webrtc/src/transport/ice.ts"),JB=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,YB.randomUUID)().toString();connection;state="new";waitStart;renominating=!1;onStateChange=new Ie;onIceCandidate=new Ie;onNegotiationNeeded=new Ie;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(ZB(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?(Ak("renomination",r),this.connection.resetNominatedPair(),this.renominating=!1):(Ak("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 Ie,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}},b$=["new","checking","connected","completed","disconnected","failed","closed"],v$=["new","gathering","complete"],QB=class{constructor(r={}){this.options=r,this.connection=new bB(!1,this.options),this.connection.onIceCandidate.subscribe(e=>{this.onIceCandidate(of(e))})}onIceCandidate=()=>{};gatheringState="new";connection;onGatheringStateChange=new Ie;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 nE({usernameFragment:this.connection.localUsername,password:this.connection.localPassword})}setState(r){r!==this.gatheringState&&(this.gatheringState=r,this.onGatheringStateChange.execute(r))}};e7=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}}},sE=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 e7({candidate:aE(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=cE(r.candidate);return e.sdpMLineIndex=r.sdpMLineIndex??void 0,e.sdpMid=r.sdpMid??void 0,e}catch{}}},nE=class{iceLite=!1;usernameFragment;password;constructor(r={}){Object.assign(this,r)}},yi=class r7{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 r7.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(t0(this.body.length))].map(()=>Buffer.from("\0"))])}},iE=class extends yi{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=_7(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,S7(this.params)])}},qy=class s7 extends iE{static type=1;get type(){return s7.type}},$_=class n7 extends iE{static type=2;get type(){return n7.type}},w$=class i7 extends iE{static type=130;get type(){return i7.type}},zy=class o7 extends yi{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 o7.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})])}},$y=class a7 extends yi{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 a7.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(t0(e))].map(()=>Buffer.from("\0"))])),s}},V_=class c7 extends yi{static type=10;get type(){return c7.type}},K_=class d7 extends yi{static type=11;get type(){return d7.type}},e0=class extends yi{constructor(r=0,e=void 0){super(r,e),this.flags=r,e&&(this.params=_7(e))}params=[];get body(){return S7(this.params)}},W_=class u7 extends e0{static type=6;get type(){return u7.type}},Vy=class G_ extends e0{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 G_.type}get descriptions(){return this.params.map(([e,t])=>({name:(Object.entries(G_.CODE).find(([,n])=>n===e)||[])[0],body:t}))}},X_=class f7 extends e0{static type=4;get type(){return f7.type}},l7=class h7 extends e0{static type=5;get type(){return h7.type}},Y_=class p7 extends e0{static type=130;get type(){return p7.type}},J_=class m7 extends yi{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 m7.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}},g7=class y7 extends yi{constructor(e=0,t){super(e,t),this.flags=e,t&&(this.cumulativeTsn=t.readUInt32BE(0))}static type=7;get type(){return y7.type}cumulativeTsn=0;get body(){let e=Buffer.alloc(4);return e.writeUInt32BE(this.cumulativeTsn,0),e}},x7=class b7 extends yi{static type=8;get type(){return b7.type}},v7=class w7 extends yi{static type=14;get type(){return w7.type}},S$=[$y,qy,$_,J_,X_,l7,W_,g7,x7,Vy,V_,K_,v7,Y_,zy],_$=S$.reduce((r,e)=>(r[e.type]=e,r),{});Q_=class Z_{constructor(e,t,s,n){this.requestSequence=e,this.responseSequence=t,this.lastTsn=s,this.streams=n}static type=13;get type(){return Z_.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 Z_(t,s,n,i)}},E7=class e2{constructor(e,t){this.requestSequence=e,this.newStreams=t}static type=17;get type(){return e2.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 e2(t,s)}},Ay={ReconfigResultSuccessPerformed:1,BadSequenceNumber:5},Ky=class t2{constructor(e,t){this.responseSequence=e,this.result=t}static type=16;get type(){return t2.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 t2(t,s)}},Ik={13:Q_,16:Ky,17:E7},Lt=ut("werift/sctp/sctp"),I$=24,R$=60,Rk=65535,wn=1200,vp=1,C7=2,r2=4,kk=10,k$=8,Pk=1/8,Bk=1/4,Nk=3,P$=1,B$=60,ox=2**32,N$=200,O$=30,Ok=135,Lk=7,Dk=32776,Mk=49152,L$=["new","closed","connected","connecting"],D$=class s2{constructor(e,t=5e3){this.transport=e,this.port=t,this.localPort=this.port,this.transport.onData=s=>{this.handleData(s)}}flush=new Ie;stateChanged=A$(L$);onReconfigStreams=new Ie;onReceive=new Ie;onSackReceived=async()=>{};associationState=1;started=!1;state="new";isServer=!0;isStopping=!1;isClosed=!1;hmacKey=(0,zp.randomBytes)(16);localPartialReliability=!0;localPort;localVerificationTag=Gy();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=Rk;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=Rk;localTsn=Number(Gy());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=Nk;timer1Handle;timer1Chunk;timer1Failures=0;timer2Handle;timer2Chunk;timer2Failures=0;timer3Handle;timerReconfigHandle;timerReconfigFailures=0;timerHeartbeatHandle;heartbeatInterval=O$;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 s2(e,t);return s.isServer=!1,s}static server(e,t=5e3){let s=new s2(e,t);return s.isServer=!0,s}async handleData(e){if(this.isStopped)return;let t,[,,s,n]=E$(e);if(n.filter(o=>o.type===qy.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)})},N$))}}async sendSack(){if(this.isStopped||!this.sackNeeded)return;let e=[],t;[...this.sackMisOrdered].sort().forEach(n=>{let i=(n-this.lastReceivedTsn)%ox;n===t?e[e.length-1][1]=i:e.push([i,i]),t=Wu(n)});let s=new J_(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 $y.type:this.receiveDataChunk(e);break;case qy.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 $_;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(Fy.jspack.Pack("!L",[n]));i=Buffer.concat([i,(0,zp.createHmac)("sha1",this.hmacKey).update(i).digest()]),s.params.push([Lk,i]),Lt("send initAck",s),await this.sendChunk(s).catch(o=>{Lt("send initAck failed",o.message)})}break;case $_.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 V_;for(let[n,i]of t.params)if(n===Lk){s.body=i;break}await this.sendChunk(s).catch(n=>{Lt("send echo failed",n.message)}),this.timer1Start(s),this.setState(3)}break;case J_.type:await this.receiveSackChunk(e);break;case X_.type:{let t=new l7;t.params=e.params,await this.sendChunk(t).catch(s=>{Lt("send heartbeat ack failed",s.message)})}break;case W_.type:this.setState(1);break;case g7.type:{this.timer2Cancel(),this.setState(7);let t=new x7;await this.sendChunk(t).catch(s=>{Lt("send shutdown ack failed",s.message)}),this.t2Start(t),this.setState(6)}break;case Vy.type:Lt("ErrorChunk",e.descriptions);break;case V_.type:{if(!this.isServer)return;let s=e.body,n=(0,zp.createHmac)("sha1",this.hmacKey).update(s.slice(0,4)).digest();if(s?.length!=I$||!s.slice(4).equals(n)){Lt("x State cookie is invalid");return}let i=Date.now()/1e3,o=Fy.jspack.Unpack("!L",s)[0];if(o<i-R$||o>i){let c=new Vy(0,void 0);c.params.push([Vy.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 K_;await this.sendChunk(a).catch(c=>{Lt("send cookieAck failed",c.message)}),this.setState(4)}break;case K_.type:{if(this.associationState!=3)return;this.timer1Cancel(),this.setState(4)}break;case v7.type:{if(this.associationState!=8)return;this.timer2Cancel(),this.setState(1)}break;case Y_.type:{if(this.associationState!=4)return;let t=e;for(let[s,n]of t.params){let i=Ik[s];i&&await this.receiveReconfigParam(i.parse(n))}}break;case zy.type:this.receiveForwardTsnChunk(e);break}}getExtensions(e){for(let[t,s]of e)t===Mk?this.remotePartialReliability=!0:t===Dk&&(this.remoteExtensions=[...s])}async receiveReconfigParam(e){switch(Lt("receiveReconfigParam",Ik[e.type]),e.type){case Q_.type:{let t=e,s=new Ky(t.requestSequence,Ay.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 Ky.type:{let t=e;if(t.result!==Ay.ReconfigResultSuccessPerformed)Lt("OutgoingSSNResetRequestParam failed",Object.keys(Ay).find(s=>Ay[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=Nk,this.timerReconfigFailures=0,this.reconfigQueue.length>0&&await this.transmitReconfigRequest()}}break;case E7.type:{let t=e;this._inboundStreamsCount+=t.newStreams;let s=new Ky(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&vp)===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(li(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)%ox,a.add(c)});let d=e.cumulativeTsn;for(let u of this.sentQueue){if(li(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(li(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=>li(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-Bk)*this.rttvar+Bk*Math.abs(this.srtt-e),this.srtt=(1-Pk)*this.srtt+Pk*e):(this.rttvar=e/2,this.srtt=e),this.rto=Math.max(P$,Math.min(this.srtt+4*this.rttvar,B$))}receive(e,t,s){this.onReceive.execute(e,t,s)}getInboundStream(e){return this.inboundStreams[e]||(this.inboundStreams[e]=new M$),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=>li(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 $y(0,void 0);h.flags=0,o||(h.flags=r2),f===0&&(h.flags|=C7),f===c-1&&(h.flags|=vp),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,Ok);this.reconfigQueue=e.slice(Ok);let s=new Q_(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 Y_;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 $y(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>k$)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>kk)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>kk)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 X_;e.params.push([1,Buffer.from(Fy.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(){li(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&r2||(t[s.streamId]=s.streamSeqNum)}this.sentQueue.length||(this.sentQueue=[]),e&&(this.forwardTsnChunk=new zy(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&vp)break}for(let n=s;n<this.sentQueue.length;n++){let i=this.sentQueue[n];if(i.abandoned=!0,i.retransmit=!1,i.flags&vp)break}return!0}static getCapabilities(){return new U$(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 qy;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([Mk,Buffer.from("")]),t.push(zy.type)),t.push(w$.type),e.push([Dk,Buffer.from(t)])}async sendChunk(e){if(this.state==="closed")return;if(this.remotePort===void 0)throw new Error("invalid remote port");let t=C$(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 W_;await this.sendChunk(e).catch(t=>{Lt("send abort failed",t.message)})}removeAllListeners(){Object.values(this.stateChanged).forEach(e=>e.allUnsubscribe())}},M$=class{reassembly=[];streamSequenceNumber=0;constructor(){}addChunk(r){if(this.reassembly.length===0||li(r.tsn,this.reassembly[this.reassembly.length-1].tsn)){this.reassembly.push(r);return}for(let[e,t]of T$(this.reassembly)){if(t.tsn===r.tsn)throw new Error("duplicate chunk in reassembly");if(li(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&r2),!(n.flags&C7)){if(s)break;r++;continue}if(s&&ux(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&vp){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}},U$=class{constructor(r){this.maxMessageSize=r}};qu=ut("werift:packages/webrtc/src/transport/sctp.ts"),Xu=65536,T7=class A7{constructor(e=5e3,t=Xu){this.port=e,this.maxMessageSize=t}dtlsTransport;sctp;onDataChannel=new Ie;id=(0,t7.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 D$(new j$(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===Ty&&s.length>0)switch(qu("DCEP",e,t,s),s[0]){case bk:{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]=Hy.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 F2({label:u,ordered:(i&128)===0,maxPacketLifeTime:y,maxRetransmits:h,protocol:f,id:e}),S=new H2(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,Ty,Buffer.from(Hy.jspack.Pack("!B",[xk]))]),await this.dataChannelFlush()}break;case xk:{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 vk:return s.toString("utf8");case Qz:return"";case wk:return s;case Zz: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=Jz,s=0,n=0;e.ordered||(t=128),e.maxRetransmits?(t=1,n=e.maxRetransmits):e.maxPacketLifeTime&&(t=2,n=e.maxPacketLifeTime);let i=Hy.jspack.Pack("!BBHLHH",[bk,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,Ty,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===Ty)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=wB(t);return this.assertSendableMessageSize(n),e.addBufferedAmount(n),this.dataChannelQueue.push(typeof t=="string"?[e,vk,s]:[e,wk,s]),this.sctp.associationState!==4&&qu("sctp not established",this.sctp.associationState),this.dataChannelFlush(),n};getCapabilities(){return A7.getCapabilities(this.maxMessageSize)}static getCapabilities(e=Xu){return new oE(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")))}},oE=class{constructor(r){this.maxMessageSize=r}},j$=class{constructor(r){this.dtls=r}set onData(r){this.dtls.dataReceiver=r}send=r=>this.dtls.sendData(r);close(){}},Ep=class I7{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]=H$(e),n=new I7;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=QS(o.slice(2));else if(o.startsWith("t="))n.time=o.slice(2);else if(o.startsWith("a=")){let[a,c]=ZS(o);switch(a){case"fingerprint":{let[d,u]=c?.split(" ")||[];n.dtlsFingerprints.push(new nx(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":Wy(n.group,c);break;case"msid-semantic":Wy(n.msidSemantic,c);break;case"setup":n.dtlsRole=_k[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 ax(d,Number.parseInt(c[2]),c[3],f||u);if(h.dtlsParams=new ix([...n.dtlsFingerprints],n.dtlsRole),h.iceParams=new nE({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=QS(v.slice(2));else if(v.startsWith("a=")){let[S,C]=ZS(v);switch(S){case"candidate":if(!C)throw new Error;h.iceCandidates.push(cE(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 gi({id:Number.parseInt(O),uri:K}))}break;case"fingerprint":{if(!C)throw new Error;let[O,K]=C.split(" ");h.dtlsParams?.fingerprints.push(new nx(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 oE(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=QS(K)}break;case"rtcp-mux":h.rtcpMux=!0;break;case"setup":h.dtlsParams.role=_k[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("/"),te;h.kind==="audio"&&(te=oe?Number.parseInt(oe):1);let Ee=new _a({mimeType:h.kind+"/"+z,channels:te,clockRate:Number.parseInt(Q),payloadType:Number.parseInt(O)});h.rtp.codecs.push(Ee)}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,":"),te=h.ssrc.find(Ee=>Ee.ssrc===z);te||(te=new cx({ssrc:z}),h.ssrc.push(te)),NB.includes(Q)&&(te[Q]=oe)}break;case"ssrc-group":Wy(h.ssrcGroup,C);break;case"rid":{let[O,K]=ao(C," ");h.simulcastParameters.push(new q2({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]=ZS(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 _B({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=${n2(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 R7(this.string,this.type)}toSdp(){return{type:this.type,sdp:this.string}}},ax=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=${n2(this.host)}`),this.iceCandidates.forEach(e=>{r.push(`a=candidate:${aE(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:${q_[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} ${n2(this.rtcpHost)}`),this.rtcpMux&&r.push("a=rtcp-mux")),this.ssrcGroup.forEach(e=>{r.push(`a=ssrc-group:${e.str}`)}),this.ssrc.forEach(e=>{NB.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(" ")}`}};R7=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}}};cx=class{ssrc;cname;msid;msLabel;label;constructor(r){Object.assign(this,r)}},Iy=ut("werift:packages/webrtc/src/media/rtpReceiver.ts"),dE=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 u$(this);audioRedHandler=new _P;type="receiver";uuid=(0,RB.randomUUID)().toString();tracks=[];trackBySSRC={};trackByRID={};lastSRtimestamp={};receiveLastSRTimestamp={};onPacketLost=this.nack.onPacketLost;onRtcp=new Ie;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 Hp({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===SB().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 l$(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,My.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=Fp()-this.receiveLastSRTimestamp[t];o>0&&o<65536&&(i=Yu(o*65536))}return new bx({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,My.setTimeout)(this.config.debug.receiverReportDelay),await this.dtlsTransport.sendRtcp([e])}catch(t){Iy("sendRtcp failed",t),await(0,My.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){Iy("pli not supported",{mediaSsrc:r});return}if(this.stopped)return;Iy("sendRtcpPLI",{mediaSsrc:r});let e=new tf({feedback:new Np({senderSsrc:this.rtcpSsrc,mediaSsrc:r})});try{await this.dtlsTransport.sendRtcp([e])}catch(t){Iy(t)}}handleRtcpPacket(r){switch(r.type){case sd.type:{let e=r;this.lastSRtimestamp[e.ssrc]=tE(e.senderInfo.ntpTimestamp),this.receiveLastSRTimestamp[e.ssrc]=Fp();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 h$(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=$p(s.parameters??""),a=this.codecs[o.apt];if(r.payload.length<2)return;r=CP(r,a.payloadType,i),t=this.trackBySSRC[i]}let n;if(!(s.name.toLowerCase()==="red"&&(n=C2.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()}}},op=ut("werift:packages/webrtc/src/media/router.ts"),k7=class{ssrcTable={};ridTable={};extIdUriMap={};constructor(){}registerRtpSender(r){this.ssrcTable[r.ssrc]=r}registerRtpReceiver(r,e){op("registerRtpReceiver",e),this.ssrcTable[e]=r}registerRtpReceiverBySsrc(r,e){op("registerRtpReceiverBySsrc",e),e.encodings.filter(t=>t.ssrc!=null).forEach((t,s)=>{this.registerRtpReceiver(r.receiver,t.ssrc),r.addTrack(new Hp({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;op("registerRtpReceiverByRid",e),r.addTrack(new Hp({rid:e.rid,kind:r.kind,id:r.sender.trackId,remote:!0,codec:s})),this.ridTable[e.rid]=r.receiver}routeRtp=r=>{let e=dP(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 dE).find(o=>o.trackBySSRC[r.header.ssrc]),t&&(op("simulcast register receiver by ssrc",r.header.ssrc),this.registerRtpReceiver(t,r.header.ssrc),t.handleRtpBySsrc(r,e))),!t){op("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 Mp.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 Op.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))}},q$=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 Bp(e)}get sendBitrate(){let r=this.lastPacketSentAtMs-this.firstPacketSentAtMs,e=this.totalSize/r*8*1e3;return Bp(e)}},zu=20,z$=10,$$=class{congestion=!1;onAvailableBitrate=new Ie;onCongestion=new Ie;onCongestionScore=new Ie;congestionCounter=0;cumulativeResult=new q$;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=eE()-this.cumulativeResult.firstPacketSentAtMs;t>1e3&&(this.cumulativeResult.reset(),this.congestionCounter<zu?this.congestionCounter++:this.congestionScore<z$&&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=Bp(zu/2)+1,n=Bp(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}},e_=ut("werift:packages/webrtc/src/media/rtpSender.ts"),Uk=128,jk=.85,P7=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=a2.jspack.Unpack("!L",(0,o2.randomBytes)(4))[0];rtxSsrc=a2.jspack.Unpack("!L",(0,o2.randomBytes)(4))[0];streamId=(0,c2.randomUUID)().toString();trackId=(0,c2.randomUUID)().toString();onReady=new Ie;onRtcp=new Ie;onPictureLossIndication=new Ie;onGenericNack=new Ie;senderBWE=new $$;cname;mid;rtpStreamId;repairedRtpStreamId;rtxPayloadType;rtxSequenceNumber=h2();redRedundantPayloadType;_redDistance=2;redEncoder=new SP(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=$p(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),e_("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,d2.setTimeout)(500+Math.random()*1e3,void 0,{signal:this.rtcpCancel.signal});let r=[new sd({ssrc:this.ssrc,senderInfo:new E2({ntpTimestamp:this.ntpTimestamp,rtpTimestamp:this.rtpTimestamp,packetCount:this.packetCount,octetCount:this.octetCount})})];this.lastSRtimestamp=tE(this.ntpTimestamp),this.lastSentSRTimestamp=Fp(),this.cname&&r.push(new Mp({chunks:[new S2({source:this.ssrc,items:[new _2({type:1,text:this.cname})]})]}));try{await this.dtlsTransport.sendRtcp(r)}catch(e){e_("sendRtcp failed",e),await(0,d2.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=[],e_("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=FB(),n=[...e.extensions];e.extensions=this.headerExtensions.map(d=>{let u=(()=>{switch(d.uri){case Yt.sdesMid:return this.mid?uP(this.mid):void 0;case Yt.sdesRTPStreamID:return this.rtpStreamId?fP(this.rtpStreamId):void 0;case Yt.repairedRtpStreamId:return this.repairedRtpStreamId?lP(this.repairedRtpStreamId):void 0;case Yt.transportWideCC:return this.dtlsTransport.transportSequenceNumber=Ur(this.dtlsTransport.transportSequenceNumber,1),hP(this.dtlsTransport.transportSequenceNumber);case Yt.absSendTime:return pP(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%Uk]=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=eE(),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=Fp()-this.lastSentSRTimestamp-t.dlsr/65536;this.rtt===void 0?this.rtt=s:this.rtt=jk*this.rtt+(1-jk)*s}});break;case rd.type:{let e=r;switch(e.feedback.count){case Dp.count:{let t=e.feedback;this.senderBWE.receiveTWCC(t)}break;case Lp.count:{let t=e.feedback;t.lost.forEach(async s=>{let n=this.rtpCache[s%Uk];n&&n.header.sequenceNumber!==s&&(n=void 0),n&&(this.rtxPayloadType!=null&&(n=TP(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 Op.count:{let t=e.feedback;this.receiverEstimatedMaxBitrate=t.bitrate}break;case Np.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}},V$=ut("werift:packages/webrtc/src/transport/sctpManager.ts"),K$=class{sctpTransport;sctpRemotePort;dataChannelsOpened=0;dataChannelsClosed=0;dataChannels=[];onDataChannel=new Ie;constructor(){}createSctpTransport(r){let e=new T7(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 F2({id:s.id,label:r,maxPacketLifeTime:s.maxPacketLifeTime,maxRetransmits:s.maxRetransmits,negotiated:s.negotiated,ordered:s.ordered,protocol:s.protocol}),i=new H2(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(),V$("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}},N7=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 ax(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 cx({ssrc:r.sender.ssrc,cname:this.cname})],r.options.simulcast&&(t.simulcastParameters=r.options.simulcast.map(s=>new q2(s))),t.rtp.codecs.find(s=>s.name.toLowerCase()==="rtx")&&(t.ssrc.push(new cx({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 ax("application",Sk,"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=e$,r.port=Sk,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=Ep.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 Ep;i2("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 Ep;i2("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,Z2(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)}},ap=ut("werift:packages/webrtc/src/transport/secureTransportManager.ts"),W$=class{connectionState="new";iceConnectionState="new";iceGatheringState="new";certificate;iceGatheringStateChange=new Ie;iceConnectionStateChange=new Ie;onIceCandidate=new Ie;connectionStateChange=new Ie;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 rE(r.keyPem,r.certPem,r.signatureHash)}createTransport(){let r=this.iceTransports.find(n=>n.state!=="closed"),e=new QB({...qB(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 JB(e);return t.onStateChange.subscribe(()=>{this.updateIceConnectionState()}),new z_(this.config,t,this.certificate,G$)}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=sE.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):ap("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&&(ap("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?ap("skipping ICE gathering for bundled connection"):await Promise.allSettled(this.iceTransports.map(t=>t.gather())).catch(t=>{ap("gatherCandidates failed",t)})}setConnectionState(r){ap("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 z_.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()}},G$=[Ek.SRTP_AEAD_AES_128_GCM,Ek.SRTP_AES128_CM_HMAC_SHA1_80],Sn=ut("werift:packages/webrtc/src/peerConnection.ts"),X$=class extends j2{cname=(0,B7.randomUUID)().toString();config=O7();signalingState="stable";negotiationneeded=!1;needRestart=!1;router=new k7;sdpManager;transceiverManager;sctpManager;secureManager;isClosed=!1;shouldNegotiationneeded=!1;remoteBundleNegotiated=!1;iceGatheringStateChange=new Ie;iceConnectionStateChange=new Ie;signalingStateChange=new Ie;connectionStateChange=new Ie;onDataChannel=new Ie;onRemoteTransceiverAdded=new Ie;onTransceiverAdded=new Ie;onIceCandidate=new Ie;onNegotiationneeded=new Ie;onTrack=new Ie;ondatachannel;onicecandidate;onicecandidateerror;onicegatheringstatechange;onnegotiationneeded;onsignalingstatechange;ontrack;onconnectionstatechange;oniceconnectionstatechange;constructor(r={}){super(),this.setConfiguration(r),this.sdpManager=new N7({cname:this.cname,bundlePolicy:this.config.bundlePolicy}),this.transceiverManager=new L7(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 K$,this.sctpManager.onDataChannel.subscribe(e=>{this.onDataChannel.execute(e);let t={channel:e};this.ondatachannel?.(t),this.emit("datachannel",t)}),this.secureManager=new W$({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(zB(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 yk([...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 yk(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=Z2(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 Ep&&(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 OB(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"))}},u2=(r,e)=>r.find(t=>t.mimeType.toLowerCase()===e.mimeType.toLowerCase())?e:void 0;Y$=O7(),J$=ut("werift:packages/webrtc/src/media/rtpTransceiverManager.ts"),L7=class{constructor(r,e,t){this.cname=r,this.config=e,this.router=t}transceivers=[];onTransceiverAdded=new Ie;onRemoteTransceiverAdded=new Ie;onTrack=new Ie;onNegotiationNeeded=new Ie;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 P7(r),o=new dE(this.config,s,i.ssrc),a=new LB(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&&Uy.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&&Uy.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!!r$.includes(r.direction);case"sendonly":return!!Uy.includes(r.direction);case"sendrecv":return!![X2,G2,W2].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=$p(n.parameters??""),o=s[i.apt];return o&&r.ssrc.length===2&&(o.rtx=new EB({ssrc:r.ssrc[1].ssrc})),s}return s[n.payloadType]=new CB({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=u2(c,a);if(!d)return!1;if(d?.name.toLowerCase()==="rtx"){let f=$p(d.parameters??"").apt,h=e.rtp.codecs.find(y=>y.payloadType===f);return h?!!u2(c,h):!1}return!0}),J$("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=jB(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 MB({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()}},Q$=["stable","have-local-offer","have-remote-offer","have-local-pranswer","have-remote-pranswer","closed"],Z$=["closed","failed","disconnected","new","connecting","connected"]});var KV={};Cf(KV,{App:()=>nN,DEFAULT_DOC_SYNC_TIMEOUT_MS:()=>bE,RequestAbortError:()=>yo,RequestCancelledError:()=>gf,RequestDocSyncError:()=>mf,RequestError:()=>In,RequestTimeoutError:()=>pf,Session:()=>yf,createStore:()=>aN,videoStream:()=>cN});module.exports=Px(KV);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 W7=Ge(fb());var Nb=Ge(a6(),1);function _x(){return typeof window>"u"&&typeof process<"u"&&process.versions!=null&&process.versions.node!=null}function j7(){return _x()?"Chrome111":void 0}var eV=["RTCSessionDescription","RTCIceCandidate","RTCRtpReceiver","RTCRtpSender","RTCRtpTransceiver","RTCDataChannel","MediaStream","MediaStreamTrack"],Sx=null;function H7(){return _x()?Sx||(Sx=tV(),Sx):Promise.resolve()}async function tV(){let r=globalThis;if(typeof r.WebSocket>"u")try{let e=await import("ws"),t=e.default??e;r.WebSocket=t}catch(e){U7("WebSocket",e)}if(typeof r.RTCPeerConnection>"u")try{let e=await Promise.resolve().then(()=>(M7(),D7));rV(r,e)}catch(e){U7("werift",e)}}function rV(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 eV)e[v]!=null&&typeof r[v]>"u"&&(r[v]=e[v])}function U7(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 F7="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function sV(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 Ex(r=16){let e=sV(r),t="";for(let s=0;s<r;s++)t+=F7[e[s]%F7.length];return t}var q7=[1e3,2e3,4e3,8e3,3e4],z7=5,nV=15e3,iV=2e3,oV=6e3,aV=2,cV=750,dV=3,$7=[1e3,2e3,4e3],uV=15e3,uE="control",G7=0,X7=1,fE=64;function fV(r,e){if(r===uE){let n=new Uint8Array(1+e.length);return n[0]=G7,n.set(e,1),n}let t=new TextEncoder().encode(r);if(t.length<1||t.length>fE)throw new Error(`[urun] doc key length out of range (1..${fE}): ${t.length}`);let s=new Uint8Array(3+t.length+e.length);return s[0]=X7,s[1]=t.length>>>8&255,s[2]=t.length&255,s.set(t,3),s.set(e,3+t.length),s}function lV(r){if(r.length===0)return{docKey:uE,payload:r.slice()};let e=r[0];if(e===G7)return{docKey:uE,payload:r.slice(1)};if(e===X7){if(r.length<3)return null;let t=r[1]<<8|r[2];if(t<1||t>fE||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 hV={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"},pV=8e3,V7=[{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 Nb.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=mV()),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=yV(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?aV:1;for(let c=0;c<a;c++)if(c>0&&(await K7(cV),i()),await o())return;if(this._resolveConnection)for(let c=0;c<dV;c++){this._setState("reconnecting"),await K7($7[Math.min(c,$7.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(fV(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=lV(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&&hV[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){_x()&&await H7();let t=j7(),s=new W7.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??V7}),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")},pV))}_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??V7}),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?iV:e}_mediaStallTimeoutMs(){let e=this._options.mediaLiveness?.stallTimeoutMs;return e===void 0?oV: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 gV(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>=z7){this._setState("failed"),this._emitError(new Error(`Failed after ${z7} attempts`));return}let t=q7[Math.min(this._reconnectAttempts,q7.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"))},nV),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},uV))}_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 K7(r){return new Promise(e=>setTimeout(e,r))}function mV(){return Ex()}async function gV(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 yV(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 xV="session-api.prod.cloud.urun.sh",bV=["https://session-api.use2.prod.cloud.urun.sh","https://session-api.usw2.prod.cloud.urun.sh"];function Cx(r){return r.trim().replace(/\/+$/,"")}function Y7(r,e){let t=[],s=n=>{if(!n)return;let i=Cx(n);i&&!t.includes(i)&&t.push(i)};s(r);for(let n of e??[])s(n);for(let n of IV(r))s(n);return t}var vV=120,wV=1e3,SV=3;function _V(r){if(!r)return null;try{let e=new URL(r),t=e.pathname.replace(/\/api\/sessions\/create\/?$/,"");return Cx(`${e.origin}${t}`)}catch{return null}}async function J7(r){let e=Y7(r.baseUrl,r.fallbackUrls),t=null,s=e.length>1;for(let n of e)try{return await EV(n,r,{pollAttempts:vV,retryAfterLimitMs:s?wV: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 EV(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 hE(e),i=void 0;let u=s?await fetch(`${o}/api/session-requests/${encodeURIComponent(s)}`,{headers:lE(e,n)}):await fetch(`${o}/api/sessions/create`,{method:"POST",redirect:"manual",headers:{...lE(e,n),"Content-Type":"application/json","Idempotency-Key":e.idempotencyKey},body:JSON.stringify(CV(e))});if(!s&&(u.status===307||u.status===308)){let v=_V(u.headers.get("location"));if(v&&v!==o&&a<SV){a+=1,o=v;continue}throw new Error(`[urun] session create redirected from ${o} without a usable target`)}let f=await Z7(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(!eN(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 AV(TV(u,f,t.retryAfterLimitMs));continue}if((u.status===401||u.status===403)&&e.getAccessToken){let v=n??"";c.add(v);let S=await hE(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 lE(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 hE(r,e){return r.getAccessToken?await r.getAccessToken(e)??void 0:r.jwt}function CV(r){return{app:r.app,function:r.functionName,gpus:1,idempotency_key:r.idempotencyKey}}async function Q7(r){let e=Y7(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 hE(n),o=await fetch(`${Cx(s)}/api/sessions/${encodeURIComponent(r.sessionId)}/viewer-connect`,{headers:lE(n,i)});if(!o.ok)throw new Error(`[urun] viewer-connect for ${r.sessionId} failed: HTTP ${o.status}`);let a=await Z7(o);if(!a.ws_url||!eN(a.ws_url))throw new cd(`[urun] viewer-connect returned no usable ws_url for ${r.sessionId}`);return{baseUrl:Cx(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 Z7(r){try{let e=await r.json();return e&&typeof e=="object"?e:{}}catch{return{}}}function TV(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 AV(r){return new Promise(e=>setTimeout(e,r))}var cd=class extends Error{};function eN(r){try{let e=new URL(r);return e.protocol==="ws:"||e.protocol==="wss:"}catch{return!1}}function IV(r){try{return new URL(r).hostname!==xV?[]:bV}catch{return[]}}var hf=Ge(require("yjs")),tN=Symbol("urun:doc:remote"),RV=Symbol("urun:doc:local");function dd(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}var Tx="$bytes";function kV(r){return r instanceof Uint8Array||r instanceof ArrayBuffer}function PV(r){if(!dd(r))return!1;let e=Object.keys(r);return e.length===1&&e[0]===Tx&&typeof r[Tx]=="string"}function BV(r){return r instanceof ArrayBuffer?new Uint8Array(r):r}function NV(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 OV(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 pE(r){if(kV(r))return{[Tx]:NV(BV(r))};if(Array.isArray(r))return r.map(pE);if(dd(r)){let e={};for(let[t,s]of Object.entries(r))e[t]=pE(s);return e}return r}function r0(r){if(PV(r))return OV(r[Tx]);if(Array.isArray(r))return r.map(r0);if(dd(r)){let e={};for(let[t,s]of Object.entries(r))e[t]=r0(s);return e}return r}function mE(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]=mE(i,n):t[s]=n}return t}var sN=Symbol("urun:doc:path-absent");function LV(r,e){let t=e.split("."),s=r;for(let n of t){if(s===null||typeof s!="object"||!(n in s))return sN;s=s[n]}return s}function rN(r){return r===void 0?r:JSON.parse(JSON.stringify(r))}var Ax=class{_doc=new hf.Doc;_root=this._doc.getMap("session");_listeners=new Set;_key;_sessionId;_transport;_transportUnsubs=[];_synced;_pendingPatches=[];_syncWaiters=new Set;_texts=new Map;_observer=()=>this.notify();_updateHandler=(e,t)=>{t!==tN&&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}get synced(){return this._synced}onSynced(e){return this._synced?(e(),()=>{}):(this._syncWaiters.add(e),()=>this._syncWaiters.delete(e))}set(e){if(e=pE(e),!this._synced){this._pendingPatches.push(rN(e)),this.notify();return}this.applyPatch(e)}get(e,t){let s=this.snapshot();if(!e)return r0(s);let n=LV(s,e);return n===sN?t:r0(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 gE(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(),this._syncWaiters.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,tN),!this._synced){this._synced=!0;let t=this._pendingPatches.splice(0);for(let n of t)this.applyPatch(n);let s=[...this._syncWaiters];this._syncWaiters.clear();for(let n of s)n()}}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)?mE(i,n):rN(n);JSON.stringify(o)!==JSON.stringify(i)&&this._root.set(s,o)}},RV)}snapshot(){let e=this._root.toJSON();for(let t of this._pendingPatches)e=mE(e,t);return e}notify(){let e=r0(this.snapshot());for(let t of this._listeners)t(e)}},gE=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 In=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 In{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)}},mf=class extends In{timeoutMs;constructor(e,t){super(`[urun] request doc-sync did not establish within ${e}ms \u2014 the request was never delivered to the runtime (the session doc never synced with the session-server; check the doc-sync transport / connection)`,{requestId:t}),this.name="RequestDocSyncError",this.timeoutMs=e,Object.setPrototypeOf(this,new.target.prototype)}},yo=class extends In{constructor(e){super("[urun] request aborted",{requestId:e}),this.name="RequestAbortError",Object.setPrototypeOf(this,new.target.prototype)}},gf=class extends In{constructor(e){super("[urun] request cancelled: session disconnected",{requestId:e}),this.name="RequestCancelledError",Object.setPrototypeOf(this,new.target.prototype)}};var DV=new Set,MV="rpc",UV="llm",bE=3e4,jV="llm-resp";function HV(r){return`${jV}:${r}`}function yE(){return Ex()}function FV(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 qV(r,e,t,s,n,i,o,a,c){let d=[],u=null,f=!1,h=null,y=!1,v,S,C=new Promise((ne,T)=>{v=ne,S=T});C.catch(()=>{});let O=i(),K=null,z=null,Q=null,oe=null,te=!0,Ee=()=>{Q&&(clearTimeout(Q),Q=null),oe&&(oe(),oe=null)},ge=()=>{te=!1,Ee(),K?.(),K=null,z?.(),z=null,o?.removeEventListener("abort",$),O.dispose(),y&&r.set({requests:{[e]:null}})},Y=()=>{if(u){if(d.length>0){let ne=u;u=null,ne.resolve({value:d.shift(),done:!1})}else if(h!==null){let ne=u;u=null,ne.reject(h)}else if(f){let ne=u;u=null,ne.resolve({value:void 0,done:!0})}}},Ze=ne=>{f||(d.push(ne),Y())},vt=ne=>{f||(h=ne,f=!0,S(ne),ge(),Y())},Fe=ne=>{f||(f=!0,v(ne),ge(),Y())},$=()=>vt(new yo(e)),V=ne=>{if(!(f||!ne||typeof ne!="object"))switch(ne.t){case"delta":typeof ne.delta=="string"&&Ze(ne.delta);break;case"response":Fe(ne.body);break;case"error":{let{message:T,code:R}=FV(ne.body);vt(new In(T,{requestId:e,code:ne.code??R}));break}}},H=()=>{let ne=O.messages()[Symbol.asyncIterator]();K=()=>{ne.return?.(void 0)};let T=()=>{te&&ne.next().then(R=>{if(te){if(R.done){f||Fe(void 0);return}V(R.value),T()}},R=>{te&&vt(R)})};T()},me=()=>{if(!y){if(y=!0,o){if(o.aborted){vt(new yo(e));return}o.addEventListener("abort",$,{once:!0})}z=a?.(ne=>vt(ne))??null,H(),r.set({requests:{[e]:{payload:t,consumer_id:s,stream:n}}}),c&&c>0&&!r.synced&&(Q=setTimeout(()=>{Q=null,!f&&!r.synced&&vt(new mf(c,e))},c),oe=r.onSynced(()=>Ee()))}};return{deltas:{[Symbol.asyncIterator](){return{next(){if(me(),d.length>0)return Promise.resolve({value:d.shift(),done:!1});if(h!==null){let ne=h;return h=null,Promise.reject(ne)}return f?Promise.resolve({value:void 0,done:!0}):new Promise((ne,T)=>{u={resolve:ne,reject:T}})},return(){return f||(f=!0,v(void 0),ge()),Promise.resolve({value:void 0,done:!0})},throw(ne){return f||(f=!0,S(ne),ge()),Promise.reject(ne)}}}},body:C,start:me}}function zV(r,e){return[`streams/${r}/${e}`,`streams/${r}/*`]}var xE=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;_replay=[];_disposed=!1;messages(){this._ensureSubscribed();let e=this;return{[Symbol.asyncIterator](){let t=[...e._replay],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 zV(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];this._replay.push(i);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)}},yf=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 Q7({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 xE(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 Ax(e,this._sessionId,DV.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(MV),n=yE();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 In(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,i){let o=this.doc(UV);return qV(o,e,t,this._transport.consumerId,s,()=>this.stream(HV(e)),n,a=>(this._activeRequests.add(a),()=>this._activeRequests.delete(a)),i??bE)}requestStream(e,t={}){let s=yE();return this._consumeResponse(s,e,!0,t.signal,t.docSyncTimeout).deltas}complete(e,t={}){let s=yE(),n=this._consumeResponse(s,e,!1,t.signal,t.docSyncTimeout);return n.start(),n.body}disconnect(){let e=Array.from(this._activeRequests);this._activeRequests.clear();for(let t of e)try{t(new gf)}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 $V=new Set(["then","catch","finally","toJSON",Symbol.toPrimitive]);function nN(r,e){return new Proxy({},{get(t,s){if(!($V.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 yf(a,c,d),f=async h=>{let y=await J7({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 iN=3e4,oN="stream:",vE=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=`${oN}${e}`;return this._multiplexer.on(s,n=>{t(n)})}emit(e,t){let s=`${oN}${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 ${iN}ms`)))},iN);this._pendingRpc.set(i,{resolve:s,reject:n,timer:o}),this._ws.send(JSON.stringify({rpcId:i,type:e,...t}))})}};function aN(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 vE(n,i)}var VV='video/mp4; codecs="avc1.42E01E"';function cN(r,e){let t=e?.codec??VV,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,DEFAULT_DOC_SYNC_TIMEOUT_MS,RequestAbortError,RequestCancelledError,RequestDocSyncError,RequestError,RequestTimeoutError,Session,createStore,videoStream});
|
|
7
|
+
`}});var ve=C(le=>{"use strict";var De=Bn(),Ja=Wn(),Xa=Zt();le.grammar=Xa;le.write=Ja;le.parse=De.parse;le.parseParams=De.parseParams;le.parseFmtpConfig=De.parseFmtpConfig;le.parsePayloads=De.parsePayloads;le.parseRemoteCandidates=De.parseRemoteCandidates;le.parseImageAttributes=De.parseImageAttributes;le.parseSimulcastStreamList=De.parseSimulcastStreamList});var Ie=C(es=>{"use strict";Object.defineProperty(es,"__esModule",{value:!0});es.parse=ec;var Za=new RegExp("^[LS]([1-9]\\d{0,1})T([1-9]\\d{0,1})");function ec(s){let e=Za.exec(s??"");return e?{spatialLayers:Number(e[1]),temporalLayers:Number(e[2])}:{spatialLayers:1,temporalLayers:1}}});var Kn=C(Ce=>{"use strict";Object.defineProperty(Ce,"__esModule",{value:!0});Ce.OfferMediaSection=Ce.AnswerMediaSection=Ce.MediaSection=void 0;var tc=ve(),Hn=ke(),yt=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=yt;var ts=class extends yt{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:Gn(p),rate:p.clockRate};p.channels>1&&(l.encoding=p.channels),this._mediaObject.rtp.push(l);let u=Hn.clone(p.parameters)??{},m=Hn.clone(p.rtcpFeedback)??[];if(d){let{opusStereo:h,opusFec:g,opusDtx:_,opusMaxPlaybackRate:y,opusMaxAverageBitrate:x,opusPtime:P,opusNack:k,videoGoogleStartBitrate:I,videoGoogleMaxBitrate:he,videoGoogleMinBitrate:ae}=d,Y=a.codecs.find(fe=>fe.payloadType===p.payloadType);switch(p.mimeType.toLowerCase()){case"audio/opus":case"audio/multiopus":{h!==void 0&&(Y.parameters["sprop-stereo"]=h?1:0,u.stereo=h?1:0),g!==void 0&&(Y.parameters.useinbandfec=g?1:0,u.useinbandfec=g?1:0),_!==void 0&&(Y.parameters.usedtx=_?1:0,u.usedtx=_?1:0),y!==void 0&&(u.maxplaybackrate=y),x!==void 0&&(u.maxaveragebitrate=x),P!==void 0&&(Y.parameters.ptime=P,u.ptime=P),k||(Y.rtcpFeedback=Y.rtcpFeedback.filter(fe=>fe.type!=="nack"||fe.parameter),m=m.filter(fe=>fe.type!=="nack"||fe.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),he!==void 0&&(u["x-google-max-bitrate"]=he),ae!==void 0&&(u["x-google-min-bitrate"]=ae);break}}}let f={payload:p.payloadType,config:""};for(let h of Object.keys(u))f.config&&(f.config+=";"),f.config+=`${h}=${u[h]}`;f.config&&this._mediaObject.fmtp.push(f);for(let h of m)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=tc.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=ts;var rs=class extends yt{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 f of c.codecs){let h={payload:f.payloadType,codec:Gn(f),rate:f.clockRate};f.channels>1&&(h.encoding=f.channels),this._mediaObject.rtp.push(h);let g={payload:f.payloadType,config:""};for(let _ of Object.keys(f.parameters??{}))g.config&&(g.config+=";"),g.config+=`${_}=${f.parameters[_]}`;g.config&&this._mediaObject.fmtp.push(g);for(let _ of f.rtcpFeedback)this._mediaObject.rtcpFb.push({payload:f.payloadType,type:_.type,subtype:_.parameter})}this._mediaObject.payloads=c.codecs.map(f=>f.payloadType).join(" "),this._mediaObject.ext=[];for(let f of c.headerExtensions)this._mediaObject.ext.push({uri:f.uri,value:f.id});this._mediaObject.rtcpMux="rtcp-mux",this._mediaObject.rtcpRsize="rtcp-rsize";let l=c.encodings[0],u=l.ssrc,m=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}),m&&(c.rtcp.cname&&this._mediaObject.ssrcs.push({id:m,attribute:"cname",value:c.rtcp.cname}),u&&this._mediaObject.ssrcGroups.push({semantics:"FID",ssrcs:`${u} ${m}`}));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=rs;function Gn(s){let t=new RegExp("^(audio|video)/(.+)","i").exec(s.mimeType);if(!t)throw new TypeError("invalid codec.mimeType");return t[2]}});var rt=C(rr=>{"use strict";Object.defineProperty(rr,"__esModule",{value:!0});rr.RemoteSdp=void 0;var rc=ve(),sc=z(),er=Kn(),nc=ns(),ic=["av1","h264"],tr=new sc.Logger("RemoteSdp"),ss=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${nc.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){tr.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){tr.debug("updateDtlsRole() [role:%s]",e),this._dtlsParameters.role=e;for(let t of this._mediaSections)t.setDtlsRole(e)}setSessionExtmapAllowMixed(){tr.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 er.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=>ic.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 er.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?(tr.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 er.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 er.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++,rc.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(" "))}};rr.RemoteSdp=ss});var st=C(Le=>{"use strict";Object.defineProperty(Le,"__esModule",{value:!0});Le.extractRtpCapabilities=oc;Le.extractDtlsParameters=ac;Le.getCname=cc;Le.applyCodecParameters=dc;Le.addHeaderExtension=pc;var Qn=ve();function oc({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 ac({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 cc({offerMediaObject:s}){let e=(s.ssrcs??[]).find(t=>t.attribute==="cname");return e?e.value:""}function dc({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 pc({offerMediaObject:s,headerExtensionUri:e,headerExtensionId:t}){s.ext||(s.ext=[]),s.ext.push({uri:e,value:t})}});var nt=C(sr=>{"use strict";Object.defineProperty(sr,"__esModule",{value:!0});sr.getRtpEncodings=lc;sr.addLegacySimulcast=uc;function lc({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 uc({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],m=p[l];s.ssrcs.push({id:m,attribute:"cname",value:c}),s.ssrcs.push({id:m,attribute:"msid",value:`${r} ${n}`}),s.ssrcGroups.push({semantics:"FID",ssrcs:`${u} ${m}`})}}});var it=C(bt=>{"use strict";Object.defineProperty(bt,"__esModule",{value:!0});bt.addNackSupportForOpus=hc;bt.addHeaderExtensionSupport=fc;bt.getMsidStreamIdAndTrackId=mc;function hc(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 fc(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 mc(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 Zn=C(nr=>{"use strict";Object.defineProperty(nr,"__esModule",{value:!0});nr.Chrome111=void 0;var ue=ve(),gc=G(),_c=z(),St=ce(),vc=X(),wc=Ie(),yc=rt(),Rt=st(),Yn=nt(),is=it(),T=new _c.Logger("Chrome111"),Jn="Chrome111",Xn={OS:65535,MIS:65535},os=class s extends gc.EnhancedEventEmitter{_closed=!1;_direction;_remoteSdp;_getSendExtendedRtpCapabilities;_forcedLocalDtlsRole;_pc;_mapMidTransceiver=new Map;_sendStream=new MediaStream;_hasDataChannelMediaSection=!1;_nextSendSctpStreamId=0;_transportReady=!1;static createFactory(){return{name:Jn,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=ue.parse(r.sdp);return s.getLocalRtpCapabilities(n)}catch(r){try{t?.close()}catch{}throw t=void 0,r}},getNativeSctpCapabilities:async()=>(T.debug("getNativeSctpCapabilities()"),{numStreams:Xn})}}static getLocalRtpCapabilities(e,t=[]){let r=Rt.extractRtpCapabilities({sdpObject:e});St.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(),T.debug("constructor()"),this._direction=e,this._remoteSdp=new yc.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 Jn}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,wc.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=ue.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 m=s.getLocalRtpCapabilities(l,u),f=this._getSendExtendedRtpCapabilities(m),h=St.getSendingRtpParameters(e.kind,f);h.codecs=St.reduceCodecs(h.codecs,o);let g=St.getSendingRemoteRtpParameters(e.kind,f);if(g.codecs=St.reduceCodecs(g.codecs,o),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:l}),i?.absCaptureTime){let P=l.media[c.idx];Rt.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:ue.write(l)}}T.debug("send() | calling pc.setLocalDescription() [offer:%o]",p),await this._pc.setLocalDescription(p);let _=d.mid;h.mid=_,l=ue.parse(this._pc.localDescription.sdp);let y=l.media[c.idx];if(h.rtcp.cname=Rt.getCname({offerMediaObject:y}),h.msid=`${t??this._sendStream.id} ${e.id}`,!r)h.encodings=Yn.getRtpEncodings({offerMediaObject:y,codecs:h.codecs});else if(r.length===1){let P=Yn.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%Xn.MIS,!this._hasDataChannelMediaSection){let i=await this._pc.createOffer(),o=ue.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:m}=is.getMsidStreamIdAndTrackId(p.msid);this._remoteSdp.receive({mid:u,kind:d,offerRtpParameters:p,streamId:l??m??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=ue.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);Rt.applyCodecParameters({offerRtpParameters:d,answerMediaObject:l})}i={type:"answer",sdp:ue.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(),m=ue.parse(u.sdp),f=m.media.find(h=>h.type==="application");f.maxMessageSize=e,this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:m}),u={type:"answer",sdp:ue.write(m)},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=ue.parse(this._pc.localDescription.sdp));let r=Rt.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 vc.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.Chrome111=os});var ri=C(ir=>{"use strict";Object.defineProperty(ir,"__esModule",{value:!0});ir.Chrome74=void 0;var Z=ve(),bc=z(),Sc=G(),Ct=ce(),Rc=X(),Cc=Ie(),Tc=rt(),Tt=st(),as=nt(),cs=it(),S=new bc.Logger("Chrome74"),ei="Chrome74",ti={OS:1024,MIS:1024},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:ei,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:ti})}}static getLocalRtpCapabilities(e,t=[]){let r=Tt.extractRtpCapabilities({sdpObject:e});Ct.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(),S.debug("constructor()"),this._direction=e,this._remoteSdp=new Tc.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 ei}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),m=this._getSendExtendedRtpCapabilities(u),f=Ct.getSendingRtpParameters(e.kind,m);f.codecs=Ct.reduceCodecs(f.codecs,o);let h=Ct.getSendingRemoteRtpParameters(e.kind,m);h.codecs=Ct.reduceCodecs(h.codecs,o),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:p});let g=!1,_=(0,Cc.parse)((r??[{}])[0].scalabilityMode),y;r?.length===1&&_.spatialLayers>1&&f.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],as.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],Tt.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(f.mid=x,p=Z.parse(this._pc.localDescription.sdp),y=p.media[a.idx],f.rtcp.cname=Tt.getCname({offerMediaObject:y}),f.msid=`${t??this._sendStream.id} ${e.id}`,!r)f.encodings=as.getRtpEncodings({offerMediaObject:y,codecs:f.codecs});else if(r.length===1){let k=as.getRtpEncodings({offerMediaObject:y,codecs:f.codecs});Object.assign(k[0],r[0]),g&&(k=[k[0]]),f.encodings=k}else f.encodings=r;if(f.encodings.length>1&&(f.codecs[0].mimeType.toLowerCase()==="video/vp8"||f.codecs[0].mimeType.toLowerCase()==="video/h264"))for(let k of f.encodings)k.scalabilityMode?k.scalabilityMode=`L1T${_.temporalLayers}`:k.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:y,reuseMid:a.reuseMid,offerRtpParameters:f,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:f,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%ti.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:m}=cs.getMsidStreamIdAndTrackId(p.msid);this._remoteSdp.receive({mid:u,kind:d,offerRtpParameters:p,streamId:l??m??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);Tt.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(),m=Z.parse(u.sdp),f=m.media.find(h=>h.type==="application");f.maxMessageSize=e,this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:m}),u={type:"answer",sdp:Z.write(m)},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=Tt.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 Rc.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')}};ir.Chrome74=ds});var ai=C(ar=>{"use strict";Object.defineProperty(ar,"__esModule",{value:!0});ar.Firefox120=void 0;var we=ve(),Ec=G(),kc=z(),si=X(),Et=ce(),xc=Ie(),Pc=rt(),or=st(),ni=nt(),Dc=it(),E=new kc.Logger("Firefox120"),ii="Firefox120",oi={OS:16,MIS:2048},ps=class s extends Ec.EnhancedEventEmitter{_closed=!1;_direction;_remoteSdp;_getSendExtendedRtpCapabilities;_pc;_mapMidTransceiver=new Map;_sendStream=new MediaStream;_hasDataChannelMediaSection=!1;_nextSendSctpStreamId=0;_transportReady=!1;static createFactory(){return{name:ii,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=we.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:oi})}}static getLocalRtpCapabilities(e){let t=or.extractRtpCapabilities({sdpObject:e});return Et.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 Pc.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 ii}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 si.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=we.parse(c.sdp);d.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();let p=s.getLocalRtpCapabilities(d),l=this._getSendExtendedRtpCapabilities(p),u=Et.getSendingRtpParameters(e.kind,l);u.codecs=Et.reduceCodecs(u.codecs,i);let m=Et.getSendingRemoteRtpParameters(e.kind,l);m.codecs=Et.reduceCodecs(m.codecs,i),this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:d});let f=(0,xc.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=we.parse(this._pc.localDescription.sdp);let g=d.media[d.media.length-1];if(u.rtcp.cname=or.getCname({offerMediaObject:g}),u.msid=`${t??this._sendStream.id} ${e.id}`,!r)u.encodings=ni.getRtpEncodings({offerMediaObject:g,codecs:u.codecs});else if(r.length===1){let y=ni.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${f.temporalLayers}`:y.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:g,offerRtpParameters:u,answerRtpParameters:m,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%oi.MIS,!this._hasDataChannelMediaSection){let i=await this._pc.createOffer(),o=we.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:m}=Dc.getMsidStreamIdAndTrackId(p.msid);this._remoteSdp.receive({mid:u,kind:d,offerRtpParameters:p,streamId:l??m??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=we.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);or.applyCodecParameters({offerRtpParameters:d,answerMediaObject:l}),i={type:"answer",sdp:we.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(),m=we.parse(u.sdp),f=m.media.find(h=>h.type==="application");f.maxMessageSize=e,this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:m}),u={type:"answer",sdp:we.write(m)},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=we.parse(this._pc.localDescription.sdp));let r=or.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 si.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')}};ar.Firefox120=ps});var li=C(cr=>{"use strict";Object.defineProperty(cr,"__esModule",{value:!0});cr.Safari12=void 0;var ee=ve(),Ic=G(),Lc=z(),kt=ce(),Mc=X(),Oc=Ie(),Ac=rt(),xt=st(),ci=nt(),ls=it(),R=new Lc.Logger("Safari12"),di="Safari12",pi={OS:65535,MIS:65535},us=class s extends Ic.EnhancedEventEmitter{_closed=!1;_direction;_remoteSdp;_getSendExtendedRtpCapabilities;_forcedLocalDtlsRole;_pc;_mapMidTransceiver=new Map;_sendStream=new MediaStream;_hasDataChannelMediaSection=!1;_nextSendSctpStreamId=0;_transportReady=!1;static createFactory(){return{name:di,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:pi})}}static getLocalRtpCapabilities(e,t=[]){let r=xt.extractRtpCapabilities({sdpObject:e});kt.validateAndNormalizeRtpCapabilities(r),ls.addNackSupportForOpus(r);for(let n of t)ls.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 Ac.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 di}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 m=s.getLocalRtpCapabilities(l,u),f=this._getSendExtendedRtpCapabilities(m),h=kt.getSendingRtpParameters(e.kind,f);h.codecs=kt.reduceCodecs(h.codecs,o);let g=kt.getSendingRemoteRtpParameters(e.kind,f);g.codecs=kt.reduceCodecs(g.codecs,o);let _;this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:l});let y=(0,Oc.parse)((r??[{}])[0].scalabilityMode);r&&r.length>1&&(R.debug("send() | enabling legacy simulcast"),l=ee.parse(p.sdp),_=l.media[c.idx],ci.addLegacySimulcast({offerMediaObject:_,numStreams:r.length}),p={type:"offer",sdp:ee.write(l)}),i?.absCaptureTime&&(_=l.media[c.idx],xt.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=xt.getCname({offerMediaObject:_}),h.msid=`${t??this._sendStream.id} ${e.id}`,h.encodings=ci.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%pi.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:m}=ls.getMsidStreamIdAndTrackId(p.msid);this._remoteSdp.receive({mid:u,kind:d,offerRtpParameters:p,streamId:l??m??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);xt.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(),m=ee.parse(u.sdp),f=m.media.find(h=>h.type==="application");f.maxMessageSize=e,this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:m}),u={type:"answer",sdp:ee.write(m)},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=xt.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 Mc.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')}};cr.Safari12=us});var fi=C(dr=>{"use strict";Object.defineProperty(dr,"__esModule",{value:!0});dr.ReactNative106=void 0;var te=ve(),Nc=G(),jc=z(),Pt=ce(),Fc=X(),qc=Ie(),$c=rt(),Dt=st(),hs=nt(),fs=it(),b=new jc.Logger("ReactNative106"),ui="ReactNative106",hi={OS:65535,MIS:65535},ms=class s extends Nc.EnhancedEventEmitter{_closed=!1;_direction;_remoteSdp;_getSendExtendedRtpCapabilities;_forcedLocalDtlsRole;_pc;_mapMidTransceiver=new Map;_sendStream=new MediaStream;_hasDataChannelMediaSection=!1;_nextSendSctpStreamId=0;_transportReady=!1;static createFactory(){return{name:ui,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:hi})}}static getLocalRtpCapabilities(e,t=[]){let r=Dt.extractRtpCapabilities({sdpObject:e});Pt.validateAndNormalizeRtpCapabilities(r),fs.addNackSupportForOpus(r);for(let n of t)fs.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 $c.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 ui}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,he)=>{I.rid=`r${he}`});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 m=s.getLocalRtpCapabilities(l,u),f=this._getSendExtendedRtpCapabilities(m),h=Pt.getSendingRtpParameters(e.kind,f);h.codecs=Pt.reduceCodecs(h.codecs,o);let g=Pt.getSendingRemoteRtpParameters(e.kind,f);g.codecs=Pt.reduceCodecs(g.codecs,o),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:l});let _=!1,y=(0,qc.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],hs.addLegacySimulcast({offerMediaObject:x,numStreams:y.spatialLayers}),p={type:"offer",sdp:te.write(l)}),i?.absCaptureTime&&(x=l.media[c.idx],Dt.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=Dt.getCname({offerMediaObject:x}),h.msid=`${t??this._sendStream.id} ${e.id}`,!r)h.encodings=hs.getRtpEncodings({offerMediaObject:x,codecs:h.codecs});else if(r.length===1){let I=hs.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%hi.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:m}=fs.getMsidStreamIdAndTrackId(p.msid);this._remoteSdp.receive({mid:u,kind:d,offerRtpParameters:p,streamId:l??m??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);Dt.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(),m=te.parse(u.sdp),f=m.media.find(h=>h.type==="application");f.maxMessageSize=e,this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:m}),u={type:"answer",sdp:te.write(m)},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=Dt.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 Fc.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')}};dr.ReactNative106=ms});var vi=C(ot=>{"use strict";Object.defineProperty(ot,"__esModule",{value:!0});ot.Device=void 0;ot.detectDevice=mi;ot.detectDeviceAsync=gi;var Uc=z(),zc=G(),Te=X(),pr=ke(),K=ce(),Bc=Fn(),Vc=Zn(),Wc=ri(),Hc=ai(),Gc=li(),Kc=fi(),w=new Uc.Logger("Device");function mi(s,e){return w.debug("detectDevice()"),!s&&typeof navigator=="object"&&(s=navigator.userAgent),!e&&typeof navigator=="object"&&(e=navigator.userAgentData),_i(s,e)}async function gi(s,e){return w.debug("detectDeviceAsync()"),!s&&typeof navigator=="object"&&(s=navigator.userAgent),!e&&typeof navigator=="object"&&(e=navigator.userAgentData),_i(s,e)}var gs=class s{_handlerFactory;_handlerName;_loaded=!1;_getSendExtendedRtpCapabilities;_recvRtpCapabilities;_sendRtpCapabilities;_canProduceByKind={audio:!1,video:!1};_sctpCapabilities;_observer=new zc.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 gi(),!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=mi(),e)w.debug("constructor() | detected handler: %s",e);else throw new Te.UnsupportedError("device not supported");switch(e){case"Chrome111":{this._handlerFactory=Vc.Chrome111.createFactory();break}case"Chrome74":{this._handlerFactory=Wc.Chrome74.createFactory();break}case"Firefox120":{this._handlerFactory=Hc.Firefox120.createFactory();break}case"Safari12":{this._handlerFactory=Gc.Safari12.createFactory();break}case"ReactNative106":{this._handlerFactory=Kc.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=pr.clone(e);K.validateAndNormalizeRtpCapabilities(r);let{getNativeRtpCapabilities:n,getNativeSctpCapabilities:i}=this._handlerFactory,o=pr.clone(await n({direction:"recvonly"}));w.debug("load() | got native receiving RTP capabilities:%o",o),K.validateAndNormalizeRtpCapabilities(o);let a=pr.clone(await n({direction:"sendonly"}));w.debug("load() | got native sending RTP capabilities:%o",a),K.validateAndNormalizeRtpCapabilities(a),this._getSendExtendedRtpCapabilities=p=>pr.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 Bc.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}};ot.Device=gs;function _i(s,e){w.debug('detectDeviceImpl() [userAgent:"%s", userAgentData:%o]',s,e);let t=Qc(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=Yc(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=Xc(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(It()){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 Qc(s,e){if(w.debug("getChromiumMajorVersion()"),lr(s,e)){w.debug("getChromiumMajorVersion() | this is iOS => undefined");return}if(It()){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 Yc(s){if(w.debug("getFirefoxMajorVersion()"),lr(s)){w.debug("getFirefoxMajorVersion() | this is iOS => undefined");return}if(It()){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()"),lr(s)){w.debug("getMacOSWebKitMajorVersion() | this is iOS => undefined");return}if(It()){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 Xc(s){if(w.debug("getIOSWebKitMajorVersion()"),!lr(s)){w.debug("getIOSWebKitMajorVersion() | this is not iOS => undefined");return}if(It()){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 lr(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 It(){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 yi=C(wi=>{"use strict";var Me=256,hr=[],ur;for(;Me--;)hr[Me]=(Me+256).toString(16).substring(1);function Zc(){var s=0,e,t="";if(!ur||Me+16>256){for(ur=Array(s=256);s--;)ur[s]=256*Math.random()|0;s=Me=0}for(;s<16;s++)e=ur[Me+s],s==6?t+=hr[e&15|64]:s==8?t+=hr[e&63|128]:t+=hr[e],s&1&&s>1&&s<11&&(t+="-");return Me++,t}wi.v4=Zc});var bi=C(fr=>{"use strict";Object.defineProperty(fr,"__esModule",{value:!0});fr.FakeEventTarget=void 0;var _s=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}};fr.FakeEventTarget=_s});var Si=C(mr=>{"use strict";Object.defineProperty(mr,"__esModule",{value:!0});mr.FakeEvent=void 0;var vs=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){}};mr.FakeEvent=vs});var Ri=C(ws=>{"use strict";Object.defineProperty(ws,"__esModule",{value:!0});ws.clone=ed;function ed(s){if(s!==void 0)return Number.isNaN(s)?NaN:typeof structuredClone=="function"?structuredClone(s):JSON.parse(JSON.stringify(s))}});var Ti=C(_r=>{"use strict";Object.defineProperty(_r,"__esModule",{value:!0});_r.FakeMediaStreamTrack=void 0;var Ci=yi(),td=bi(),at=Si(),gr=Ri(),ys=class s extends td.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,Ci.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 at.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 at.FakeEvent("stopped")))}clone({id:e,data:t}={}){return new s({id:e??(0,Ci.v4)(),kind:this.#l,label:this.#u,contentHint:this.#s,enabled:this.#r,muted:this.#t,readyState:this.#e,capabilities:(0,gr.clone)(this.#h),constraints:(0,gr.clone)(this.#n),settings:(0,gr.clone)(this.#f),data:t??(0,gr.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 at.FakeEvent("stopped")),this.dispatchEvent(new at.FakeEvent("ended")))}remoteMute(){this.#t||(this.#t=!0,this.dispatchEvent(new at.FakeEvent("mute")))}remoteUnmute(){this.#t&&(this.#t=!1,this.dispatchEvent(new at.FakeEvent("unmute")))}};_r.FakeMediaStreamTrack=ys});var Ei=C(vr=>{"use strict";Object.defineProperty(vr,"__esModule",{value:!0});vr.FakeEventTarget=void 0;var bs=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}};vr.FakeEventTarget=bs});var Pi=C(yr=>{"use strict";Object.defineProperty(yr,"__esModule",{value:!0});yr.FakeHandler=void 0;var rd=Ti(),sd=G(),nd=z(),ct=ke(),Ss=ce(),xi=X(),id=Ei(),$=new nd.Logger("FakeHandler"),ki="FakeHandler",Rs=class s extends sd.EnhancedEventEmitter{_closed=!1;_fakeParameters;_getSendExtendedRtpCapabilities;_cname=`CNAME-${ct.generateRandomNumber()}`;_defaultSendStreamId=`${ct.generateRandomNumber()}`;_transportReady=!1;_nextLocalId=1;_tracks=new Map;_nextSctpStreamId=0;static createFactory(e){return{name:ki,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 Ss.validateAndNormalizeRtpCapabilities(t),t}constructor({getSendExtendedRtpCapabilities:e},t){super(),$.debug("constructor()"),this._getSendExtendedRtpCapabilities=e,this._fakeParameters=t}get name(){return ki}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=Ss.getSendingRtpParameters(e.kind,a);c.codecs=Ss.reduceCodecs(c.codecs,i);let d=c.codecs.some(l=>/.+\/rtx$/i.test(l.mimeType));c.mid=`mid-${ct.generateRandomNumber()}`,c.msid=`${t??"-"} ${e.id}`,r||(r=[{}]);for(let l of r)l.ssrc=ct.generateRandomNumber(),d&&(l.rtx={ssrc:ct.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 wr({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 rd.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 wr({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=ct.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 xi.InvalidStateError("method called in a closed handler")}};yr.FakeHandler=Rs;var wr=class extends id.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 xi.InvalidStateError("not open")}}});var Di=C(ie=>{"use strict";Object.defineProperty(ie,"__esModule",{value:!0});ie.generateRouterRtpCapabilities=od;ie.generateNativeRtpCapabilities=ad;ie.generateNativeSctpCapabilities=cd;ie.generateLocalDtlsParameters=dd;ie.generateTransportRemoteParameters=pd;ie.generateProducerRemoteParameters=ld;ie.generateConsumerRemoteParameters=ud;ie.generateDataProducerRemoteParameters=hd;ie.generateDataConsumerRemoteParameters=fd;var V=ke();function Q(){return String(V.generateRandomNumber())}function od(){return V.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 ad(){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 cd(){return V.deepFreeze({numStreams:{OS:2048,MIS:2048}})}function dd(){return V.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 pd(){return{id:Q(),iceParameters:V.deepFreeze({iceLite:!0,password:"yku5ej8nvfaor28lvtrabcx0wkrpkztz",usernameFragment:"h3hk1iz6qqlnqlne"}),iceCandidates:V.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:V.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:V.deepFreeze({port:5e3,OS:2048,MIS:2048,maxMessageSize:2e6})}}function ld(){return V.deepFreeze({id:Q()})}function ud({id:s,codecMimeType:e}={}){switch(e){case"audio/opus":return{id:s??Q(),producerId:Q(),kind:"audio",rtpParameters:V.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:V.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:V.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:V.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 hd(){return V.deepFreeze({id:Q()})}function fd({id:s}={}){return{id:s??Q(),dataProducerId:Q(),sctpStreamParameters:V.deepFreeze({streamId:666,maxPacketLifeTime:5e3,maxRetransmits:void 0})}}});var ns=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 md=gt();A.debug=md.default;A.types=en();A.version="3.20.0";var Cs=vi();Object.defineProperty(A,"Device",{enumerable:!0,get:function(){return Cs.Device}});Object.defineProperty(A,"detectDevice",{enumerable:!0,get:function(){return Cs.detectDevice}});Object.defineProperty(A,"detectDeviceAsync",{enumerable:!0,get:function(){return Cs.detectDeviceAsync}});var gd=Ie();Object.defineProperty(A,"parseScalabilityMode",{enumerable:!0,get:function(){return gd.parse}});A.ortc=ce();A.enhancedEvents=G();var _d=Pi();Object.defineProperty(A,"FakeHandler",{enumerable:!0,get:function(){return _d.FakeHandler}});A.testFakeParameters=Di()});var Li=C((pl,Ts)=>{"use strict";var vd=Object.prototype.hasOwnProperty,W="~";function Lt(){}Object.create&&(Lt.prototype=Object.create(null),new Lt().__proto__||(W=!1));function wd(s,e,t){this.fn=s,this.context=e,this.once=t||!1}function Ii(s,e,t,r,n){if(typeof t!="function")throw new TypeError("The listener must be a function");var i=new wd(t,r||s,n),o=W?W+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 br(s,e){--s._eventsCount===0?s._events=new Lt:delete s._events[e]}function U(){this._events=new Lt,this._eventsCount=0}U.prototype.eventNames=function(){var e=[],t,r;if(this._eventsCount===0)return e;for(r in t=this._events)vd.call(t,r)&&e.push(W?r.slice(1):r);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};U.prototype.listeners=function(e){var t=W?W+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=W?W+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=W?W+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,m;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(m=1,p=new Array(d-1);m<d;m++)p[m-1]=arguments[m];c[l].fn.apply(c[l].context,p)}}return!0};U.prototype.on=function(e,t,r){return Ii(this,e,t,r,!1)};U.prototype.once=function(e,t,r){return Ii(this,e,t,r,!0)};U.prototype.removeListener=function(e,t,r,n){var i=W?W+e:e;if(!this._events[i])return this;if(!t)return br(this,i),this;var o=this._events[i];if(o.fn)o.fn===t&&(!n||o.once)&&(!r||o.context===r)&&br(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:br(this,i)}return this};U.prototype.removeAllListeners=function(e){var t;return e?(t=W?W+e:e,this._events[t]&&br(this,t)):(this._events=new Lt,this._eventsCount=0),this};U.prototype.off=U.prototype.removeListener;U.prototype.addListener=U.prototype.on;U.prefixed=W;U.EventEmitter=U;typeof Ts<"u"&&(Ts.exports=U)});var fp={};Us(fp,{App:()=>Zi,DEFAULT_DOC_SYNC_TIMEOUT_MS:()=>Ns,RequestAbortError:()=>ye,RequestCancelledError:()=>ft,RequestDocSyncError:()=>ut,RequestError:()=>oe,RequestTimeoutError:()=>lt,Session:()=>mt,StreamDirectionConflict:()=>ht,createStore:()=>ro,videoStream:()=>so});module.exports=Bs(fp);var Fe=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))}},qe=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 zi=Se(ns());var Es=Se(Li(),1);function Rr(){return typeof window>"u"&&typeof process<"u"&&process.versions!=null&&process.versions.node!=null}function Oi(){return Rr()?"Chrome111":void 0}var yd=["RTCSessionDescription","RTCIceCandidate","RTCRtpReceiver","RTCRtpSender","RTCRtpTransceiver","RTCDataChannel","MediaStream","MediaStreamTrack"],Sr=null;function Ai(){return Rr()?Sr||(Sr=bd(),Sr):Promise.resolve()}async function bd(){let s=globalThis;if(typeof s.WebSocket>"u")try{let e=await import("ws"),t=e.default??e;s.WebSocket=t}catch(e){Mi("WebSocket",e)}if(typeof s.RTCPeerConnection>"u")try{let e=await import("werift");Sd(s,e)}catch(e){Mi("werift",e)}}function Sd(s,e){let{RTCPeerConnection:t,useH264:r,useVP8:n,useOPUS:i,useSdesMid:o,useSdesRTPStreamId:a,useAbsSendTime:c,useTransportWideCC:d,useVideoOrientation:p}=e,l=()=>({video:[r(),n()],audio:[i()]}),u=()=>({video:[o(),a(),c(),d(),p()],audio:[o(),c(),d()]});class m extends t{constructor(h){super({...h,codecs:h?.codecs??l(),headerExtensions:h?.headerExtensions??u()})}}s.RTCPeerConnection=m;for(let f of yd)e[f]!=null&&typeof s[f]>"u"&&(s[f]=e[f])}function Mi(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 Ni="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function Rd(s){let e=globalThis.crypto,t=new Uint8Array(s);if(e?.getRandomValues)return e.getRandomValues(t),t;for(let r=0;r<s;r++)t[r]=Math.floor(Math.random()*256);return t}function Cr(s=16){let e=Rd(s),t="";for(let r=0;r<s;r++)t+=Ni[e[r]%Ni.length];return t}var ji=[1e3,2e3,4e3,8e3,3e4],Fi=5,Cd=15e3,Td=2e3,Ed=6e3,kd=2,xd=750,Pd=3,qi=[1e3,2e3,4e3],Dd=15e3,ks="control",Bi=0,Vi=1,xs=64;function Id(s,e){if(s===ks){let n=new Uint8Array(1+e.length);return n[0]=Bi,n.set(e,1),n}let t=new TextEncoder().encode(s);if(t.length<1||t.length>xs)throw new Error(`[urun] doc key length out of range (1..${xs}): ${t.length}`);let r=new Uint8Array(3+t.length+e.length);return r[0]=Vi,r[1]=t.length>>>8&255,r[2]=t.length&255,r.set(t,3),r.set(e,3+t.length),r}function Ld(s){if(s.length===0)return{docKey:ks,payload:s.slice()};let e=s[0];if(e===Bi)return{docKey:ks,payload:s.slice(1)};if(e===Vi){if(s.length<3)return null;let t=s[1]<<8|s[2];if(t<1||t>xs||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 Md={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"},Od=8e3,$i=[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun1.l.google.com:19302"}],dt=class{_state="disconnected";_sessionId=null;_tracks=new Map;_tracksByName=new Map;_options;_emitter=new Es.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=Ad()),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=jd(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?kd:1;for(let c=0;c<a;c++)if(c>0&&(await Ui(xd),i()),await o())return;if(this._resolveConnection)for(let c=0;c<Pd;c++){this._setState("reconnecting"),await Ui(qi[Math.min(c,qi.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");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}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(Id(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=Ld(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 r=typeof e.status=="string"?e.status:void 0,n=(r&&Md[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){Rr()&&await Ai();let t=Oi(),r=new zi.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:this._options.iceServers??$i}),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")},Od))}_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??$i}),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?Td:e}_mediaStallTimeoutMs(){let e=this._options.mediaLiveness?.stallTimeoutMs;return e===void 0?Ed: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 Nd(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>=Fi){this._setState("failed"),this._emitError(new Error(`Failed after ${Fi} attempts`));return}let t=ji[Math.min(this._reconnectAttempts,ji.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 Fe(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},Dd))}_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 Ui(s){return new Promise(e=>setTimeout(e,s))}function Ad(){return Cr()}async function Nd(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 jd(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 Fd="session-api.prod.cloud.urun.sh",qd=["https://session-api.use2.prod.cloud.urun.sh","https://session-api.usw2.prod.cloud.urun.sh"];function Tr(s){return s.trim().replace(/\/+$/,"")}function Wi(s,e){let t=[],r=n=>{if(!n)return;let i=Tr(n);i&&!t.includes(i)&&t.push(i)};r(s);for(let n of e??[])r(n);for(let n of Kd(s))r(n);return t}var $d=120,Ud=1e3,zd=3;function Bd(s){if(!s)return null;try{let e=new URL(s),t=e.pathname.replace(/\/api\/sessions\/create\/?$/,"");return Tr(`${e.origin}${t}`)}catch{return null}}async function Hi(s){let e=Wi(s.baseUrl,s.fallbackUrls),t=null,r=e.length>1;for(let n of e)try{return await Vd(n,s,{pollAttempts:$d,retryAfterLimitMs:r?Ud: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 Vd(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 Ds(e),i=void 0;let p=r?await fetch(`${o}/api/session-requests/${encodeURIComponent(r)}`,{headers:Ps(e,n)}):await fetch(`${o}/api/sessions/create`,{method:"POST",redirect:"manual",headers:{...Ps(e,n),"Content-Type":"application/json","Idempotency-Key":e.idempotencyKey},body:JSON.stringify(Wd(e))});if(!r&&(p.status===307||p.status===308)){let f=Bd(p.headers.get("location"));if(f&&f!==o&&a<zd){a+=1,o=f;continue}throw new Error(`[urun] session create redirected from ${o} without a usable target`)}let l=await Ki(p);if(p.ok&&(l.status==="allocated"||!l.status&&!!l.session_id)&&!!l.session_id){let f=l.session_id;if(!l.ws_url)throw new Oe(`[urun] gateway allocated session ${f} without ws_url`);if(!Qi(l.ws_url))throw new Oe(`[urun] gateway allocated session ${f} with non-absolute ws_url`);return{baseUrl:o,sessionId:f,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 Gd(Hd(p,l,t.retryAfterLimitMs));continue}if((p.status===401||p.status===403)&&e.getAccessToken){let f=n??"";c.add(f);let h=await Ds(e,{forceRefresh:!0,reason:"unauthorized"});if(h&&!c.has(h)){i=h,r=void 0;continue}}let m=l.error_message||l.error_code||`HTTP ${p.status}`;throw new Error(`[urun] session allocation failed at ${o}: ${m}`)}throw new Error(`[urun] timed out waiting for session allocation at ${o}`)}function Ps(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 Ds(s,e){return s.getAccessToken?await s.getAccessToken(e)??void 0:s.jwt}function Wd(s){return{app:s.app,function:s.functionName,gpus:1,idempotency_key:s.idempotencyKey}}async function Gi(s){let e=Wi(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 Ds(n),o=await fetch(`${Tr(r)}/api/sessions/${encodeURIComponent(s.sessionId)}/viewer-connect`,{headers:Ps(n,i)});if(!o.ok)throw new Error(`[urun] viewer-connect for ${s.sessionId} failed: HTTP ${o.status}`);let a=await Ki(o);if(!a.ws_url||!Qi(a.ws_url))throw new Oe(`[urun] viewer-connect returned no usable ws_url for ${s.sessionId}`);return{baseUrl:Tr(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 Ki(s){try{let e=await s.json();return e&&typeof e=="object"?e:{}}catch{return{}}}function Hd(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 Gd(s){return new Promise(e=>setTimeout(e,s))}var Oe=class extends Error{};function Qi(s){try{let e=new URL(s);return e.protocol==="ws:"||e.protocol==="wss:"}catch{return!1}}function Kd(s){try{return new URL(s).hostname!==Fd?[]:qd}catch{return[]}}var pt=Se(require("yjs")),Yi=Symbol("urun:doc:remote"),Qd=Symbol("urun:doc:local");function Ae(s){return s!==null&&typeof s=="object"&&!Array.isArray(s)}var Er="$bytes";function Yd(s){return s instanceof Uint8Array||s instanceof ArrayBuffer}function Jd(s){if(!Ae(s))return!1;let e=Object.keys(s);return e.length===1&&e[0]===Er&&typeof s[Er]=="string"}function Xd(s){return s instanceof ArrayBuffer?new Uint8Array(s):s}function Zd(s){if(typeof Buffer<"u")return Buffer.from(s).toString("base64");let e="";for(let t=0;t<s.length;t++)e+=String.fromCharCode(s[t]);return btoa(e)}function ep(s){if(typeof Buffer<"u")return new Uint8Array(Buffer.from(s,"base64"));let e=atob(s),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}function Is(s){if(Yd(s))return{[Er]:Zd(Xd(s))};if(Array.isArray(s))return s.map(Is);if(Ae(s)){let e={};for(let[t,r]of Object.entries(s))e[t]=Is(r);return e}return s}function Mt(s){if(Jd(s))return ep(s[Er]);if(Array.isArray(s))return s.map(Mt);if(Ae(s)){let e={};for(let[t,r]of Object.entries(s))e[t]=Mt(r);return e}return s}function Ls(s,e){let t={...s};for(let r of Object.keys(e)){let n=e[r],i=t[r];Ae(n)&&Ae(i)?t[r]=Ls(i,n):t[r]=n}return t}var Xi=Symbol("urun:doc:path-absent");function tp(s,e){let t=e.split("."),r=s;for(let n of t){if(r===null||typeof r!="object"||!(n in r))return Xi;r=r[n]}return r}function Ji(s){return s===void 0?s:JSON.parse(JSON.stringify(s))}var kr=class{_doc=new pt.Doc;_root=this._doc.getMap("session");_listeners=new Set;_key;_sessionId;_transport;_transportUnsubs=[];_synced;_pendingPatches=[];_syncWaiters=new Set;_texts=new Map;_observer=()=>this.notify();_updateHandler=(e,t)=>{t!==Yi&&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}get synced(){return this._synced}onSynced(e){return this._synced?(e(),()=>{}):(this._syncWaiters.add(e),()=>this._syncWaiters.delete(e))}set(e){if(e=Is(e),!this._synced){this._pendingPatches.push(Ji(e)),this.notify();return}this.applyPatch(e)}get(e,t){let r=this.snapshot();if(!e)return Mt(r);let n=tp(r,e);return n===Xi?t:Mt(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 Ms(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(),this._syncWaiters.clear();for(let e of this._texts.values())e.dispose();this._texts.clear(),this._doc.destroy()}sendHello(){this._transport&&this._transport.sendDocSync(this._key,pt.encodeStateAsUpdate(this._doc))}applyRemote(e){if(pt.applyUpdate(this._doc,e,Yi),!this._synced){this._synced=!0;let t=this._pendingPatches.splice(0);for(let n of t)this.applyPatch(n);let r=[...this._syncWaiters];this._syncWaiters.clear();for(let n of r)n()}}applyPatch(e){this._doc.transact(()=>{let t=this._root.toJSON();for(let[r,n]of Object.entries(e)){let i=t[r],o=Ae(n)&&Ae(i)?Ls(i,n):Ji(n);JSON.stringify(o)!==JSON.stringify(i)&&this._root.set(r,o)}},Qd)}snapshot(){let e=this._root.toJSON();for(let t of this._pendingPatches)e=Ls(e,t);return e}notify(){let e=Mt(this.snapshot());for(let t of this._listeners)t(e)}},Ms=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 oe=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)}},lt=class extends oe{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)}},ut=class extends oe{timeoutMs;constructor(e,t){super(`[urun] request doc-sync did not establish within ${e}ms \u2014 the request was never delivered to the runtime (the session doc never synced with the session-server; check the doc-sync transport / connection)`,{requestId:t}),this.name="RequestDocSyncError",this.timeoutMs=e,Object.setPrototypeOf(this,new.target.prototype)}},ht=class extends Error{stream;owner;attempted;constructor(e,t,r){super(`[urun] stream "${e}" is already produced by the ${t}; this (${r}) peer cannot also produce it \u2014 a named stream has exactly one producer (consume it instead, or use a distinct name for the reverse direction)`),this.name="StreamDirectionConflict",this.stream=e,this.owner=t,this.attempted=r,Object.setPrototypeOf(this,new.target.prototype)}},ye=class extends oe{constructor(e){super("[urun] request aborted",{requestId:e}),this.name="RequestAbortError",Object.setPrototypeOf(this,new.target.prototype)}},ft=class extends oe{constructor(e){super("[urun] request cancelled: session disconnected",{requestId:e}),this.name="RequestCancelledError",Object.setPrototypeOf(this,new.target.prototype)}};var rp=new Set,sp="rpc",np="llm",Ns=3e4,ip="llm-resp";function op(s){return`${ip}:${s}`}function Os(){return Cr()}function ap(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 cp(s,e,t,r,n,i,o,a,c){let d=[],p=null,l=!1,u=null,m=!1,f,h,g=new Promise((D,be)=>{f=D,h=be});g.catch(()=>{});let _=i(),y=null,x=null,P=null,k=null,I=!0,he=()=>{P&&(clearTimeout(P),P=null),k&&(k(),k=null)},ae=()=>{I=!1,he(),y?.(),y=null,x?.(),x=null,o?.removeEventListener("abort",qs),_.dispose(),m&&s.set({requests:{[e]:null}})},Y=()=>{if(p){if(d.length>0){let D=p;p=null,D.resolve({value:d.shift(),done:!1})}else if(u!==null){let D=p;p=null,D.reject(u)}else if(l){let D=p;p=null,D.resolve({value:void 0,done:!0})}}},fe=D=>{l||(d.push(D),Y())},Ne=D=>{l||(u=D,l=!0,h(D),ae(),Y())},Fs=D=>{l||(l=!0,f(D),ae(),Y())},qs=()=>Ne(new ye(e)),no=D=>{if(!(l||!D||typeof D!="object"))switch(D.t){case"delta":typeof D.delta=="string"&&fe(D.delta);break;case"response":Fs(D.body);break;case"error":{let{message:be,code:je}=ap(D.body);Ne(new oe(be,{requestId:e,code:D.code??je}));break}}},io=()=>{let D=_.messages()[Symbol.asyncIterator]();y=()=>{D.return?.(void 0)};let be=()=>{I&&D.next().then(je=>{if(I){if(je.done){l||Fs(void 0);return}no(je.value),be()}},je=>{I&&Ne(je)})};be()},$s=()=>{if(!m){if(m=!0,o){if(o.aborted){Ne(new ye(e));return}o.addEventListener("abort",qs,{once:!0})}x=a?.(D=>Ne(D))??null,io(),s.set({requests:{[e]:{payload:t,consumer_id:r,stream:n}}}),c&&c>0&&!s.synced&&(P=setTimeout(()=>{P=null,!l&&!s.synced&&Ne(new ut(c,e))},c),k=s.onSynced(()=>he()))}};return{deltas:{[Symbol.asyncIterator](){return{next(){if($s(),d.length>0)return Promise.resolve({value:d.shift(),done:!1});if(u!==null){let D=u;return u=null,Promise.reject(D)}return l?Promise.resolve({value:void 0,done:!0}):new Promise((D,be)=>{p={resolve:D,reject:be}})},return(){return l||(l=!0,f(void 0),ae()),Promise.resolve({value:void 0,done:!0})},throw(D){return l||(l=!0,h(D),ae()),Promise.reject(D)}}}},body:g,start:$s}}function dp(s,e){return[`streams/${s}/${e}`,`streams/${s}/*`]}function pp(s,e){return`streams/${s}/${e??"*"}`}function lp(s,e){let r=s.get("streams")?.[e];if(r&&typeof r=="object"){let{producer:n,epoch:i}=r;if(n==="runtime"||n==="browser")return{producer:n,epoch:typeof i=="number"?i:0}}return null}var As=class{constructor(e,t,r,n){this._name=e;this._transport=t;this._laneDoc=r;this._controlDoc=n;this._track=this._transport.getTrackByName(this._name)??null,this._unsubscribeTransport=this._transport.on("track",()=>{let i=this._transport.getTrackByName(this._name)??null;i!==this._track&&this._setTrack(i)})}_name;_transport;_laneDoc;_controlDoc;_track=null;_handlers=new Map;_unsubscribeTransport=null;_subscribed=!1;_messageConsumers=new Set;_laneUnsubs=[];_laneSeen=new Map;_replay=[];_disposed=!1;messages(){this._ensureSubscribed();let e=this;return{[Symbol.asyncIterator](){let t=[...e._replay],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 dp(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];this._replay.push(i);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}_claimBrowserProducer(){if(!this._controlDoc)return;let e=this._controlDoc(),t=lp(e,this._name);if(t&&t.producer==="runtime")throw new ht(this._name,"runtime","browser");if(t&&t.producer==="browser")return;let r=(typeof t?.epoch=="number"?t.epoch:0)+1;e.set({streams:{[this._name]:{producer:"browser",epoch:r}}})}async attach(e){this._claimBrowserProducer(),await this._transport.addTrack(e)}async attachVideo(e){this._claimBrowserProducer(),await this._transport.addVideoTrack(e)}async emit(e,t={}){if(this._claimBrowserProducer(),!this._laneDoc)throw new Error("[urun] stream.emit requires the session doc transport (no laneDoc wired)");let r=pp(this._name,t.to),n=this._laneDoc(r),i=n.get("messages"),o=Array.isArray(i)?[...i]:[];o.push(e),n.set({messages:o})}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 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)}},mt=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 Gi({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 qe,o=new dt({url:r.wsUrl,orgId:t.orgId,jwt:n,authProvider:t.authProvider,sessionId:e,iceServers:r.response.ice_servers}),a=new s(e,i,o);return o.on("connected",()=>{o.multiplexer&&i.setTarget(o.multiplexer)}),o.setConnection({url:r.wsUrl,sessionId:e,iceServers:r.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 r of this._docs.values())r.setSessionId(e)}stream(e){let t=this._streams.get(e);return t||(t=new As(e,this._transport,r=>this.doc(r),()=>this.doc("control")),this._streams.set(e,t)),t}doc(e){let t=this._docs.get(e);return t||(t=new kr(e,this._sessionId,rp.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 r=this.doc(sp),n=Os();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",m),r.set({requests:{[n]:null}})},u=h=>{a||(a=!0,l(),h())},m=()=>u(()=>o(new ye(n)));if(t.signal){if(t.signal.aborted){a=!0,o(new ye(n));return}t.signal.addEventListener("abort",m,{once:!0})}let f=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 oe(x,{requestId:n,code:y.code})))}else u(()=>i(y.result))};c=r.on("change",f),p=h=>u(()=>o(h)),this._activeRequests.add(p),typeof t.timeout=="number"&&t.timeout>=0&&(d=setTimeout(()=>u(()=>o(new lt(t.timeout,n))),t.timeout)),r.set({requests:{[n]:{payload:e}}}),f(r.get())})}_consumeResponse(e,t,r,n,i){let o=this.doc(np);return cp(o,e,t,this._transport.consumerId,r,()=>this.stream(op(e)),n,a=>(this._activeRequests.add(a),()=>this._activeRequests.delete(a)),i??Ns)}requestStream(e,t={}){let r=Os();return this._consumeResponse(r,e,!0,t.signal,t.docSyncTimeout).deltas}complete(e,t={}){let r=Os(),n=this._consumeResponse(r,e,!1,t.signal,t.docSyncTimeout);return n.start(),n.body}disconnect(){let e=Array.from(this._activeRequests);this._activeRequests.clear();for(let t of e)try{t(new ft)}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 up=new Set(["then","catch","finally","toJSON",Symbol.toPrimitive]);function Zi(s,e){return new Proxy({},{get(t,r){if(!(up.has(r)||typeof r!="string"))return n=>{let i=n??{},o=()=>`s_${Date.now()}_${Math.random().toString(36).slice(2)}`,a=o(),c=new qe,d=new dt({url:"",orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionId:a}),p=new mt(a,c,d),l=async u=>{let m=await Hi({baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,app:s,functionName:r,orgId:e.orgId,jwt:e.jwt,getAccessToken:e.getAccessToken,authProvider:e.authProvider,idempotencyKey:u}),f=e.getAccessToken?await e.getAccessToken()??void 0:e.jwt;return p.setSessionId(m.sessionId),{url:m.wsUrl,sessionId:m.sessionId,jwt:f,iceServers:m.response.ice_servers}};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,iceServers:u.iceServers}),await d.connect({app:s,functionName:r,args:i})})().catch(u=>{console.error(`[urun] Failed to connect session for ${r}:`,u)}),p}}})}var eo=3e4,to="stream:",js=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=`${to}${e}`;return this._multiplexer.on(r,n=>{t(n)})}emit(e,t){let r=`${to}${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 ${eo}ms`)))},eo);this._pendingRpc.set(i,{resolve:r,reject:n,timer:o}),this._ws.send(JSON.stringify({rpcId:i,type:e,...t}))})}};function ro(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 Fe(n);return new js(n,i)}var hp='video/mp4; codecs="avc1.42E01E"';function so(s,e){let t=e?.codec??hp,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 m=s.getReader();function f(){return u.updating?new Promise(g=>{u.addEventListener("updateend",()=>g(),{once:!0})}):Promise.resolve()}async function h(){try{for(;;){let{done:g,value:_}=await m.read();if(g){await f(),n.readyState==="open"&&n.endOfStream();return}await f();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 f(),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,DEFAULT_DOC_SYNC_TIMEOUT_MS,RequestAbortError,RequestCancelledError,RequestDocSyncError,RequestError,RequestTimeoutError,Session,StreamDirectionConflict,createStore,videoStream});
|